From 8f888689ed1133fc1b2b3ce1b45a4bcdb805052e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 14:05:22 -0400 Subject: [PATCH 001/558] feat(worldgen): prototype pure hex WFC solver + tests (research spike, not wired to UI) Palette-agnostic simple-tiled WFC over the hex grid: symmetric adjacency deck (allow-by-default deny list, or deny-by-default allow list), weights, pre-fixed (painted) cells, seeded mulberry32 RNG, trail-based backtracking with bounded restarts, and clean invalid-input / fixed-conflict / contradiction results. Neighbours come from hexGeometry.hexNeighbors so odd-q/odd-r + stagger can't drift. Includes learnRulesFromSample for deriving a deck from a painted sample. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/worldgen/wfc.ts | 429 ++++++++++++++++++++++++++++++++++++++++++++ tests/wfc.test.ts | 217 ++++++++++++++++++++++ 2 files changed, 646 insertions(+) create mode 100644 src/worldgen/wfc.ts create mode 100644 tests/wfc.test.ts diff --git a/src/worldgen/wfc.ts b/src/worldgen/wfc.ts new file mode 100644 index 00000000..6f61c0ac --- /dev/null +++ b/src/worldgen/wfc.ts @@ -0,0 +1,429 @@ +/** + * Hex-grid Wave Function Collapse (simple tiled model) — PROTOTYPE. + * + * Pure, DOM-free, Obsidian-free. Not wired into any UI yet; see the KB plan + * note `plan-wfc-worldgen` for the design this module is a spike for. + * + * Model: each hex is a cell whose domain is a set of terrain names taken from + * the user's palette. Adjacency is undirected and the same in all six + * directions (terrain hexes have no rotation or edge sockets), so a single + * symmetric compatibility matrix is enough. + * + * Invariants: + * - Palette-agnostic: terrains are opaque strings; nothing is hardcoded. + * - Fixed cells (hexes the user already painted) are never changed. If they + * are mutually inconsistent the solver reports `fixed-conflict` instead of + * silently overwriting them. + * - Deterministic: the same input (including `seed`) gives the same output. + * - Neighbour topology is delegated to `hexNeighbors` from hexGeometry so it + * can never drift from the map renderer (odd-q / odd-r with stagger). + */ + +import { hexNeighbors } from "../hex-map/hexGeometry"; + +// ── Public types ───────────────────────────────────────────────────────────── + +/** + * Adjacency "deck". + * - `default: "allow"` → every pair may touch except those in `pairs` + * (the "ocean is never next to desert" style; an empty list = no constraints). + * - `default: "deny"` → only the pairs in `pairs` may touch (classic WFC). + * Self-adjacency must then be listed explicitly, e.g. ["forest", "forest"]. + * Pairs are unordered: ["a","b"] also covers ["b","a"]. + */ +export interface AdjacencyRules { + default: "allow" | "deny"; + pairs: [string, string][]; +} + +export interface WfcInput { + cols: number; + rows: number; + /** Absolute coordinate of the top-left cell (MapData.gridOffset). Parity of + * absolute coords drives the stagger, so this matters for neighbours. */ + offset?: { x: number; y: number }; + orientation: "flat" | "pointy"; + stagger?: "odd" | "even"; + terrains: string[]; + rules: AdjacencyRules; + /** Relative frequency per terrain. Missing = 1. 0 = never chosen by the + * solver (still allowed in fixed cells). */ + weights?: Record; + /** Pre-painted hexes keyed by "x_y" (absolute coords). Never changed. */ + fixed?: Record; + seed: number; + /** Backtracks allowed per attempt before restarting. Default 2000. */ + maxBacktracks?: number; + /** Fresh attempts (re-seeded) after the first one. Default 5. */ + maxRestarts?: number; +} + +export interface WfcStats { + attempts: number; + backtracks: number; + decisions: number; + ms: number; +} + +export type WfcResult = + | { ok: true; cells: Map; stats: WfcStats } + | { + ok: false; + reason: "invalid-input" | "fixed-conflict" | "contradiction"; + message: string; + /** Cell where the problem was detected, when known. */ + at?: { x: number; y: number }; + stats: WfcStats; + }; + +// ── Seeded RNG ─────────────────────────────────────────────────────────────── + +/** mulberry32 — tiny, fast, good enough for map generation. Returns [0, 1). */ +export function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +// ── Helpers ────────────────────────────────────────────────────────────────── + +export const cellKey = (x: number, y: number): string => `${x}_${y}`; + +/** Build the symmetric allowed-pair lookup used by both solver and validator. */ +export function buildAllowed(terrains: string[], rules: AdjacencyRules): (a: string, b: string) => boolean { + const listed = new Set(); + for (const [a, b] of rules.pairs) { + listed.add(`${a}\u0000${b}`); + listed.add(`${b}\u0000${a}`); + } + const allowByDefault = rules.default === "allow"; + return (a, b) => { + const inList = listed.has(`${a}\u0000${b}`); + return allowByDefault ? !inList : inList; + }; +} + +/** + * Check a finished map against the rules. Returns the first violating + * neighbour pair, or null if everything is consistent. Used by tests and + * would be used to validate a hand-painted map in the UI. + */ +export function findViolation( + cells: Map, + input: Pick, +): { a: [number, number]; b: [number, number]; ta: string; tb: string } | null { + const allowed = buildAllowed(input.terrains, input.rules); + for (const [key, ta] of cells) { + const [x, y] = key.split("_").map(Number); + for (const [nx, ny] of hexNeighbors(x, y, input.orientation, input.stagger ?? "odd")) { + const tb = cells.get(cellKey(nx, ny)); + if (tb !== undefined && !allowed(ta, tb)) return { a: [x, y], b: [nx, ny], ta, tb }; + } + } + return null; +} + +/** + * Learn a rule deck + weights from an already-painted map ("example-based" + * authoring): any pair seen adjacent is allowed, everything else denied, and + * weights follow observed frequency. One answer to "the palette has no rules + * yet" — paint a small sample, then derive the deck from it. + */ +export function learnRulesFromSample( + cells: Map, + orientation: "flat" | "pointy", + stagger: "odd" | "even" = "odd", +): { rules: AdjacencyRules; weights: Record } { + const pairs = new Map(); + const weights: Record = {}; + for (const [key, ta] of cells) { + weights[ta] = (weights[ta] ?? 0) + 1; + const [x, y] = key.split("_").map(Number); + for (const [nx, ny] of hexNeighbors(x, y, orientation, stagger)) { + const tb = cells.get(cellKey(nx, ny)); + if (tb === undefined) continue; + const [p, q] = ta < tb ? [ta, tb] : [tb, ta]; + pairs.set(`${p}\u0000${q}`, [p, q]); + } + } + return { rules: { default: "deny", pairs: [...pairs.values()] }, weights }; +} + +// ── Solver ─────────────────────────────────────────────────────────────────── + +export function solveHexWfc(input: WfcInput): WfcResult { + const t0 = Date.now(); + const stats: WfcStats = { attempts: 0, backtracks: 0, decisions: 0, ms: 0 }; + const fail = ( + reason: "invalid-input" | "fixed-conflict" | "contradiction", + message: string, + at?: { x: number; y: number }, + ): WfcResult => { + stats.ms = Date.now() - t0; + return { ok: false, reason, message, at, stats }; + }; + + const { cols, rows, orientation } = input; + const stagger = input.stagger ?? "odd"; + const ox = input.offset?.x ?? 0; + const oy = input.offset?.y ?? 0; + const terrains = [...new Set(input.terrains)]; + const T = terrains.length; + if (cols <= 0 || rows <= 0) return fail("invalid-input", "Grid must be at least 1×1"); + if (T === 0) return fail("invalid-input", "No terrains supplied"); + const tIndex = new Map(terrains.map((t, i) => [t, i])); + + const N = cols * rows; + const W = (T + 31) >>> 5; // 32-bit words per domain bitset + const idx = (x: number, y: number) => (y - oy) * cols + (x - ox); + const inGrid = (x: number, y: number) => x >= ox && x < ox + cols && y >= oy && y < oy + rows; + + // Neighbour table (−1 = off-grid), 6 per cell. + const nbr = new Int32Array(N * 6).fill(-1); + for (let j = 0; j < rows; j++) { + for (let i = 0; i < cols; i++) { + const x = ox + i, y = oy + j, c = j * cols + i; + const ns = hexNeighbors(x, y, orientation, stagger); + for (let d = 0; d < ns.length; d++) { + const [nx, ny] = ns[d]; + if (inGrid(nx, ny)) nbr[c * 6 + d] = idx(nx, ny); + } + } + } + + // Compatibility bitsets: compat[t] = set of terrains allowed next to t. + const allowed = buildAllowed(terrains, input.rules); + const compat = new Uint32Array(T * W); + for (let a = 0; a < T; a++) + for (let b = 0; b < T; b++) + if (allowed(terrains[a], terrains[b])) compat[a * W + (b >>> 5)] |= 1 << (b & 31); + + const weight = new Float64Array(T); + for (let t = 0; t < T; t++) { + const w = input.weights?.[terrains[t]] ?? 1; + weight[t] = Number.isFinite(w) && w > 0 ? w : 0; + } + const solverMask = new Uint32Array(W); // terrains the solver may pick + for (let t = 0; t < T; t++) if (weight[t] > 0) solverMask[t >>> 5] |= 1 << (t & 31); + + // Fixed cells (only those inside the grid matter). + const fixedCells: [number, number][] = []; // [cellIndex, terrainIndex] + for (const [key, terr] of Object.entries(input.fixed ?? {})) { + const [x, y] = key.split("_").map(Number); + if (!Number.isInteger(x) || !Number.isInteger(y) || !inGrid(x, y)) continue; + const ti = tIndex.get(terr); + if (ti === undefined) + return fail("invalid-input", `Fixed hex ${key} uses terrain "${terr}" which is not in the generator's terrain list`, { x, y }); + fixedCells.push([idx(x, y), ti]); + } + // Direct fixed–fixed conflicts give the clearest message, so check first. + const fixedAt = new Int32Array(N).fill(-1); + for (const [c, t] of fixedCells) fixedAt[c] = t; + for (const [c, t] of fixedCells) { + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n < 0 || fixedAt[n] < 0) continue; + const u = fixedAt[n]; + if (!((compat[t * W + (u >>> 5)] >>> (u & 31)) & 1)) { + const x = ox + (c % cols), y = oy + Math.floor(c / cols); + return fail("fixed-conflict", `Painted hexes ${cellKey(x, y)} (${terrains[t]}) and ${cellKey(ox + (n % cols), oy + Math.floor(n / cols))} (${terrains[u]}) break the adjacency rules`, { x, y }); + } + } + } + + if (fixedCells.length < N && solverMask.every((v) => v === 0)) + return fail("invalid-input", "Every terrain has weight 0, so unpainted hexes cannot be filled"); + + const maxBacktracks = input.maxBacktracks ?? 2000; + const maxRestarts = input.maxRestarts ?? 5; + const masterRng = mulberry32(input.seed); + + const dom = new Uint32Array(N * W); + // Trail of [wordIndex, previousValue] for cheap undo. + let trailIdx: number[] = []; + let trailVal: number[] = []; + const popcount = (v: number) => { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24; + }; + const count = (c: number) => { + let s = 0; + for (let w = 0; w < W; w++) s += popcount(dom[c * W + w]); + return s; + }; + // Entropy cache: recomputed only for cells whose domain changed. + const dirty = new Uint8Array(N).fill(1); + const hCache = new Float64Array(N); + const cntCache = new Int32Array(N); + const noise = new Float64Array(N); // per-attempt tie-breaker + const setWord = (i: number, v: number) => { + if (dom[i] === v) return; + trailIdx.push(i); + trailVal.push(dom[i]); + dom[i] = v; + dirty[(i / W) | 0] = 1; + }; + const undoTo = (mark: number) => { + for (let k = trailIdx.length - 1; k >= mark; k--) { + dom[trailIdx[k]] = trailVal[k]; + dirty[(trailIdx[k] / W) | 0] = 1; + } + trailIdx.length = mark; + trailVal.length = mark; + }; + + const queue = new Int32Array(N); + const inQueue = new Uint8Array(N); + const support = new Uint32Array(W); + /** AC-3 style propagation from `seeds`. Returns the emptied cell or −1. */ + const propagate = (seeds: number[]): number => { + let head = 0, tail = 0; + for (const s of seeds) if (!inQueue[s]) { inQueue[s] = 1; queue[tail++ % N] = s; } + let size = tail; + while (size > 0) { + const c = queue[head++ % N]; + size--; + inQueue[c] = 0; + // Union of what c's remaining terrains allow next to them. + support.fill(0); + for (let w = 0; w < W; w++) { + let bits = dom[c * W + w]; + while (bits) { + const low = bits & -bits; + const t = (w << 5) + (31 - Math.clz32(low)); + for (let v = 0; v < W; v++) support[v] |= compat[t * W + v]; + bits ^= low; + } + } + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n < 0) continue; + let changed = false, empty = true; + for (let w = 0; w < W; w++) { + const i = n * W + w; + const nv = dom[i] & support[w]; + if (nv !== dom[i]) { setWord(i, nv); changed = true; } + if (nv) empty = false; + } + if (empty) { + // Drain queue flags so the next propagate starts clean. + while (size > 0) { inQueue[queue[head++ % N]] = 0; size--; } + return n; + } + if (changed && !inQueue[n]) { inQueue[n] = 1; queue[tail++ % N] = n; size++; } + } + } + return -1; + }; + + const cellXY = (c: number) => ({ x: ox + (c % cols), y: oy + Math.floor(c / cols) }); + + for (let attempt = 0; attempt <= maxRestarts; attempt++) { + stats.attempts++; + const rng = mulberry32(Math.floor(masterRng() * 4294967296)); + trailIdx = []; + trailVal = []; + for (let c = 0; c < N; c++) noise[c] = rng() * 1e-6; + dirty.fill(1); + // Init domains: fixed cells are singletons, others get the solver mask. + for (let c = 0; c < N; c++) { + const ft = fixedAt[c]; + for (let w = 0; w < W; w++) dom[c * W + w] = ft >= 0 ? (ft >>> 5 === w ? 1 << (ft & 31) : 0) : solverMask[w]; + } + const allCells: number[] = []; + for (let c = 0; c < N; c++) allCells.push(c); + const bad = propagate(allCells); + if (bad >= 0) + return fail("fixed-conflict", "The painted hexes cannot be completed under these rules (or every terrain has weight 0)", cellXY(bad)); + trailIdx = []; + trailVal = []; + + // Decision stack: [trailMark, cell, terrain] + const stack: [number, number, number][] = []; + let backtracksThisAttempt = 0; + let gaveUp = false; + + for (;;) { + // Pick the undecided cell with minimum weighted entropy (+ tiny noise). + let best = -1, bestH = Infinity; + for (let c = 0; c < N; c++) { + if (dirty[c]) { + dirty[c] = 0; + const k = count(c); + cntCache[c] = k; + if (k > 1) { + let sw = 0, swl = 0; + for (let w = 0; w < W; w++) { + let bits = dom[c * W + w]; + while (bits) { + const low = bits & -bits; + const t = (w << 5) + (31 - Math.clz32(low)); + const wt = weight[t] > 0 ? weight[t] : 1e-9; + sw += wt; swl += wt * Math.log(wt); + bits ^= low; + } + } + hCache[c] = Math.log(sw) - swl / sw + noise[c]; + } + } + if (cntCache[c] <= 1) continue; + if (hCache[c] < bestH) { bestH = hCache[c]; best = c; } + } + if (best < 0) break; // all collapsed + + // Weighted pick among the remaining terrains. + let total = 0; + for (let t = 0; t < T; t++) if ((dom[best * W + (t >>> 5)] >>> (t & 31)) & 1) total += weight[t]; + let r = rng() * total, choice = -1; + for (let t = 0; t < T; t++) { + if (!((dom[best * W + (t >>> 5)] >>> (t & 31)) & 1)) continue; + choice = t; + r -= weight[t]; + if (r < 0) break; + } + + stats.decisions++; + stack.push([trailIdx.length, best, choice]); + for (let w = 0; w < W; w++) setWord(best * W + w, choice >>> 5 === w ? 1 << (choice & 31) : 0); + let contradiction = propagate([best]) >= 0; + + // Backtrack: undo the last decision and ban that choice; repeat while + // the ban itself causes a contradiction. + while (contradiction) { + const top = stack.pop(); + if (!top || backtracksThisAttempt >= maxBacktracks) { gaveUp = true; break; } + backtracksThisAttempt++; + stats.backtracks++; + const [mark, cell, t] = top; + undoTo(mark); + const wi = cell * W + (t >>> 5); + setWord(wi, dom[wi] & ~(1 << (t & 31))); + contradiction = count(cell) === 0 || propagate([cell]) >= 0; + } + if (gaveUp) break; + } + + if (!gaveUp) { + const cells = new Map(); + for (let c = 0; c < N; c++) { + const { x, y } = cellXY(c); + for (let t = 0; t < T; t++) { + if ((dom[c * W + (t >>> 5)] >>> (t & 31)) & 1) { cells.set(cellKey(x, y), terrains[t]); break; } + } + } + stats.ms = Date.now() - t0; + return { ok: true, cells, stats }; + } + } + + return fail( + "contradiction", + `No valid map found after ${stats.attempts} attempt(s) and ${stats.backtracks} backtrack(s); the rules may be too strict for this grid`, + ); +} diff --git a/tests/wfc.test.ts b/tests/wfc.test.ts new file mode 100644 index 00000000..095ace24 --- /dev/null +++ b/tests/wfc.test.ts @@ -0,0 +1,217 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + solveHexWfc, + findViolation, + learnRulesFromSample, + mulberry32, + type WfcInput, + type AdjacencyRules, +} from "../src/worldgen/wfc"; + +// A user-style palette with deliberately non-default names: the solver must +// not care what the terrains are called. +const TERRAINS = ["Deep Sea", "Shallows", "Grass", "Woods", "Hills", "Peaks", "Dunes"]; + +// "Deny list" deck — everything may touch except these pairs. +const RULES: AdjacencyRules = { + default: "allow", + pairs: [ + ["Deep Sea", "Grass"], ["Deep Sea", "Woods"], ["Deep Sea", "Hills"], + ["Deep Sea", "Peaks"], ["Deep Sea", "Dunes"], + ["Shallows", "Peaks"], ["Shallows", "Hills"], + ["Peaks", "Grass"], ["Peaks", "Dunes"], + ["Dunes", "Woods"], + ], +}; + +const WEIGHTS = { "Deep Sea": 4, Shallows: 2, Grass: 4, Woods: 3, Hills: 2, Peaks: 1, Dunes: 1 }; + +function base(overrides: Partial = {}): WfcInput { + return { + cols: 20, rows: 15, orientation: "flat", + terrains: TERRAINS, rules: RULES, weights: WEIGHTS, seed: 1234, + ...overrides, + }; +} + +describe("solveHexWfc — adjacency", () => { + for (const orientation of ["flat", "pointy"] as const) { + for (const stagger of ["odd", "even"] as const) { + it(`respects every rule (${orientation}/${stagger})`, () => { + const res = solveHexWfc(base({ orientation, stagger })); + expect(res.ok).toBe(true); + if (!res.ok) return; + expect(res.cells.size).toBe(20 * 15); + expect(findViolation(res.cells, { orientation, stagger, terrains: TERRAINS, rules: RULES })).toBeNull(); + }); + } + } + + it("honours an allow-list ('deny' default) deck", () => { + // Banded deck: each terrain may only touch itself and the next band. + const bands = ["A", "B", "C", "D"]; + const rules: AdjacencyRules = { + default: "deny", + pairs: [["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"], ["A", "B"], ["B", "C"], ["C", "D"]], + }; + const res = solveHexWfc({ cols: 25, rows: 25, orientation: "pointy", terrains: bands, rules, seed: 7 }); + expect(res.ok).toBe(true); + if (!res.ok) return; + expect(findViolation(res.cells, { orientation: "pointy", terrains: bands, rules })).toBeNull(); + }); + + it("uses absolute coords (gridOffset) for stagger parity", () => { + const offset = { x: -3, y: 5 }; + const res = solveHexWfc(base({ offset })); + expect(res.ok).toBe(true); + if (!res.ok) return; + expect(res.cells.has("-3_5")).toBe(true); + expect(res.cells.has("16_19")).toBe(true); + expect(res.cells.has("0_0")).toBe(false); + expect(findViolation(res.cells, { orientation: "flat", terrains: TERRAINS, rules: RULES })).toBeNull(); + }); + + it("treats an empty deck as 'everything allowed'", () => { + const res = solveHexWfc(base({ rules: { default: "allow", pairs: [] } })); + expect(res.ok).toBe(true); + }); + + it("never picks a weight-0 terrain for unpainted hexes", () => { + const res = solveHexWfc(base({ weights: { ...WEIGHTS, Dunes: 0 } })); + expect(res.ok).toBe(true); + if (!res.ok) return; + expect([...res.cells.values()]).not.toContain("Dunes"); + }); +}); + +describe("solveHexWfc — fixed cells", () => { + it("preserves pre-painted hexes and fills around them consistently", () => { + const fixed = { "3_3": "Deep Sea", "4_3": "Deep Sea", "10_7": "Peaks", "15_2": "Dunes", "0_0": "Woods" }; + const res = solveHexWfc(base({ fixed })); + expect(res.ok).toBe(true); + if (!res.ok) return; + for (const [k, t] of Object.entries(fixed)) expect(res.cells.get(k)).toBe(t); + expect(findViolation(res.cells, { orientation: "flat", terrains: TERRAINS, rules: RULES })).toBeNull(); + }); + + it("keeps fixed weight-0 terrains", () => { + const res = solveHexWfc(base({ weights: { ...WEIGHTS, Peaks: 0 }, fixed: { "5_5": "Peaks" } })); + expect(res.ok).toBe(true); + if (!res.ok) return; + expect(res.cells.get("5_5")).toBe("Peaks"); + }); + + it("ignores fixed hexes outside the grid", () => { + const res = solveHexWfc(base({ fixed: { "999_999": "Peaks" } })); + expect(res.ok).toBe(true); + }); + + it("reports adjacent painted hexes that break the rules as fixed-conflict", () => { + // (2,2) and (2,3) are vertical neighbours in any orientation/stagger. + const res = solveHexWfc(base({ fixed: { "2_2": "Deep Sea", "2_3": "Peaks" } })); + expect(res.ok).toBe(false); + if (res.ok) return; + expect(res.reason).toBe("fixed-conflict"); + expect(res.at).toBeDefined(); + }); + + it("reports unknown terrain names in fixed hexes as invalid-input", () => { + const res = solveHexWfc(base({ fixed: { "1_1": "Lava" } })); + expect(res.ok).toBe(false); + if (res.ok) return; + expect(res.reason).toBe("invalid-input"); + expect(res.message).toContain("Lava"); + }); +}); + +describe("solveHexWfc — determinism", () => { + it("same seed ⇒ identical map", () => { + const a = solveHexWfc(base({ seed: 42 })); + const b = solveHexWfc(base({ seed: 42 })); + expect(a.ok && b.ok).toBe(true); + if (!a.ok || !b.ok) return; + expect([...a.cells.entries()]).toEqual([...b.cells.entries()]); + }); + + it("different seeds ⇒ different maps", () => { + const a = solveHexWfc(base({ seed: 1 })); + const b = solveHexWfc(base({ seed: 2 })); + expect(a.ok && b.ok).toBe(true); + if (!a.ok || !b.ok) return; + expect([...a.cells.entries()]).not.toEqual([...b.cells.entries()]); + }); + + it("mulberry32 is deterministic and in [0,1)", () => { + const r1 = mulberry32(99), r2 = mulberry32(99); + for (let i = 0; i < 100; i++) { + const v = r1(); + expect(v).toBe(r2()); + expect(v >= 0 && v < 1).toBe(true); + } + }); +}); + +describe("solveHexWfc — contradictions", () => { + it("reports an unsatisfiable deck cleanly instead of throwing or looping", () => { + // Two terrains that may only touch each other: a 2-colouring, impossible + // on a hex grid because neighbouring hexes form triangles. + const res = solveHexWfc({ + cols: 6, rows: 6, orientation: "flat", + terrains: ["X", "Y"], rules: { default: "deny", pairs: [["X", "Y"]] }, + seed: 3, maxBacktracks: 50, maxRestarts: 2, + }); + expect(res.ok).toBe(false); + if (res.ok) return; + expect(["contradiction", "fixed-conflict"]).toContain(res.reason); + expect(res.message.length).toBeGreaterThan(0); + }); + + it("reports contradiction (not fixed-conflict) when only search fails", () => { + // Initial propagation can't see the triangle problem (every cell still + // has X and Y), so this exercises backtracking + restarts to exhaustion. + const res = solveHexWfc({ + cols: 6, rows: 6, orientation: "pointy", + terrains: ["X", "Y"], rules: { default: "deny", pairs: [["X", "Y"]] }, + seed: 5, maxBacktracks: 20, maxRestarts: 1, + }); + expect(res.ok).toBe(false); + if (res.ok) return; + expect(res.reason).toBe("contradiction"); + expect(res.stats.attempts).toBe(2); + }); + + it("rejects empty input", () => { + expect(solveHexWfc(base({ terrains: [] })).ok).toBe(false); + expect(solveHexWfc(base({ cols: 0 })).ok).toBe(false); + }); +}); + +describe("learnRulesFromSample", () => { + it("derives a deck that the sample itself satisfies, and regenerates from it", () => { + const sample = solveHexWfc(base({ cols: 12, rows: 12, seed: 11 })); + expect(sample.ok).toBe(true); + if (!sample.ok) return; + const { rules, weights } = learnRulesFromSample(sample.cells, "flat"); + expect(findViolation(sample.cells, { orientation: "flat", terrains: TERRAINS, rules })).toBeNull(); + const regen = solveHexWfc(base({ rules, weights, seed: 12 })); + expect(regen.ok).toBe(true); + if (!regen.ok) return; + expect(findViolation(regen.cells, { orientation: "flat", terrains: TERRAINS, rules })).toBeNull(); + }); +}); + +describe("solveHexWfc — performance", () => { + it("solves a 60×60 map (3600 hexes) quickly", () => { + const t0 = Date.now(); + const res = solveHexWfc(base({ cols: 60, rows: 60, seed: 2026 })); + const ms = Date.now() - t0; + expect(res.ok).toBe(true); + if (!res.ok) return; + expect(res.cells.size).toBe(3600); + expect(findViolation(res.cells, { orientation: "flat", terrains: TERRAINS, rules: RULES })).toBeNull(); + console.log(`[wfc] 60x60: ${ms} ms, decisions=${res.stats.decisions}, backtracks=${res.stats.backtracks}, attempts=${res.stats.attempts}`); + // Generous bound so CI noise doesn't flake; real number is logged above. + expect(ms).toBeLessThan(5000); + }); +}); From d916be1b82a2c8af01d9168cdd3a7014423d0523 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 15:12:20 -0400 Subject: [PATCH 002/558] feat(worldgen): hex-wfc library + learn generators from painted maps Adds packages/hex-wfc, a dependency-free wave function collapse library for offset hex grids (no Hexmaker/Obsidian imports, MIT, meant to be published separately): - learnModel: terrain + pair counts from a painted map; pairs that never touch in the example can never touch in output - solve: AC-3 propagation + backtracking/restarts, fixed cells, seeded; soft neighbour weighting (geometric mean), frequency feedback toward the example's terrain mix, and selection scatter so enclosed features (a lake inside its shore) can form - Markdown format (frontmatter + Terrains/Adjacency tables) for hand edits Hexmaker integration: - Maps > Properties: "Generate solver from map" saves a generator to {world}/generators/.md (never overwrites) and opens it - Maps > New map: optional Generator picker (default Blank), filtered to generators whose terrains are all in the chosen palette; solved before any note is created so a failure leaves nothing behind - New hex notes are written with terrain already set; encounter links synced when a terrain encounters table exists Replaces the src/worldgen/wfc.ts research prototype. Co-Authored-By: Claude Opus 5.5 (1M context) --- dev/wfc-ascii.mts | 18 + packages/hex-wfc/README.md | 71 +++ packages/hex-wfc/package.json | 11 + packages/hex-wfc/src/format.ts | 190 ++++++++ packages/hex-wfc/src/grid.ts | 41 ++ packages/hex-wfc/src/index.ts | 19 + packages/hex-wfc/src/learn.ts | 58 +++ packages/hex-wfc/src/model.ts | 85 ++++ packages/hex-wfc/src/rng.ts | 16 + packages/hex-wfc/src/solve.ts | 427 +++++++++++++++++ src/HexmakerPlugin.ts | 31 +- src/frontmatter.ts | 16 + src/hex-map/MapModal.ts | 101 ++++- src/worldgen/generators.ts | 157 +++++++ src/worldgen/wfc.ts | 429 ------------------ tests/frontmatter.test.ts | 756 ++++++++++++++++--------------- tests/hexWfc.test.ts | 246 ++++++++++ tests/wfc.test.ts | 217 --------- tests/worldgenGenerators.test.ts | 142 ++++++ 19 files changed, 2015 insertions(+), 1016 deletions(-) create mode 100644 dev/wfc-ascii.mts create mode 100644 packages/hex-wfc/README.md create mode 100644 packages/hex-wfc/package.json create mode 100644 packages/hex-wfc/src/format.ts create mode 100644 packages/hex-wfc/src/grid.ts create mode 100644 packages/hex-wfc/src/index.ts create mode 100644 packages/hex-wfc/src/learn.ts create mode 100644 packages/hex-wfc/src/model.ts create mode 100644 packages/hex-wfc/src/rng.ts create mode 100644 packages/hex-wfc/src/solve.ts create mode 100644 src/worldgen/generators.ts delete mode 100644 src/worldgen/wfc.ts create mode 100644 tests/hexWfc.test.ts delete mode 100644 tests/wfc.test.ts create mode 100644 tests/worldgenGenerators.test.ts diff --git a/dev/wfc-ascii.mts b/dev/wfc-ascii.mts new file mode 100644 index 00000000..c147232b --- /dev/null +++ b/dev/wfc-ascii.mts @@ -0,0 +1,18 @@ +// Prints a generated map as ASCII for eyeballing hex-wfc output. +// Usage (from WSL): npx tsx dev/wfc-ascii.mts [seed] [flat|pointy] +import { learnModel, solve, cellKey } from "../packages/hex-wfc/src"; +const seed = Number(process.argv[2] ?? 5); +const o = (process.argv[3] ?? "flat") as "flat" | "pointy"; +const ex = new Map(); +for (let x = 0; x < 20; x++) for (let y = 0; y < 16; y++) { + const dx = x - 6, dy = y - 7; let t = "G"; + if (dx*dx+dy*dy < 12) t = "~"; else if (dx*dx+dy*dy < 22) t = "s"; else if (x >= 14) t = "F"; + ex.set(cellKey(x, y), t); +} +const m = learnModel(ex, { name: "example", orientation: o }); +const r = solve(m, { cols: 50, rows: 18, orientation: o, seed }); +if (!r.ok) { console.log(r.message); process.exit(); } +const counts: Record = {}; +for (const t of r.cells.values()) counts[t] = (counts[t] ?? 0) + 1; +console.log("seed", seed, o, JSON.stringify(counts), JSON.stringify(r.stats)); +for (let y = 0; y < 18; y++) { let s = ""; for (let x = 0; x < 50; x++) s += r.cells.get(cellKey(x, y)); console.log(s); } diff --git a/packages/hex-wfc/README.md b/packages/hex-wfc/README.md new file mode 100644 index 00000000..644ef6c3 --- /dev/null +++ b/packages/hex-wfc/README.md @@ -0,0 +1,71 @@ +# hex-wfc + +Wave function collapse for hex maps, with no dependencies. Draw an example map, learn a generator from it, then generate new maps that follow the same rules. + +It works with any terrain names. Terrains are plain strings, so it doesn't matter whether they're called "Deep Sea" or "lava". + +It lives inside the [Hexmaker](https://github.com/sbuffkin/hexmaker) Obsidian plugin for now, but it doesn't depend on Hexmaker or Obsidian. The plan is to publish it as its own package. It has no build step yet: import the TypeScript sources directly, or bundle them. + +## How it works + +- **Learning**: `learnModel` counts how often each terrain appears and how often each pair of terrains touches. If two terrains never touch in the example, they can never touch in generated maps. That includes a terrain next to itself. +- **Solving**: `solve` runs WFC with propagation, backtracking and restarts. Pairs with weight 0 are hard rules. Pair weights are also soft rules: each choice is scored from the neighbours that are already decided, so a lake in the example grows as a lake rather than scattering. `neighbourInfluence` sets how strong that effect is. +- **Fixed hexes**: pass hexes that are already painted as `fixed`. They are never changed, and the rest of the map is filled around them. +- **Deterministic**: the same model, options and seed always give the same map. + +## Usage + +```ts +import { learnModel, solve, modelToMarkdown, parseModelMarkdown } from "hex-wfc"; + +const painted = new Map([["0_0", "Water"], ["1_0", "Water"], ["2_0", "Grass"] /* ... */]); +const model = learnModel(painted, { name: "lakes", orientation: "flat" }); + +const result = solve(model, { cols: 30, rows: 20, orientation: "flat", seed: 42 }); +if (result.ok) result.cells; // Map<"x_y", terrain> +else console.warn(result.reason, result.message); + +const text = modelToMarkdown(model); // save it +const { model: again } = parseModelMarkdown(text); // load it +``` + +Coordinates are offset coordinates keyed as `"x_y"`. Flat-top grids stagger columns and pointy-top grids stagger rows. `stagger: "odd" | "even"` chooses which columns or rows are shifted. + +## File format + +Models save as Markdown with frontmatter and two tables, so you can edit them by hand: + +```markdown +--- +hex-wfc: 1 +name: lakes +palette: Default +--- +## Terrains + +| Terrain | Weight | +| --- | ---: | +| Grass | 120 | +| Water | 40 | + +## Adjacency + +| Terrain | Next to | Weight | +| --- | --- | ---: | +| Grass | Grass | 300 | +| Grass | Water | 25 | +| Water | Water | 90 | +``` + +- A pair that isn't listed, or has weight 0, can never touch. +- Pairs work in both directions, so *A | B* also covers *B | A*. +- Extra frontmatter keys are kept in `model.meta`. + +## Limits + +- This is the simple tiled model: only which terrain sits next to which. It learns blobs (lakes, forests, coastlines) well, but not long thin features. A river drawn as hex terrain comes back as streaks and clumps, not as a connected line. +- The solver scans every cell on each step, so the cost grows with roughly the square of the map size. 60×60 takes well under a second. + +## License + +MIT diff --git a/packages/hex-wfc/package.json b/packages/hex-wfc/package.json new file mode 100644 index 00000000..bdacab13 --- /dev/null +++ b/packages/hex-wfc/package.json @@ -0,0 +1,11 @@ +{ + "name": "hex-wfc", + "version": "0.1.0", + "description": "Wave function collapse for offset-coordinate hex maps: learn adjacency rules from a painted example map, then generate new maps that follow them.", + "type": "module", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "MIT", + "keywords": ["wave-function-collapse", "wfc", "hex", "hexmap", "procedural-generation"], + "sideEffects": false +} diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts new file mode 100644 index 00000000..52260042 --- /dev/null +++ b/packages/hex-wfc/src/format.ts @@ -0,0 +1,190 @@ +/** + * Plain-text file format for a model: Markdown with YAML frontmatter and two + * tables. It's meant to be read and edited by hand (and renders nicely in + * Obsidian or on GitHub). + * + * --- + * hex-wfc: 1 + * name: lakes + * palette: Default <- any other keys are kept as `meta` + * --- + * ## Terrains + * | Terrain | Weight | + * ... + * ## Adjacency + * | Terrain | Next to | Weight | + * ... + */ + +import type { HexWfcModel } from "./model"; + +export const FORMAT_VERSION = 1; +const MARKER = "hex-wfc"; + +function yamlValue(v: string): string { + return /^[A-Za-z0-9_][A-Za-z0-9 _./()-]*$/.test(v) && !v.endsWith(" ") ? v : JSON.stringify(v); +} + +function parseYamlValue(raw: string): string { + const v = raw.trim(); + if (v.startsWith('"')) { + try { + return String(JSON.parse(v)); + } catch { + return v.slice(1, -1); + } + } + if (v.startsWith("'") && v.endsWith("'")) return v.slice(1, -1).replace(/''/g, "'"); + return v; +} + +const cell = (s: string) => s.replace(/\\/g, "\\\\").replace(/\|/g, "\\|"); +const num = (n: number) => String(Math.round(n * 1000) / 1000); + +export function modelToMarkdown(model: HexWfcModel): string { + const fm = [`${MARKER}: ${FORMAT_VERSION}`, `name: ${yamlValue(model.name)}`]; + for (const [k, v] of Object.entries(model.meta)) { + if (k === MARKER || k === "name") continue; + fm.push(`${k}: ${yamlValue(v)}`); + } + const lines = [ + "---", + ...fm, + "---", + "", + `# ${model.name}`, + "", + "A wave function collapse generator. You can edit both tables by hand.", + "", + "- **Terrains**: *Weight* is how common the terrain is. 0 means it is never placed.", + "- **Adjacency**: pairs that may touch, and how often (higher is more likely).", + " A pair that isn't listed can never touch, including a terrain next to itself.", + " Order doesn't matter, so *A | B* also covers *B | A*.", + "", + "## Terrains", + "", + "| Terrain | Weight |", + "| --- | ---: |", + ...model.terrains.map((t) => `| ${cell(t.name)} | ${num(t.weight)} |`), + "", + "## Adjacency", + "", + "| Terrain | Next to | Weight |", + "| --- | --- | ---: |", + ...model.adjacency.map((e) => `| ${cell(e.a)} | ${cell(e.b)} | ${num(e.weight)} |`), + "", + ]; + return lines.join("\n"); +} + +/** Split a Markdown table row into trimmed cells, honouring `\|` escapes. */ +function splitRow(line: string): string[] | null { + const s = line.trim(); + if (!s.startsWith("|")) return null; + const out: string[] = []; + let cur = ""; + for (let i = 1; i < s.length; i++) { + const ch = s[i]; + if (ch === "\\" && i + 1 < s.length) { + cur += s[++i]; + } else if (ch === "|") { + out.push(cur.trim()); + cur = ""; + } else { + cur += ch; + } + } + if (cur.trim()) out.push(cur.trim()); + return out; +} + +export interface ParseResult { + model: HexWfcModel; + /** Non-fatal issues, e.g. a row with a bad weight that was skipped. */ + warnings: string[]; +} + +export function isModelMarkdown(text: string): boolean { + return new RegExp(`^---\\r?\\n(?:.*\\r?\\n)*?${MARKER}\\s*:`).test(text); +} + +/** + * Parse a model file. Throws if the text isn't a hex-wfc file at all; bad + * individual rows become warnings instead. + */ +export function parseModelMarkdown(text: string, fallbackName = "Untitled"): ParseResult { + const lines = text.split(/\r?\n/); + const warnings: string[] = []; + const meta: Record = {}; + let name = ""; + let version: number | null = null; + + let i = 0; + if (lines[0]?.trim() === "---") { + for (i = 1; i < lines.length && lines[i].trim() !== "---"; i++) { + const m = /^([^:#][^:]*):(.*)$/.exec(lines[i]); + if (!m) continue; + const key = m[1].trim(); + const value = parseYamlValue(m[2]); + if (key === MARKER) version = Number(value); + else if (key === "name") name = value; + else meta[key] = value; + } + i++; + } + if (version === null) throw new Error(`Not a ${MARKER} file (missing "${MARKER}:" in the frontmatter)`); + if (version > FORMAT_VERSION) + warnings.push(`File is ${MARKER} version ${version}; this reader understands version ${FORMAT_VERSION}`); + + let section: "terrains" | "adjacency" | null = null; + let headerSeen = false; + const model: HexWfcModel = { name: "", terrains: [], adjacency: [], meta }; + const weightOf = (raw: string | undefined, where: string): number | null => { + if (raw === undefined || raw === "") return 1; + const n = Number(raw); + if (!Number.isFinite(n) || n < 0) { + warnings.push(`${where}: weight "${raw}" isn't a number ≥ 0, row skipped`); + return null; + } + return n; + }; + + for (; i < lines.length; i++) { + const line = lines[i]; + const h = /^#{1,6}\s+(.*)$/.exec(line.trim()); + if (h) { + const title = h[1].trim().toLowerCase(); + if (!name && line.trim().startsWith("# ")) name = h[1].trim(); + section = title === "terrains" ? "terrains" : title === "adjacency" ? "adjacency" : null; + headerSeen = false; + continue; + } + if (!section) continue; + const cells = splitRow(line); + if (!cells) { + if (line.trim()) headerSeen = false; // prose between tables + continue; + } + if (cells.every((c) => /^:?-+:?$/.test(c))) continue; // separator + if (!headerSeen) { + headerSeen = true; // first row of each table is the header + continue; + } + const where = `${section === "terrains" ? "Terrains" : "Adjacency"} row "${cells.join(" | ")}"`; + if (section === "terrains") { + if (!cells[0]) continue; + const w = weightOf(cells[1], where); + if (w !== null) model.terrains.push({ name: cells[0], weight: w }); + } else { + if (!cells[0] || !cells[1]) { + if (cells.some(Boolean)) warnings.push(`${where}: needs two terrains, row skipped`); + continue; + } + const w = weightOf(cells[2], where); + if (w !== null) model.adjacency.push({ a: cells[0], b: cells[1], weight: w }); + } + } + + model.name = name || fallbackName; + return { model, warnings }; +} diff --git a/packages/hex-wfc/src/grid.ts b/packages/hex-wfc/src/grid.ts new file mode 100644 index 00000000..86b4e299 --- /dev/null +++ b/packages/hex-wfc/src/grid.ts @@ -0,0 +1,41 @@ +/** + * Offset-coordinate hex grid helpers. + * + * Flat-top grids stagger columns (odd-q / even-q); pointy-top grids stagger + * rows (odd-r / even-r). "odd" means odd columns/rows are pushed down/right. + */ + +export type Orientation = "flat" | "pointy"; +export type Stagger = "odd" | "even"; + +export const cellKey = (x: number, y: number): string => `${x}_${y}`; + +/** Parse an "x_y" key. Returns null for anything that isn't two integers. */ +export function parseCellKey(key: string): [number, number] | null { + const m = /^(-?\d+)_(-?\d+)$/.exec(key); + return m ? [Number(m[1]), Number(m[2])] : null; +} + +/** The six neighbours of (x, y), in a fixed order. */ +export function hexNeighbors( + x: number, + y: number, + orientation: Orientation, + stagger: Stagger = "odd", +): [number, number][] { + const isShifted = (n: number) => (stagger === "odd" ? n % 2 !== 0 : n % 2 === 0); + + if (orientation === "flat") { + return !isShifted(x) + ? [[x, y - 1], [x, y + 1], [x + 1, y - 1], [x + 1, y], [x - 1, y - 1], [x - 1, y]] + : [[x, y - 1], [x, y + 1], [x + 1, y], [x + 1, y + 1], [x - 1, y], [x - 1, y + 1]]; + } + return !isShifted(y) + ? [[x + 1, y], [x - 1, y], [x - 1, y - 1], [x, y - 1], [x - 1, y + 1], [x, y + 1]] + : [[x + 1, y], [x - 1, y], [x, y - 1], [x + 1, y - 1], [x, y + 1], [x + 1, y + 1]]; +} + +/** Accept either a Map or a plain object of "x_y" → terrain. */ +export function toCellMap(cells: Map | Record): Map { + return cells instanceof Map ? cells : new Map(Object.entries(cells)); +} diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts new file mode 100644 index 00000000..a68f31f1 --- /dev/null +++ b/packages/hex-wfc/src/index.ts @@ -0,0 +1,19 @@ +export { hexNeighbors, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; +export { + adjacencyLookup, + validateModel, + restrictModel, + type HexWfcModel, + type TerrainEntry, + type AdjacencyEntry, +} from "./model"; +export { learnModel, type LearnOptions } from "./learn"; +export { solve, findViolation, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; +export { + modelToMarkdown, + parseModelMarkdown, + isModelMarkdown, + FORMAT_VERSION, + type ParseResult, +} from "./format"; +export { mulberry32, randomSeed } from "./rng"; diff --git a/packages/hex-wfc/src/learn.ts b/packages/hex-wfc/src/learn.ts new file mode 100644 index 00000000..5910242b --- /dev/null +++ b/packages/hex-wfc/src/learn.ts @@ -0,0 +1,58 @@ +import { hexNeighbors, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; +import type { HexWfcModel } from "./model"; + +export interface LearnOptions { + name: string; + orientation: Orientation; + stagger?: Stagger; + meta?: Record; +} + +/** + * Build a model from a painted example map. + * + * - Terrain weight = how many hexes use it. + * - Adjacency weight = how many edges join the pair. Pairs that never touch + * in the example are left out, so they can never touch in generated maps. + * + * Cells that are missing (unpainted) are ignored, along with their edges. + */ +export function learnModel( + cells: Map | Record, + opts: LearnOptions, +): HexWfcModel { + const map = toCellMap(cells); + const stagger = opts.stagger ?? "odd"; + const terrainCount = new Map(); + // Each undirected edge is seen from both ends, so counts are halved below. + const edgeCount = new Map(); + + for (const [key, ta] of map) { + const xy = parseCellKey(key); + if (!xy || !ta) continue; + terrainCount.set(ta, (terrainCount.get(ta) ?? 0) + 1); + for (const [nx, ny] of hexNeighbors(xy[0], xy[1], opts.orientation, stagger)) { + const tb = map.get(cellKey(nx, ny)); + if (!tb) continue; + const [a, b] = ta <= tb ? [ta, tb] : [tb, ta]; + const k = `${a}\u0000${b}`; + const e = edgeCount.get(k); + if (e) e.n++; + else edgeCount.set(k, { a, b, n: 1 }); + } + } + + const terrains = [...terrainCount] + .map(([name, weight]) => ({ name, weight })) + .sort((p, q) => q.weight - p.weight || p.name.localeCompare(q.name)); + const order = new Map(terrains.map((t, i) => [t.name, i])); + const adjacency = [...edgeCount.values()] + .map(({ a, b, n }) => { + // List each row under the more common terrain first; reads better. + const [p, q] = order.get(a)! <= order.get(b)! ? [a, b] : [b, a]; + return { a: p, b: q, weight: n / 2 }; + }) + .sort((p, q) => order.get(p.a)! - order.get(q.a)! || q.weight - p.weight || p.b.localeCompare(q.b)); + + return { name: opts.name, terrains, adjacency, meta: { ...(opts.meta ?? {}) } }; +} diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts new file mode 100644 index 00000000..a8eb811e --- /dev/null +++ b/packages/hex-wfc/src/model.ts @@ -0,0 +1,85 @@ +/** + * The generator model ("solver"): which terrains exist, how common each is, + * and which pairs may sit next to each other. + * + * Terrains are opaque strings, so any palette works. Adjacency is undirected + * and the same in all six directions. A pair that is not listed (or is listed + * with weight 0) may never touch. That includes a terrain next to itself. + */ + +export interface TerrainEntry { + name: string; + /** Relative frequency. 0 = never placed by the solver (still valid in fixed cells). */ + weight: number; +} + +export interface AdjacencyEntry { + a: string; + b: string; + /** How often this pair touches. Higher = more likely. 0 = forbidden. */ + weight: number; +} + +export interface HexWfcModel { + name: string; + terrains: TerrainEntry[]; + adjacency: AdjacencyEntry[]; + /** Free-form string metadata (palette, source map, ...). Preserved by the file format. */ + meta: Record; +} + +const pairKey = (a: string, b: string) => (a < b ? `${a}\u0000${b}` : `${b}\u0000${a}`); + +/** + * Symmetric lookup of adjacency weights. Duplicate rows (in either order) are + * summed, so a hand-edited file that lists "A | B" and "B | A" still works. + */ +export function adjacencyLookup(model: HexWfcModel): (a: string, b: string) => number { + const m = new Map(); + for (const { a, b, weight } of model.adjacency) { + if (!(weight > 0)) continue; + const k = pairKey(a, b); + m.set(k, (m.get(k) ?? 0) + weight); + } + return (a, b) => m.get(pairKey(a, b)) ?? 0; +} + +/** Problems that make a model unusable or surprising. Empty = fine. */ +export function validateModel(model: HexWfcModel): string[] { + const problems: string[] = []; + const names = new Set(); + for (const t of model.terrains) { + if (!t.name) problems.push("A terrain has an empty name"); + else if (names.has(t.name)) problems.push(`Terrain "${t.name}" is listed twice`); + names.add(t.name); + if (!Number.isFinite(t.weight) || t.weight < 0) + problems.push(`Terrain "${t.name}" has an invalid weight`); + } + if (model.terrains.length === 0) problems.push("No terrains listed"); + for (const { a, b, weight } of model.adjacency) { + for (const n of [a, b]) + if (!names.has(n)) problems.push(`Adjacency row "${a} | ${b}" uses unknown terrain "${n}"`); + if (!Number.isFinite(weight) || weight < 0) + problems.push(`Adjacency row "${a} | ${b}" has an invalid weight`); + } + const adj = adjacencyLookup(model); + for (const t of model.terrains) { + if (t.weight > 0 && !model.terrains.some((u) => adj(t.name, u.name) > 0)) + problems.push(`Terrain "${t.name}" is not allowed next to anything, so it can only appear alone`); + } + return problems; +} + +/** + * Drop terrains that aren't in `allowed` (and their adjacency rows). Use it to + * fit a model to a palette that lacks some of its terrains. + */ +export function restrictModel(model: HexWfcModel, allowed: Iterable): HexWfcModel { + const keep = new Set(allowed); + return { + ...model, + terrains: model.terrains.filter((t) => keep.has(t.name)), + adjacency: model.adjacency.filter((e) => keep.has(e.a) && keep.has(e.b)), + meta: { ...model.meta }, + }; +} diff --git a/packages/hex-wfc/src/rng.ts b/packages/hex-wfc/src/rng.ts new file mode 100644 index 00000000..0c13702a --- /dev/null +++ b/packages/hex-wfc/src/rng.ts @@ -0,0 +1,16 @@ +/** mulberry32: tiny, fast seeded PRNG. Returns floats in [0, 1). */ +export function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** A random 32-bit seed (not reproducible; use for "roll a new map"). */ +export function randomSeed(): number { + return Math.floor(Math.random() * 4294967296) >>> 0; +} diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts new file mode 100644 index 00000000..71069826 --- /dev/null +++ b/packages/hex-wfc/src/solve.ts @@ -0,0 +1,427 @@ +/** + * Hex Wave Function Collapse (simple tiled model) with neighbour-weighted + * choices. + * + * Hard rules: a pair with adjacency weight 0 can never touch (enforced by + * arc-consistency propagation plus backtracking). + * + * Soft rules: when a hex is collapsed, each candidate terrain t is scored + * weight(t) × (geometric mean over decided neighbours u of adj(t,u) / Σ_v adj(t,v))^influence + * A model learned from a map with a lake therefore grows lake next to lake + * rather than scattering it. (A plain product over neighbours overcounts, + * because neighbours are correlated, and lets one terrain swallow the map.) + * The same scores drive the entropy used to pick the next hex. + * + * Two more terms keep the result looking like the example: + * - frequency feedback nudges each choice toward the model's terrain mix; + * - scatter adds randomness to the order hexes are decided in, so + * features start in many places instead of one frontier swallowing all. + * + * Deterministic for a given model, options and seed. + */ + +import { hexNeighbors, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; +import { adjacencyLookup, type HexWfcModel } from "./model"; +import { mulberry32 } from "./rng"; + +export interface SolveOptions { + cols: number; + rows: number; + /** Coordinate of the top-left hex. Stagger parity uses absolute coords, so this matters. */ + offset?: { x: number; y: number }; + orientation: Orientation; + stagger?: Stagger; + /** Hexes that must keep their terrain, keyed "x_y" in absolute coords. */ + fixed?: Map | Record; + seed: number; + /** + * How strongly decided neighbours steer each choice (clumping). 0 uses only + * the hard rules and terrain weights, which gives speckled noise. Default 3. + */ + neighbourInfluence?: number; + /** + * How hard the solver steers the overall terrain mix toward the model's + * terrain weights. Without it, the most common terrain tends to swallow the + * map, because every new hex copies its neighbours. 0 turns it off. + * Default 1. + */ + frequencyFeedback?: number; + /** + * Randomness in which hex is decided next. Low values grow one region + * outward from a single start; higher values start features in many + * places, which lets enclosed features (a lake inside its shore) form. + * Default 3. + */ + scatter?: number; + /** Backtracks allowed per attempt before restarting. Default 2000. */ + maxBacktracks?: number; + /** Fresh attempts after the first. Default 5. */ + maxRestarts?: number; +} + +export interface SolveStats { + attempts: number; + backtracks: number; + decisions: number; + ms: number; +} + +export type SolveResult = + | { ok: true; cells: Map; stats: SolveStats } + | { + ok: false; + reason: "invalid-input" | "fixed-conflict" | "contradiction"; + message: string; + at?: { x: number; y: number }; + stats: SolveStats; + }; + +/** First pair of neighbouring cells the model forbids, or null. */ +export function findViolation( + model: HexWfcModel, + cells: Map | Record, + orientation: Orientation, + stagger: Stagger = "odd", +): { a: [number, number]; b: [number, number]; ta: string; tb: string } | null { + const adj = adjacencyLookup(model); + const map = toCellMap(cells); + for (const [key, ta] of map) { + const xy = parseCellKey(key); + if (!xy) continue; + for (const [nx, ny] of hexNeighbors(xy[0], xy[1], orientation, stagger)) { + const tb = map.get(cellKey(nx, ny)); + if (tb !== undefined && adj(ta, tb) <= 0) return { a: xy, b: [nx, ny], ta, tb }; + } + } + return null; +} + +/** Feedback never boosts or damps a terrain by more than this factor per choice. */ +const FEEDBACK_CAP = 8; + +export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { + const t0 = Date.now(); + const stats: SolveStats = { attempts: 0, backtracks: 0, decisions: 0, ms: 0 }; + const fail = ( + reason: "invalid-input" | "fixed-conflict" | "contradiction", + message: string, + at?: { x: number; y: number }, + ): SolveResult => { + stats.ms = Date.now() - t0; + return { ok: false, reason, message, at, stats }; + }; + + const { cols, rows, orientation } = opts; + const stagger = opts.stagger ?? "odd"; + const ox = opts.offset?.x ?? 0; + const oy = opts.offset?.y ?? 0; + const influence = opts.neighbourInfluence ?? 3; + const feedback = opts.frequencyFeedback ?? 1; + const scatter = opts.scatter ?? 3; + const terrains = [...new Set(model.terrains.map((t) => t.name))]; + const T = terrains.length; + if (!(cols > 0 && rows > 0)) return fail("invalid-input", "Grid must be at least 1×1"); + if (T === 0) return fail("invalid-input", "The model has no terrains"); + const tIndex = new Map(terrains.map((t, i) => [t, i])); + + const N = cols * rows; + const W = (T + 31) >>> 5; // 32-bit words per domain bitset + const idx = (x: number, y: number) => (y - oy) * cols + (x - ox); + const inGrid = (x: number, y: number) => x >= ox && x < ox + cols && y >= oy && y < oy + rows; + const cellXY = (c: number) => ({ x: ox + (c % cols), y: oy + Math.floor(c / cols) }); + + // Neighbour table (−1 = off-grid), 6 per cell. + const nbr = new Int32Array(N * 6).fill(-1); + for (let c = 0; c < N; c++) { + const { x, y } = cellXY(c); + const ns = hexNeighbors(x, y, orientation, stagger); + for (let d = 0; d < 6; d++) if (inGrid(ns[d][0], ns[d][1])) nbr[c * 6 + d] = idx(ns[d][0], ns[d][1]); + } + + // Adjacency: hard compat bitsets + soft log-likelihoods. + const adj = adjacencyLookup(model); + const compat = new Uint32Array(T * W); + const logP = new Float64Array(T * T); + for (let a = 0; a < T; a++) { + let deg = 0; + for (let b = 0; b < T; b++) deg += adj(terrains[a], terrains[b]); + for (let b = 0; b < T; b++) { + const w = adj(terrains[a], terrains[b]); + if (w > 0) { + compat[a * W + (b >>> 5)] |= 1 << (b & 31); + logP[a * T + b] = influence * Math.log(w / deg); + } + } + } + + const logW = new Float64Array(T); + const share = new Float64Array(T); // target fraction of the map per terrain + const solverMask = new Uint32Array(W); // terrains the solver may place + let weightSum = 0; + for (const entry of model.terrains) { + const t = tIndex.get(entry.name)!; + if (Number.isFinite(entry.weight) && entry.weight > 0) { + logW[t] = Math.log(entry.weight); + share[t] = entry.weight; + weightSum += entry.weight; + solverMask[t >>> 5] |= 1 << (t & 31); + } + } + for (let t = 0; t < T; t++) share[t] /= weightSum || 1; + + // Fixed cells (only those inside the grid matter). + const fixedAt = new Int32Array(N).fill(-1); + const fixedCells: number[] = []; + for (const [key, terr] of toCellMap(opts.fixed ?? {})) { + const xy = parseCellKey(key); + if (!xy || !inGrid(xy[0], xy[1])) continue; + const ti = tIndex.get(terr); + if (ti === undefined) + return fail("invalid-input", `Hex ${key} is "${terr}", which the model doesn't know`, { x: xy[0], y: xy[1] }); + const c = idx(xy[0], xy[1]); + fixedAt[c] = ti; + fixedCells.push(c); + } + for (const c of fixedCells) { + const t = fixedAt[c]; + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n < 0 || fixedAt[n] < 0) continue; + const u = fixedAt[n]; + if (!((compat[t * W + (u >>> 5)] >>> (u & 31)) & 1)) { + const a = cellXY(c), b = cellXY(n); + return fail( + "fixed-conflict", + `Fixed hexes ${cellKey(a.x, a.y)} (${terrains[t]}) and ${cellKey(b.x, b.y)} (${terrains[u]}) may not touch`, + a, + ); + } + } + } + if (fixedCells.length < N && solverMask.every((v) => v === 0)) + return fail("invalid-input", "Every terrain has weight 0, so empty hexes cannot be filled"); + + const maxBacktracks = opts.maxBacktracks ?? 2000; + const maxRestarts = opts.maxRestarts ?? 5; + const masterRng = mulberry32(opts.seed); + + // ── Domain state with an undo trail ────────────────────────────────────── + const dom = new Uint32Array(N * W); + let trailIdx: number[] = []; + let trailVal: number[] = []; + const dirty = new Uint8Array(N).fill(1); + const markDirty = (c: number) => { + // A cell's scores depend on its decided neighbours, so they go stale too. + dirty[c] = 1; + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n >= 0) dirty[n] = 1; + } + }; + const setWord = (i: number, v: number) => { + if (dom[i] === v) return; + trailIdx.push(i); + trailVal.push(dom[i]); + dom[i] = v; + markDirty((i / W) | 0); + }; + const undoTo = (mark: number) => { + for (let k = trailIdx.length - 1; k >= mark; k--) { + dom[trailIdx[k]] = trailVal[k]; + markDirty((trailIdx[k] / W) | 0); + } + trailIdx.length = mark; + trailVal.length = mark; + }; + const has = (c: number, t: number) => ((dom[c * W + (t >>> 5)] >>> (t & 31)) & 1) === 1; + /** Terrain index if the cell is decided, −1 if open, −2 if empty. */ + const single = (c: number): number => { + let found = -2; + for (let w = 0; w < W; w++) { + const bits = dom[c * W + w]; + if (!bits) continue; + if (found !== -2 || (bits & (bits - 1)) !== 0) return -1; + found = (w << 5) + (31 - Math.clz32(bits)); + } + return found; + }; + + // ── Propagation (AC-3) ─────────────────────────────────────────────────── + const queue = new Int32Array(N); + const inQueue = new Uint8Array(N); + const support = new Uint32Array(W); + /** Returns the cell whose domain emptied, or −1. */ + const propagate = (seeds: number[]): number => { + let head = 0, tail = 0, size = 0; + for (const s of seeds) if (!inQueue[s]) { inQueue[s] = 1; queue[tail++ % N] = s; size++; } + while (size > 0) { + const c = queue[head++ % N]; + size--; + inQueue[c] = 0; + support.fill(0); + for (let w = 0; w < W; w++) { + let bits = dom[c * W + w]; + while (bits) { + const low = bits & -bits; + const t = (w << 5) + (31 - Math.clz32(low)); + for (let v = 0; v < W; v++) support[v] |= compat[t * W + v]; + bits ^= low; + } + } + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n < 0) continue; + let changed = false, empty = true; + for (let w = 0; w < W; w++) { + const i = n * W + w; + const nv = dom[i] & support[w]; + if (nv !== dom[i]) { setWord(i, nv); changed = true; } + if (nv) empty = false; + } + if (empty) { + while (size > 0) { inQueue[queue[head++ % N]] = 0; size--; } + return n; + } + if (changed && !inQueue[n]) { inQueue[n] = 1; queue[tail++ % N] = n; size++; } + } + } + return -1; + }; + + // ── Scoring ────────────────────────────────────────────────────────────── + const scores = new Float64Array(T); + /** Fill `scores` with relative probabilities for an open cell; returns their sum. */ + const score = (c: number): number => { + const decided: number[] = []; + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n >= 0) { + const u = single(n); + if (u >= 0) decided.push(u); + } + } + let max = -Infinity; + for (let t = 0; t < T; t++) { + if (!has(c, t)) { scores[t] = -Infinity; continue; } + let s = logW[t]; + if (decided.length) { + let e = 0; + for (const u of decided) e += logP[t * T + u]; + s += e / decided.length; + } + scores[t] = s; + if (s > max) max = s; + } + let sum = 0; + for (let t = 0; t < T; t++) { + scores[t] = scores[t] === -Infinity ? 0 : Math.exp(scores[t] - max); + sum += scores[t]; + } + return sum; + }; + const placed = new Int32Array(T); // decided hexes per terrain, refreshed each step + const entropy = new Float64Array(N); + const open = new Uint8Array(N); + const noise = new Float64Array(N); + + for (let attempt = 0; attempt <= maxRestarts; attempt++) { + stats.attempts++; + const rng = mulberry32(Math.floor(masterRng() * 4294967296)); + trailIdx = []; + trailVal = []; + for (let c = 0; c < N; c++) noise[c] = rng() * scatter; + for (let c = 0; c < N; c++) { + const ft = fixedAt[c]; + for (let w = 0; w < W; w++) dom[c * W + w] = ft >= 0 ? (ft >>> 5 === w ? 1 << (ft & 31) : 0) : solverMask[w]; + } + dirty.fill(1); + const all: number[] = []; + for (let c = 0; c < N; c++) all.push(c); + const bad = propagate(all); + if (bad >= 0) + return fail("fixed-conflict", "The fixed hexes can't be completed under these rules", cellXY(bad)); + trailIdx = []; + trailVal = []; + + const stack: [number, number, number][] = []; // [trailMark, cell, terrain] + let backtracks = 0; + let gaveUp = false; + + for (;;) { + let best = -1, bestH = Infinity, decidedCount = 0; + placed.fill(0); + for (let c = 0; c < N; c++) { + const s = single(c); + if (s >= 0) { placed[s]++; decidedCount++; } + if (dirty[c]) { + dirty[c] = 0; + open[c] = s === -1 ? 1 : 0; + if (open[c]) { + const sum = score(c); + let h = Math.log(sum); + for (let t = 0; t < T; t++) if (scores[t] > 0) h -= (scores[t] / sum) * Math.log(scores[t]); + entropy[c] = h + noise[c]; + } + } + if (open[c] && entropy[c] < bestH) { bestH = entropy[c]; best = c; } + } + if (best < 0) break; // everything decided + + // Frequency feedback is applied to the choice only, not to the entropy + // cache: it changes after every step, and rescoring every hex each + // step would make the solver quadratic in a much worse way. + let sum = score(best); + if (feedback > 0) { + sum = 0; + for (let t = 0; t < T; t++) { + if (scores[t] <= 0) continue; + const ratio = Math.min(FEEDBACK_CAP, Math.max(1 / FEEDBACK_CAP, (share[t] * decidedCount + 1) / (placed[t] + 1))); + scores[t] *= Math.pow(ratio, feedback); + sum += scores[t]; + } + } + let r = rng() * sum, choice = -1; + for (let t = 0; t < T; t++) { + if (scores[t] <= 0) continue; + choice = t; + r -= scores[t]; + if (r < 0) break; + } + + stats.decisions++; + stack.push([trailIdx.length, best, choice]); + for (let w = 0; w < W; w++) setWord(best * W + w, choice >>> 5 === w ? 1 << (choice & 31) : 0); + let contradiction = propagate([best]) >= 0; + + // Undo the last decision and ban that choice; repeat while the ban + // itself leads to a contradiction. + while (contradiction) { + const top = stack.pop(); + if (!top || backtracks >= maxBacktracks) { gaveUp = true; break; } + backtracks++; + stats.backtracks++; + const [mark, cell, t] = top; + undoTo(mark); + const wi = cell * W + (t >>> 5); + setWord(wi, dom[wi] & ~(1 << (t & 31))); + contradiction = single(cell) === -2 || propagate([cell]) >= 0; + } + if (gaveUp) break; + } + + if (!gaveUp) { + const cells = new Map(); + for (let c = 0; c < N; c++) { + const { x, y } = cellXY(c); + cells.set(cellKey(x, y), terrains[single(c)]); + } + stats.ms = Date.now() - t0; + return { ok: true, cells, stats }; + } + } + + return fail( + "contradiction", + `No valid map found after ${stats.attempts} attempt(s) and ${stats.backtracks} backtrack(s); the rules may be too strict for this grid`, + ); +} diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index d6f98c96..749e94f1 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -31,7 +31,7 @@ import type { TerrainPalette, } from "./types"; import DEFAULT_HEX_TEMPLATE from "./defaultHexTemplate.md"; -import { getTerrainFromFile, setTerrainInFile, setSubmapInFile } from "./frontmatter"; +import { getTerrainFromFile, setTerrainInFile, setSubmapInFile, withFrontmatterField } from "./frontmatter"; import { addLinkToSection, getLinksInSection, @@ -820,6 +820,13 @@ export default class HexmakerPlugin extends Plugin { * Removes any existing link that resolves to a file in the terrain subfolder, then adds * the correct link for the new terrain (if non-null and the table file exists). */ + /** Whether `{tablesFolder}/terrain/encounters/{terrain}.md` exists. */ + hasTerrainEncounterTable(terrain: string): boolean { + const tablesFolder = normalizeFolder(this.settings.tablesFolder); + const subfolder = tablesFolder ? `${tablesFolder}/terrain` : "terrain"; + return this.app.vault.getAbstractFileByPath(`${subfolder}/encounters/${terrain}.md`) instanceof TFile; + } + async syncHexEncounterTableLink( hexFilePath: string, terrain: string | null, @@ -1054,6 +1061,7 @@ export default class HexmakerPlugin extends Plugin { y: number, mapName: string, preloadedTemplate?: string, + terrain?: string, ): Promise { const path = this.hexPath(x, y, mapName); let content: string; @@ -1068,6 +1076,7 @@ export default class HexmakerPlugin extends Plugin { .replace(/\{\{x\}\}/g, String(x)) .replace(/\{\{y\}\}/g, String(y)) .replace(/\{\{title\}\}/g, `Hex ${x}, ${y}`); + if (terrain) content = withFrontmatterField(content, "terrain", terrain); const hexBase = normalizeFolder(this.settings.hexFolder); const mapFolder = hexBase ? `${hexBase}/${mapName}` : mapName; @@ -1143,6 +1152,8 @@ export default class HexmakerPlugin extends Plugin { initialY = 0, staggerOffset?: "odd" | "even", onProgress?: (done: number, total: number) => void, + /** Optional generated terrain per hex, keyed "x_y". */ + terrainAt?: Map, ): Promise<{ name: string } | { error: string }> { const name = slugify(rawName); if (!name) return { error: "Enter a map name." }; @@ -1170,8 +1181,12 @@ export default class HexmakerPlugin extends Plugin { const xs = Array.from({ length: cols }, (_, i) => i + initialX); const ys = Array.from({ length: rows }, (_, i) => i + initialY); const total = cols * rows; - const created = await this.generateHexNotes(name, xs, ys, (done) => - onProgress?.(done, total), + const created = await this.generateHexNotes( + name, + xs, + ys, + (done) => onProgress?.(done, total), + terrainAt, ); if (created > 0) new Notice( @@ -1186,6 +1201,7 @@ export default class HexmakerPlugin extends Plugin { xs: number[], ys: number[], onProgress?: (done: number) => void, + terrainAt?: Map, ): Promise { // Read template once — avoids N vault reads for the same file const template = await this.loadHexTemplate(); @@ -1201,8 +1217,13 @@ export default class HexmakerPlugin extends Plugin { pairs.slice(i, i + CHUNK).map(async ([x, y]) => { const path = this.hexPath(x, y, mapName); if (!this.app.vault.getAbstractFileByPath(path)) { - const result = await this.createHexNote(x, y, mapName, template); - if (result) created++; + const terrain = terrainAt?.get(`${x}_${y}`); + const result = await this.createHexNote(x, y, mapName, template, terrain); + if (result) { + created++; + if (terrain && this.hasTerrainEncounterTable(terrain)) + await this.syncHexEncounterTableLink(path, terrain); + } } done++; }), diff --git a/src/frontmatter.ts b/src/frontmatter.ts index ff58f363..17763270 100644 --- a/src/frontmatter.ts +++ b/src/frontmatter.ts @@ -51,6 +51,22 @@ export interface Frontmatter { "region-outline-width"?: string; } +/** + * Set a top-level string field in raw note text before the note is written, + * adding a frontmatter block if there isn't one. Used when bulk-creating hex + * notes so each note is written once rather than created then patched. + */ +export function withFrontmatterField(content: string, key: string, value: string): string { + const yaml = /^[\w][\w .()/-]*$/.test(value) && !value.endsWith(" ") ? value : JSON.stringify(value); + const line = `${key}: ${yaml}`; + const m = /^---\r?\n([\s\S]*?)\r?\n?---(\r?\n|$)/.exec(content); + if (!m) return `---\n${line}\n---\n${content}`; + const body = m[1]; + const keyRe = new RegExp(`^${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*:.*$`, "m"); + const newBody = keyRe.test(body) ? body.replace(keyRe, line) : body ? `${body}\n${line}` : line; + return `---\n${newBody}\n---${m[2]}${content.slice(m[0].length)}`; +} + export function getFrontMatter(app: App, path: string) { const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return null; diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index c917518e..8e0a2a2f 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -7,6 +7,14 @@ import { getSubmapFromFile, setSubmapInFile } from "../frontmatter"; import { exportMapAsPng } from "../export/mapPngRenderer"; import { exportMapAsPdf } from "../export/exporters/mapWithTable"; import { FileLinkSuggestModal } from "./FileLinkSuggestModal"; +import { + listGenerators, + generatorFitsPalette, + saveGeneratorFromMap, + generateMapTerrain, + type GeneratorFile, +} from "../worldgen/generators"; +import { randomSeed } from "../../packages/hex-wfc/src"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; @@ -437,6 +445,40 @@ export class MapModal extends HexmakerModal { this.view.enterBgCalibration(); }); } + + // ── Terrain generator ────────────────────────────────────────────────── + el.createEl("h4", { text: "Terrain generator" }); + el.createEl("p", { + text: "Learn a wave function collapse generator from the terrain painted on this map. Terrains that never touch here never touch in generated maps. Pick the generator when you create a new map.", + cls: "duckmage-map-origin-desc", + }); + const genRow = el.createDiv({ cls: "duckmage-region-row" }); + const genNameInput = genRow.createEl("input", { + type: "text", + value: this.view.activeMapName, + placeholder: "generator-name", + }); + const genBtn = genRow.createEl("button", { + text: "Generate solver from map", + cls: "mod-cta", + }); + genBtn.addEventListener("click", () => void this.learnGenerator(genNameInput.value, genBtn)); + } + + private async learnGenerator(rawName: string, btn: HTMLButtonElement): Promise { + btn.disabled = true; + const result = await saveGeneratorFromMap(this.plugin, this.view.activeMapName, rawName); + btn.disabled = false; + if ("error" in result) { + new Notice(result.error); + return; + } + const { model, file } = result; + new Notice( + `Saved generator "${model.name}": ${model.terrains.length} terrains, ${model.adjacency.length} neighbour pairs.`, + ); + this.close(); + await this.app.workspace.getLeaf("tab").openFile(file); } /** Compute the folder where dropped bg images should land for a given map. */ @@ -552,6 +594,34 @@ export class MapModal extends HexmakerModal { paletteSelect.createEl("option", { value: pal.name, text: pal.name }); } + // Generator (optional). Only generators whose terrains all exist in the + // chosen palette are offered. + el.createEl("label", { text: "Generator", cls: "duckmage-map-field-label" }); + el.createEl("p", { + text: "Fill the new map with generated terrain, or leave it blank. Make one from a painted map on the properties tab.", + cls: "duckmage-map-origin-desc", + }); + const generatorRow = el.createDiv({ cls: "duckmage-region-row" }); + const generatorSelect = generatorRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); + let generators: GeneratorFile[] = []; + const fillGenerators = () => { + const current = generatorSelect.value; + generatorSelect.empty(); + generatorSelect.createEl("option", { value: "", text: "Blank" }); + const names = this.plugin.getPaletteByName(paletteSelect.value)?.terrains.map((t) => t.name) ?? []; + for (const g of generators) { + if (generatorFitsPalette(g.model, names)) + generatorSelect.createEl("option", { value: g.file.path, text: g.model.name }); + } + generatorSelect.value = Array.from(generatorSelect.options).some((o) => o.value === current) ? current : ""; + }; + fillGenerators(); + paletteSelect.addEventListener("change", fillGenerators); + void listGenerators(this.plugin).then((list) => { + generators = list; + fillGenerators(); + }); + // Stagger offset el.createEl("label", { text: "Stagger offset", cls: "duckmage-map-field-label" }); const staggerRow = el.createDiv({ cls: "duckmage-region-row" }); @@ -624,7 +694,7 @@ export class MapModal extends HexmakerModal { const createRow = el.createDiv({ cls: "duckmage-region-row duckmage-map-create-row" }); const createBtn = createRow.createEl("button", { text: "Create", cls: "mod-cta" }); const allInputs: (HTMLInputElement | HTMLSelectElement)[] = [ - nameInput, colsInput, rowsInput, paletteSelect, originXInput, originYInput, + nameInput, colsInput, rowsInput, paletteSelect, generatorSelect, originXInput, originYInput, ]; const doCreate = () => void this.handleCreate( @@ -639,6 +709,7 @@ export class MapModal extends HexmakerModal { allInputs, pendingBgPath, pendingBgFile, + generators.find((g) => g.file.path === generatorSelect.value) ?? null, ); createBtn.addEventListener("click", doCreate); nameInput.addEventListener("keydown", (e: KeyboardEvent) => { @@ -745,21 +816,43 @@ export class MapModal extends HexmakerModal { inputs: (HTMLInputElement | HTMLSelectElement)[], bgImagePath: string | null, bgImageFile: File | null, + generator: GeneratorFile | null, ): Promise { btn.setText("Generating…"); btn.disabled = true; for (const input of inputs) input.disabled = true; + const reset = () => { + btn.setText("Create"); + btn.disabled = false; + for (const input of inputs) input.disabled = false; + }; + + // Solve before creating anything, so a generator that can't fill the + // map leaves no half-made map behind. + let terrainAt: Map | undefined; + if (generator) { + const palette = this.plugin.getPaletteByName(paletteName)?.terrains.map((t) => t.name) ?? []; + const solved = generateMapTerrain( + this.plugin, generator.model, palette, cols, rows, + { x: initialX, y: initialY }, staggerOffset, randomSeed(), + ); + if (!solved.ok) { + new Notice(`Generator "${generator.model.name}" couldn't fill this map: ${solved.message}`); + reset(); + return; + } + terrainAt = solved.cells; + } const result = await this.plugin.createNewMap( raw, cols, rows, paletteName, initialX, initialY, staggerOffset, (done, total) => btn.setText(`Generating ${done} / ${total}…`), + terrainAt, ); if ("error" in result) { new Notice(result.error); - btn.setText("Create"); - btn.disabled = false; - for (const input of inputs) input.disabled = false; + reset(); return; } diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts new file mode 100644 index 00000000..36e2b199 --- /dev/null +++ b/src/worldgen/generators.ts @@ -0,0 +1,157 @@ +/** + * Hexmaker glue for the hex-wfc library: where generator files live, learning + * a generator from a painted map, and generating terrain for a new map. + * + * Generators are Markdown files (see packages/hex-wfc/src/format.ts) under + * `{worldFolder}/generators`, so users can open and edit them by hand. A + * palette can have any number of them (one learned from a lakes map, another + * from a mountain range, ...). Each records the palette and map it came from + * in its frontmatter. + */ + +import { TFile, TFolder } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { getTerrainFromFile } from "../frontmatter"; +import { normalizeFolder, slugify } from "../utils"; +import { + learnModel, + modelToMarkdown, + parseModelMarkdown, + isModelMarkdown, + restrictModel, + solve, + cellKey, + type HexWfcModel, + type SolveResult, +} from "../../packages/hex-wfc/src"; + +export interface GeneratorFile { + file: TFile; + model: HexWfcModel; + warnings: string[]; +} + +export function generatorsFolder(plugin: HexmakerPlugin): string { + const world = normalizeFolder(plugin.settings.worldFolder); + return world ? `${world}/generators` : "generators"; +} + +/** Every generator file in the generators folder (sub-folders included). */ +export async function listGenerators(plugin: HexmakerPlugin): Promise { + const folder = generatorsFolder(plugin); + const files = plugin.app.vault + .getMarkdownFiles() + .filter((f) => f.path.startsWith(folder + "/") && !f.basename.startsWith("_")); + const out: GeneratorFile[] = []; + for (const file of files) { + const text = await plugin.app.vault.cachedRead(file); + if (!isModelMarkdown(text)) continue; + try { + const { model, warnings } = parseModelMarkdown(text, file.basename); + out.push({ file, model, warnings }); + } catch { + /* not a generator after all */ + } + } + return out.sort((a, b) => a.model.name.localeCompare(b.model.name)); +} + +/** True when every terrain the generator can place exists in the palette. */ +export function generatorFitsPalette(model: HexWfcModel, paletteTerrains: string[]): boolean { + const names = new Set(paletteTerrains); + const placeable = model.terrains.filter((t) => t.weight > 0); + return placeable.length > 0 && placeable.every((t) => names.has(t.name)); +} + +function mapStagger(plugin: HexmakerPlugin, mapName: string): "odd" | "even" { + return plugin.getMap(mapName)?.staggerOffset ?? plugin.settings.staggerOffset ?? "odd"; +} + +/** Painted terrain of every hex on the map, keyed "x_y". Unpainted hexes are left out. */ +export function readMapTerrain(plugin: HexmakerPlugin, mapName: string): Map { + const map = plugin.getMap(mapName); + const cells = new Map(); + if (!map) return cells; + const { cols, rows } = map.gridSize; + const { x: ox, y: oy } = map.gridOffset; + for (let x = ox; x < ox + cols; x++) { + for (let y = oy; y < oy + rows; y++) { + const terrain = getTerrainFromFile(plugin.app, plugin.hexPath(x, y, mapName)); + if (terrain) cells.set(cellKey(x, y), terrain); + } + } + return cells; +} + +/** + * Learn a generator from the map's painted hexes and save it as a new file. + * Never overwrites: a name clash gets a numeric suffix. + */ +export async function saveGeneratorFromMap( + plugin: HexmakerPlugin, + mapName: string, + rawName: string, +): Promise<{ file: TFile; model: HexWfcModel } | { error: string }> { + const map = plugin.getMap(mapName); + if (!map) return { error: `Map "${mapName}" not found.` }; + const name = slugify(rawName) || slugify(mapName); + if (!name) return { error: "Enter a generator name." }; + + const cells = readMapTerrain(plugin, mapName); + if (cells.size < 2) + return { error: "Paint some terrain on this map first. The generator learns from painted hexes." }; + + const model = learnModel(cells, { + name, + orientation: plugin.settings.hexOrientation, + stagger: mapStagger(plugin, mapName), + meta: { + palette: map.paletteName, + "source-map": mapName, + "painted-hexes": String(cells.size), + created: new Date().toISOString().slice(0, 10), + }, + }); + if (model.adjacency.length === 0) + return { error: "No painted hexes touch each other, so there is nothing to learn yet." }; + + const folder = generatorsFolder(plugin); + if (!(plugin.app.vault.getAbstractFileByPath(folder) instanceof TFolder)) { + try { + await plugin.app.vault.createFolder(folder); + } catch { + /* exists */ + } + } + let path = `${folder}/${name}.md`; + for (let n = 2; plugin.app.vault.getAbstractFileByPath(path); n++) { + path = `${folder}/${name}-${n}.md`; + model.name = `${name}-${n}`; + } + const file = await plugin.app.vault.create(path, modelToMarkdown(model)); + return { file, model }; +} + +/** + * Generate terrain for a whole new map. Terrains the palette lacks are dropped + * from the generator first. + */ +export function generateMapTerrain( + plugin: HexmakerPlugin, + model: HexWfcModel, + paletteTerrains: string[], + cols: number, + rows: number, + offset: { x: number; y: number }, + stagger: "odd" | "even", + seed: number, +): SolveResult { + return solve(restrictModel(model, paletteTerrains), { + cols, + rows, + offset, + orientation: plugin.settings.hexOrientation, + stagger, + seed, + }); +} diff --git a/src/worldgen/wfc.ts b/src/worldgen/wfc.ts deleted file mode 100644 index 6f61c0ac..00000000 --- a/src/worldgen/wfc.ts +++ /dev/null @@ -1,429 +0,0 @@ -/** - * Hex-grid Wave Function Collapse (simple tiled model) — PROTOTYPE. - * - * Pure, DOM-free, Obsidian-free. Not wired into any UI yet; see the KB plan - * note `plan-wfc-worldgen` for the design this module is a spike for. - * - * Model: each hex is a cell whose domain is a set of terrain names taken from - * the user's palette. Adjacency is undirected and the same in all six - * directions (terrain hexes have no rotation or edge sockets), so a single - * symmetric compatibility matrix is enough. - * - * Invariants: - * - Palette-agnostic: terrains are opaque strings; nothing is hardcoded. - * - Fixed cells (hexes the user already painted) are never changed. If they - * are mutually inconsistent the solver reports `fixed-conflict` instead of - * silently overwriting them. - * - Deterministic: the same input (including `seed`) gives the same output. - * - Neighbour topology is delegated to `hexNeighbors` from hexGeometry so it - * can never drift from the map renderer (odd-q / odd-r with stagger). - */ - -import { hexNeighbors } from "../hex-map/hexGeometry"; - -// ── Public types ───────────────────────────────────────────────────────────── - -/** - * Adjacency "deck". - * - `default: "allow"` → every pair may touch except those in `pairs` - * (the "ocean is never next to desert" style; an empty list = no constraints). - * - `default: "deny"` → only the pairs in `pairs` may touch (classic WFC). - * Self-adjacency must then be listed explicitly, e.g. ["forest", "forest"]. - * Pairs are unordered: ["a","b"] also covers ["b","a"]. - */ -export interface AdjacencyRules { - default: "allow" | "deny"; - pairs: [string, string][]; -} - -export interface WfcInput { - cols: number; - rows: number; - /** Absolute coordinate of the top-left cell (MapData.gridOffset). Parity of - * absolute coords drives the stagger, so this matters for neighbours. */ - offset?: { x: number; y: number }; - orientation: "flat" | "pointy"; - stagger?: "odd" | "even"; - terrains: string[]; - rules: AdjacencyRules; - /** Relative frequency per terrain. Missing = 1. 0 = never chosen by the - * solver (still allowed in fixed cells). */ - weights?: Record; - /** Pre-painted hexes keyed by "x_y" (absolute coords). Never changed. */ - fixed?: Record; - seed: number; - /** Backtracks allowed per attempt before restarting. Default 2000. */ - maxBacktracks?: number; - /** Fresh attempts (re-seeded) after the first one. Default 5. */ - maxRestarts?: number; -} - -export interface WfcStats { - attempts: number; - backtracks: number; - decisions: number; - ms: number; -} - -export type WfcResult = - | { ok: true; cells: Map; stats: WfcStats } - | { - ok: false; - reason: "invalid-input" | "fixed-conflict" | "contradiction"; - message: string; - /** Cell where the problem was detected, when known. */ - at?: { x: number; y: number }; - stats: WfcStats; - }; - -// ── Seeded RNG ─────────────────────────────────────────────────────────────── - -/** mulberry32 — tiny, fast, good enough for map generation. Returns [0, 1). */ -export function mulberry32(seed: number): () => number { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) >>> 0; - let t = a; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -// ── Helpers ────────────────────────────────────────────────────────────────── - -export const cellKey = (x: number, y: number): string => `${x}_${y}`; - -/** Build the symmetric allowed-pair lookup used by both solver and validator. */ -export function buildAllowed(terrains: string[], rules: AdjacencyRules): (a: string, b: string) => boolean { - const listed = new Set(); - for (const [a, b] of rules.pairs) { - listed.add(`${a}\u0000${b}`); - listed.add(`${b}\u0000${a}`); - } - const allowByDefault = rules.default === "allow"; - return (a, b) => { - const inList = listed.has(`${a}\u0000${b}`); - return allowByDefault ? !inList : inList; - }; -} - -/** - * Check a finished map against the rules. Returns the first violating - * neighbour pair, or null if everything is consistent. Used by tests and - * would be used to validate a hand-painted map in the UI. - */ -export function findViolation( - cells: Map, - input: Pick, -): { a: [number, number]; b: [number, number]; ta: string; tb: string } | null { - const allowed = buildAllowed(input.terrains, input.rules); - for (const [key, ta] of cells) { - const [x, y] = key.split("_").map(Number); - for (const [nx, ny] of hexNeighbors(x, y, input.orientation, input.stagger ?? "odd")) { - const tb = cells.get(cellKey(nx, ny)); - if (tb !== undefined && !allowed(ta, tb)) return { a: [x, y], b: [nx, ny], ta, tb }; - } - } - return null; -} - -/** - * Learn a rule deck + weights from an already-painted map ("example-based" - * authoring): any pair seen adjacent is allowed, everything else denied, and - * weights follow observed frequency. One answer to "the palette has no rules - * yet" — paint a small sample, then derive the deck from it. - */ -export function learnRulesFromSample( - cells: Map, - orientation: "flat" | "pointy", - stagger: "odd" | "even" = "odd", -): { rules: AdjacencyRules; weights: Record } { - const pairs = new Map(); - const weights: Record = {}; - for (const [key, ta] of cells) { - weights[ta] = (weights[ta] ?? 0) + 1; - const [x, y] = key.split("_").map(Number); - for (const [nx, ny] of hexNeighbors(x, y, orientation, stagger)) { - const tb = cells.get(cellKey(nx, ny)); - if (tb === undefined) continue; - const [p, q] = ta < tb ? [ta, tb] : [tb, ta]; - pairs.set(`${p}\u0000${q}`, [p, q]); - } - } - return { rules: { default: "deny", pairs: [...pairs.values()] }, weights }; -} - -// ── Solver ─────────────────────────────────────────────────────────────────── - -export function solveHexWfc(input: WfcInput): WfcResult { - const t0 = Date.now(); - const stats: WfcStats = { attempts: 0, backtracks: 0, decisions: 0, ms: 0 }; - const fail = ( - reason: "invalid-input" | "fixed-conflict" | "contradiction", - message: string, - at?: { x: number; y: number }, - ): WfcResult => { - stats.ms = Date.now() - t0; - return { ok: false, reason, message, at, stats }; - }; - - const { cols, rows, orientation } = input; - const stagger = input.stagger ?? "odd"; - const ox = input.offset?.x ?? 0; - const oy = input.offset?.y ?? 0; - const terrains = [...new Set(input.terrains)]; - const T = terrains.length; - if (cols <= 0 || rows <= 0) return fail("invalid-input", "Grid must be at least 1×1"); - if (T === 0) return fail("invalid-input", "No terrains supplied"); - const tIndex = new Map(terrains.map((t, i) => [t, i])); - - const N = cols * rows; - const W = (T + 31) >>> 5; // 32-bit words per domain bitset - const idx = (x: number, y: number) => (y - oy) * cols + (x - ox); - const inGrid = (x: number, y: number) => x >= ox && x < ox + cols && y >= oy && y < oy + rows; - - // Neighbour table (−1 = off-grid), 6 per cell. - const nbr = new Int32Array(N * 6).fill(-1); - for (let j = 0; j < rows; j++) { - for (let i = 0; i < cols; i++) { - const x = ox + i, y = oy + j, c = j * cols + i; - const ns = hexNeighbors(x, y, orientation, stagger); - for (let d = 0; d < ns.length; d++) { - const [nx, ny] = ns[d]; - if (inGrid(nx, ny)) nbr[c * 6 + d] = idx(nx, ny); - } - } - } - - // Compatibility bitsets: compat[t] = set of terrains allowed next to t. - const allowed = buildAllowed(terrains, input.rules); - const compat = new Uint32Array(T * W); - for (let a = 0; a < T; a++) - for (let b = 0; b < T; b++) - if (allowed(terrains[a], terrains[b])) compat[a * W + (b >>> 5)] |= 1 << (b & 31); - - const weight = new Float64Array(T); - for (let t = 0; t < T; t++) { - const w = input.weights?.[terrains[t]] ?? 1; - weight[t] = Number.isFinite(w) && w > 0 ? w : 0; - } - const solverMask = new Uint32Array(W); // terrains the solver may pick - for (let t = 0; t < T; t++) if (weight[t] > 0) solverMask[t >>> 5] |= 1 << (t & 31); - - // Fixed cells (only those inside the grid matter). - const fixedCells: [number, number][] = []; // [cellIndex, terrainIndex] - for (const [key, terr] of Object.entries(input.fixed ?? {})) { - const [x, y] = key.split("_").map(Number); - if (!Number.isInteger(x) || !Number.isInteger(y) || !inGrid(x, y)) continue; - const ti = tIndex.get(terr); - if (ti === undefined) - return fail("invalid-input", `Fixed hex ${key} uses terrain "${terr}" which is not in the generator's terrain list`, { x, y }); - fixedCells.push([idx(x, y), ti]); - } - // Direct fixed–fixed conflicts give the clearest message, so check first. - const fixedAt = new Int32Array(N).fill(-1); - for (const [c, t] of fixedCells) fixedAt[c] = t; - for (const [c, t] of fixedCells) { - for (let d = 0; d < 6; d++) { - const n = nbr[c * 6 + d]; - if (n < 0 || fixedAt[n] < 0) continue; - const u = fixedAt[n]; - if (!((compat[t * W + (u >>> 5)] >>> (u & 31)) & 1)) { - const x = ox + (c % cols), y = oy + Math.floor(c / cols); - return fail("fixed-conflict", `Painted hexes ${cellKey(x, y)} (${terrains[t]}) and ${cellKey(ox + (n % cols), oy + Math.floor(n / cols))} (${terrains[u]}) break the adjacency rules`, { x, y }); - } - } - } - - if (fixedCells.length < N && solverMask.every((v) => v === 0)) - return fail("invalid-input", "Every terrain has weight 0, so unpainted hexes cannot be filled"); - - const maxBacktracks = input.maxBacktracks ?? 2000; - const maxRestarts = input.maxRestarts ?? 5; - const masterRng = mulberry32(input.seed); - - const dom = new Uint32Array(N * W); - // Trail of [wordIndex, previousValue] for cheap undo. - let trailIdx: number[] = []; - let trailVal: number[] = []; - const popcount = (v: number) => { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24; - }; - const count = (c: number) => { - let s = 0; - for (let w = 0; w < W; w++) s += popcount(dom[c * W + w]); - return s; - }; - // Entropy cache: recomputed only for cells whose domain changed. - const dirty = new Uint8Array(N).fill(1); - const hCache = new Float64Array(N); - const cntCache = new Int32Array(N); - const noise = new Float64Array(N); // per-attempt tie-breaker - const setWord = (i: number, v: number) => { - if (dom[i] === v) return; - trailIdx.push(i); - trailVal.push(dom[i]); - dom[i] = v; - dirty[(i / W) | 0] = 1; - }; - const undoTo = (mark: number) => { - for (let k = trailIdx.length - 1; k >= mark; k--) { - dom[trailIdx[k]] = trailVal[k]; - dirty[(trailIdx[k] / W) | 0] = 1; - } - trailIdx.length = mark; - trailVal.length = mark; - }; - - const queue = new Int32Array(N); - const inQueue = new Uint8Array(N); - const support = new Uint32Array(W); - /** AC-3 style propagation from `seeds`. Returns the emptied cell or −1. */ - const propagate = (seeds: number[]): number => { - let head = 0, tail = 0; - for (const s of seeds) if (!inQueue[s]) { inQueue[s] = 1; queue[tail++ % N] = s; } - let size = tail; - while (size > 0) { - const c = queue[head++ % N]; - size--; - inQueue[c] = 0; - // Union of what c's remaining terrains allow next to them. - support.fill(0); - for (let w = 0; w < W; w++) { - let bits = dom[c * W + w]; - while (bits) { - const low = bits & -bits; - const t = (w << 5) + (31 - Math.clz32(low)); - for (let v = 0; v < W; v++) support[v] |= compat[t * W + v]; - bits ^= low; - } - } - for (let d = 0; d < 6; d++) { - const n = nbr[c * 6 + d]; - if (n < 0) continue; - let changed = false, empty = true; - for (let w = 0; w < W; w++) { - const i = n * W + w; - const nv = dom[i] & support[w]; - if (nv !== dom[i]) { setWord(i, nv); changed = true; } - if (nv) empty = false; - } - if (empty) { - // Drain queue flags so the next propagate starts clean. - while (size > 0) { inQueue[queue[head++ % N]] = 0; size--; } - return n; - } - if (changed && !inQueue[n]) { inQueue[n] = 1; queue[tail++ % N] = n; size++; } - } - } - return -1; - }; - - const cellXY = (c: number) => ({ x: ox + (c % cols), y: oy + Math.floor(c / cols) }); - - for (let attempt = 0; attempt <= maxRestarts; attempt++) { - stats.attempts++; - const rng = mulberry32(Math.floor(masterRng() * 4294967296)); - trailIdx = []; - trailVal = []; - for (let c = 0; c < N; c++) noise[c] = rng() * 1e-6; - dirty.fill(1); - // Init domains: fixed cells are singletons, others get the solver mask. - for (let c = 0; c < N; c++) { - const ft = fixedAt[c]; - for (let w = 0; w < W; w++) dom[c * W + w] = ft >= 0 ? (ft >>> 5 === w ? 1 << (ft & 31) : 0) : solverMask[w]; - } - const allCells: number[] = []; - for (let c = 0; c < N; c++) allCells.push(c); - const bad = propagate(allCells); - if (bad >= 0) - return fail("fixed-conflict", "The painted hexes cannot be completed under these rules (or every terrain has weight 0)", cellXY(bad)); - trailIdx = []; - trailVal = []; - - // Decision stack: [trailMark, cell, terrain] - const stack: [number, number, number][] = []; - let backtracksThisAttempt = 0; - let gaveUp = false; - - for (;;) { - // Pick the undecided cell with minimum weighted entropy (+ tiny noise). - let best = -1, bestH = Infinity; - for (let c = 0; c < N; c++) { - if (dirty[c]) { - dirty[c] = 0; - const k = count(c); - cntCache[c] = k; - if (k > 1) { - let sw = 0, swl = 0; - for (let w = 0; w < W; w++) { - let bits = dom[c * W + w]; - while (bits) { - const low = bits & -bits; - const t = (w << 5) + (31 - Math.clz32(low)); - const wt = weight[t] > 0 ? weight[t] : 1e-9; - sw += wt; swl += wt * Math.log(wt); - bits ^= low; - } - } - hCache[c] = Math.log(sw) - swl / sw + noise[c]; - } - } - if (cntCache[c] <= 1) continue; - if (hCache[c] < bestH) { bestH = hCache[c]; best = c; } - } - if (best < 0) break; // all collapsed - - // Weighted pick among the remaining terrains. - let total = 0; - for (let t = 0; t < T; t++) if ((dom[best * W + (t >>> 5)] >>> (t & 31)) & 1) total += weight[t]; - let r = rng() * total, choice = -1; - for (let t = 0; t < T; t++) { - if (!((dom[best * W + (t >>> 5)] >>> (t & 31)) & 1)) continue; - choice = t; - r -= weight[t]; - if (r < 0) break; - } - - stats.decisions++; - stack.push([trailIdx.length, best, choice]); - for (let w = 0; w < W; w++) setWord(best * W + w, choice >>> 5 === w ? 1 << (choice & 31) : 0); - let contradiction = propagate([best]) >= 0; - - // Backtrack: undo the last decision and ban that choice; repeat while - // the ban itself causes a contradiction. - while (contradiction) { - const top = stack.pop(); - if (!top || backtracksThisAttempt >= maxBacktracks) { gaveUp = true; break; } - backtracksThisAttempt++; - stats.backtracks++; - const [mark, cell, t] = top; - undoTo(mark); - const wi = cell * W + (t >>> 5); - setWord(wi, dom[wi] & ~(1 << (t & 31))); - contradiction = count(cell) === 0 || propagate([cell]) >= 0; - } - if (gaveUp) break; - } - - if (!gaveUp) { - const cells = new Map(); - for (let c = 0; c < N; c++) { - const { x, y } = cellXY(c); - for (let t = 0; t < T; t++) { - if ((dom[c * W + (t >>> 5)] >>> (t & 31)) & 1) { cells.set(cellKey(x, y), terrains[t]); break; } - } - } - stats.ms = Date.now() - t0; - return { ok: true, cells, stats }; - } - } - - return fail( - "contradiction", - `No valid map found after ${stats.attempts} attempt(s) and ${stats.backtracks} backtrack(s); the rules may be too strict for this grid`, - ); -} diff --git a/tests/frontmatter.test.ts b/tests/frontmatter.test.ts index ca12d0b3..db0b5c0b 100644 --- a/tests/frontmatter.test.ts +++ b/tests/frontmatter.test.ts @@ -1,364 +1,364 @@ -import { describe, it, mock } from "node:test"; -import expect from "expect"; -import { TFile } from "obsidian"; -import { getTerrainFromFile, setTerrainInFile, getIconOverrideFromFile, setIconOverrideInFile, getSubmapFromFile, setSubmapInFile, terrainFromFm, iconOverrideFromFm, gmIconsFromFm } from "../src/frontmatter"; - -/** Build a minimal mock App backed by an in-memory string. */ -function makeApp(filePath: string, initialContent: string) { - let stored = initialContent; - - const file = Object.create(TFile.prototype) as TFile; - file.path = filePath; - - const app = { - vault: { - getAbstractFileByPath: (p: string) => (p === filePath ? file : null), - }, - fileManager: { - processFrontMatter: mock.fn(async (_f: unknown, fn: (fm: Record) => void) => { - const fmMatch = stored.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/); - const fm: Record = {}; - if (fmMatch) { - for (const line of fmMatch[1].split("\n")) { - const m = line.match(/^([\w-]+):\s*(.+)$/); - if (m) fm[m[1]] = m[2].trim(); - } - } - const rest = fmMatch ? stored.slice(fmMatch[0].length) : stored; - fn(fm); - const fmLines = Object.entries(fm).map(([k, v]) => `${k}: ${v}`).join("\n"); - stored = fmLines ? `---\n${fmLines}\n---\n${rest}` : rest; - }), - }, - metadataCache: { - getFileCache: mock.fn(() => null), - }, - } as unknown as import("obsidian").App; - - return { app, getContent: () => stored }; -} - -// ── setTerrainInFile ────────────────────────────────────────────────────────── - -describe("setTerrainInFile", () => { - it("returns false when the file does not exist", async () => { - const { app } = makeApp("world/hexes/1_1.md", ""); - const result = await setTerrainInFile(app, "world/hexes/MISSING.md", "forest"); - expect(result).toBe(false); - }); - - it("adds terrain to existing frontmatter that lacks it", async () => { - const { app, getContent } = makeApp("hex.md", "---\ntitle: test\n---\n\nContent"); - await setTerrainInFile(app, "hex.md", "forest"); - expect(getContent()).toContain("terrain: forest"); - expect(getContent()).toContain("title: test"); - }); - - it("updates an existing terrain field", async () => { - const { app, getContent } = makeApp("hex.md", "---\nterrain: plains\n---\n\nContent"); - await setTerrainInFile(app, "hex.md", "forest"); - expect(getContent()).toContain("terrain: forest"); - expect(getContent()).not.toContain("terrain: plains"); - }); - - it("removes the terrain field when passed null", async () => { - const { app, getContent } = makeApp("hex.md", "---\nterrain: forest\ntitle: x\n---\n\nContent"); - await setTerrainInFile(app, "hex.md", null); - expect(getContent()).not.toContain("terrain:"); - expect(getContent()).toContain("title: x"); - }); - - it("creates frontmatter when none exists", async () => { - const { app, getContent } = makeApp("hex.md", "Just content."); - await setTerrainInFile(app, "hex.md", "desert"); - expect(getContent()).toMatch(/^---\n/); - expect(getContent()).toContain("terrain: desert"); - expect(getContent()).toContain("Just content."); - }); - - it("returns true and makes no change when removing terrain from a file with no frontmatter", async () => { - const { app, getContent } = makeApp("hex.md", "No frontmatter."); - const result = await setTerrainInFile(app, "hex.md", null); - expect(result).toBe(true); - expect(getContent()).toBe("No frontmatter."); - }); - - it("preserves content body after the frontmatter", async () => { - const body = "\n### Towns\n\n[[Town A]]\n"; - const { app, getContent } = makeApp("hex.md", `---\nterrain: plains\n---\n${body}`); - await setTerrainInFile(app, "hex.md", "forest"); - expect(getContent()).toContain("### Towns"); - expect(getContent()).toContain("[[Town A]]"); - }); -}); - -// ── setIconOverrideInFile ───────────────────────────────────────────────────── - -describe("setIconOverrideInFile", () => { - it("returns false when the file does not exist", async () => { - const { app } = makeApp("hex.md", ""); - const result = await setIconOverrideInFile(app, "MISSING.md", "castle.png"); - expect(result).toBe(false); - }); - - it("adds icon to existing frontmatter that lacks it", async () => { - const { app, getContent } = makeApp("hex.md", "---\nterrain: forest\n---\n\nContent"); - await setIconOverrideInFile(app, "hex.md", "castle.png"); - expect(getContent()).toContain("icon: castle.png"); - expect(getContent()).toContain("terrain: forest"); - }); - - it("updates an existing icon field", async () => { - const { app, getContent } = makeApp("hex.md", "---\nicon: tower.png\n---\n\nContent"); - await setIconOverrideInFile(app, "hex.md", "castle.png"); - expect(getContent()).toContain("icon: castle.png"); - expect(getContent()).not.toContain("icon: tower.png"); - }); - - it("removes the icon field when passed null", async () => { - const { app, getContent } = makeApp("hex.md", "---\nicon: castle.png\nterrain: forest\n---\n\nContent"); - await setIconOverrideInFile(app, "hex.md", null); - expect(getContent()).not.toContain("icon:"); - expect(getContent()).toContain("terrain: forest"); - }); - - it("creates frontmatter when none exists", async () => { - const { app, getContent } = makeApp("hex.md", "Bare content."); - await setIconOverrideInFile(app, "hex.md", "ruin.png"); - expect(getContent()).toMatch(/^---\n/); - expect(getContent()).toContain("icon: ruin.png"); - expect(getContent()).toContain("Bare content."); - }); - - it("returns true and makes no change when removing icon from a file with no frontmatter", async () => { - const { app, getContent } = makeApp("hex.md", "No frontmatter."); - const result = await setIconOverrideInFile(app, "hex.md", null); - expect(result).toBe(true); - expect(getContent()).toBe("No frontmatter."); - }); -}); - -// ── helpers for cache-based reads ──────────────────────────────────────────── - -/** Build a minimal mock App that returns a metadata cache with the given frontmatter. */ -function makeAppWithCache(filePath: string, frontmatter: Record | null) { - const file = Object.create(TFile.prototype) as TFile; - file.path = filePath; - - const app = { - vault: { - getAbstractFileByPath: (p: string) => (p === filePath ? file : null), - }, - metadataCache: { - getFileCache: mock.fn(() => (frontmatter !== null ? { frontmatter } : null)), - }, - } as unknown as import("obsidian").App; - - return { app }; -} - -// ── getTerrainFromFile ──────────────────────────────────────────────────────── - -describe("getTerrainFromFile", () => { - it("returns null when the file does not exist", () => { - const { app } = makeAppWithCache("hex.md", { terrain: "forest" }); - expect(getTerrainFromFile(app, "MISSING.md")).toBeNull(); - }); - - it("returns the terrain string from the metadata cache", () => { - const { app } = makeAppWithCache("hex.md", { terrain: "forest" }); - expect(getTerrainFromFile(app, "hex.md")).toBe("forest"); - }); - - it("returns null when terrain field is absent from frontmatter", () => { - const { app } = makeAppWithCache("hex.md", { title: "Test" }); - expect(getTerrainFromFile(app, "hex.md")).toBeNull(); - }); - - it("returns null when there is no file cache", () => { - const { app } = makeAppWithCache("hex.md", null); - expect(getTerrainFromFile(app, "hex.md")).toBeNull(); - }); - - it("returns null when terrain field is not a string (e.g. array)", () => { - const { app } = makeAppWithCache("hex.md", { terrain: ["forest", "plains"] }); - expect(getTerrainFromFile(app, "hex.md")).toBeNull(); - }); - - it("returns null when terrain field is a number", () => { - const { app } = makeAppWithCache("hex.md", { terrain: 42 }); - expect(getTerrainFromFile(app, "hex.md")).toBeNull(); - }); -}); - -// ── getIconOverrideFromFile ─────────────────────────────────────────────────── - -describe("getIconOverrideFromFile", () => { - it("returns null when the file does not exist", () => { - const { app } = makeAppWithCache("hex.md", { icon: "castle.png" }); - expect(getIconOverrideFromFile(app, "MISSING.md")).toBeNull(); - }); - - it("returns the icon string from the metadata cache", () => { - const { app } = makeAppWithCache("hex.md", { icon: "castle.png" }); - expect(getIconOverrideFromFile(app, "hex.md")).toBe("castle.png"); - }); - - it("returns null when icon field is absent from frontmatter", () => { - const { app } = makeAppWithCache("hex.md", { terrain: "forest" }); - expect(getIconOverrideFromFile(app, "hex.md")).toBeNull(); - }); - - it("returns null when there is no file cache", () => { - const { app } = makeAppWithCache("hex.md", null); - expect(getIconOverrideFromFile(app, "hex.md")).toBeNull(); - }); - - it("returns null when icon field is not a string (e.g. boolean)", () => { - const { app } = makeAppWithCache("hex.md", { icon: true }); - expect(getIconOverrideFromFile(app, "hex.md")).toBeNull(); - }); -}); - -// ── setSubmapInFile ─────────────────────────────────────────────────────────── - -describe("setSubmapInFile", () => { - it("returns false when the file does not exist", async () => { - const { app } = makeApp("hex.md", ""); - const result = await setSubmapInFile(app, "missing.md", "the-coast"); - expect(result).toBe(false); - }); - - it("writes duckmage-submap to a file with no existing frontmatter", async () => { - const { app, getContent } = makeApp("hex.md", "Body text."); - await setSubmapInFile(app, "hex.md", "the-coast"); - expect(getContent()).toContain("duckmage-submap: the-coast"); - }); - - it("updates an existing duckmage-submap value", async () => { - const { app, getContent } = makeApp("hex.md", "---\nduckmage-submap: old-map\n---\n"); - await setSubmapInFile(app, "hex.md", "new-map"); - expect(getContent()).toContain("duckmage-submap: new-map"); - expect(getContent()).not.toContain("old-map"); - }); - - it("removes duckmage-submap when passed null", async () => { - const { app, getContent } = makeApp("hex.md", "---\nduckmage-submap: the-coast\nterrain: plains\n---\n"); - await setSubmapInFile(app, "hex.md", null); - expect(getContent()).not.toContain("duckmage-submap"); - expect(getContent()).toContain("terrain: plains"); - }); -}); - -// ── getSubmapFromFile ───────────────────────────────────────────────────────── - -describe("getSubmapFromFile", () => { - it("returns the submap name when present", () => { - const { app } = makeAppWithCache("hex.md", { "duckmage-submap": "the-coast" }); - expect(getSubmapFromFile(app, "hex.md")).toBe("the-coast"); - }); - - it("returns undefined when the key is absent", () => { - const { app } = makeAppWithCache("hex.md", { terrain: "plains" }); - expect(getSubmapFromFile(app, "hex.md")).toBeUndefined(); - }); - - it("returns undefined when the file does not exist", () => { - const { app } = makeAppWithCache("hex.md", null); - expect(getSubmapFromFile(app, "missing.md")).toBeUndefined(); - }); - - it("returns undefined when the value is not a string", () => { - const { app } = makeAppWithCache("hex.md", { "duckmage-submap": 42 }); - expect(getSubmapFromFile(app, "hex.md")).toBeUndefined(); - }); -}); - -// ── updateSubmapReferences ──────────────────────────────────────────────────── - -describe("updateSubmapReferences", () => { - function makeMultiFileApp(files: Record) { - const stored: Record = {}; - const tfiles: Record = {}; - - for (const [path, { content }] of Object.entries(files)) { - stored[path] = content; - const f = Object.create(TFile.prototype) as TFile; - f.path = path; - tfiles[path] = f; - } - - const app = { - vault: { - getAbstractFileByPath: (p: string) => tfiles[p] ?? null, - getMarkdownFiles: () => Object.values(tfiles), - }, - fileManager: { - processFrontMatter: mock.fn(async (file: TFile, fn: (fm: Record) => void) => { - const content = stored[file.path] ?? ""; - const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/); - const fm: Record = {}; - if (fmMatch) { - for (const line of fmMatch[1].split("\n")) { - const m = line.match(/^([\w-]+):\s*(.+)$/); - if (m) fm[m[1]] = m[2].trim(); - } - } - const rest = fmMatch ? content.slice(fmMatch[0].length) : content; - fn(fm); - const fmLines = Object.entries(fm).map(([k, v]) => `${k}: ${v}`).join("\n"); - stored[file.path] = fmLines ? `---\n${fmLines}\n---\n${rest}` : rest; - }), - }, - metadataCache: { - getFileCache: mock.fn((file: TFile) => { - const submap = files[file.path]?.submap; - return submap ? { frontmatter: { "duckmage-submap": submap } } : null; - }), - }, - } as unknown as import("obsidian").App; - - return { app, getContent: (p: string) => stored[p] ?? "" }; - } - - it("updates duckmage-submap in all matching hex notes", async () => { - const { app, getContent } = makeMultiFileApp({ - "world/hexes/map-a/1_1.md": { content: "---\nduckmage-submap: old-map\n---\n", submap: "old-map" }, - "world/hexes/map-a/2_2.md": { content: "---\nduckmage-submap: old-map\n---\n", submap: "old-map" }, - "world/hexes/map-a/3_3.md": { content: "---\nterrain: plains\n---\n" }, - }); - - // Simulate updateSubmapReferences logic directly - const hexFolder = "world/hexes"; - const files = app.vault.getMarkdownFiles().filter( - (f: TFile) => f.path.startsWith(hexFolder + "/"), - ); - for (const file of files) { - const submap = app.metadataCache.getFileCache(file)?.frontmatter?.["duckmage-submap"]; - if (submap !== "old-map") continue; - await setSubmapInFile(app, file.path, "new-map"); - } - - expect(getContent("world/hexes/map-a/1_1.md")).toContain("duckmage-submap: new-map"); - expect(getContent("world/hexes/map-a/2_2.md")).toContain("duckmage-submap: new-map"); - expect(getContent("world/hexes/map-a/3_3.md")).not.toContain("duckmage-submap"); - }); - - it("does not touch notes whose submap points to a different map", async () => { - const { app, getContent } = makeMultiFileApp({ - "world/hexes/map-a/1_1.md": { content: "---\nduckmage-submap: other-map\n---\n", submap: "other-map" }, - }); - - const files = app.vault.getMarkdownFiles(); - for (const file of files) { - const submap = app.metadataCache.getFileCache(file)?.frontmatter?.["duckmage-submap"]; - if (submap !== "old-map") continue; - await setSubmapInFile(app, file.path, "new-map"); - } - - expect(getContent("world/hexes/map-a/1_1.md")).toContain("duckmage-submap: other-map"); - }); -}); +import { describe, it, mock } from "node:test"; +import expect from "expect"; +import { TFile } from "obsidian"; +import { getTerrainFromFile, setTerrainInFile, getIconOverrideFromFile, setIconOverrideInFile, getSubmapFromFile, setSubmapInFile, terrainFromFm, iconOverrideFromFm, gmIconsFromFm, withFrontmatterField } from "../src/frontmatter"; + +/** Build a minimal mock App backed by an in-memory string. */ +function makeApp(filePath: string, initialContent: string) { + let stored = initialContent; + + const file = Object.create(TFile.prototype) as TFile; + file.path = filePath; + + const app = { + vault: { + getAbstractFileByPath: (p: string) => (p === filePath ? file : null), + }, + fileManager: { + processFrontMatter: mock.fn(async (_f: unknown, fn: (fm: Record) => void) => { + const fmMatch = stored.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/); + const fm: Record = {}; + if (fmMatch) { + for (const line of fmMatch[1].split("\n")) { + const m = line.match(/^([\w-]+):\s*(.+)$/); + if (m) fm[m[1]] = m[2].trim(); + } + } + const rest = fmMatch ? stored.slice(fmMatch[0].length) : stored; + fn(fm); + const fmLines = Object.entries(fm).map(([k, v]) => `${k}: ${v}`).join("\n"); + stored = fmLines ? `---\n${fmLines}\n---\n${rest}` : rest; + }), + }, + metadataCache: { + getFileCache: mock.fn(() => null), + }, + } as unknown as import("obsidian").App; + + return { app, getContent: () => stored }; +} + +// ── setTerrainInFile ────────────────────────────────────────────────────────── + +describe("setTerrainInFile", () => { + it("returns false when the file does not exist", async () => { + const { app } = makeApp("world/hexes/1_1.md", ""); + const result = await setTerrainInFile(app, "world/hexes/MISSING.md", "forest"); + expect(result).toBe(false); + }); + + it("adds terrain to existing frontmatter that lacks it", async () => { + const { app, getContent } = makeApp("hex.md", "---\ntitle: test\n---\n\nContent"); + await setTerrainInFile(app, "hex.md", "forest"); + expect(getContent()).toContain("terrain: forest"); + expect(getContent()).toContain("title: test"); + }); + + it("updates an existing terrain field", async () => { + const { app, getContent } = makeApp("hex.md", "---\nterrain: plains\n---\n\nContent"); + await setTerrainInFile(app, "hex.md", "forest"); + expect(getContent()).toContain("terrain: forest"); + expect(getContent()).not.toContain("terrain: plains"); + }); + + it("removes the terrain field when passed null", async () => { + const { app, getContent } = makeApp("hex.md", "---\nterrain: forest\ntitle: x\n---\n\nContent"); + await setTerrainInFile(app, "hex.md", null); + expect(getContent()).not.toContain("terrain:"); + expect(getContent()).toContain("title: x"); + }); + + it("creates frontmatter when none exists", async () => { + const { app, getContent } = makeApp("hex.md", "Just content."); + await setTerrainInFile(app, "hex.md", "desert"); + expect(getContent()).toMatch(/^---\n/); + expect(getContent()).toContain("terrain: desert"); + expect(getContent()).toContain("Just content."); + }); + + it("returns true and makes no change when removing terrain from a file with no frontmatter", async () => { + const { app, getContent } = makeApp("hex.md", "No frontmatter."); + const result = await setTerrainInFile(app, "hex.md", null); + expect(result).toBe(true); + expect(getContent()).toBe("No frontmatter."); + }); + + it("preserves content body after the frontmatter", async () => { + const body = "\n### Towns\n\n[[Town A]]\n"; + const { app, getContent } = makeApp("hex.md", `---\nterrain: plains\n---\n${body}`); + await setTerrainInFile(app, "hex.md", "forest"); + expect(getContent()).toContain("### Towns"); + expect(getContent()).toContain("[[Town A]]"); + }); +}); + +// ── setIconOverrideInFile ───────────────────────────────────────────────────── + +describe("setIconOverrideInFile", () => { + it("returns false when the file does not exist", async () => { + const { app } = makeApp("hex.md", ""); + const result = await setIconOverrideInFile(app, "MISSING.md", "castle.png"); + expect(result).toBe(false); + }); + + it("adds icon to existing frontmatter that lacks it", async () => { + const { app, getContent } = makeApp("hex.md", "---\nterrain: forest\n---\n\nContent"); + await setIconOverrideInFile(app, "hex.md", "castle.png"); + expect(getContent()).toContain("icon: castle.png"); + expect(getContent()).toContain("terrain: forest"); + }); + + it("updates an existing icon field", async () => { + const { app, getContent } = makeApp("hex.md", "---\nicon: tower.png\n---\n\nContent"); + await setIconOverrideInFile(app, "hex.md", "castle.png"); + expect(getContent()).toContain("icon: castle.png"); + expect(getContent()).not.toContain("icon: tower.png"); + }); + + it("removes the icon field when passed null", async () => { + const { app, getContent } = makeApp("hex.md", "---\nicon: castle.png\nterrain: forest\n---\n\nContent"); + await setIconOverrideInFile(app, "hex.md", null); + expect(getContent()).not.toContain("icon:"); + expect(getContent()).toContain("terrain: forest"); + }); + + it("creates frontmatter when none exists", async () => { + const { app, getContent } = makeApp("hex.md", "Bare content."); + await setIconOverrideInFile(app, "hex.md", "ruin.png"); + expect(getContent()).toMatch(/^---\n/); + expect(getContent()).toContain("icon: ruin.png"); + expect(getContent()).toContain("Bare content."); + }); + + it("returns true and makes no change when removing icon from a file with no frontmatter", async () => { + const { app, getContent } = makeApp("hex.md", "No frontmatter."); + const result = await setIconOverrideInFile(app, "hex.md", null); + expect(result).toBe(true); + expect(getContent()).toBe("No frontmatter."); + }); +}); + +// ── helpers for cache-based reads ──────────────────────────────────────────── + +/** Build a minimal mock App that returns a metadata cache with the given frontmatter. */ +function makeAppWithCache(filePath: string, frontmatter: Record | null) { + const file = Object.create(TFile.prototype) as TFile; + file.path = filePath; + + const app = { + vault: { + getAbstractFileByPath: (p: string) => (p === filePath ? file : null), + }, + metadataCache: { + getFileCache: mock.fn(() => (frontmatter !== null ? { frontmatter } : null)), + }, + } as unknown as import("obsidian").App; + + return { app }; +} + +// ── getTerrainFromFile ──────────────────────────────────────────────────────── + +describe("getTerrainFromFile", () => { + it("returns null when the file does not exist", () => { + const { app } = makeAppWithCache("hex.md", { terrain: "forest" }); + expect(getTerrainFromFile(app, "MISSING.md")).toBeNull(); + }); + + it("returns the terrain string from the metadata cache", () => { + const { app } = makeAppWithCache("hex.md", { terrain: "forest" }); + expect(getTerrainFromFile(app, "hex.md")).toBe("forest"); + }); + + it("returns null when terrain field is absent from frontmatter", () => { + const { app } = makeAppWithCache("hex.md", { title: "Test" }); + expect(getTerrainFromFile(app, "hex.md")).toBeNull(); + }); + + it("returns null when there is no file cache", () => { + const { app } = makeAppWithCache("hex.md", null); + expect(getTerrainFromFile(app, "hex.md")).toBeNull(); + }); + + it("returns null when terrain field is not a string (e.g. array)", () => { + const { app } = makeAppWithCache("hex.md", { terrain: ["forest", "plains"] }); + expect(getTerrainFromFile(app, "hex.md")).toBeNull(); + }); + + it("returns null when terrain field is a number", () => { + const { app } = makeAppWithCache("hex.md", { terrain: 42 }); + expect(getTerrainFromFile(app, "hex.md")).toBeNull(); + }); +}); + +// ── getIconOverrideFromFile ─────────────────────────────────────────────────── + +describe("getIconOverrideFromFile", () => { + it("returns null when the file does not exist", () => { + const { app } = makeAppWithCache("hex.md", { icon: "castle.png" }); + expect(getIconOverrideFromFile(app, "MISSING.md")).toBeNull(); + }); + + it("returns the icon string from the metadata cache", () => { + const { app } = makeAppWithCache("hex.md", { icon: "castle.png" }); + expect(getIconOverrideFromFile(app, "hex.md")).toBe("castle.png"); + }); + + it("returns null when icon field is absent from frontmatter", () => { + const { app } = makeAppWithCache("hex.md", { terrain: "forest" }); + expect(getIconOverrideFromFile(app, "hex.md")).toBeNull(); + }); + + it("returns null when there is no file cache", () => { + const { app } = makeAppWithCache("hex.md", null); + expect(getIconOverrideFromFile(app, "hex.md")).toBeNull(); + }); + + it("returns null when icon field is not a string (e.g. boolean)", () => { + const { app } = makeAppWithCache("hex.md", { icon: true }); + expect(getIconOverrideFromFile(app, "hex.md")).toBeNull(); + }); +}); + +// ── setSubmapInFile ─────────────────────────────────────────────────────────── + +describe("setSubmapInFile", () => { + it("returns false when the file does not exist", async () => { + const { app } = makeApp("hex.md", ""); + const result = await setSubmapInFile(app, "missing.md", "the-coast"); + expect(result).toBe(false); + }); + + it("writes duckmage-submap to a file with no existing frontmatter", async () => { + const { app, getContent } = makeApp("hex.md", "Body text."); + await setSubmapInFile(app, "hex.md", "the-coast"); + expect(getContent()).toContain("duckmage-submap: the-coast"); + }); + + it("updates an existing duckmage-submap value", async () => { + const { app, getContent } = makeApp("hex.md", "---\nduckmage-submap: old-map\n---\n"); + await setSubmapInFile(app, "hex.md", "new-map"); + expect(getContent()).toContain("duckmage-submap: new-map"); + expect(getContent()).not.toContain("old-map"); + }); + + it("removes duckmage-submap when passed null", async () => { + const { app, getContent } = makeApp("hex.md", "---\nduckmage-submap: the-coast\nterrain: plains\n---\n"); + await setSubmapInFile(app, "hex.md", null); + expect(getContent()).not.toContain("duckmage-submap"); + expect(getContent()).toContain("terrain: plains"); + }); +}); + +// ── getSubmapFromFile ───────────────────────────────────────────────────────── + +describe("getSubmapFromFile", () => { + it("returns the submap name when present", () => { + const { app } = makeAppWithCache("hex.md", { "duckmage-submap": "the-coast" }); + expect(getSubmapFromFile(app, "hex.md")).toBe("the-coast"); + }); + + it("returns undefined when the key is absent", () => { + const { app } = makeAppWithCache("hex.md", { terrain: "plains" }); + expect(getSubmapFromFile(app, "hex.md")).toBeUndefined(); + }); + + it("returns undefined when the file does not exist", () => { + const { app } = makeAppWithCache("hex.md", null); + expect(getSubmapFromFile(app, "missing.md")).toBeUndefined(); + }); + + it("returns undefined when the value is not a string", () => { + const { app } = makeAppWithCache("hex.md", { "duckmage-submap": 42 }); + expect(getSubmapFromFile(app, "hex.md")).toBeUndefined(); + }); +}); + +// ── updateSubmapReferences ──────────────────────────────────────────────────── + +describe("updateSubmapReferences", () => { + function makeMultiFileApp(files: Record) { + const stored: Record = {}; + const tfiles: Record = {}; + + for (const [path, { content }] of Object.entries(files)) { + stored[path] = content; + const f = Object.create(TFile.prototype) as TFile; + f.path = path; + tfiles[path] = f; + } + + const app = { + vault: { + getAbstractFileByPath: (p: string) => tfiles[p] ?? null, + getMarkdownFiles: () => Object.values(tfiles), + }, + fileManager: { + processFrontMatter: mock.fn(async (file: TFile, fn: (fm: Record) => void) => { + const content = stored[file.path] ?? ""; + const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/); + const fm: Record = {}; + if (fmMatch) { + for (const line of fmMatch[1].split("\n")) { + const m = line.match(/^([\w-]+):\s*(.+)$/); + if (m) fm[m[1]] = m[2].trim(); + } + } + const rest = fmMatch ? content.slice(fmMatch[0].length) : content; + fn(fm); + const fmLines = Object.entries(fm).map(([k, v]) => `${k}: ${v}`).join("\n"); + stored[file.path] = fmLines ? `---\n${fmLines}\n---\n${rest}` : rest; + }), + }, + metadataCache: { + getFileCache: mock.fn((file: TFile) => { + const submap = files[file.path]?.submap; + return submap ? { frontmatter: { "duckmage-submap": submap } } : null; + }), + }, + } as unknown as import("obsidian").App; + + return { app, getContent: (p: string) => stored[p] ?? "" }; + } + + it("updates duckmage-submap in all matching hex notes", async () => { + const { app, getContent } = makeMultiFileApp({ + "world/hexes/map-a/1_1.md": { content: "---\nduckmage-submap: old-map\n---\n", submap: "old-map" }, + "world/hexes/map-a/2_2.md": { content: "---\nduckmage-submap: old-map\n---\n", submap: "old-map" }, + "world/hexes/map-a/3_3.md": { content: "---\nterrain: plains\n---\n" }, + }); + + // Simulate updateSubmapReferences logic directly + const hexFolder = "world/hexes"; + const files = app.vault.getMarkdownFiles().filter( + (f: TFile) => f.path.startsWith(hexFolder + "/"), + ); + for (const file of files) { + const submap = app.metadataCache.getFileCache(file)?.frontmatter?.["duckmage-submap"]; + if (submap !== "old-map") continue; + await setSubmapInFile(app, file.path, "new-map"); + } + + expect(getContent("world/hexes/map-a/1_1.md")).toContain("duckmage-submap: new-map"); + expect(getContent("world/hexes/map-a/2_2.md")).toContain("duckmage-submap: new-map"); + expect(getContent("world/hexes/map-a/3_3.md")).not.toContain("duckmage-submap"); + }); + + it("does not touch notes whose submap points to a different map", async () => { + const { app, getContent } = makeMultiFileApp({ + "world/hexes/map-a/1_1.md": { content: "---\nduckmage-submap: other-map\n---\n", submap: "other-map" }, + }); + + const files = app.vault.getMarkdownFiles(); + for (const file of files) { + const submap = app.metadataCache.getFileCache(file)?.frontmatter?.["duckmage-submap"]; + if (submap !== "old-map") continue; + await setSubmapInFile(app, file.path, "new-map"); + } + + expect(getContent("world/hexes/map-a/1_1.md")).toContain("duckmage-submap: other-map"); + }); +}); // ── Pure frontmatter extractors (used by the hex-grid render loop, which // fetches frontmatter once per hex and feeds it to all three) ────────────── @@ -403,3 +403,37 @@ describe("gmIconsFromFm", () => { expect(gmIconsFromFm(undefined)).toEqual([]); }); }); + +describe("withFrontmatterField", () => { + it("fills an empty key in the default hex template", () => { + const out = withFrontmatterField("---\nterrain:\n---\n\n# Hex 1, 2\n", "terrain", "Grass"); + expect(out).toBe("---\nterrain: Grass\n---\n\n# Hex 1, 2\n"); + }); + + it("replaces an existing value and keeps other keys", () => { + const out = withFrontmatterField("---\nicon: a.png\nterrain: Sea\ntags: [x]\n---\nbody", "terrain", "Hills"); + expect(out).toBe("---\nicon: a.png\nterrain: Hills\ntags: [x]\n---\nbody"); + }); + + it("adds the key when the frontmatter lacks it", () => { + expect(withFrontmatterField("---\nicon: a.png\n---\nbody", "terrain", "Hills")).toBe( + "---\nicon: a.png\nterrain: Hills\n---\nbody", + ); + }); + + it("adds a frontmatter block when there is none", () => { + expect(withFrontmatterField("# Hex\n", "terrain", "Hills")).toBe("---\nterrain: Hills\n---\n# Hex\n"); + }); + + it("quotes values YAML would misread", () => { + expect(withFrontmatterField("---\nterrain:\n---\n", "terrain", "Sea: deep #1")).toBe( + '---\nterrain: "Sea: deep #1"\n---\n', + ); + }); + + it("does not match a longer key with the same prefix", () => { + expect(withFrontmatterField("---\nterrain-note: x\n---\n", "terrain", "Hills")).toBe( + "---\nterrain-note: x\nterrain: Hills\n---\n", + ); + }); +}); diff --git a/tests/hexWfc.test.ts b/tests/hexWfc.test.ts new file mode 100644 index 00000000..b60ccab0 --- /dev/null +++ b/tests/hexWfc.test.ts @@ -0,0 +1,246 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + hexNeighbors, + cellKey, + learnModel, + solve, + findViolation, + validateModel, + restrictModel, + modelToMarkdown, + parseModelMarkdown, + isModelMarkdown, + type HexWfcModel, +} from "../packages/hex-wfc/src"; +import { hexNeighbors as pluginHexNeighbors } from "../src/hex-map/hexGeometry"; + +/** Paint a cols×rows example: a round lake in grassland with a forest band. */ +function exampleMap(cols = 20, rows = 16): Map { + const cells = new Map(); + for (let x = 0; x < cols; x++) { + for (let y = 0; y < rows; y++) { + const dx = x - 6, dy = y - 7; + let t = "Grass"; + if (dx * dx + dy * dy < 12) t = "Water"; + else if (dx * dx + dy * dy < 22) t = "Sand"; + else if (x >= 14) t = "Forest"; + cells.set(cellKey(x, y), t); + } + } + return cells; +} + +const lakes = () => learnModel(exampleMap(), { name: "lakes", orientation: "flat", meta: { palette: "Default" } }); + +describe("hex-wfc grid", () => { + it("matches the plugin's neighbour function for every orientation and stagger", () => { + for (const o of ["flat", "pointy"] as const) + for (const s of ["odd", "even"] as const) + for (let x = -3; x < 4; x++) + for (let y = -3; y < 4; y++) + expect(hexNeighbors(x, y, o, s)).toEqual(pluginHexNeighbors(x, y, o, s)); + }); +}); + +describe("learnModel", () => { + it("counts terrains and touching pairs, leaving out pairs that never touch", () => { + const m = lakes(); + expect(m.name).toBe("lakes"); + expect(m.meta.palette).toBe("Default"); + const names = m.terrains.map((t) => t.name).sort(); + expect(names).toEqual(["Forest", "Grass", "Sand", "Water"]); + expect(m.terrains.reduce((s, t) => s + t.weight, 0)).toBe(20 * 16); + const pair = (a: string, b: string) => + m.adjacency.find((e) => (e.a === a && e.b === b) || (e.a === b && e.b === a)); + expect(pair("Water", "Water")?.weight).toBeGreaterThan(0); + expect(pair("Water", "Sand")?.weight).toBeGreaterThan(0); + expect(pair("Water", "Grass")).toBeUndefined(); // sand ring always separates them + expect(pair("Water", "Forest")).toBeUndefined(); + expect(validateModel(m)).toEqual([]); + }); + + it("counts each edge once", () => { + // Two hexes side by side: exactly one edge. + const m = learnModel({ "0_0": "A", "0_1": "B" }, { name: "t", orientation: "flat" }); + expect(m.adjacency).toEqual([{ a: "A", b: "B", weight: 1 }]); + const n = learnModel({ "0_0": "A", "0_1": "A" }, { name: "t", orientation: "flat" }); + expect(n.adjacency).toEqual([{ a: "A", b: "A", weight: 1 }]); + }); + + it("ignores unpainted hexes", () => { + const m = learnModel({ "0_0": "A", "5_5": "B" }, { name: "t", orientation: "pointy" }); + expect(m.adjacency).toEqual([]); + expect(validateModel(m).length).toBeGreaterThan(0); // neither can touch anything + }); +}); + +describe("solve", () => { + for (const orientation of ["flat", "pointy"] as const) { + for (const stagger of ["odd", "even"] as const) { + it(`never breaks a learned rule (${orientation}/${stagger})`, () => { + const model = learnModel(exampleMap(), { name: "lakes", orientation, stagger }); + const r = solve(model, { cols: 25, rows: 20, orientation, stagger, seed: 7 }); + expect(r.ok).toBe(true); + if (!r.ok) return; + expect(r.cells.size).toBe(25 * 20); + expect(findViolation(model, r.cells, orientation, stagger)).toBeNull(); + }); + } + } + + it("is deterministic per seed", () => { + const model = lakes(); + const a = solve(model, { cols: 20, rows: 15, orientation: "flat", seed: 123 }); + const b = solve(model, { cols: 20, rows: 15, orientation: "flat", seed: 123 }); + const c = solve(model, { cols: 20, rows: 15, orientation: "flat", seed: 124 }); + expect(a.ok && b.ok && c.ok).toBe(true); + if (!a.ok || !b.ok || !c.ok) return; + expect([...a.cells]).toEqual([...b.cells]); + expect([...a.cells]).not.toEqual([...c.cells]); + }); + + it("respects the offset (absolute coordinates)", () => { + const r = solve(lakes(), { cols: 4, rows: 3, offset: { x: 10, y: -2 }, orientation: "flat", seed: 1 }); + expect(r.ok).toBe(true); + if (!r.ok) return; + expect(r.cells.has("10_-2")).toBe(true); + expect(r.cells.has("13_0")).toBe(true); + expect(r.cells.has("0_0")).toBe(false); + }); + + it("keeps fixed hexes and fills around them", () => { + const fixed = { "5_5": "Water", "15_5": "Forest" }; + const model = lakes(); + const r = solve(model, { cols: 20, rows: 12, orientation: "flat", seed: 3, fixed }); + expect(r.ok).toBe(true); + if (!r.ok) return; + expect(r.cells.get("5_5")).toBe("Water"); + expect(r.cells.get("15_5")).toBe("Forest"); + expect(findViolation(model, r.cells, "flat")).toBeNull(); + }); + + it("reports fixed hexes that break the rules", () => { + const r = solve(lakes(), { + cols: 5, rows: 5, orientation: "flat", seed: 1, + fixed: { "2_2": "Water", "2_3": "Forest" }, + }); + expect(r.ok).toBe(false); + if (r.ok) return; + expect(r.reason).toBe("fixed-conflict"); + }); + + it("rejects fixed hexes with terrains the model doesn't know", () => { + const r = solve(lakes(), { cols: 3, rows: 3, orientation: "flat", seed: 1, fixed: { "1_1": "Lava" } }); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.reason).toBe("invalid-input"); + }); + + it("reports an impossible model cleanly", () => { + // A only next to B, B only next to A: a hex triangle can't be 2-coloured. + const model: HexWfcModel = { + name: "impossible", meta: {}, + terrains: [{ name: "A", weight: 1 }, { name: "B", weight: 1 }], + adjacency: [{ a: "A", b: "B", weight: 1 }], + }; + const r = solve(model, { cols: 4, rows: 4, orientation: "flat", seed: 1, maxRestarts: 1 }); + expect(r.ok).toBe(false); + if (!r.ok) expect(["contradiction", "fixed-conflict"]).toContain(r.reason); + }); + + it("neighbour weights make terrain clump", () => { + // Fraction of edges joining two different terrains: lower = clumpier. + const model = lakes(); + const mixed = (cells: Map) => { + let diff = 0, total = 0; + for (const [k, t] of cells) { + const [x, y] = k.split("_").map(Number); + for (const [nx, ny] of hexNeighbors(x, y, "flat")) { + const u = cells.get(cellKey(nx, ny)); + if (u === undefined) continue; + total++; + if (u !== t) diff++; + } + } + return diff / total; + }; + const weighted = solve(model, { cols: 30, rows: 30, orientation: "flat", seed: 9 }); + const flat = solve(model, { cols: 30, rows: 30, orientation: "flat", seed: 9, neighbourInfluence: 0 }); + expect(weighted.ok && flat.ok).toBe(true); + if (!weighted.ok || !flat.ok) return; + expect(mixed(weighted.cells)).toBeLessThan(mixed(flat.cells)); + }); + + it("solves a 60×60 map quickly", () => { + const r = solve(lakes(), { cols: 60, rows: 60, orientation: "flat", seed: 11 }); + expect(r.ok).toBe(true); + if (r.ok) expect(r.stats.ms).toBeLessThan(5000); + }); +}); + +describe("model helpers", () => { + it("restrictModel drops terrains missing from a palette", () => { + const m = restrictModel(lakes(), ["Grass", "Forest", "Sand"]); + expect(m.terrains.map((t) => t.name).sort()).toEqual(["Forest", "Grass", "Sand"]); + expect(m.adjacency.every((e) => e.a !== "Water" && e.b !== "Water")).toBe(true); + }); + + it("validateModel flags unknown terrains and bad weights", () => { + const problems = validateModel({ + name: "x", meta: {}, + terrains: [{ name: "A", weight: 1 }, { name: "A", weight: -1 }], + adjacency: [{ a: "A", b: "Z", weight: 1 }], + }); + expect(problems.some((p) => p.includes("twice"))).toBe(true); + expect(problems.some((p) => p.includes('unknown terrain "Z"'))).toBe(true); + expect(problems.some((p) => p.includes("invalid weight"))).toBe(true); + }); +}); + +describe("markdown format", () => { + it("round-trips a learned model", () => { + const m = lakes(); + const text = modelToMarkdown(m); + expect(isModelMarkdown(text)).toBe(true); + const { model, warnings } = parseModelMarkdown(text); + expect(warnings).toEqual([]); + expect(model).toEqual(m); + }); + + it("round-trips awkward names and metadata", () => { + const m: HexWfcModel = { + name: "Isles: north #2", meta: { palette: "My palette", "source-map": "a|b" }, + terrains: [{ name: "Deep | Sea", weight: 2.5 }, { name: "Peak\\s", weight: 0 }], + adjacency: [{ a: "Deep | Sea", b: "Peak\\s", weight: 1 }], + }; + expect(parseModelMarkdown(modelToMarkdown(m)).model).toEqual(m); + }); + + it("accepts hand edits: reordered pairs, blank weights, extra prose", () => { + const text = [ + "---", "hex-wfc: 1", "palette: Default", "---", + "# My generator", "", "Some notes I wrote.", "", + "## Terrains", "", "| Terrain | Weight |", "|---|---|", "| Grass | |", "| Water | 3 |", "", + "Prose between tables.", "", + "## Adjacency", "", "| Terrain | Next to | Weight |", "| --- | --- | --- |", + "| Water | Grass | 2 |", "| Grass | Water | 1 |", "| Grass | Grass | 5 |", "| Water | Water | nope |", + ].join("\n"); + const { model, warnings } = parseModelMarkdown(text); + expect(model.name).toBe("My generator"); + expect(model.meta).toEqual({ palette: "Default" }); + expect(model.terrains).toEqual([{ name: "Grass", weight: 1 }, { name: "Water", weight: 3 }]); + expect(model.adjacency).toHaveLength(3); + expect(warnings).toHaveLength(1); // the "nope" row + const r = solve(model, { cols: 8, rows: 8, orientation: "pointy", seed: 2 }); + expect(r.ok).toBe(true); + if (r.ok) { + // Water–Water was dropped, so water hexes never touch each other. + expect(findViolation(model, r.cells, "pointy")).toBeNull(); + } + }); + + it("refuses files that aren't generators", () => { + expect(isModelMarkdown("---\nterrain: Grass\n---\n# Hex")).toBe(false); + expect(() => parseModelMarkdown("# Hello")).toThrow(); + }); +}); diff --git a/tests/wfc.test.ts b/tests/wfc.test.ts deleted file mode 100644 index 095ace24..00000000 --- a/tests/wfc.test.ts +++ /dev/null @@ -1,217 +0,0 @@ -import { describe, it } from "node:test"; -import expect from "expect"; -import { - solveHexWfc, - findViolation, - learnRulesFromSample, - mulberry32, - type WfcInput, - type AdjacencyRules, -} from "../src/worldgen/wfc"; - -// A user-style palette with deliberately non-default names: the solver must -// not care what the terrains are called. -const TERRAINS = ["Deep Sea", "Shallows", "Grass", "Woods", "Hills", "Peaks", "Dunes"]; - -// "Deny list" deck — everything may touch except these pairs. -const RULES: AdjacencyRules = { - default: "allow", - pairs: [ - ["Deep Sea", "Grass"], ["Deep Sea", "Woods"], ["Deep Sea", "Hills"], - ["Deep Sea", "Peaks"], ["Deep Sea", "Dunes"], - ["Shallows", "Peaks"], ["Shallows", "Hills"], - ["Peaks", "Grass"], ["Peaks", "Dunes"], - ["Dunes", "Woods"], - ], -}; - -const WEIGHTS = { "Deep Sea": 4, Shallows: 2, Grass: 4, Woods: 3, Hills: 2, Peaks: 1, Dunes: 1 }; - -function base(overrides: Partial = {}): WfcInput { - return { - cols: 20, rows: 15, orientation: "flat", - terrains: TERRAINS, rules: RULES, weights: WEIGHTS, seed: 1234, - ...overrides, - }; -} - -describe("solveHexWfc — adjacency", () => { - for (const orientation of ["flat", "pointy"] as const) { - for (const stagger of ["odd", "even"] as const) { - it(`respects every rule (${orientation}/${stagger})`, () => { - const res = solveHexWfc(base({ orientation, stagger })); - expect(res.ok).toBe(true); - if (!res.ok) return; - expect(res.cells.size).toBe(20 * 15); - expect(findViolation(res.cells, { orientation, stagger, terrains: TERRAINS, rules: RULES })).toBeNull(); - }); - } - } - - it("honours an allow-list ('deny' default) deck", () => { - // Banded deck: each terrain may only touch itself and the next band. - const bands = ["A", "B", "C", "D"]; - const rules: AdjacencyRules = { - default: "deny", - pairs: [["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"], ["A", "B"], ["B", "C"], ["C", "D"]], - }; - const res = solveHexWfc({ cols: 25, rows: 25, orientation: "pointy", terrains: bands, rules, seed: 7 }); - expect(res.ok).toBe(true); - if (!res.ok) return; - expect(findViolation(res.cells, { orientation: "pointy", terrains: bands, rules })).toBeNull(); - }); - - it("uses absolute coords (gridOffset) for stagger parity", () => { - const offset = { x: -3, y: 5 }; - const res = solveHexWfc(base({ offset })); - expect(res.ok).toBe(true); - if (!res.ok) return; - expect(res.cells.has("-3_5")).toBe(true); - expect(res.cells.has("16_19")).toBe(true); - expect(res.cells.has("0_0")).toBe(false); - expect(findViolation(res.cells, { orientation: "flat", terrains: TERRAINS, rules: RULES })).toBeNull(); - }); - - it("treats an empty deck as 'everything allowed'", () => { - const res = solveHexWfc(base({ rules: { default: "allow", pairs: [] } })); - expect(res.ok).toBe(true); - }); - - it("never picks a weight-0 terrain for unpainted hexes", () => { - const res = solveHexWfc(base({ weights: { ...WEIGHTS, Dunes: 0 } })); - expect(res.ok).toBe(true); - if (!res.ok) return; - expect([...res.cells.values()]).not.toContain("Dunes"); - }); -}); - -describe("solveHexWfc — fixed cells", () => { - it("preserves pre-painted hexes and fills around them consistently", () => { - const fixed = { "3_3": "Deep Sea", "4_3": "Deep Sea", "10_7": "Peaks", "15_2": "Dunes", "0_0": "Woods" }; - const res = solveHexWfc(base({ fixed })); - expect(res.ok).toBe(true); - if (!res.ok) return; - for (const [k, t] of Object.entries(fixed)) expect(res.cells.get(k)).toBe(t); - expect(findViolation(res.cells, { orientation: "flat", terrains: TERRAINS, rules: RULES })).toBeNull(); - }); - - it("keeps fixed weight-0 terrains", () => { - const res = solveHexWfc(base({ weights: { ...WEIGHTS, Peaks: 0 }, fixed: { "5_5": "Peaks" } })); - expect(res.ok).toBe(true); - if (!res.ok) return; - expect(res.cells.get("5_5")).toBe("Peaks"); - }); - - it("ignores fixed hexes outside the grid", () => { - const res = solveHexWfc(base({ fixed: { "999_999": "Peaks" } })); - expect(res.ok).toBe(true); - }); - - it("reports adjacent painted hexes that break the rules as fixed-conflict", () => { - // (2,2) and (2,3) are vertical neighbours in any orientation/stagger. - const res = solveHexWfc(base({ fixed: { "2_2": "Deep Sea", "2_3": "Peaks" } })); - expect(res.ok).toBe(false); - if (res.ok) return; - expect(res.reason).toBe("fixed-conflict"); - expect(res.at).toBeDefined(); - }); - - it("reports unknown terrain names in fixed hexes as invalid-input", () => { - const res = solveHexWfc(base({ fixed: { "1_1": "Lava" } })); - expect(res.ok).toBe(false); - if (res.ok) return; - expect(res.reason).toBe("invalid-input"); - expect(res.message).toContain("Lava"); - }); -}); - -describe("solveHexWfc — determinism", () => { - it("same seed ⇒ identical map", () => { - const a = solveHexWfc(base({ seed: 42 })); - const b = solveHexWfc(base({ seed: 42 })); - expect(a.ok && b.ok).toBe(true); - if (!a.ok || !b.ok) return; - expect([...a.cells.entries()]).toEqual([...b.cells.entries()]); - }); - - it("different seeds ⇒ different maps", () => { - const a = solveHexWfc(base({ seed: 1 })); - const b = solveHexWfc(base({ seed: 2 })); - expect(a.ok && b.ok).toBe(true); - if (!a.ok || !b.ok) return; - expect([...a.cells.entries()]).not.toEqual([...b.cells.entries()]); - }); - - it("mulberry32 is deterministic and in [0,1)", () => { - const r1 = mulberry32(99), r2 = mulberry32(99); - for (let i = 0; i < 100; i++) { - const v = r1(); - expect(v).toBe(r2()); - expect(v >= 0 && v < 1).toBe(true); - } - }); -}); - -describe("solveHexWfc — contradictions", () => { - it("reports an unsatisfiable deck cleanly instead of throwing or looping", () => { - // Two terrains that may only touch each other: a 2-colouring, impossible - // on a hex grid because neighbouring hexes form triangles. - const res = solveHexWfc({ - cols: 6, rows: 6, orientation: "flat", - terrains: ["X", "Y"], rules: { default: "deny", pairs: [["X", "Y"]] }, - seed: 3, maxBacktracks: 50, maxRestarts: 2, - }); - expect(res.ok).toBe(false); - if (res.ok) return; - expect(["contradiction", "fixed-conflict"]).toContain(res.reason); - expect(res.message.length).toBeGreaterThan(0); - }); - - it("reports contradiction (not fixed-conflict) when only search fails", () => { - // Initial propagation can't see the triangle problem (every cell still - // has X and Y), so this exercises backtracking + restarts to exhaustion. - const res = solveHexWfc({ - cols: 6, rows: 6, orientation: "pointy", - terrains: ["X", "Y"], rules: { default: "deny", pairs: [["X", "Y"]] }, - seed: 5, maxBacktracks: 20, maxRestarts: 1, - }); - expect(res.ok).toBe(false); - if (res.ok) return; - expect(res.reason).toBe("contradiction"); - expect(res.stats.attempts).toBe(2); - }); - - it("rejects empty input", () => { - expect(solveHexWfc(base({ terrains: [] })).ok).toBe(false); - expect(solveHexWfc(base({ cols: 0 })).ok).toBe(false); - }); -}); - -describe("learnRulesFromSample", () => { - it("derives a deck that the sample itself satisfies, and regenerates from it", () => { - const sample = solveHexWfc(base({ cols: 12, rows: 12, seed: 11 })); - expect(sample.ok).toBe(true); - if (!sample.ok) return; - const { rules, weights } = learnRulesFromSample(sample.cells, "flat"); - expect(findViolation(sample.cells, { orientation: "flat", terrains: TERRAINS, rules })).toBeNull(); - const regen = solveHexWfc(base({ rules, weights, seed: 12 })); - expect(regen.ok).toBe(true); - if (!regen.ok) return; - expect(findViolation(regen.cells, { orientation: "flat", terrains: TERRAINS, rules })).toBeNull(); - }); -}); - -describe("solveHexWfc — performance", () => { - it("solves a 60×60 map (3600 hexes) quickly", () => { - const t0 = Date.now(); - const res = solveHexWfc(base({ cols: 60, rows: 60, seed: 2026 })); - const ms = Date.now() - t0; - expect(res.ok).toBe(true); - if (!res.ok) return; - expect(res.cells.size).toBe(3600); - expect(findViolation(res.cells, { orientation: "flat", terrains: TERRAINS, rules: RULES })).toBeNull(); - console.log(`[wfc] 60x60: ${ms} ms, decisions=${res.stats.decisions}, backtracks=${res.stats.backtracks}, attempts=${res.stats.attempts}`); - // Generous bound so CI noise doesn't flake; real number is logged above. - expect(ms).toBeLessThan(5000); - }); -}); diff --git a/tests/worldgenGenerators.test.ts b/tests/worldgenGenerators.test.ts new file mode 100644 index 00000000..b56ce2f8 --- /dev/null +++ b/tests/worldgenGenerators.test.ts @@ -0,0 +1,142 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { TFile, TFolder } from "obsidian"; +import { + generatorsFolder, + generatorFitsPalette, + listGenerators, + readMapTerrain, + saveGeneratorFromMap, + generateMapTerrain, +} from "../src/worldgen/generators"; +import { findViolation, type HexWfcModel } from "../packages/hex-wfc/src"; +import type HexmakerPlugin from "../src/HexmakerPlugin"; + +/** + * In-memory vault + plugin stub. Hex notes are represented only by their + * terrain frontmatter; written files are kept as text. + */ +function makePlugin(painted: Record) { + const files = new Map(); + const folders = new Set(); + const fileObj = (path: string) => { + const f = Object.create(TFile.prototype) as TFile; + f.path = path; + f.basename = path.split("/").pop()!.replace(/\.md$/, ""); + return f; + }; + const hexPath = (x: number, y: number, map: string) => `world/hexes/${map}/${x}_${y}.md`; + const terrainByPath = new Map( + Object.entries(painted).map(([k, t]) => { + const [x, y] = k.split("_").map(Number); + return [hexPath(x, y, "sample"), t]; + }), + ); + const app = { + vault: { + getAbstractFileByPath: (p: string) => { + if (files.has(p) || terrainByPath.has(p)) return fileObj(p); + if (folders.has(p)) return Object.create(TFolder.prototype) as TFolder; + return null; + }, + createFolder: async (p: string) => void folders.add(p), + create: async (p: string, text: string) => { + files.set(p, text); + return fileObj(p); + }, + getMarkdownFiles: () => [...files.keys()].map(fileObj), + cachedRead: async (f: TFile) => files.get(f.path) ?? "", + }, + metadataCache: { + getFileCache: (f: TFile) => { + const terrain = terrainByPath.get(f.path); + return terrain ? { frontmatter: { terrain } } : null; + }, + }, + }; + const plugin = { + app, + settings: { + worldFolder: "world", + hexOrientation: "flat", + staggerOffset: "odd", + maps: [{ name: "sample", paletteName: "Default", gridSize: { cols: 12, rows: 10 }, gridOffset: { x: 0, y: 0 } }], + }, + getMap: (name: string) => plugin.settings.maps.find((m) => m.name === name), + hexPath, + } as unknown as HexmakerPlugin; + return { plugin, files }; +} + +/** A 12×10 painted sample: a lake ringed by sand in grassland. */ +function lakeSample(): Record { + const out: Record = {}; + for (let x = 0; x < 12; x++) + for (let y = 0; y < 10; y++) { + const d = (x - 5) ** 2 + (y - 5) ** 2; + out[`${x}_${y}`] = d < 6 ? "Water" : d < 14 ? "Sand" : "Grass"; + } + return out; +} + +describe("worldgen generators", () => { + it("stores generators under the world folder", () => { + const { plugin } = makePlugin({}); + expect(generatorsFolder(plugin)).toBe("world/generators"); + }); + + it("reads painted terrain from the map's hex notes", () => { + const { plugin } = makePlugin({ "0_0": "Grass", "3_4": "Water" }); + expect([...readMapTerrain(plugin, "sample")]).toEqual([["0_0", "Grass"], ["3_4", "Water"]]); + }); + + it("learns from a map, saves a readable file, and lists it back", async () => { + const { plugin, files } = makePlugin(lakeSample()); + const saved = await saveGeneratorFromMap(plugin, "sample", "My Lakes"); + expect("error" in saved).toBe(false); + if ("error" in saved) return; + expect(saved.file.path).toBe("world/generators/my-lakes.md"); + const text = files.get("world/generators/my-lakes.md")!; + expect(text).toContain("hex-wfc: 1"); + expect(text).toContain("palette: Default"); + expect(text).toContain("source-map: sample"); + expect(text).toMatch(/\| (Water \| Sand|Sand \| Water) \|/); + expect(text).not.toMatch(/\| (Water \| Grass|Grass \| Water) \|/); // never touched + + // A second save with the same name doesn't overwrite. + const again = await saveGeneratorFromMap(plugin, "sample", "my-lakes"); + expect("error" in again ? "" : again.file.path).toBe("world/generators/my-lakes-2.md"); + + const listed = await listGenerators(plugin); + expect(listed.map((g) => g.model.name)).toEqual(["my-lakes", "my-lakes-2"]); + expect(listed[0].model.adjacency).toEqual(saved.model.adjacency); + }); + + it("refuses to learn from an unpainted map", async () => { + const { plugin } = makePlugin({}); + const r = await saveGeneratorFromMap(plugin, "sample", "x"); + expect("error" in r).toBe(true); + }); + + it("only offers generators whose terrains are all in the palette", () => { + const model: HexWfcModel = { + name: "m", meta: {}, + terrains: [{ name: "Grass", weight: 3 }, { name: "Water", weight: 1 }, { name: "Lava", weight: 0 }], + adjacency: [], + }; + expect(generatorFitsPalette(model, ["Grass", "Water", "Hills"])).toBe(true); // weight-0 Lava ignored + expect(generatorFitsPalette(model, ["Grass"])).toBe(false); + }); + + it("generates a full new map that obeys the learned rules", async () => { + const { plugin } = makePlugin(lakeSample()); + const saved = await saveGeneratorFromMap(plugin, "sample", "lakes"); + if ("error" in saved) throw new Error(saved.error); + const r = generateMapTerrain(plugin, saved.model, ["Grass", "Sand", "Water"], 30, 20, { x: 5, y: 5 }, "odd", 42); + expect(r.ok).toBe(true); + if (!r.ok) return; + expect(r.cells.size).toBe(600); + expect(r.cells.has("5_5")).toBe(true); + expect(findViolation(saved.model, r.cells, "flat", "odd")).toBeNull(); + }); +}); From adf3f05231b41e00ac0525c4fa793cb6cd44042e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 15:50:38 -0400 Subject: [PATCH 003/558] feat(worldgen): growth moves, scale-invariant patches, directional bias, Generator tab hex-wfc: - Learning measures each terrain's patches (size-weighted mean size, elongation, thickness) and classifies them as blob / line / none. Patch size is stored as a share of the map, so a generator learned on 50x50 reproduces the same relative features and terrain mix on 20x20. - Solver growth moves: a hex that starts a new blob/line patch spreads (blob: compact frontier; line: heading with learned turn rate, both ends). Each move is place + propagate, undone alone on contradiction. - Scale fixes found while tuning: grow only from new-patch seeds; divide seed odds by the realised patch size; score growth terrains on their border composition and chance-level self-adjacency (learned self-adjacency only for enclosed holes); frequency feedback default 2. - Directional bias: learned 3x3 layout per terrain; bias 0..1 keeps terrain where it sat in the example (ocean along the bottom). - Randomness: mixes a context-free weight-only pick into each choice so rare terrain (towns) peppers the map. Default 0.1. - Settings saved in the file's frontmatter (feature-size, directional-bias, clumping, mix-strength, scatter, randomness); a Layout table; Terrains table gains Patch % / Shape / Turn. Older 2-column files still load. Hexmaker: - Maps modal gets a Generator tab after New map: "Generate solver from map" (moved from Properties) and per-generator sliders saved to the generator file's frontmatter. New map picks a generator and uses its settings. dev/wfc-ascii.mts, wfc-mix.mts, wfc-bias.mts print sample maps and terrain mix by size for tuning. Co-Authored-By: Claude Opus 5.5 (1M context) --- dev/wfc-ascii.mts | 45 ++++-- dev/wfc-bias.mts | 19 +++ dev/wfc-mix.mts | 20 +++ packages/hex-wfc/README.md | 19 ++- packages/hex-wfc/src/format.ts | 110 +++++++++++++-- packages/hex-wfc/src/grid.ts | 22 +++ packages/hex-wfc/src/index.ts | 9 +- packages/hex-wfc/src/learn.ts | 157 ++++++++++++++++++++- packages/hex-wfc/src/model.ts | 61 ++++++++ packages/hex-wfc/src/solve.ts | 250 ++++++++++++++++++++++++++++++--- src/hex-map/MapModal.ts | 191 ++++++++++++++++++++++--- src/worldgen/generators.ts | 20 +++ tests/hexWfc.test.ts | 236 +++++++++++++++++++++++++++++++ 13 files changed, 1088 insertions(+), 71 deletions(-) create mode 100644 dev/wfc-bias.mts create mode 100644 dev/wfc-mix.mts diff --git a/dev/wfc-ascii.mts b/dev/wfc-ascii.mts index c147232b..4557de13 100644 --- a/dev/wfc-ascii.mts +++ b/dev/wfc-ascii.mts @@ -1,18 +1,41 @@ -// Prints a generated map as ASCII for eyeballing hex-wfc output. -// Usage (from WSL): npx tsx dev/wfc-ascii.mts [seed] [flat|pointy] +// Prints generated maps as ASCII for eyeballing hex-wfc output. +// Usage (from WSL): npx tsx dev/wfc-ascii.mts [seed] [flat|pointy] [featureSize] +// Learns from a 50×50 example (lakes ringed by sand, a mountain ridge, forest +// patches on grass), then generates 20×20 and 50×50 maps. import { learnModel, solve, cellKey } from "../packages/hex-wfc/src"; const seed = Number(process.argv[2] ?? 5); const o = (process.argv[3] ?? "flat") as "flat" | "pointy"; +const featureSize = Number(process.argv[4] ?? 1); + const ex = new Map(); -for (let x = 0; x < 20; x++) for (let y = 0; y < 16; y++) { - const dx = x - 6, dy = y - 7; let t = "G"; - if (dx*dx+dy*dy < 12) t = "~"; else if (dx*dx+dy*dy < 22) t = "s"; else if (x >= 14) t = "F"; +const lakes = [[12, 14, 4], [36, 34, 3.5]]; +const forests = [[38, 10, 5], [10, 38, 4]]; +for (let x = 0; x < 50; x++) for (let y = 0; y < 50; y++) { + let t = "G"; + for (const [fx, fy, r] of forests) if ((x - fx) ** 2 + (y - fy) ** 2 < r * r) t = "F"; + // Ridge: a 2-wide diagonal-ish band + const ridgeY = 0.6 * x + 8 + 3 * Math.sin(x / 5); + if (x > 18 && x < 46 && Math.abs(y - ridgeY) < 1.1) t = "^"; + for (const [lx, ly, r] of lakes) { + const d = Math.sqrt((x - lx) ** 2 + (y - ly) ** 2); + if (d < r) t = "~"; else if (d < r + 1.3) t = "s"; + } ex.set(cellKey(x, y), t); } const m = learnModel(ex, { name: "example", orientation: o }); -const r = solve(m, { cols: 50, rows: 18, orientation: o, seed }); -if (!r.ok) { console.log(r.message); process.exit(); } -const counts: Record = {}; -for (const t of r.cells.values()) counts[t] = (counts[t] ?? 0) + 1; -console.log("seed", seed, o, JSON.stringify(counts), JSON.stringify(r.stats)); -for (let y = 0; y < 18; y++) { let s = ""; for (let x = 0; x < 50; x++) s += r.cells.get(cellKey(x, y)); console.log(s); } +console.log(m.terrains.map((t) => `${t.name}: w${t.weight} patch ${(t.patch! * 100).toFixed(1)}% ${t.shape}${t.turn ? " turn " + t.turn : ""}`).join("\n")); +const share = (cells: Map) => { + const c: Record = {}; + for (const t of cells.values()) c[t] = (c[t] ?? 0) + 1; + return Object.entries(c).map(([k, v]) => `${k} ${((100 * v) / cells.size).toFixed(0)}%`).join(" "); +}; +console.log("example mix:", share(ex)); +const show = (cells: Map, cols: number, rows: number) => { + for (let y = 0; y < rows; y++) { let s = ""; for (let x = 0; x < cols; x++) s += cells.get(cellKey(x, y)); console.log(s); } +}; +for (const [cols, rows] of [[20, 20], [50, 30]]) { + const r = solve(m, { cols, rows, orientation: o, seed, featureSize }); + if (!r.ok) { console.log(cols, rows, r.message); continue; } + console.log(`\n${cols}x${rows}`, share(r.cells), JSON.stringify(r.stats)); + show(r.cells, cols, rows); +} diff --git a/dev/wfc-bias.mts b/dev/wfc-bias.mts new file mode 100644 index 00000000..b8533e7f --- /dev/null +++ b/dev/wfc-bias.mts @@ -0,0 +1,19 @@ +// Directional bias check: example has ocean along the bottom and forest in the +// top-left. Usage (from WSL): npx tsx dev/wfc-bias.mts [seed] +import { learnModel, solve, cellKey } from "../packages/hex-wfc/src"; +const seed = Number(process.argv[2] ?? 3); +const ex = new Map(); +for (let x = 0; x < 40; x++) for (let y = 0; y < 40; y++) { + const coast = 30 + 2 * Math.sin(x / 4); + let t = y > coast ? "~" : y > coast - 1.5 ? "s" : "G"; + if (t === "G" && Math.hypot(x - 8, y - 8) < 6) t = "F"; + ex.set(cellKey(x, y), t); +} +const m = learnModel(ex, { name: "coast", orientation: "flat" }); +for (const t of m.terrains) console.log(t.name, t.shape, t.layout?.join(" ")); +for (const bias of [0, 1]) { + const r = solve(m, { cols: 30, rows: 16, orientation: "flat", seed, directionalBias: bias }); + if (!r.ok) { console.log(r.message); continue; } + console.log(`\nbias ${bias}`); + for (let y = 0; y < 16; y++) { let s = ""; for (let x = 0; x < 30; x++) s += r.cells.get(cellKey(x, y)); console.log(s); } +} diff --git a/dev/wfc-mix.mts b/dev/wfc-mix.mts new file mode 100644 index 00000000..1f331694 --- /dev/null +++ b/dev/wfc-mix.mts @@ -0,0 +1,20 @@ +// Average terrain mix over several seeds at different sizes vs the example. +import { learnModel, solve, cellKey } from "../packages/hex-wfc/src"; +const ex = new Map(); +const lakes = [[12, 14, 4], [36, 34, 3.5]], forests = [[38, 10, 5], [10, 38, 4]]; +for (let x = 0; x < 50; x++) for (let y = 0; y < 50; y++) { + let t = "Grass"; + for (const [fx, fy, r] of forests) if ((x - fx) ** 2 + (y - fy) ** 2 < r * r) t = "Forest"; + if (x > 18 && x < 46 && Math.abs(y - (0.6 * x + 8 + 3 * Math.sin(x / 5))) < 1.1) t = "Ridge"; + for (const [lx, ly, r] of lakes) { const d = Math.hypot(x - lx, y - ly); if (d < r) t = "Water"; else if (d < r + 1.3) t = "Sand"; } + ex.set(cellKey(x, y), t); +} +const share = (c: Map) => { const o: Record = {}; for (const t of c.values()) o[t] = (o[t] ?? 0) + 100 / c.size; return o; }; +const fmt = (o: Record) => Object.entries(o).sort().map(([k, v]) => `${k} ${v.toFixed(1)}`).join(" "); +console.log("example ", fmt(share(ex))); +const m = learnModel(ex, { name: "w", orientation: "flat" }); +for (const n of [20, 30, 50, 80]) { + const avg: Record = {}; const seeds = [11, 12, 13, 14, 15, 16, 17, 18]; + for (const seed of seeds) { const r = solve(m, { cols: n, rows: n, orientation: "flat", seed, frequencyFeedback: Number(process.argv[2] ?? 2), scatter: Number(process.argv[3] ?? 3) }); if (r.ok) for (const [k, v] of Object.entries(share(r.cells))) avg[k] = (avg[k] ?? 0) + v / seeds.length; } + console.log(`${n}x${n}`.padEnd(8), fmt(avg)); +} diff --git a/packages/hex-wfc/README.md b/packages/hex-wfc/README.md index 644ef6c3..306dea27 100644 --- a/packages/hex-wfc/README.md +++ b/packages/hex-wfc/README.md @@ -10,6 +10,8 @@ It lives inside the [Hexmaker](https://github.com/sbuffkin/hexmaker) Obsidian pl - **Learning**: `learnModel` counts how often each terrain appears and how often each pair of terrains touches. If two terrains never touch in the example, they can never touch in generated maps. That includes a terrain next to itself. - **Solving**: `solve` runs WFC with propagation, backtracking and restarts. Pairs with weight 0 are hard rules. Pair weights are also soft rules: each choice is scored from the neighbours that are already decided, so a lake in the example grows as a lake rather than scattering. `neighbourInfluence` sets how strong that effect is. +- **Growth**: learning also measures the shape of each terrain's patches. Compact patches (lakes, forests) become `blob`, stretched ones (ranges, ridges) become `line`, and backgrounds, shores and scattered hexes become `none`. When the solver starts a new patch of a `blob` or `line` terrain, it gets extra moves to spread: outward for blobs, forward with occasional turns for lines. Every move still obeys the hard rules. +- **Scale**: patch sizes are stored as a share of the map, not a hex count. A generator learned on a 50×50 map makes lakes and ranges of the same relative size on a 20×20 map, and the overall terrain mix stays close to the example's at any size. `featureSize` multiplies on top: below 1 gives more, smaller features, above 1 fewer, bigger ones. - **Fixed hexes**: pass hexes that are already painted as `fixed`. They are never changed, and the rest of the map is filled around them. - **Deterministic**: the same model, options and seed always give the same map. @@ -43,10 +45,11 @@ palette: Default --- ## Terrains -| Terrain | Weight | -| --- | ---: | -| Grass | 120 | -| Water | 40 | +| Terrain | Weight | Patch % | Shape | Turn | +| --- | ---: | ---: | --- | ---: | +| Grass | 120 | 80 | none | | +| Water | 40 | 3.5 | blob | | +| Ridge | 10 | 1.2 | line | 0.2 | ## Adjacency @@ -58,12 +61,18 @@ palette: Default ``` - A pair that isn't listed, or has weight 0, can never touch. +- *Patch %*, *Shape* and *Turn* are optional. A file with only *Terrain* and *Weight* still works, without growth. - Pairs work in both directions, so *A | B* also covers *B | A*. - Extra frontmatter keys are kept in `model.meta`. +## Tuning + +The defaults were tuned by eye and by comparing terrain mix across sizes. Run `dev/wfc-ascii.mts` and `dev/wfc-mix.mts` in the Hexmaker repo to check changes. Without `scatter`, enclosed features (a lake inside its shore) never start. Without growth-aware scoring, the most common terrain swallows the map. + ## Limits -- This is the simple tiled model: only which terrain sits next to which. It learns blobs (lakes, forests, coastlines) well, but not long thin features. A river drawn as hex terrain comes back as streaks and clumps, not as a connected line. +- Growth gives ridges and ranges a direction, but nothing guarantees a feature exists or reaches anywhere in particular. A river that must run from a map edge to the sea needs a placed feature (planned). +- Learned `line` features are one hex wide, even if the example's are wider. - The solver scans every cell on each step, so the cost grows with roughly the square of the map size. 60×60 takes well under a second. ## License diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index 52260042..0844ed7f 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -16,11 +16,21 @@ * ... */ -import type { HexWfcModel } from "./model"; +import { LAYOUT_BINS, type HexWfcModel, type GeneratorSettings } from "./model"; export const FORMAT_VERSION = 1; const MARKER = "hex-wfc"; +/** Frontmatter key for each saved solver setting. */ +export const SETTING_KEYS: Record = { + featureSize: "feature-size", + directionalBias: "directional-bias", + neighbourInfluence: "clumping", + frequencyFeedback: "mix-strength", + scatter: "scatter", + randomness: "randomness", +}; + function yamlValue(v: string): string { return /^[A-Za-z0-9_][A-Za-z0-9 _./()-]*$/.test(v) && !v.endsWith(" ") ? v : JSON.stringify(v); } @@ -43,10 +53,16 @@ const num = (n: number) => String(Math.round(n * 1000) / 1000); export function modelToMarkdown(model: HexWfcModel): string { const fm = [`${MARKER}: ${FORMAT_VERSION}`, `name: ${yamlValue(model.name)}`]; + const settingKeys = new Set(Object.values(SETTING_KEYS)); for (const [k, v] of Object.entries(model.meta)) { - if (k === MARKER || k === "name") continue; + if (k === MARKER || k === "name" || settingKeys.has(k)) continue; fm.push(`${k}: ${yamlValue(v)}`); } + for (const [field, key] of Object.entries(SETTING_KEYS) as [keyof GeneratorSettings, string][]) { + const v = model.settings?.[field]; + if (v !== undefined) fm.push(`${key}: ${num(v)}`); + } + const withLayout = model.terrains.filter((t) => t.layout?.length === 9); const lines = [ "---", ...fm, @@ -57,15 +73,27 @@ export function modelToMarkdown(model: HexWfcModel): string { "A wave function collapse generator. You can edit both tables by hand.", "", "- **Terrains**: *Weight* is how common the terrain is. 0 means it is never placed.", + " *Patch %* is the size of a typical patch as a share of the map, so features", + " scale with the map. *Shape* is how it spreads: `blob` (lakes, forests),", + " `line` (ranges, ridges) or `none` (backgrounds, shores, scattered hexes).", + " *Turn* is how often a `line` changes direction (0 to 1).", "- **Adjacency**: pairs that may touch, and how often (higher is more likely).", " A pair that isn't listed can never touch, including a terrain next to itself.", " Order doesn't matter, so *A | B* also covers *B | A*.", + "- **Layout** (optional): where each terrain sat in the example map, in a 3×3", + " grid. 1 means as common there as anywhere; 3 means three times as common.", + " Directional bias uses it to keep, say, an ocean along the bottom.", + "- Frontmatter settings (optional): `feature-size`, `directional-bias`,", + " `clumping`, `mix-strength`, `scatter` and `randomness`.", "", "## Terrains", "", - "| Terrain | Weight |", - "| --- | ---: |", - ...model.terrains.map((t) => `| ${cell(t.name)} | ${num(t.weight)} |`), + "| Terrain | Weight | Patch % | Shape | Turn |", + "| --- | ---: | ---: | --- | ---: |", + ...model.terrains.map( + (t) => + `| ${cell(t.name)} | ${num(t.weight)} | ${t.patch === undefined ? "" : num(t.patch * 100)} | ${t.shape ?? ""} | ${t.turn === undefined ? "" : num(t.turn)} |`, + ), "", "## Adjacency", "", @@ -73,6 +101,16 @@ export function modelToMarkdown(model: HexWfcModel): string { "| --- | --- | ---: |", ...model.adjacency.map((e) => `| ${cell(e.a)} | ${cell(e.b)} | ${num(e.weight)} |`), "", + ...(withLayout.length + ? [ + "## Layout", + "", + `| Terrain | ${LAYOUT_BINS.join(" | ")} |`, + `| --- |${" ---: |".repeat(9)}`, + ...withLayout.map((t) => `| ${cell(t.name)} | ${t.layout!.map(num).join(" | ")} |`), + "", + ] + : []), ]; return lines.join("\n"); } @@ -116,6 +154,8 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par const lines = text.split(/\r?\n/); const warnings: string[] = []; const meta: Record = {}; + let settings: GeneratorSettings | undefined; + const layouts = new Map(); let name = ""; let version: number | null = null; @@ -128,7 +168,14 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par const value = parseYamlValue(m[2]); if (key === MARKER) version = Number(value); else if (key === "name") name = value; - else meta[key] = value; + else { + const field = (Object.keys(SETTING_KEYS) as (keyof GeneratorSettings)[]).find((f) => SETTING_KEYS[f] === key); + if (field) { + const n = Number(value); + if (value !== "" && Number.isFinite(n) && n >= 0) (settings ??= {})[field] = n; + else warnings.push(`Setting "${key}: ${value}" isn't a number ≥ 0, ignored`); + } else meta[key] = value; + } } i++; } @@ -136,8 +183,11 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par if (version > FORMAT_VERSION) warnings.push(`File is ${MARKER} version ${version}; this reader understands version ${FORMAT_VERSION}`); - let section: "terrains" | "adjacency" | null = null; + let section: "terrains" | "adjacency" | "layout" | null = null; let headerSeen = false; + // Column index by lower-cased header name, for the Terrains table's + // optional columns. Positions are the fallback for the required ones. + let columns = new Map(); const model: HexWfcModel = { name: "", terrains: [], adjacency: [], meta }; const weightOf = (raw: string | undefined, where: string): number | null => { if (raw === undefined || raw === "") return 1; @@ -155,7 +205,7 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par if (h) { const title = h[1].trim().toLowerCase(); if (!name && line.trim().startsWith("# ")) name = h[1].trim(); - section = title === "terrains" ? "terrains" : title === "adjacency" ? "adjacency" : null; + section = title === "terrains" || title === "adjacency" || title === "layout" ? title : null; headerSeen = false; continue; } @@ -168,13 +218,45 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par if (cells.every((c) => /^:?-+:?$/.test(c))) continue; // separator if (!headerSeen) { headerSeen = true; // first row of each table is the header + columns = new Map(cells.map((c, idx) => [c.toLowerCase(), idx])); + continue; + } + const sectionTitle = section === "terrains" ? "Terrains" : section === "adjacency" ? "Adjacency" : "Layout"; + const where = `${sectionTitle} row "${cells.join(" | ")}"`; + if (section === "layout") { + if (!cells[0]) continue; + const values = LAYOUT_BINS.map((b) => Number(cells[columns.get(b.toLowerCase()) ?? -1])); + if (values.every((v) => Number.isFinite(v) && v >= 0)) layouts.set(cells[0], values); + else warnings.push(`${where}: needs 9 numbers ≥ 0 under ${LAYOUT_BINS.join(", ")}, row skipped`); continue; } - const where = `${section === "terrains" ? "Terrains" : "Adjacency"} row "${cells.join(" | ")}"`; if (section === "terrains") { if (!cells[0]) continue; - const w = weightOf(cells[1], where); - if (w !== null) model.terrains.push({ name: cells[0], weight: w }); + const col = (name: string) => { + const idx = columns.get(name); + return idx === undefined ? undefined : cells[idx] || undefined; + }; + const w = weightOf(col("weight") ?? cells[1], where); + if (w === null) continue; + const entry: HexWfcModel["terrains"][number] = { name: cells[0], weight: w }; + const patch = col("patch %") ?? col("patch"); + if (patch !== undefined) { + const n = Number(patch.replace(/%$/, "")); + if (Number.isFinite(n) && n >= 0 && n <= 100) entry.patch = Math.round(n * 1000) / 100000; + else warnings.push(`${where}: patch "${patch}" isn't a percentage, ignored`); + } + const shape = col("shape")?.toLowerCase(); + if (shape !== undefined) { + if (shape === "blob" || shape === "line" || shape === "none") entry.shape = shape; + else warnings.push(`${where}: shape "${shape}" should be blob, line or none, ignored`); + } + const turn = col("turn"); + if (turn !== undefined) { + const n = Number(turn); + if (Number.isFinite(n) && n >= 0 && n <= 1) entry.turn = n; + else warnings.push(`${where}: turn "${turn}" should be between 0 and 1, ignored`); + } + model.terrains.push(entry); } else { if (!cells[0] || !cells[1]) { if (cells.some(Boolean)) warnings.push(`${where}: needs two terrains, row skipped`); @@ -185,6 +267,12 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par } } + for (const [t, values] of layouts) { + const entry = model.terrains.find((e) => e.name === t); + if (entry) entry.layout = values; + else warnings.push(`Layout row "${t}" isn't in the Terrains table, ignored`); + } + if (settings) model.settings = settings; model.name = name || fallbackName; return { model, warnings }; } diff --git a/packages/hex-wfc/src/grid.ts b/packages/hex-wfc/src/grid.ts index 86b4e299..e1be3811 100644 --- a/packages/hex-wfc/src/grid.ts +++ b/packages/hex-wfc/src/grid.ts @@ -35,6 +35,28 @@ export function hexNeighbors( : [[x + 1, y], [x - 1, y], [x, y - 1], [x + 1, y - 1], [x, y + 1], [x + 1, y + 1]]; } +/** + * Position of the hex centre in a plane where neighbouring centres are + * √3 apart (unit hex size). Used for shape measurements, not drawing. + */ +export function hexCenter(x: number, y: number, orientation: Orientation, stagger: Stagger = "odd"): [number, number] { + const isShifted = (n: number) => (stagger === "odd" ? n % 2 !== 0 : n % 2 === 0); + const r3 = Math.sqrt(3); + return orientation === "flat" + ? [x * 1.5, y * r3 + (isShifted(x) ? r3 / 2 : 0)] + : [x * r3 + (isShifted(y) ? r3 / 2 : 0), y * 1.5]; +} + +/** + * Neighbour indices (into the hexNeighbors() result) in clockwise ring + * order. The index → compass direction mapping is the same for shifted and + * unshifted hexes, so a heading can be kept as an index into this ring. + */ +export function directionRing(orientation: Orientation): number[] { + // flat: 0 N, 2 NE, 3 SE, 1 S, 5 SW, 4 NW; pointy: 0 E, 5 SE, 4 SW, 1 W, 2 NW, 3 NE + return orientation === "flat" ? [0, 2, 3, 1, 5, 4] : [0, 5, 4, 1, 2, 3]; +} + /** Accept either a Map or a plain object of "x_y" → terrain. */ export function toCellMap(cells: Map | Record): Map { return cells instanceof Map ? cells : new Map(Object.entries(cells)); diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index a68f31f1..5a0751a0 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -1,4 +1,4 @@ -export { hexNeighbors, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; +export { hexNeighbors, hexCenter, directionRing, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; export { adjacencyLookup, validateModel, @@ -6,14 +6,19 @@ export { type HexWfcModel, type TerrainEntry, type AdjacencyEntry, + type GrowthShape, + type GeneratorSettings, + DEFAULT_SETTINGS, + LAYOUT_BINS, } from "./model"; -export { learnModel, type LearnOptions } from "./learn"; +export { learnModel, measurePatches, measureLayout, SHAPE_THRESHOLDS, type LearnOptions } from "./learn"; export { solve, findViolation, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; export { modelToMarkdown, parseModelMarkdown, isModelMarkdown, FORMAT_VERSION, + SETTING_KEYS, type ParseResult, } from "./format"; export { mulberry32, randomSeed } from "./rng"; diff --git a/packages/hex-wfc/src/learn.ts b/packages/hex-wfc/src/learn.ts index 5910242b..7afc4425 100644 --- a/packages/hex-wfc/src/learn.ts +++ b/packages/hex-wfc/src/learn.ts @@ -1,5 +1,5 @@ -import { hexNeighbors, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; -import type { HexWfcModel } from "./model"; +import { hexNeighbors, hexCenter, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; +import type { HexWfcModel, GrowthShape } from "./model"; export interface LearnOptions { name: string; @@ -42,8 +42,10 @@ export function learnModel( } } + const shapes = measurePatches(map, opts.orientation, stagger); + const layouts = measureLayout(map); const terrains = [...terrainCount] - .map(([name, weight]) => ({ name, weight })) + .map(([name, weight]) => ({ name, weight, ...shapes.get(name), layout: layouts.get(name) })) .sort((p, q) => q.weight - p.weight || p.name.localeCompare(q.name)); const order = new Map(terrains.map((t, i) => [t.name, i])); const adjacency = [...edgeCount.values()] @@ -56,3 +58,152 @@ export function learnModel( return { name: opts.name, terrains, adjacency, meta: { ...(opts.meta ?? {}) } }; } + +/** Thresholds for classifying patch shapes. Exported for tests and tuning. */ +export const SHAPE_THRESHOLDS = { + /** Size-weighted mean patch below this many hexes → "none" (scattered). */ + minPatchHexes: 2.5, + /** Patch above this share of the map → "none" (it's the background). */ + maxPatchShare: 0.3, + /** Long axis / short axis at or above this → "line". */ + lineElongation: 2.2, + /** Mean same-terrain neighbours at or above this → "blob"; below → thin + * (shores, rings), left to the neighbour rules. */ + blobThickness: 3.5, +}; + +/** + * Measure each terrain's connected patches and turn them into a growth style. + * Only shape is used, never names, so it works for any palette. + * + * - patch: size-weighted mean patch size (Σs² / Σs, so one big lake counts + * for more than a few stray specks), as a fraction of all painted hexes. + * - elongation: √(λ1/λ2) of the covariance of hex centres, per patch. + * - thickness: mean number of same-terrain neighbours. + */ +export function measurePatches( + cells: Map, + orientation: Orientation, + stagger: Stagger = "odd", +): Map { + const seen = new Set(); + const stats = new Map(); + const total = cells.size; + + for (const [start, t] of cells) { + if (seen.has(start)) continue; + // Flood-fill one patch. + const patch: [number, number][] = []; + const stack = [start]; + seen.add(start); + let sameNeighbours = 0; + while (stack.length) { + const key = stack.pop()!; + const xy = parseCellKey(key); + if (!xy) continue; + patch.push(xy); + for (const [nx, ny] of hexNeighbors(xy[0], xy[1], orientation, stagger)) { + const nk = cellKey(nx, ny); + if (cells.get(nk) !== t) continue; + sameNeighbours++; + if (!seen.has(nk)) { + seen.add(nk); + stack.push(nk); + } + } + } + const s = patch.length; + const st = stats.get(t) ?? { sumS: 0, sumS2: 0, elong: 0, thick: 0, weighted: 0 }; + st.sumS += s; + st.sumS2 += s * s; + if (s >= 3) { + // Principal axes of the patch. + let mx = 0, my = 0; + const pts = patch.map(([x, y]) => hexCenter(x, y, orientation, stagger)); + for (const [px, py] of pts) { mx += px; my += py; } + mx /= s; my /= s; + let sxx = 0, syy = 0, sxy = 0; + for (const [px, py] of pts) { + sxx += (px - mx) ** 2; syy += (py - my) ** 2; sxy += (px - mx) * (py - my); + } + sxx /= s; syy /= s; sxy /= s; + const tr = sxx + syy, det = sxx * syy - sxy * sxy; + const disc = Math.sqrt(Math.max(0, (tr * tr) / 4 - det)); + const l1 = tr / 2 + disc, l2 = Math.max(0, tr / 2 - disc); + const elongation = Math.sqrt((l1 + 0.25) / (l2 + 0.25)); + // Weight by size so big patches decide the style. + st.elong += elongation * s; + st.thick += (sameNeighbours / s) * s; + st.weighted += s; + } + stats.set(t, st); + } + + const out = new Map(); + const T = SHAPE_THRESHOLDS; + for (const [t, st] of stats) { + const meanPatch = st.sumS2 / st.sumS; + const share = total ? meanPatch / total : 0; + const patch = Math.round(share * 10000) / 10000; + if (meanPatch < T.minPatchHexes || share > T.maxPatchShare || st.weighted === 0) { + out.set(t, { patch, shape: "none" }); + continue; + } + const elong = st.elong / st.weighted; + const thick = st.thick / st.weighted; + if (elong >= T.lineElongation) { + // Straighter patches (higher elongation) turn less. Heuristic. + const turn = Math.round(Math.min(0.5, Math.max(0.05, 1.2 / elong)) * 100) / 100; + out.set(t, { patch, shape: "line", turn }); + } else if (thick >= T.blobThickness) { + out.set(t, { patch, shape: "blob" }); + } else { + out.set(t, { patch, shape: "none" }); + } + } + return out; +} + +/** + * Where each terrain sits in the example: relative density in a 3×3 grid over + * the painted area's bounding box (NW, N, NE, W, C, E, SW, S, SE). 1 means as + * common as across the whole map. Smoothed toward 1 so a bin with few hexes + * doesn't forbid a terrain outright. + */ +export function measureLayout(cells: Map): Map { + let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; + const pts: [number, number, string][] = []; + for (const [key, t] of cells) { + const xy = parseCellKey(key); + if (!xy || !t) continue; + pts.push([xy[0], xy[1], t]); + minX = Math.min(minX, xy[0]); maxX = Math.max(maxX, xy[0]); + minY = Math.min(minY, xy[1]); maxY = Math.max(maxY, xy[1]); + } + const out = new Map(); + if (!pts.length) return out; + const w = maxX - minX + 1, h = maxY - minY + 1; + const bin = (x: number, y: number) => + Math.min(2, Math.floor((3 * (y - minY)) / h)) * 3 + Math.min(2, Math.floor((3 * (x - minX)) / w)); + const binTotal = new Array(9).fill(0); + const counts = new Map(); + for (const [x, y, t] of pts) { + const b = bin(x, y); + binTotal[b]++; + let c = counts.get(t); + if (!c) counts.set(t, (c = new Array(9).fill(0))); + c[b]++; + } + const PSEUDO = 4; // pseudo-hexes per bin pulling the estimate toward 1 + for (const [t, c] of counts) { + const share = c.reduce((a, b) => a + b, 0) / pts.length; + out.set( + t, + c.map((n, b) => { + const p = (n + PSEUDO * share) / (binTotal[b] + PSEUDO); + return Math.round(Math.max(0.02, p / share) * 100) / 100; + }), + ); + } + return out; +} diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index a8eb811e..fa32b95f 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -7,12 +7,62 @@ * with weight 0) may never touch. That includes a terrain next to itself. */ +/** + * How a terrain spreads when the solver places it: + * - "blob": grows outward into a compact patch (lakes, forests); + * - "line": pushes forward in a heading, turning now and then (ranges, ridges); + * - "none": no growth; its shape comes from the neighbour rules alone + * (backgrounds, shores, scattered single hexes). + */ +export type GrowthShape = "blob" | "line" | "none"; + export interface TerrainEntry { name: string; /** Relative frequency. 0 = never placed by the solver (still valid in fixed cells). */ weight: number; + /** + * Typical patch size as a fraction of the whole map (0.05 = 5%). Stored + * relative to map area so a generator learned on a 50×50 map produces the + * same-looking terrain on a 20×20 one. + */ + patch?: number; + /** Growth style. Missing = "none". */ + shape?: GrowthShape; + /** For "line": chance per step of turning (0–1). Missing = 0.2. */ + turn?: number; + /** + * Where the terrain sat in the example, as relative density in a 3×3 grid + * (row-major: NW, N, NE, W, C, E, SW, S, SE). 1 = as common as anywhere, + * 3 = three times as common there. Used by directional bias. + */ + layout?: number[]; } +/** Layout bin names, in the order of TerrainEntry.layout. */ +export const LAYOUT_BINS = ["NW", "N", "NE", "W", "C", "E", "SW", "S", "SE"] as const; + +/** + * Solver settings saved with a generator. Each maps to the SolveOptions + * field of the same name; options passed to solve() win over these. + */ +export interface GeneratorSettings { + featureSize?: number; + directionalBias?: number; + neighbourInfluence?: number; + frequencyFeedback?: number; + scatter?: number; + randomness?: number; +} + +export const DEFAULT_SETTINGS: Required = { + featureSize: 1, + directionalBias: 0, + neighbourInfluence: 3, + frequencyFeedback: 2, + scatter: 3, + randomness: 0.1, +}; + export interface AdjacencyEntry { a: string; b: string; @@ -26,6 +76,8 @@ export interface HexWfcModel { adjacency: AdjacencyEntry[]; /** Free-form string metadata (palette, source map, ...). Preserved by the file format. */ meta: Record; + /** Saved solver settings. Missing fields use DEFAULT_SETTINGS. */ + settings?: GeneratorSettings; } const pairKey = (a: string, b: string) => (a < b ? `${a}\u0000${b}` : `${b}\u0000${a}`); @@ -54,6 +106,14 @@ export function validateModel(model: HexWfcModel): string[] { names.add(t.name); if (!Number.isFinite(t.weight) || t.weight < 0) problems.push(`Terrain "${t.name}" has an invalid weight`); + if (t.patch !== undefined && !(t.patch >= 0 && t.patch <= 1)) + problems.push(`Terrain "${t.name}" has a patch size outside 0–100%`); + if (t.shape !== undefined && !["blob", "line", "none"].includes(t.shape)) + problems.push(`Terrain "${t.name}" has unknown shape "${String(t.shape)}"`); + if (t.turn !== undefined && !(t.turn >= 0 && t.turn <= 1)) + problems.push(`Terrain "${t.name}" has a turn rate outside 0–1`); + if (t.layout !== undefined && (t.layout.length !== 9 || t.layout.some((v) => !(v >= 0)))) + problems.push(`Terrain "${t.name}" needs 9 layout values ≥ 0`); } if (model.terrains.length === 0) problems.push("No terrains listed"); for (const { a, b, weight } of model.adjacency) { @@ -81,5 +141,6 @@ export function restrictModel(model: HexWfcModel, allowed: Iterable): He terrains: model.terrains.filter((t) => keep.has(t.name)), adjacency: model.adjacency.filter((e) => keep.has(e.a) && keep.has(e.b)), meta: { ...model.meta }, + ...(model.settings ? { settings: { ...model.settings } } : {}), }; } diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 71069826..613d80d8 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -20,8 +20,8 @@ * Deterministic for a given model, options and seed. */ -import { hexNeighbors, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; -import { adjacencyLookup, type HexWfcModel } from "./model"; +import { hexNeighbors, directionRing, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; +import { adjacencyLookup, DEFAULT_SETTINGS, type HexWfcModel } from "./model"; import { mulberry32 } from "./rng"; export interface SolveOptions { @@ -43,7 +43,7 @@ export interface SolveOptions { * How hard the solver steers the overall terrain mix toward the model's * terrain weights. Without it, the most common terrain tends to swallow the * map, because every new hex copies its neighbours. 0 turns it off. - * Default 1. + * Default 2. */ frequencyFeedback?: number; /** @@ -53,6 +53,26 @@ export interface SolveOptions { * Default 3. */ scatter?: number; + /** + * Multiplier on each terrain's learned patch size (its "growth moves"). + * Patch sizes are stored as a share of the map, so they already scale with + * the grid; this adjusts on top: below 1 gives more, smaller features, + * above 1 fewer, bigger ones. 0 turns growth off. Default 1. + */ + featureSize?: number; + /** + * How strongly terrain keeps to where it sat in the example (its 3×3 + * layout). 0 = anywhere; 1 = e.g. an ocean along the bottom of the example + * stays along the bottom. Default 0. + */ + directionalBias?: number; + /** + * Share of each choice made by terrain weight alone, ignoring neighbours, + * layout and growth. Lets rare terrains (towns, ruins) pepper the map + * instead of only appearing where the example had them. Hard rules still + * apply. 0–1, default 0.1. + */ + randomness?: number; /** Backtracks allowed per attempt before restarting. Default 2000. */ maxBacktracks?: number; /** Fresh attempts after the first. Default 5. */ @@ -63,6 +83,8 @@ export interface SolveStats { attempts: number; backtracks: number; decisions: number; + /** Hexes placed by growth moves (blob/line spreading). */ + grown: number; ms: number; } @@ -101,7 +123,7 @@ const FEEDBACK_CAP = 8; export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { const t0 = Date.now(); - const stats: SolveStats = { attempts: 0, backtracks: 0, decisions: 0, ms: 0 }; + const stats: SolveStats = { attempts: 0, backtracks: 0, decisions: 0, grown: 0, ms: 0 }; const fail = ( reason: "invalid-input" | "fixed-conflict" | "contradiction", message: string, @@ -115,9 +137,14 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { const stagger = opts.stagger ?? "odd"; const ox = opts.offset?.x ?? 0; const oy = opts.offset?.y ?? 0; - const influence = opts.neighbourInfluence ?? 3; - const feedback = opts.frequencyFeedback ?? 1; - const scatter = opts.scatter ?? 3; + // Options passed in win over settings saved with the model. + const saved = { ...DEFAULT_SETTINGS, ...model.settings }; + const influence = opts.neighbourInfluence ?? saved.neighbourInfluence; + const feedback = opts.frequencyFeedback ?? saved.frequencyFeedback; + const scatter = opts.scatter ?? saved.scatter; + const featureSize = opts.featureSize ?? saved.featureSize; + const bias = opts.directionalBias ?? saved.directionalBias; + const randomness = Math.min(1, Math.max(0, opts.randomness ?? saved.randomness)); const terrains = [...new Set(model.terrains.map((t) => t.name))]; const T = terrains.length; if (!(cols > 0 && rows > 0)) return fail("invalid-input", "Grid must be at least 1×1"); @@ -154,6 +181,32 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { } } + // Directional bias: per hex, log of each terrain's learned layout density + // at that position (bilinear between the 3×3 bin centres), times bias. + let logBias: Float32Array | null = null; + if (bias > 0 && model.terrains.some((e) => e.layout?.length === 9)) { + logBias = new Float32Array(N * T); + const centre = [1 / 6, 1 / 2, 5 / 6]; + const axis = (f: number): [number, number, number] => { + if (f <= centre[0]) return [0, 0, 0]; + if (f >= centre[2]) return [2, 2, 0]; + const i = f < centre[1] ? 0 : 1; + return [i, i + 1, (f - centre[i]) * 3]; + }; + for (const entry of model.terrains) { + const lay = entry.layout; + if (lay?.length !== 9) continue; + const t = tIndex.get(entry.name)!; + for (let c = 0; c < N; c++) { + const [cx0, cx1, fx] = axis(((c % cols) + 0.5) / cols); + const [cy0, cy1, fy] = axis((Math.floor(c / cols) + 0.5) / rows); + const top = lay[cy0 * 3 + cx0] * (1 - fx) + lay[cy0 * 3 + cx1] * fx; + const bottom = lay[cy1 * 3 + cx0] * (1 - fx) + lay[cy1 * 3 + cx1] * fx; + logBias[c * T + t] = bias * Math.log(Math.max(0.02, top * (1 - fy) + bottom * fy)); + } + } + } + const logW = new Float64Array(T); const share = new Float64Array(T); // target fraction of the map per terrain const solverMask = new Uint32Array(W); // terrains the solver may place @@ -303,10 +356,12 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { let max = -Infinity; for (let t = 0; t < T; t++) { if (!has(c, t)) { scores[t] = -Infinity; continue; } - let s = logW[t]; + let s = logW[t] + (logBias ? logBias[c * T + t] : 0); if (decided.length) { - let e = 0; - for (const u of decided) e += logP[t * T + u]; + let e = 0, same = 0; + for (const u of decided) if (u === t) same++; + const enclosed = growShape[t] !== 0 && same >= 3; + for (const u of decided) e += u === t && enclosed ? learnedSelf[t] : logP[t * T + u]; s += e / decided.length; } scores[t] = s; @@ -319,6 +374,142 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { } return sum; }; + // ── Growth moves ───────────────────────────────────────────────────────── + // After the solver chooses a terrain for a hex, a "blob" or "line" terrain + // spreads into nearby open hexes. Every move is a normal place + propagate, + // undone on its own if it breaks a rule, so hard rules always hold. + const growShape = new Uint8Array(T); // 0 none, 1 blob, 2 line + // Learned self-adjacency of growth terrains, used only to fill holes: a hex + // mostly surrounded by one growth terrain (e.g. a gap inside a lake) should + // still become that terrain. + const learnedSelf = new Float64Array(T); + const growMoves = new Int32Array(T); + const growTurn = new Float64Array(T); + for (const entry of model.terrains) { + const t = tIndex.get(entry.name)!; + const shape = entry.shape === "blob" ? 1 : entry.shape === "line" ? 2 : 0; + const moves = Math.min(Math.floor(N / 2), Math.round((entry.patch ?? 0) * N * featureSize) - 1); + if (shape && moves > 0) { + growShape[t] = shape; + growMoves[t] = moves; + growTurn[t] = entry.turn ?? 0.2; + // Growth owns this terrain's clumping. If the neighbour score also + // rewarded "same terrain next door", every patch would keep spreading + // past its learned size. Score self-adjacency at chance level instead. + if ((compat[t * W + (t >>> 5)] >>> (t & 31)) & 1) { + learnedSelf[t] = logP[t * T + t]; + logP[t * T + t] = influence * Math.log(share[t] || 1e-9); + } + // Likewise, judge other neighbours by what lines this terrain's + // border, not by all its edges: most edges of a learned patch are + // interior (forest–forest), which would make "forest next to grass" + // look rare and stop new patches from ever starting. + let border = 0; + for (let u = 0; u < T; u++) if (u !== t) border += adj(terrains[t], terrains[u]); + for (let u = 0; u < T; u++) { + const w = adj(terrains[t], terrains[u]); + if (u !== t && w > 0) logP[t * T + u] = influence * Math.log(w / border); + } + } + } + const ring = directionRing(orientation); + const touchesTerrain = (c: number, t: number): boolean => { + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n >= 0 && single(n) === t) return true; + } + return false; + }; + + /** Decide open cell c as t and propagate; undo just this move on contradiction. */ + // Patches often stop short (rules, map edge, other patches), so track the + // size patches actually reach this attempt and use that as the divisor. + const patchesStarted = new Int32Array(T); + const patchHexes = new Int32Array(T); + const expectedPatch = (t: number) => + patchesStarted[t] >= 3 ? Math.max(1, patchHexes[t] / patchesStarted[t]) : growMoves[t] + 1; + + const tryPlace = (c: number, t: number): boolean => { + if (single(c) !== -1 || !has(c, t)) return false; + const mark = trailIdx.length; + for (let w = 0; w < W; w++) setWord(c * W + w, t >>> 5 === w ? 1 << (t & 31) : 0); + if (propagate([c]) >= 0) { + undoTo(mark); + return false; + } + stats.grown++; + return true; + }; + + const growBlob = (seed: number, t: number, rng: () => number) => { + let budget = growMoves[t]; + const inPatch = new Set([seed]); + const rejected = new Set(); + const frontier: number[] = []; + const addNeighbours = (c: number) => { + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n >= 0 && !inPatch.has(n) && !rejected.has(n)) frontier.push(n); + } + }; + const touching = (c: number) => { + let k = 0; + for (let d = 0; d < 6; d++) if (inPatch.has(nbr[c * 6 + d])) k++; + return k; + }; + addNeighbours(seed); + while (budget > 0 && frontier.length) { + // Best of three random frontier hexes, favouring ones that touch more + // of the patch, keeps blobs compact without being perfectly round. + let bi = 0, bs = -1; + for (let k = 0; k < 3; k++) { + const i = Math.floor(rng() * frontier.length); + const sc = touching(frontier[i]) + rng(); + if (sc > bs) { bs = sc; bi = i; } + } + const n = frontier[bi]; + frontier[bi] = frontier[frontier.length - 1]; + frontier.pop(); + if (inPatch.has(n) || rejected.has(n)) continue; + if (tryPlace(n, t)) { + inPatch.add(n); + budget--; + addNeighbours(n); + } else { + rejected.add(n); + } + } + }; + + const growLine = (seed: number, t: number, rng: () => number) => { + let budget = growMoves[t]; + const h0 = Math.floor(rng() * 6); + // Grow from both ends so the seed sits mid-line. + const ends = [ + { c: seed, h: h0, alive: true }, + { c: seed, h: (h0 + 3) % 6, alive: true }, + ]; + let e = 0; + while (budget > 0 && (ends[0].alive || ends[1].alive)) { + const end = ends[e]; + e ^= 1; + if (!end.alive) continue; + let h = end.h; + if (rng() < growTurn[t]) h = (h + (rng() < 0.5 ? 1 : 5)) % 6; + end.alive = false; + for (const hh of [h, (h + 1) % 6, (h + 5) % 6]) { + const n = nbr[end.c * 6 + ring[hh]]; + if (n >= 0 && tryPlace(n, t)) { + end.c = n; + end.h = hh; + end.alive = true; + budget--; + break; + } + } + } + }; + const placed = new Int32Array(T); // decided hexes per terrain, refreshed each step const entropy = new Float64Array(N); const open = new Uint8Array(N); @@ -328,6 +519,8 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { stats.attempts++; const rng = mulberry32(Math.floor(masterRng() * 4294967296)); trailIdx = []; + patchesStarted.fill(0); + patchHexes.fill(0); trailVal = []; for (let c = 0; c < N; c++) noise[c] = rng() * scatter; for (let c = 0; c < N; c++) { @@ -370,15 +563,29 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { // Frequency feedback is applied to the choice only, not to the entropy // cache: it changes after every step, and rescoring every hex each // step would make the solver quadratic in a much worse way. - let sum = score(best); - if (feedback > 0) { - sum = 0; - for (let t = 0; t < T; t++) { - if (scores[t] <= 0) continue; + const contextSum = score(best); + if (randomness > 0) { + // Mix in a context-free pick by terrain weight (still only among + // terrains the hard rules allow here). + let baseSum = 0; + for (let t = 0; t < T; t++) if (scores[t] > 0) baseSum += Math.exp(logW[t]); + for (let t = 0; t < T; t++) + if (scores[t] > 0) + scores[t] = (1 - randomness) * (scores[t] / contextSum) + (randomness * Math.exp(logW[t])) / baseSum; + } + let sum = 0; + for (let t = 0; t < T; t++) { + if (scores[t] <= 0) continue; + // Choosing a growth terrain here starts a whole patch, so it must + // start (patch size) times less often. Otherwise coverage grows + // with map size: patches scale with the map, and so would the + // number of patches. + if (growShape[t] && !touchesTerrain(best, t)) scores[t] /= expectedPatch(t); + if (feedback > 0) { const ratio = Math.min(FEEDBACK_CAP, Math.max(1 / FEEDBACK_CAP, (share[t] * decidedCount + 1) / (placed[t] + 1))); scores[t] *= Math.pow(ratio, feedback); - sum += scores[t]; } + sum += scores[t]; } let r = rng() * sum, choice = -1; for (let t = 0; t < T; t++) { @@ -391,7 +598,18 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { stats.decisions++; stack.push([trailIdx.length, best, choice]); for (let w = 0; w < W; w++) setWord(best * W + w, choice >>> 5 === w ? 1 << (choice & 31) : 0); + // Grow only from a hex that starts a new patch. A hex joining an + // existing patch of the same terrain must not trigger another full + // growth, or the terrain cascades across the whole map. + const startsPatch = growShape[choice] !== 0 && !touchesTerrain(best, choice); let contradiction = propagate([best]) >= 0; + if (!contradiction && startsPatch) { + const before = stats.grown; + if (growShape[choice] === 1) growBlob(best, choice, rng); + else growLine(best, choice, rng); + patchesStarted[choice]++; + patchHexes[choice] += 1 + stats.grown - before; + } // Undo the last decision and ban that choice; repeat while the ban // itself leads to a contradiction. diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 8e0a2a2f..0a63fb5b 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -12,13 +12,14 @@ import { generatorFitsPalette, saveGeneratorFromMap, generateMapTerrain, + saveGeneratorSettings, type GeneratorFile, } from "../worldgen/generators"; -import { randomSeed } from "../../packages/hex-wfc/src"; +import { randomSeed, DEFAULT_SETTINGS, type GeneratorSettings } from "../../packages/hex-wfc/src"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; -type ModalTab = "Maps" | "Properties" | "New map" | "Export"; +type ModalTab = "Maps" | "Properties" | "New map" | "Generator" | "Export"; function makeCheckbox( parent: HTMLElement, @@ -48,6 +49,7 @@ function clampInt(v: number, lo: number, hi: number, fallback: number): number { export class MapModal extends HexmakerModal { private confirmingDelete: string | null = null; private activeTab: ModalTab = "Maps"; + private selectedGeneratorPath = ""; constructor( app: App, @@ -71,7 +73,7 @@ export class MapModal extends HexmakerModal { // Tab bar const tabBar = contentEl.createDiv({ cls: "duckmage-rt-mode-tabs duckmage-map-modal-tabs" }); - const tabNames: ModalTab[] = ["Maps", "Properties", "New map", "Export"]; + const tabNames: ModalTab[] = ["Maps", "Properties", "New map", "Generator", "Export"]; const contentDivs = new Map(); for (const tab of tabNames) { @@ -101,6 +103,7 @@ export class MapModal extends HexmakerModal { this.renderMapsTab(contentDivs.get("Maps")!); this.renderPropertiesTab(contentDivs.get("Properties")!); this.renderNewMapTab(contentDivs.get("New map")!); + this.renderGeneratorTab(contentDivs.get("Generator")!); this.renderExportTab(contentDivs.get("Export")!); } @@ -445,24 +448,6 @@ export class MapModal extends HexmakerModal { this.view.enterBgCalibration(); }); } - - // ── Terrain generator ────────────────────────────────────────────────── - el.createEl("h4", { text: "Terrain generator" }); - el.createEl("p", { - text: "Learn a wave function collapse generator from the terrain painted on this map. Terrains that never touch here never touch in generated maps. Pick the generator when you create a new map.", - cls: "duckmage-map-origin-desc", - }); - const genRow = el.createDiv({ cls: "duckmage-region-row" }); - const genNameInput = genRow.createEl("input", { - type: "text", - value: this.view.activeMapName, - placeholder: "generator-name", - }); - const genBtn = genRow.createEl("button", { - text: "Generate solver from map", - cls: "mod-cta", - }); - genBtn.addEventListener("click", () => void this.learnGenerator(genNameInput.value, genBtn)); } private async learnGenerator(rawName: string, btn: HTMLButtonElement): Promise { @@ -477,8 +462,9 @@ export class MapModal extends HexmakerModal { new Notice( `Saved generator "${model.name}": ${model.terrains.length} terrains, ${model.adjacency.length} neighbour pairs.`, ); - this.close(); - await this.app.workspace.getLeaf("tab").openFile(file); + this.selectedGeneratorPath = file.path; + this.activeTab = "Generator"; + this.render(); } /** Compute the folder where dropped bg images should land for a given map. */ @@ -622,6 +608,11 @@ export class MapModal extends HexmakerModal { fillGenerators(); }); + el.createEl("p", { + text: "Each generator's settings are on the generator tab.", + cls: "duckmage-map-origin-desc", + }); + // Stagger offset el.createEl("label", { text: "Stagger offset", cls: "duckmage-map-field-label" }); const staggerRow = el.createDiv({ cls: "duckmage-region-row" }); @@ -717,6 +708,160 @@ export class MapModal extends HexmakerModal { }); } + // ── Generator tab ───────────────────────────────────────────────────────── + + private renderGeneratorTab(el: HTMLElement): void { + el.empty(); + + // Learn from the active map + el.createEl("h4", { text: "Learn from this map" }); + el.createEl("p", { + text: "Make a wave function collapse generator from the terrain painted on this map. Terrains that never touch here never touch in generated maps, and lakes, ridges and forests keep their shape and relative size. Pick it on the new map tab.", + cls: "duckmage-map-origin-desc", + }); + const learnRow = el.createDiv({ cls: "duckmage-region-row" }); + const nameInput = learnRow.createEl("input", { + type: "text", + value: this.view.activeMapName, + placeholder: "generator-name", + }); + const learnBtn = learnRow.createEl("button", { text: "Generate solver from map", cls: "mod-cta" }); + learnBtn.addEventListener("click", () => void this.learnGenerator(nameInput.value, learnBtn)); + + // Settings of a saved generator + el.createEl("h4", { text: "Generator settings" }); + el.createEl("p", { + text: "Each generator keeps its own settings in its file. New maps made with it use them.", + cls: "duckmage-map-origin-desc", + }); + const pickRow = el.createDiv({ cls: "duckmage-region-row" }); + const select = pickRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); + const openBtn = pickRow.createEl("button", { text: "Open file" }); + const settingsEl = el.createDiv(); + let generators: GeneratorFile[] = []; + + const current = () => generators.find((g) => g.file.path === select.value); + const show = () => { + this.selectedGeneratorPath = select.value; + settingsEl.empty(); + const g = current(); + openBtn.disabled = !g; + if (!g) { + settingsEl.createEl("p", { + text: generators.length ? "Pick a generator." : "No generators yet. Paint a map, then use the button above.", + cls: "duckmage-map-origin-desc", + }); + return; + } + this.renderGeneratorSettings(settingsEl, g); + }; + openBtn.addEventListener("click", () => { + const g = current(); + if (!g) return; + this.close(); + void this.app.workspace.getLeaf("tab").openFile(g.file); + }); + select.addEventListener("change", show); + + select.createEl("option", { value: "", text: "Loading…" }); + openBtn.disabled = true; + void listGenerators(this.plugin).then((list) => { + generators = list; + select.empty(); + if (!list.length) select.createEl("option", { value: "", text: "No generators" }); + for (const g of list) { + const palette = g.model.meta.palette; + select.createEl("option", { + value: g.file.path, + text: palette ? `${g.model.name} (${palette})` : g.model.name, + }); + } + select.value = list.some((g) => g.file.path === this.selectedGeneratorPath) + ? this.selectedGeneratorPath + : (list[0]?.file.path ?? ""); + show(); + }); + } + + private renderGeneratorSettings(el: HTMLElement, g: GeneratorFile): void { + const { model } = g; + const byShape = (shape: string) => + model.terrains.filter((t) => (t.shape ?? "none") === shape).map((t) => t.name); + const parts = [`${model.terrains.length} terrains`]; + if (byShape("blob").length) parts.push(`blobs: ${byShape("blob").join(", ")}`); + if (byShape("line").length) parts.push(`lines: ${byShape("line").join(", ")}`); + if (model.meta["source-map"]) parts.push(`learned from ${model.meta["source-map"]}`); + el.createEl("p", { text: parts.join(" · "), cls: "duckmage-map-origin-desc" }); + + const sliders: { + field: keyof GeneratorSettings; + label: string; + hint: string; + min: number; + max: number; + step: number; + }[] = [ + { + field: "featureSize", label: "Feature size", min: 0, max: 3, step: 0.25, + hint: "Size of lakes, ranges and forests relative to the map. 1 = like the example map; lower = more, smaller features; 0 = no growth.", + }, + { + field: "directionalBias", label: "Directional bias", min: 0, max: 1, step: 0.05, + hint: "0 = features can go anywhere. 1 = they keep to where they were in the example, so an ocean along the bottom stays along the bottom.", + }, + { + field: "neighbourInfluence", label: "Clumping", min: 0, max: 6, step: 0.5, + hint: "How strongly each hex follows its neighbours. 0 gives speckled noise.", + }, + { + field: "frequencyFeedback", label: "Mix strength", min: 0, max: 4, step: 0.5, + hint: "How closely the overall terrain mix follows the example.", + }, + { + field: "randomness", label: "Randomness", min: 0, max: 1, step: 0.05, + hint: "Share of hexes chosen by plain chance, ignoring neighbours and layout. Lets rare terrain like towns pepper the map. Hard rules still apply.", + }, + { + field: "scatter", label: "Scatter", min: 0, max: 6, step: 0.5, + hint: "Randomness in where features start. Too low and one terrain can take over the map.", + }, + ]; + + const values: Required = { ...DEFAULT_SETTINGS, ...model.settings }; + const inputs = new Map(); + const save = (patch: GeneratorSettings) => { + model.settings = { ...model.settings, ...patch }; + saveGeneratorSettings(this.plugin, g.file, patch).catch((e: unknown) => { + new Notice(`Couldn't save generator settings: ${e instanceof Error ? e.message : String(e)}`); + }); + }; + + for (const def of sliders) { + el.createEl("label", { text: def.label, cls: "duckmage-map-field-label" }); + const row = el.createDiv({ cls: "duckmage-region-row" }); + const slider = row.createEl("input", { type: "range" }); + slider.min = String(def.min); + slider.max = String(def.max); + slider.step = String(def.step); + slider.value = String(values[def.field]); + const valueEl = row.createSpan({ text: String(values[def.field]) }); + el.createEl("p", { text: def.hint, cls: "duckmage-map-origin-desc" }); + inputs.set(def.field, [slider, valueEl]); + slider.addEventListener("input", () => valueEl.setText(slider.value)); + slider.addEventListener("change", () => save({ [def.field]: Number(slider.value) })); + } + + const resetRow = el.createDiv({ cls: "duckmage-region-row" }); + const resetBtn = resetRow.createEl("button", { text: "Reset to defaults" }); + resetBtn.addEventListener("click", () => { + for (const [field, [slider, valueEl]] of inputs) { + slider.value = String(DEFAULT_SETTINGS[field]); + valueEl.setText(slider.value); + } + save({ ...DEFAULT_SETTINGS }); + }); + } + // ── Delete ──────────────────────────────────────────────────────────────── private async deleteMap(name: string): Promise { diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index 36e2b199..9f33df52 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -22,7 +22,9 @@ import { solve, cellKey, type HexWfcModel, + SETTING_KEYS, type SolveResult, + type GeneratorSettings, } from "../../packages/hex-wfc/src"; export interface GeneratorFile { @@ -145,6 +147,7 @@ export function generateMapTerrain( offset: { x: number; y: number }, stagger: "odd" | "even", seed: number, + featureSize = 1, ): SolveResult { return solve(restrictModel(model, paletteTerrains), { cols, @@ -153,5 +156,22 @@ export function generateMapTerrain( orientation: plugin.settings.hexOrientation, stagger, seed, + featureSize, + }); +} + +/** + * Save solver settings into a generator file's frontmatter. Only the + * frontmatter changes, so the tables and any notes the user wrote are kept. + */ +export async function saveGeneratorSettings( + plugin: HexmakerPlugin, + file: TFile, + settings: GeneratorSettings, +): Promise { + await plugin.app.fileManager.processFrontMatter(file, (fm: Record) => { + for (const [field, value] of Object.entries(settings) as [keyof GeneratorSettings, number | undefined][]) { + if (value !== undefined) fm[SETTING_KEYS[field]] = value; + } }); } diff --git a/tests/hexWfc.test.ts b/tests/hexWfc.test.ts index b60ccab0..fe8770ae 100644 --- a/tests/hexWfc.test.ts +++ b/tests/hexWfc.test.ts @@ -2,6 +2,9 @@ import { describe, it } from "node:test"; import expect from "expect"; import { hexNeighbors, + hexCenter, + directionRing, + measurePatches, cellKey, learnModel, solve, @@ -244,3 +247,236 @@ describe("markdown format", () => { expect(() => parseModelMarkdown("# Hello")).toThrow(); }); }); + +/** 50×50 example: two lakes ringed by sand, a 2-wide ridge, two forests, grass. */ +function worldExample(): Map { + const ex = new Map(); + const lakes = [[12, 14, 4], [36, 34, 3.5]]; + const forests = [[38, 10, 5], [10, 38, 4]]; + for (let x = 0; x < 50; x++) + for (let y = 0; y < 50; y++) { + let t = "Grass"; + for (const [fx, fy, r] of forests) if ((x - fx) ** 2 + (y - fy) ** 2 < r * r) t = "Forest"; + if (x > 18 && x < 46 && Math.abs(y - (0.6 * x + 8 + 3 * Math.sin(x / 5))) < 1.1) t = "Ridge"; + for (const [lx, ly, r] of lakes) { + const d = Math.hypot(x - lx, y - ly); + if (d < r) t = "Water"; + else if (d < r + 1.3) t = "Sand"; + } + ex.set(cellKey(x, y), t); + } + return ex; +} + +const shareOf = (cells: Map) => { + const out: Record = {}; + for (const t of cells.values()) out[t] = (out[t] ?? 0) + 1 / cells.size; + return out; +}; + +describe("growth: shape learning", () => { + it("classifies blobs, lines, shores and the background by shape alone", () => { + const shapes = measurePatches(worldExample(), "flat"); + expect(shapes.get("Water")?.shape).toBe("blob"); + expect(shapes.get("Forest")?.shape).toBe("blob"); + expect(shapes.get("Ridge")?.shape).toBe("line"); + expect(shapes.get("Ridge")?.turn).toBeGreaterThan(0); + expect(shapes.get("Sand")?.shape).toBe("none"); // thin ring: left to the neighbour rules + expect(shapes.get("Grass")?.shape).toBe("none"); // background + }); + + it("stores patch size as a share of the map, not a hex count", () => { + // The same picture at two resolutions gives about the same patch share. + const disc = (n: number) => { + const m = new Map(); + for (let x = 0; x < n; x++) + for (let y = 0; y < n; y++) + m.set(cellKey(x, y), Math.hypot(x - n / 2, y - n / 2) < n / 6 ? "Lake" : "Grass"); + return m; + }; + const small = measurePatches(disc(24), "flat").get("Lake")!; + const big = measurePatches(disc(60), "flat").get("Lake")!; + expect(small.shape).toBe("blob"); + expect(big.shape).toBe("blob"); + expect(Math.abs(small.patch - big.patch)).toBeLessThan(0.02); + }); + + it("treats single scattered hexes as no-growth", () => { + const m = new Map(); + for (let x = 0; x < 20; x++) for (let y = 0; y < 20; y++) m.set(cellKey(x, y), (x * 7 + y * 3) % 11 === 0 ? "Rock" : "Grass"); + expect(measurePatches(m, "pointy").get("Rock")?.shape).toBe("none"); + }); + + it("directionRing walks the neighbours clockwise in 60° steps", () => { + for (const o of ["flat", "pointy"] as const) + for (const s of ["odd", "even"] as const) + for (const [x, y] of [[4, 4], [5, 4], [4, 5], [5, 5]]) { + const [cx, cy] = hexCenter(x, y, o, s); + const ns = hexNeighbors(x, y, o, s); + const angles = directionRing(o).map((i) => { + const [nx, ny] = hexCenter(ns[i][0], ns[i][1], o, s); + expect(Math.hypot(nx - cx, ny - cy)).toBeCloseTo(Math.sqrt(3), 5); // really a neighbour + return Math.atan2(ny - cy, nx - cx); + }); + for (let k = 0; k < 6; k++) { + let step = angles[(k + 1) % 6] - angles[k]; + while (step <= -Math.PI) step += 2 * Math.PI; + while (step > Math.PI) step -= 2 * Math.PI; + expect(step).toBeCloseTo(Math.PI / 3, 5); // clockwise on screen (y down) + } + } + }); +}); + +describe("growth: solving", () => { + const model = learnModel(worldExample(), { name: "world", orientation: "flat" }); + + it("keeps every learned rule while growing", () => { + for (const seed of [1, 2, 3]) { + const r = solve(model, { cols: 40, rows: 30, orientation: "flat", seed }); + expect(r.ok).toBe(true); + if (!r.ok) continue; + expect(r.stats.grown).toBeGreaterThan(0); + expect(findViolation(model, r.cells, "flat")).toBeNull(); + } + }); + + it("produces about the example's terrain mix at different map sizes", () => { + const target = shareOf(worldExample()); + for (const [cols, rows] of [[20, 20], [50, 50]]) { + const avg: Record = {}; + const seeds = [11, 12, 13, 14, 15]; + for (const seed of seeds) { + const r = solve(model, { cols, rows, orientation: "flat", seed }); + expect(r.ok).toBe(true); + if (!r.ok) continue; + for (const [t, v] of Object.entries(shareOf(r.cells))) avg[t] = (avg[t] ?? 0) + v / seeds.length; + } + for (const t of Object.keys(target)) { + // Within 5 percentage points of the example for every terrain. + expect(Math.abs((avg[t] ?? 0) - target[t])).toBeLessThan(0.05); + } + } + }); + + it("featureSize 0 turns growth off", () => { + const r = solve(model, { cols: 20, rows: 20, orientation: "flat", seed: 4, featureSize: 0 }); + expect(r.ok).toBe(true); + if (r.ok) expect(r.stats.grown).toBe(0); + }); + + it("is still deterministic with growth", () => { + const a = solve(model, { cols: 25, rows: 25, orientation: "pointy", seed: 99 }); + const b = solve(model, { cols: 25, rows: 25, orientation: "pointy", seed: 99 }); + expect(a.ok && b.ok).toBe(true); + if (a.ok && b.ok) expect([...a.cells]).toEqual([...b.cells]); + }); + + it("round-trips growth columns and tolerates bad ones", () => { + const text = modelToMarkdown(model); + expect(text).toContain("| Terrain | Weight | Patch % | Shape | Turn |"); + expect(parseModelMarkdown(text).model).toEqual(model); + const edited = text.replace(/\| blob \|/, "| splodge |"); + const { warnings } = parseModelMarkdown(edited); + expect(warnings.some((w) => w.includes('shape "splodge"'))).toBe(true); + }); +}); + +/** 40×40 example: ocean along the bottom, a forest top-left, towns only in the top half. */ +function coastExample(): Map { + const ex = new Map(); + for (let x = 0; x < 40; x++) + for (let y = 0; y < 40; y++) { + const coast = 30 + 2 * Math.sin(x / 4); + let t = y > coast ? "Ocean" : y > coast - 1.5 ? "Sand" : "Grass"; + if (t === "Grass" && Math.hypot(x - 8, y - 8) < 6) t = "Forest"; + if (t === "Grass" && y < 20 && x > 16 && (x * 7 + y * 13) % 29 === 0) t = "Town"; + ex.set(cellKey(x, y), t); + } + return ex; +} + +/** Share of a terrain in the top and bottom thirds of a generated map. */ +function thirds(cells: Map, rows: number, terrain: string): [number, number] { + let top = 0, bottom = 0, nTop = 0, nBottom = 0; + for (const [k, t] of cells) { + const y = Number(k.split("_")[1]); + if (y < rows / 3) { nTop++; if (t === terrain) top++; } + else if (y >= (2 * rows) / 3) { nBottom++; if (t === terrain) bottom++; } + } + return [top / nTop, bottom / nBottom]; +} + +describe("directional bias, randomness and saved settings", () => { + const model = learnModel(coastExample(), { name: "coast", orientation: "flat" }); + + it("learns where each terrain sat", () => { + const ocean = model.terrains.find((t) => t.name === "Ocean")!.layout!; + expect(ocean).toHaveLength(9); + expect(ocean[7]).toBeGreaterThan(2); // S: much more ocean than average + expect(ocean[1]).toBeLessThan(0.2); // N: almost none + }); + + it("bias 1 keeps the ocean along the bottom; bias 0 doesn't care", () => { + let biasedTop = 0, biasedBottom = 0, freeTop = 0, freeBottom = 0; + for (const seed of [1, 2, 3, 4]) { + const b = solve(model, { cols: 30, rows: 24, orientation: "flat", seed, directionalBias: 1 }); + const f = solve(model, { cols: 30, rows: 24, orientation: "flat", seed, directionalBias: 0 }); + expect(b.ok && f.ok).toBe(true); + if (!b.ok || !f.ok) return; + const [bt, bb] = thirds(b.cells, 24, "Ocean"); + const [ft, fb] = thirds(f.cells, 24, "Ocean"); + biasedTop += bt; biasedBottom += bb; freeTop += ft; freeBottom += fb; + expect(findViolation(model, b.cells, "flat")).toBeNull(); + } + expect(biasedBottom).toBeGreaterThan(biasedTop * 5); + // Without bias, the ocean has no particular preference for the bottom. + expect(freeBottom / (freeTop + freeBottom + 1e-9)).toBeLessThan(0.85); + }); + + it("randomness peppers rare terrain where the example never had it", () => { + const townsInBottomHalf = (randomness: number) => { + let n = 0; + for (const seed of [5, 6, 7, 8]) { + const r = solve(model, { cols: 30, rows: 30, orientation: "flat", seed, directionalBias: 1, randomness }); + if (!r.ok) continue; + for (const [k, t] of r.cells) if (t === "Town" && Number(k.split("_")[1]) >= 15) n++; + } + return n; + }; + expect(townsInBottomHalf(0.6)).toBeGreaterThan(townsInBottomHalf(0)); + }); + + it("uses settings saved with the model, and options override them", () => { + const saved = { ...model, settings: { featureSize: 0 } }; + const fromModel = solve(saved, { cols: 20, rows: 20, orientation: "flat", seed: 3 }); + const overridden = solve(saved, { cols: 20, rows: 20, orientation: "flat", seed: 3, featureSize: 1 }); + expect(fromModel.ok && overridden.ok).toBe(true); + if (fromModel.ok && overridden.ok) { + expect(fromModel.stats.grown).toBe(0); + expect(overridden.stats.grown).toBeGreaterThan(0); + } + }); + + it("round-trips settings (frontmatter) and layout (table)", () => { + const m = { ...model, settings: { featureSize: 1.5, directionalBias: 0.75, randomness: 0.2 } }; + const text = modelToMarkdown(m); + expect(text).toContain("feature-size: 1.5"); + expect(text).toContain("directional-bias: 0.75"); + expect(text).toContain("| Terrain | NW | N | NE | W | C | E | SW | S | SE |"); + const back = parseModelMarkdown(text); + expect(back.warnings).toEqual([]); + expect(back.model).toEqual(m); + expect(back.model.meta["feature-size"]).toBeUndefined(); // settings aren't duplicated into meta + }); + + it("warns about bad settings and layout rows instead of failing", () => { + const text = modelToMarkdown({ ...model, settings: { scatter: 2 } }) + .replace("scatter: 2", "scatter: lots") + .replace(/\| Ocean \|[^\n]*\n/g, (row) => (row.includes("NW") ? row : "| Ocean | 1 | 2 |\n")); + const { model: back, warnings } = parseModelMarkdown(text); + expect(warnings.some((w) => w.includes('"scatter: lots"'))).toBe(true); + expect(warnings.some((w) => w.startsWith("Layout row"))).toBe(true); + expect(back.settings).toBeUndefined(); + }); +}); From 925961fe1624a603e2fdd7ce8ad067119e40d3f5 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 16:19:30 -0400 Subject: [PATCH 004/558] feat(hex-wfc): scatter/spacing, guaranteed river features, edge style, line width, symmetry, smoothing, counts, connected land, per-terrain mix Library only (UI next): - learn: one patch-analysis pass; shapes gain 'scatter' (single hexes, learned min spacing); lines must be thin (bands become blobs) and not boundaries (a shore with different terrain on each side stays 'none'); learned line width, edge preference, example size; line patches anchored at both ends (edge/edge or edge/lake) become guaranteed features - solve(): wrapper over the collapse: explicit edge terrain laid down as a wavy fixed border (islands), features drawn as fixed paths with an anchor blob at a terrain end, whole-map retries keeping the best for counts / connected land, then post passes (smoothing, connect land, count top-ups). Every post change keeps all adjacency rules. - core: spacing for scatter terrain, max counts steering, line width, mirrored placement, learned edge preference, blob growth and random picks respect directional bias - format: Terrains table gains Width / Spacing / Edge; Features table; example-hexes; all settings in frontmatter with readable codecs ("Forest 1.5; Water 0.5", "Town 3; Lake 1-") - 54 library tests incl. an invariant that no setting breaks a rule Co-Authored-By: Claude Opus 5.5 (1M context) --- dev/wfc-controls.mts | 35 +++ dev/wfc-learned.mts | 52 ++++ dev/wfc-river.mts | 13 + packages/hex-wfc/src/features.ts | 261 +++++++++++++++++ packages/hex-wfc/src/format.ts | 319 ++++++++++++++++----- packages/hex-wfc/src/grid.ts | 24 ++ packages/hex-wfc/src/index.ts | 27 +- packages/hex-wfc/src/learn.ts | 330 ++++++++++++++++----- packages/hex-wfc/src/model.ts | 118 +++++++- packages/hex-wfc/src/post.ts | 246 ++++++++++++++++ packages/hex-wfc/src/solve.ts | 475 ++++++++++++++++++++++--------- tests/hexWfc.test.ts | 283 +++++++++++++++++- 12 files changed, 1889 insertions(+), 294 deletions(-) create mode 100644 dev/wfc-controls.mts create mode 100644 dev/wfc-learned.mts create mode 100644 dev/wfc-river.mts create mode 100644 packages/hex-wfc/src/features.ts create mode 100644 packages/hex-wfc/src/post.ts diff --git a/dev/wfc-controls.mts b/dev/wfc-controls.mts new file mode 100644 index 00000000..adfce9e9 --- /dev/null +++ b/dev/wfc-controls.mts @@ -0,0 +1,35 @@ +// Eyeball check for solver controls on the world example. +// Usage (from WSL): npx tsx dev/wfc-controls.mts +import { learnModel, solve, cellKey, countPatches, type SolveOptions } from "../packages/hex-wfc/src"; +const world = new Map(); +const lakes = [[12, 14, 4], [36, 34, 3.5]], forests = [[38, 10, 5], [10, 38, 4]]; +for (let x = 0; x < 50; x++) for (let y = 0; y < 50; y++) { + let t = "Grass"; + for (const [fx, fy, r] of forests) if ((x - fx) ** 2 + (y - fy) ** 2 < r * r) t = "Forest"; + if (x > 18 && x < 46 && Math.abs(y - (0.6 * x + 8 + 3 * Math.sin(x / 5))) < 1.1) t = "Ridge"; + if (t === "Grass" && (x * 7 + y * 13) % 53 === 0) t = "Town"; + for (const [lx, ly, r] of lakes) { const d = Math.hypot(x - lx, y - ly); if (d < r) t = "Water"; else if (d < r + 1.3) t = "Sand"; } + world.set(cellKey(x, y), t); +} +const m = learnModel(world, { name: "world", orientation: "flat" }); +const glyph: Record = { Grass: ".", Water: "~", Sand: "s", Ridge: "^", Forest: "F", Town: "T" }; +const show = (label: string, extra: Partial, cols = 40, rows = 16) => { + const r = solve(m, { cols, rows, orientation: "flat", seed: 4, ...extra }); + if (!r.ok) { console.log(label, r.message); return; } + const pc = countPatches(r.cells, { cols, rows, ox: 0, oy: 0, orientation: "flat", stagger: "odd" }); + console.log(`\n## ${label} towns=${pc.get("Town") ?? 0} lakes=${pc.get("Water") ?? 0}`, JSON.stringify(r.stats), r.warnings.join("; ")); + for (let y = 0; y < rows; y++) { let s = ""; for (let x = 0; x < cols; x++) s += glyph[r.cells.get(cellKey(x, y))!] ?? "?"; console.log(s); } +}; +const arg = process.argv[2] ?? "all"; +const runs: [string, Partial][] = [ + ["baseline", {}], + ["smoothing 1", { smoothing: 1 }], + ["symmetry left-right", { symmetry: "left-right" }], + ["island: edge Water strength 1", { edgeTerrain: "Water", edgeStrength: 1 }], + ["counts: Town 3, Water 2-", { counts: { Town: { min: 3, max: 3 }, Water: { min: 2 } } }], + ["spacing 2x", { spacing: 2 }], + ["line width 3", { lineWidth: 3 }], + ["connected, impassable Water+Ridge", { connected: true, impassable: ["Water", "Ridge"] }], + ["mix Forest x3", { mix: { Forest: 3 } }], +]; +for (const [label, extra] of runs) if (arg === "all" || label.startsWith(arg)) show(label, extra); diff --git a/dev/wfc-learned.mts b/dev/wfc-learned.mts new file mode 100644 index 00000000..b4e7fa00 --- /dev/null +++ b/dev/wfc-learned.mts @@ -0,0 +1,52 @@ +// Prints what a generator learns from the dev example maps. +// Usage (from WSL): npx tsx dev/wfc-learned.mts +import { learnModel, cellKey, hexNeighbors } from "../packages/hex-wfc/src"; +const world = new Map(); +const lakes = [[12, 14, 4], [36, 34, 3.5]], forests = [[38, 10, 5], [10, 38, 4]]; +for (let x = 0; x < 50; x++) for (let y = 0; y < 50; y++) { + let t = "Grass"; + for (const [fx, fy, r] of forests) if ((x - fx) ** 2 + (y - fy) ** 2 < r * r) t = "Forest"; + if (x > 18 && x < 46 && Math.abs(y - (0.6 * x + 8 + 3 * Math.sin(x / 5))) < 1.1) t = "Ridge"; + for (const [lx, ly, r] of lakes) { const d = Math.hypot(x - lx, y - ly); if (d < r) t = "Water"; else if (d < r + 1.3) t = "Sand"; } + world.set(cellKey(x, y), t); +} +const coast = new Map(); +for (let x = 0; x < 40; x++) for (let y = 0; y < 40; y++) { + const c = 30 + 2 * Math.sin(x / 4); + let t = y > c ? "Ocean" : y > c - 1.5 ? "Sand" : "Grass"; + if (t === "Grass" && Math.hypot(x - 8, y - 8) < 6) t = "Forest"; + if (t === "Grass" && y < 20 && x > 16 && (x * 7 + y * 13) % 29 === 0) t = "Town"; + coast.set(cellKey(x, y), t); +} +for (const [name, ex] of [["world", world], ["coast", coast]] as const) { + const m = learnModel(ex, { name, orientation: "flat" }); + console.log(`\n${name}:`); + for (const t of m.terrains) console.log(" ", t.name.padEnd(7), (t.shape ?? "").padEnd(8), `patch ${((t.patch ?? 0) * 100).toFixed(1)}%`, t.width ? `width ${t.width}` : "", t.turn ? `turn ${t.turn}` : "", t.spacing ? `spacing ${t.spacing}` : "", t.edge ? `edge ${t.edge}` : ""); + console.log(" features:", JSON.stringify(m.features ?? [])); +} + +// River example: a winding 1-wide river from the top edge into a lake, +// walked along real hex neighbours so it is one connected line. +export function riverExample(): Map { + const m = new Map(); + for (let x = 0; x < 40; x++) for (let y = 0; y < 40; y++) { + const d = Math.hypot(x - 26, y - 28); + m.set(cellKey(x, y), d < 4.5 ? "Water" : d < 5.8 ? "Sand" : "Grass"); + } + let cur: [number, number] = [8, 0]; + for (let step = 0; step < 80; step++) { + m.set(cellKey(cur[0], cur[1]), "River"); + const ns = hexNeighbors(cur[0], cur[1], "flat", "odd"); + if (ns.some(([x, y]) => m.get(cellKey(x, y)) === "Water")) break; + // Head for the lake, wobbling sideways every few steps. + const wobble = Math.sin(step / 3) * 6; + const goal: [number, number] = [26 + wobble, 28]; + ns.sort((a, b) => Math.hypot(a[0] - goal[0], a[1] - goal[1]) - Math.hypot(b[0] - goal[0], b[1] - goal[1])); + cur = ns.find(([x, y]) => m.get(cellKey(x, y)) !== "River" && x >= 0 && y >= 0)!; + } + return m; +} +const rm = learnModel(riverExample(), { name: "river", orientation: "flat" }); +console.log("\nriver:"); +for (const t of rm.terrains) console.log(" ", t.name.padEnd(7), (t.shape ?? "").padEnd(8), `patch ${((t.patch ?? 0) * 100).toFixed(1)}%`, t.width ? `width ${t.width}` : "", t.turn ? `turn ${t.turn}` : ""); +console.log(" features:", JSON.stringify(rm.features ?? [])); diff --git a/dev/wfc-river.mts b/dev/wfc-river.mts new file mode 100644 index 00000000..8c3059ba --- /dev/null +++ b/dev/wfc-river.mts @@ -0,0 +1,13 @@ +// Guaranteed river check: learns from the river example (edge → lake) and +// prints generated maps. Usage (from WSL): npx tsx dev/wfc-river.mts [seed] +import { learnModel, solve, cellKey } from "../packages/hex-wfc/src"; +import { riverExample } from "./wfc-learned.mts"; +const seed = Number(process.argv[2] ?? 1); +const m = learnModel(riverExample(), { name: "river", orientation: "flat" }); +const glyph: Record = { Grass: ".", Water: "~", Sand: "s", River: "R" }; +for (const [cols, rows] of [[30, 20], [20, 14]]) { + const r = solve(m, { cols, rows, orientation: "flat", seed }); + if (!r.ok) { console.log(cols, rows, r.message); continue; } + console.log(`\n${cols}x${rows}`, JSON.stringify(r.stats), r.warnings); + for (let y = 0; y < rows; y++) { let s = ""; for (let x = 0; x < cols; x++) s += glyph[r.cells.get(cellKey(x, y))!] ?? "?"; console.log(s); } +} diff --git a/packages/hex-wfc/src/features.ts b/packages/hex-wfc/src/features.ts new file mode 100644 index 00000000..36362d41 --- /dev/null +++ b/packages/hex-wfc/src/features.ts @@ -0,0 +1,261 @@ +/** + * Guaranteed line features (rivers): drawn as fixed hexes before the solver + * runs, so they always exist, then the solver fills in around them. + * + * A path starts at its `from` anchor (a map edge, or a patch of a terrain it + * creates there) and wanders toward its `to` anchor, turning about as often + * as the example's line did. A terrain anchor gets a small fixed blob of that + * terrain, so "river ends in a lake" really ends in water; the solver grows + * the rest of the lake and its shore around it. + */ + +import { hexNeighbors, hexDistance, cellKey } from "./grid"; +import { adjacencyLookup, type HexWfcModel, type LineFeature, type GeneratorSettings } from "./model"; +import type { GridInfo } from "./post"; + +type Side = 0 | 1 | 2 | 3; // N, E, S, W + +export function placeFeatures( + model: HexWfcModel, + features: LineFeature[], + s: Required, + grid: GridInfo, + fixed: Map, + rng: () => number, +): { cells: Map; warnings: string[] } { + const { cols, rows, ox, oy, orientation, stagger } = grid; + const N = cols * rows; + const adj = adjacencyLookup(model); + const entryOf = new Map(model.terrains.map((t) => [t.name, t])); + const placed = new Map(); + const warnings: string[] = []; + const terrainAt = (k: string) => placed.get(k) ?? fixed.get(k); + const inGrid = (x: number, y: number) => x >= ox && x < ox + cols && y >= oy && y < oy + rows; + const nbrs = (x: number, y: number) => + hexNeighbors(x, y, orientation, stagger).filter(([nx, ny]) => inGrid(nx, ny)); + const sizeScale = model.exampleHexes ? Math.sqrt(N / model.exampleHexes) : 1; + + /** Would putting t at (x, y) break a rule with anything already placed or fixed? */ + const fitsAt = (x: number, y: number, t: string, pending: Map) => + nbrs(x, y).every(([nx, ny]) => { + const k = cellKey(nx, ny); + const u = pending.get(k) ?? terrainAt(k); + return u === undefined || adj(t, u) > 0; + }); + + const sidePoint = (side: Side): [number, number] => { + const along = (n: number) => Math.floor(rng() * n); + if (side === 0) return [ox + along(cols), oy]; + if (side === 2) return [ox + along(cols), oy + rows - 1]; + if (side === 3) return [ox, oy + along(rows)]; + return [ox + cols - 1, oy + along(rows)]; + }; + const onSide = ([x, y]: [number, number], side: Side) => + side === 0 ? y === oy : side === 2 ? y === oy + rows - 1 : side === 3 ? x === ox : x === ox + cols - 1; + const interiorPoint = (margin: number): [number, number] => { + const mx = Math.min(margin, Math.floor(cols / 3)), my = Math.min(margin, Math.floor(rows / 3)); + return [ox + mx + Math.floor(rng() * Math.max(1, cols - 2 * mx)), oy + my + Math.floor(rng() * Math.max(1, rows - 2 * my))]; + }; + /** Pick a side, weighted by where the terrain sat in the example when directional bias is on. */ + const pickSide = (terrain: string): Side => { + const lay = entryOf.get(terrain)?.layout; + const bias = s.directionalBias; + if (!lay || lay.length !== 9 || bias <= 0) return Math.floor(rng() * 4) as Side; + const w = [lay[1], lay[5], lay[7], lay[3]].map((v) => Math.pow(Math.max(0.02, v), bias)); + let r = rng() * w.reduce((a, b) => a + b, 0); + for (let i = 0; i < 4; i++) if ((r -= w[i]) < 0) return i as Side; + return 3; + }; + + /** + * A fixed blob of terrain `t` at the line's end, so it visibly ends in it. + * The blob may touch the line only at `at` (the line's last hex), so a lake + * sits at the river mouth instead of wrapping around the river. + */ + const anchorBlob = (at: [number, number], t: string, pending: Map, line: Set) => { + const atKey = cellKey(at[0], at[1]); + const touchesLineElsewhere = (x: number, y: number) => + nbrs(x, y).some(([nx, ny]) => { + const k = cellKey(nx, ny); + return k !== atKey && line.has(k); + }); + const e = entryOf.get(t); + const target = Math.max(4, Math.min(Math.floor(N / 6), Math.round((e?.patch ?? 0.01) * N * s.featureSize))); + const queue: [number, number][] = [at]; + const seen = new Set([cellKey(at[0], at[1])]); + let n = 0; + while (queue.length && n < target) { + const [x, y] = queue.shift()!; + const k = cellKey(x, y); + if (!pending.has(k) && terrainAt(k) === undefined && !touchesLineElsewhere(x, y) && fitsAt(x, y, t, pending)) { + pending.set(k, t); + n++; + } + for (const [nx, ny] of nbrs(x, y)) { + const nk = cellKey(nx, ny); + if (!seen.has(nk)) { + seen.add(nk); + queue.push([nx, ny]); + } + } + } + }; + + const drawOne = (f: LineFeature): boolean => { + const startFree = (p: [number, number]) => { + const u = terrainAt(cellKey(p[0], p[1])); + return u === undefined || u === f.terrain; + }; + const t = f.terrain; + const turn = entryOf.get(t)?.turn ?? 0.2; + const width = Math.max(1, Math.min(3, Math.round(s.lineWidth > 0 ? s.lineWidth : (entryOf.get(t)?.width ?? 1)))); + const span = Math.min(cols, rows); + + let start: [number, number]; + let startSide: Side | null = null; + if (f.from === "edge") { + startSide = pickSide(t); + start = sidePoint(startSide); + } else { + start = interiorPoint(Math.max(2, Math.floor(span / 6))); + } + if (!startFree(start)) return false; + let endSide: Side | null = null; + let target: [number, number]; + if (f.to === "edge") { + const opposite = ((startSide ?? Math.floor(rng() * 4)) + 2) % 4; + endSide = (rng() < 0.6 ? opposite : (opposite + (rng() < 0.5 ? 1 : 3)) % 4) as Side; + target = sidePoint(endSide); + } else { + // As long as the example's line, relative to map size: its patch share + // of this map, divided by its width. + const lineHexes = (entryOf.get(t)?.patch ?? 0.02) * N * s.featureSize; + const want = Math.max(3, Math.min(Math.round(span * 1.2), Math.round((lineHexes / width) * (0.8 + 0.4 * rng())))); + let best = interiorPoint(Math.max(2, Math.floor(span / 6))); + for (let k = 0; k < 12; k++) { + const p = interiorPoint(Math.max(2, Math.floor(span / 6))); + if (Math.abs(hexDistance(p, start, orientation, stagger) - want) < Math.abs(hexDistance(best, start, orientation, stagger) - want)) best = p; + } + target = best; + } + + const pending = new Map(); + const path: [number, number][] = [start]; + const onPath = new Set([cellKey(start[0], start[1])]); + const free = (x: number, y: number) => { + const k = cellKey(x, y); + return !onPath.has(k) && (terrainAt(k) === undefined || terrainAt(k) === t); + }; + let cur = start; + const maxSteps = 3 * (cols + rows); + for (let step = 0; step < maxSteps; step++) { + if (endSide !== null ? onSide(cur, endSide) && path.length > 2 : hexDistance(cur, target, orientation, stagger) === 0) break; + // Don't step next to earlier parts of the path (keeps it a clean line). + const options = nbrs(cur[0], cur[1]).filter(([x, y]) => { + if (!free(x, y)) return false; + return nbrs(x, y).every(([ax, ay]) => { + const k = cellKey(ax, ay); + return !onPath.has(k) || (ax === cur[0] && ay === cur[1]); + }); + }); + if (!options.length) break; + const dist = (p: [number, number]) => hexDistance(p, target, orientation, stagger); + options.sort((a, b) => dist(a) - dist(b)); + const here = dist(cur); + let next = options[0]; + if (rng() < turn) { + const sideways = options.filter((p) => dist(p) <= here); + if (sideways.length) next = sideways[Math.floor(rng() * sideways.length)]; + } + path.push(next); + onPath.add(cellKey(next[0], next[1])); + cur = next; + } + const reached = endSide !== null ? onSide(cur, endSide) : hexDistance(cur, target, orientation, stagger) <= 1; + if (path.length < 3 || !reached) return false; + + for (const [x, y] of path) pending.set(cellKey(x, y), t); + if (width >= 2) { + for (const [x, y] of path) { + const side = nbrs(x, y).filter(([nx, ny]) => free(nx, ny) && !pending.has(cellKey(nx, ny))); + for (const [nx, ny] of side.slice(0, width - 1)) pending.set(cellKey(nx, ny), t); + } + } + // Every line hex must fit its fixed neighbours; otherwise try another path. + for (const [k, v] of pending) { + const [x, y] = k.split("_").map(Number); + if (!fitsAt(x, y, v, pending)) return false; + } + const line = new Set(pending.keys()); + if (f.from !== "edge" && f.from !== "none") anchorBlob(start, f.from, pending, line); + if (f.to !== "edge" && f.to !== "none") anchorBlob(cur, f.to, pending, line); + for (const [k, v] of pending) placed.set(k, v); + return true; + }; + + for (const f of features) { + if (!entryOf.has(f.terrain)) continue; + const count = Math.max(1, Math.round(f.count * sizeScale)); + let made = 0; + for (let i = 0; i < count; i++) { + for (let attempt = 0; attempt < 8; attempt++) { + if (drawOne(f)) { + made++; + break; + } + } + } + if (made < count) { + const ends = `${f.from === "edge" ? "a map edge" : f.from} to ${f.to === "edge" ? "a map edge" : f.to}`; + warnings.push(`Placed ${made} of ${count} ${f.terrain} (${ends})`); + } + } + return { cells: placed, warnings }; +} + +/** + * Edge style with an explicit terrain (e.g. water all round for islands): + * a fixed border of that terrain whose width wanders along the edge, so the + * coast isn't a straight frame. The solver builds the shore around it. + */ +export function placeEdgeBorder( + model: HexWfcModel, + s: Required, + grid: GridInfo, + fixed: Map, + rng: () => number, +): Map { + const out = new Map(); + const t = s.edgeTerrain; + if (!t || !(s.edgeStrength > 0) || !model.terrains.some((e) => e.name === t)) return out; + const adj = adjacencyLookup(model); + if (adj(t, t) <= 0) return out; + const { cols, rows, ox, oy, orientation, stagger } = grid; + const maxWidth = s.edgeStrength * Math.max(2, 0.15 * Math.min(cols, rows)) * 1.5; + const phase = [0, 1, 2, 3].map(() => rng() * Math.PI * 2); + for (let j = 0; j < rows; j++) { + for (let i = 0; i < cols; i++) { + const d = Math.min(i, cols - 1 - i, j, rows - 1 - j); + // Smooth wobble in [0, 1] along both axes. + const wobble = + 0.5 + + 0.25 * Math.sin((i / cols) * Math.PI * 4 + phase[0]) * Math.cos((j / rows) * Math.PI * 2 + phase[1]) + + 0.25 * Math.sin((j / rows) * Math.PI * 4 + phase[2]) * Math.cos((i / cols) * Math.PI * 2 + phase[3]); + if (d >= maxWidth * (0.4 + 0.8 * wobble)) continue; + const k = cellKey(ox + i, oy + j); + if (fixed.has(k)) continue; + out.set(k, t); + } + } + // Drop border hexes that would break a rule with a fixed (painted) neighbour. + for (const k of [...out.keys()]) { + const [x, y] = k.split("_").map(Number); + const clash = hexNeighbors(x, y, orientation, stagger).some(([nx, ny]) => { + const u = fixed.get(cellKey(nx, ny)); + return u !== undefined && adj(t, u) <= 0; + }); + if (clash) out.delete(k); + } + return out; +} + diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index 0844ed7f..d1f986f4 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -1,25 +1,38 @@ /** - * Plain-text file format for a model: Markdown with YAML frontmatter and two - * tables. It's meant to be read and edited by hand (and renders nicely in + * Plain-text file format for a model: Markdown with YAML frontmatter and a + * few tables. It's meant to be read and edited by hand (and renders nicely in * Obsidian or on GitHub). * * --- * hex-wfc: 1 * name: lakes - * palette: Default <- any other keys are kept as `meta` + * example-hexes: 2500 + * feature-size: 1 <- solver settings (all optional) + * palette: Default <- any other keys are kept as `meta` * --- - * ## Terrains - * | Terrain | Weight | - * ... - * ## Adjacency - * | Terrain | Next to | Weight | - * ... + * ## Terrains | Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge | + * ## Adjacency | Terrain | Next to | Weight | + * ## Features | Terrain | From | To | Count | (optional) + * ## Layout | Terrain | NW | N | NE | W | C | E | SW | S | SE | (optional) */ -import { LAYOUT_BINS, type HexWfcModel, type GeneratorSettings } from "./model"; +import { + LAYOUT_BINS, + GROWTH_SHAPES, + SYMMETRIES, + type HexWfcModel, + type GeneratorSettings, + type GrowthShape, + type Symmetry, + type CountRange, + type TerrainEntry, +} from "./model"; export const FORMAT_VERSION = 1; const MARKER = "hex-wfc"; +const EXAMPLE_KEY = "example-hexes"; + +type SettingKind = "number" | "string" | "symmetry" | "boolean" | "list" | "mix" | "counts"; /** Frontmatter key for each saved solver setting. */ export const SETTING_KEYS: Record = { @@ -29,8 +42,128 @@ export const SETTING_KEYS: Record = { frequencyFeedback: "mix-strength", scatter: "scatter", randomness: "randomness", + edgeStrength: "edge-strength", + edgeTerrain: "edge-terrain", + lineWidth: "line-width", + smoothing: "smoothing", + symmetry: "symmetry", + spacing: "spacing", + connected: "connected", + impassable: "impassable", + mix: "mix", + counts: "counts", + features: "features", +}; + +const SETTING_KINDS: Record = { + featureSize: "number", + directionalBias: "number", + neighbourInfluence: "number", + frequencyFeedback: "number", + scatter: "number", + randomness: "number", + edgeStrength: "number", + edgeTerrain: "string", + lineWidth: "number", + smoothing: "number", + symmetry: "symmetry", + spacing: "number", + connected: "boolean", + impassable: "list", + mix: "mix", + counts: "counts", + features: "boolean", }; +const num = (n: number) => String(Math.round(n * 1000) / 1000); + +/** + * Value of a setting as stored in frontmatter. Lists and maps are strings + * with "; " between items, so terrain names may contain commas and spaces: + * impassable: "Water; High peaks" + * mix: "Forest 1.5; Water 0.5" + * counts: "Town 3; Lake 1-; Ruin 0-2" (exactly, at least, between) + */ +export function encodeSetting(field: keyof GeneratorSettings, value: unknown): string | number | boolean { + switch (SETTING_KINDS[field]) { + case "number": + return Number(num(value as number)); + case "boolean": + return Boolean(value); + case "list": + return (value as string[]).join("; "); + case "mix": + return Object.entries(value as Record) + .map(([t, m]) => `${t} ${num(m)}`) + .join("; "); + case "counts": + return Object.entries(value as Record) + .map(([t, r]) => { + if (r.min !== undefined && r.min === r.max) return `${t} ${r.min}`; + return `${t} ${r.min ?? ""}-${r.max ?? ""}`; + }) + .join("; "); + default: + return String(value); + } +} + +/** Parse a frontmatter value back into a setting, or explain what's wrong. */ +export function decodeSetting(field: keyof GeneratorSettings, raw: string): { value: unknown } | { error: string } { + const v = raw.trim(); + const items = () => v.split(";").map((p) => p.trim()).filter(Boolean); + const splitLast = (item: string): [string, string] => { + const i = item.lastIndexOf(" "); + return i < 0 ? ["", item] : [item.slice(0, i).trim(), item.slice(i + 1)]; + }; + switch (SETTING_KINDS[field]) { + case "number": { + const n = Number(v); + return v !== "" && Number.isFinite(n) && n >= 0 ? { value: n } : { error: "isn't a number ≥ 0" }; + } + case "boolean": + if (/^(true|yes|on|1)$/i.test(v)) return { value: true }; + if (/^(false|no|off|0)$/i.test(v)) return { value: false }; + return { error: "should be true or false" }; + case "symmetry": + return SYMMETRIES.includes(v as Symmetry) + ? { value: v as Symmetry } + : { error: `should be one of ${SYMMETRIES.join(", ")}` }; + case "string": + return { value: v }; + case "list": + return { value: items() }; + case "mix": { + const out: Record = {}; + for (const item of items()) { + const [t, m] = splitLast(item); + const n = Number(m); + if (!t || !Number.isFinite(n) || n < 0) return { error: `has "${item}"; write it like "Forest 1.5"` }; + out[t] = n; + } + return { value: out }; + } + case "counts": { + const out: Record = {}; + for (const item of items()) { + const [t, spec] = splitLast(item); + const m = /^(\d*)(-?)(\d*)$/.exec(spec); + if (!t || !m || (m[1] === "" && m[3] === "") || (!m[2] && m[3] !== "")) + return { error: `has "${item}"; write it like "Town 3", "Lake 1-" or "Ruin 0-2"` }; + const range: CountRange = {}; + if (m[2]) { + if (m[1] !== "") range.min = Number(m[1]); + if (m[3] !== "") range.max = Number(m[3]); + } else { + range.min = range.max = Number(m[1]); + } + out[t] = range; + } + return { value: out }; + } + } +} + function yamlValue(v: string): string { return /^[A-Za-z0-9_][A-Za-z0-9 _./()-]*$/.test(v) && !v.endsWith(" ") ? v : JSON.stringify(v); } @@ -49,20 +182,24 @@ function parseYamlValue(raw: string): string { } const cell = (s: string) => s.replace(/\\/g, "\\\\").replace(/\|/g, "\\|"); -const num = (n: number) => String(Math.round(n * 1000) / 1000); +const opt = (n: number | undefined, scale = 1) => (n === undefined ? "" : num(n * scale)); export function modelToMarkdown(model: HexWfcModel): string { const fm = [`${MARKER}: ${FORMAT_VERSION}`, `name: ${yamlValue(model.name)}`]; - const settingKeys = new Set(Object.values(SETTING_KEYS)); - for (const [k, v] of Object.entries(model.meta)) { - if (k === MARKER || k === "name" || settingKeys.has(k)) continue; - fm.push(`${k}: ${yamlValue(v)}`); - } + if (model.exampleHexes !== undefined) fm.push(`${EXAMPLE_KEY}: ${model.exampleHexes}`); + const reserved = new Set([MARKER, "name", EXAMPLE_KEY, ...Object.values(SETTING_KEYS)]); for (const [field, key] of Object.entries(SETTING_KEYS) as [keyof GeneratorSettings, string][]) { const v = model.settings?.[field]; - if (v !== undefined) fm.push(`${key}: ${num(v)}`); + if (v === undefined) continue; + const enc = encodeSetting(field, v); + fm.push(`${key}: ${typeof enc === "string" ? JSON.stringify(enc) : String(enc)}`); + } + for (const [k, v] of Object.entries(model.meta)) { + if (reserved.has(k)) continue; + fm.push(`${k}: ${yamlValue(v)}`); } const withLayout = model.terrains.filter((t) => t.layout?.length === 9); + const features = model.features ?? []; const lines = [ "---", ...fm, @@ -70,29 +207,34 @@ export function modelToMarkdown(model: HexWfcModel): string { "", `# ${model.name}`, "", - "A wave function collapse generator. You can edit both tables by hand.", + "A wave function collapse generator. You can edit the tables and settings by hand.", "", - "- **Terrains**: *Weight* is how common the terrain is. 0 means it is never placed.", + "- **Terrains**: *Weight* is how common the terrain is. 0 means the solver never places it.", " *Patch %* is the size of a typical patch as a share of the map, so features", " scale with the map. *Shape* is how it spreads: `blob` (lakes, forests),", - " `line` (ranges, ridges) or `none` (backgrounds, shores, scattered hexes).", - " *Turn* is how often a `line` changes direction (0 to 1).", + " `line` (ranges, ridges), `scatter` (single hexes such as towns) or `none`", + " (backgrounds, shores). *Turn* is how often a `line` changes direction (0 to 1)", + " and *Width* its thickness (1 to 3). *Spacing* is the closest two `scatter` hexes", + " may be. *Edge* is how common the terrain is along the map border (1 = as anywhere).", "- **Adjacency**: pairs that may touch, and how often (higher is more likely).", " A pair that isn't listed can never touch, including a terrain next to itself.", " Order doesn't matter, so *A | B* also covers *B | A*.", + "- **Features** (optional): lines that are always placed, e.g. a river from a map", + " edge to a lake. *From* and *To* are `edge`, `none` or a terrain name.", "- **Layout** (optional): where each terrain sat in the example map, in a 3×3", " grid. 1 means as common there as anywhere; 3 means three times as common.", - " Directional bias uses it to keep, say, an ocean along the bottom.", - "- Frontmatter settings (optional): `feature-size`, `directional-bias`,", - " `clumping`, `mix-strength`, `scatter` and `randomness`.", + "- Frontmatter settings (optional): `feature-size`, `directional-bias`, `clumping`,", + " `mix-strength`, `scatter`, `randomness`, `edge-strength`, `edge-terrain`,", + " `line-width`, `smoothing`, `symmetry`, `spacing`, `connected`, `impassable`,", + " `mix`, `counts` and `features`.", "", "## Terrains", "", - "| Terrain | Weight | Patch % | Shape | Turn |", - "| --- | ---: | ---: | --- | ---: |", + "| Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge |", + "| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: |", ...model.terrains.map( (t) => - `| ${cell(t.name)} | ${num(t.weight)} | ${t.patch === undefined ? "" : num(t.patch * 100)} | ${t.shape ?? ""} | ${t.turn === undefined ? "" : num(t.turn)} |`, + `| ${cell(t.name)} | ${num(t.weight)} | ${opt(t.patch, 100)} | ${t.shape ?? ""} | ${opt(t.turn)} | ${opt(t.width)} | ${opt(t.spacing)} | ${opt(t.edge)} |`, ), "", "## Adjacency", @@ -101,6 +243,16 @@ export function modelToMarkdown(model: HexWfcModel): string { "| --- | --- | ---: |", ...model.adjacency.map((e) => `| ${cell(e.a)} | ${cell(e.b)} | ${num(e.weight)} |`), "", + ...(features.length + ? [ + "## Features", + "", + "| Terrain | From | To | Count |", + "| --- | --- | --- | ---: |", + ...features.map((f) => `| ${cell(f.terrain)} | ${cell(f.from)} | ${cell(f.to)} | ${num(f.count)} |`), + "", + ] + : []), ...(withLayout.length ? [ "## Layout", @@ -146,36 +298,43 @@ export function isModelMarkdown(text: string): boolean { return new RegExp(`^---\\r?\\n(?:.*\\r?\\n)*?${MARKER}\\s*:`).test(text); } +type Section = "terrains" | "adjacency" | "features" | "layout"; +const SECTIONS: readonly Section[] = ["terrains", "adjacency", "features", "layout"]; + /** * Parse a model file. Throws if the text isn't a hex-wfc file at all; bad - * individual rows become warnings instead. + * individual rows and settings become warnings instead. */ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): ParseResult { const lines = text.split(/\r?\n/); const warnings: string[] = []; const meta: Record = {}; - let settings: GeneratorSettings | undefined; - const layouts = new Map(); + const settings: Record = {}; + let exampleHexes: number | undefined; let name = ""; let version: number | null = null; + const fieldByKey = new Map( + (Object.entries(SETTING_KEYS) as [keyof GeneratorSettings, string][]).map(([f, k]) => [k, f]), + ); let i = 0; if (lines[0]?.trim() === "---") { for (i = 1; i < lines.length && lines[i].trim() !== "---"; i++) { - const m = /^([^:#][^:]*):(.*)$/.exec(lines[i]); + const m = /^([^:#\s][^:]*):(.*)$/.exec(lines[i]); if (!m) continue; const key = m[1].trim(); const value = parseYamlValue(m[2]); + const field = fieldByKey.get(key); if (key === MARKER) version = Number(value); else if (key === "name") name = value; - else { - const field = (Object.keys(SETTING_KEYS) as (keyof GeneratorSettings)[]).find((f) => SETTING_KEYS[f] === key); - if (field) { - const n = Number(value); - if (value !== "" && Number.isFinite(n) && n >= 0) (settings ??= {})[field] = n; - else warnings.push(`Setting "${key}: ${value}" isn't a number ≥ 0, ignored`); - } else meta[key] = value; - } + else if (key === EXAMPLE_KEY) { + const n = Number(value); + if (Number.isFinite(n) && n > 0) exampleHexes = n; + } else if (field) { + const decoded = decodeSetting(field, value); + if ("error" in decoded) warnings.push(`Setting "${key}: ${value}" ${decoded.error}, ignored`); + else settings[field] = decoded.value; + } else meta[key] = value; } i++; } @@ -183,12 +342,14 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par if (version > FORMAT_VERSION) warnings.push(`File is ${MARKER} version ${version}; this reader understands version ${FORMAT_VERSION}`); - let section: "terrains" | "adjacency" | "layout" | null = null; + let section: Section | null = null; let headerSeen = false; - // Column index by lower-cased header name, for the Terrains table's - // optional columns. Positions are the fallback for the required ones. + // Column index by lower-cased header name; positions are the fallback for + // the required columns so older or hand-made tables still work. let columns = new Map(); const model: HexWfcModel = { name: "", terrains: [], adjacency: [], meta }; + const features: NonNullable = []; + const layouts = new Map(); const weightOf = (raw: string | undefined, where: string): number | null => { if (raw === undefined || raw === "") return 1; const n = Number(raw); @@ -205,7 +366,7 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par if (h) { const title = h[1].trim().toLowerCase(); if (!name && line.trim().startsWith("# ")) name = h[1].trim(); - section = title === "terrains" || title === "adjacency" || title === "layout" ? title : null; + section = SECTIONS.includes(title as Section) ? (title as Section) : null; headerSeen = false; continue; } @@ -221,49 +382,53 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par columns = new Map(cells.map((c, idx) => [c.toLowerCase(), idx])); continue; } - const sectionTitle = section === "terrains" ? "Terrains" : section === "adjacency" ? "Adjacency" : "Layout"; - const where = `${sectionTitle} row "${cells.join(" | ")}"`; - if (section === "layout") { - if (!cells[0]) continue; - const values = LAYOUT_BINS.map((b) => Number(cells[columns.get(b.toLowerCase()) ?? -1])); - if (values.every((v) => Number.isFinite(v) && v >= 0)) layouts.set(cells[0], values); - else warnings.push(`${where}: needs 9 numbers ≥ 0 under ${LAYOUT_BINS.join(", ")}, row skipped`); - continue; - } + const col = (colName: string) => { + const idx = columns.get(colName); + return idx === undefined ? undefined : cells[idx] || undefined; + }; + const where = `${section[0].toUpperCase()}${section.slice(1)} row "${cells.join(" | ")}"`; + if (!cells[0]) continue; + if (section === "terrains") { - if (!cells[0]) continue; - const col = (name: string) => { - const idx = columns.get(name); - return idx === undefined ? undefined : cells[idx] || undefined; - }; const w = weightOf(col("weight") ?? cells[1], where); if (w === null) continue; - const entry: HexWfcModel["terrains"][number] = { name: cells[0], weight: w }; - const patch = col("patch %") ?? col("patch"); - if (patch !== undefined) { - const n = Number(patch.replace(/%$/, "")); - if (Number.isFinite(n) && n >= 0 && n <= 100) entry.patch = Math.round(n * 1000) / 100000; - else warnings.push(`${where}: patch "${patch}" isn't a percentage, ignored`); - } + const entry: TerrainEntry = { name: cells[0], weight: w }; + const numberCol = (colName: string, lo: number, hi: number, set: (n: number) => void) => { + const raw = col(colName); + if (raw === undefined) return; + const n = Number(raw.replace(/%$/, "")); + if (Number.isFinite(n) && n >= lo && n <= hi) set(n); + else warnings.push(`${where}: ${colName} "${raw}" should be between ${lo} and ${hi}, ignored`); + }; + numberCol(columns.has("patch %") ? "patch %" : "patch", 0, 100, (n) => (entry.patch = Math.round(n * 1000) / 100000)); const shape = col("shape")?.toLowerCase(); if (shape !== undefined) { - if (shape === "blob" || shape === "line" || shape === "none") entry.shape = shape; - else warnings.push(`${where}: shape "${shape}" should be blob, line or none, ignored`); - } - const turn = col("turn"); - if (turn !== undefined) { - const n = Number(turn); - if (Number.isFinite(n) && n >= 0 && n <= 1) entry.turn = n; - else warnings.push(`${where}: turn "${turn}" should be between 0 and 1, ignored`); + if (GROWTH_SHAPES.includes(shape as GrowthShape)) entry.shape = shape as GrowthShape; + else warnings.push(`${where}: shape "${shape}" should be ${GROWTH_SHAPES.join(", ")}, ignored`); } + numberCol("turn", 0, 1, (n) => (entry.turn = n)); + numberCol("width", 1, 3, (n) => (entry.width = n)); + numberCol("spacing", 0, 1000, (n) => (entry.spacing = n)); + numberCol("edge", 0, 1000, (n) => (entry.edge = n)); model.terrains.push(entry); - } else { - if (!cells[0] || !cells[1]) { - if (cells.some(Boolean)) warnings.push(`${where}: needs two terrains, row skipped`); + } else if (section === "adjacency") { + if (!cells[1]) { + warnings.push(`${where}: needs two terrains, row skipped`); continue; } const w = weightOf(cells[2], where); if (w !== null) model.adjacency.push({ a: cells[0], b: cells[1], weight: w }); + } else if (section === "features") { + const count = Number(col("count") ?? "1"); + if (!Number.isFinite(count) || count < 0) { + warnings.push(`${where}: count should be a number ≥ 0, row skipped`); + continue; + } + features.push({ terrain: cells[0], from: col("from") ?? "none", to: col("to") ?? "none", count }); + } else { + const values = LAYOUT_BINS.map((b) => Number(cells[columns.get(b.toLowerCase()) ?? -1])); + if (values.every((v) => Number.isFinite(v) && v >= 0)) layouts.set(cells[0], values); + else warnings.push(`${where}: needs 9 numbers ≥ 0 under ${LAYOUT_BINS.join(", ")}, row skipped`); } } @@ -272,7 +437,9 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par if (entry) entry.layout = values; else warnings.push(`Layout row "${t}" isn't in the Terrains table, ignored`); } - if (settings) model.settings = settings; + if (features.length) model.features = features; + if (exampleHexes !== undefined) model.exampleHexes = exampleHexes; + if (Object.keys(settings).length) model.settings = settings as GeneratorSettings; model.name = name || fallbackName; return { model, warnings }; } diff --git a/packages/hex-wfc/src/grid.ts b/packages/hex-wfc/src/grid.ts index e1be3811..0e9b5126 100644 --- a/packages/hex-wfc/src/grid.ts +++ b/packages/hex-wfc/src/grid.ts @@ -57,6 +57,30 @@ export function directionRing(orientation: Orientation): number[] { return orientation === "flat" ? [0, 2, 3, 1, 5, 4] : [0, 5, 4, 1, 2, 3]; } +/** Offset coords → axial (q, r), matching hexNeighbors' stagger rules. */ +export function toAxial(x: number, y: number, orientation: Orientation, stagger: Stagger = "odd"): [number, number] { + // "odd": odd columns (flat) / rows (pointy) are shifted. x & 1 is 0/1 for negatives too. + if (orientation === "flat") { + const shift = stagger === "odd" ? (x - (x & 1)) / 2 : (x + (x & 1)) / 2; + return [x, y - shift]; + } + const shift = stagger === "odd" ? (y - (y & 1)) / 2 : (y + (y & 1)) / 2; + return [x - shift, y]; +} + +/** Number of steps between two hexes. */ +export function hexDistance( + a: [number, number], + b: [number, number], + orientation: Orientation, + stagger: Stagger = "odd", +): number { + const [q1, r1] = toAxial(a[0], a[1], orientation, stagger); + const [q2, r2] = toAxial(b[0], b[1], orientation, stagger); + const dq = q1 - q2, dr = r1 - r2; + return (Math.abs(dq) + Math.abs(dr) + Math.abs(dq + dr)) / 2; +} + /** Accept either a Map or a plain object of "x_y" → terrain. */ export function toCellMap(cells: Map | Record): Map { return cells instanceof Map ? cells : new Map(Object.entries(cells)); diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index 5a0751a0..a1b861e6 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -1,22 +1,41 @@ -export { hexNeighbors, hexCenter, directionRing, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; +export { + hexNeighbors, + hexCenter, + hexDistance, + toAxial, + directionRing, + cellKey, + parseCellKey, + type Orientation, + type Stagger, +} from "./grid"; export { adjacencyLookup, validateModel, restrictModel, + resolveSettings, + DEFAULT_SETTINGS, + LAYOUT_BINS, + GROWTH_SHAPES, + SYMMETRIES, type HexWfcModel, type TerrainEntry, type AdjacencyEntry, type GrowthShape, type GeneratorSettings, - DEFAULT_SETTINGS, - LAYOUT_BINS, + type LineFeature, + type Symmetry, + type CountRange, } from "./model"; -export { learnModel, measurePatches, measureLayout, SHAPE_THRESHOLDS, type LearnOptions } from "./learn"; +export { learnModel, measurePatches, measureLayout, SHAPE_THRESHOLDS, type LearnOptions, type TerrainAnalysis } from "./learn"; export { solve, findViolation, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; +export { countPatches, type GridInfo } from "./post"; export { modelToMarkdown, parseModelMarkdown, isModelMarkdown, + encodeSetting, + decodeSetting, FORMAT_VERSION, SETTING_KEYS, type ParseResult, diff --git a/packages/hex-wfc/src/learn.ts b/packages/hex-wfc/src/learn.ts index 7afc4425..703c5143 100644 --- a/packages/hex-wfc/src/learn.ts +++ b/packages/hex-wfc/src/learn.ts @@ -1,5 +1,14 @@ -import { hexNeighbors, hexCenter, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; -import type { HexWfcModel, GrowthShape } from "./model"; +import { + hexNeighbors, + hexCenter, + hexDistance, + cellKey, + parseCellKey, + toCellMap, + type Orientation, + type Stagger, +} from "./grid"; +import type { HexWfcModel, GrowthShape, LineFeature, TerrainEntry } from "./model"; export interface LearnOptions { name: string; @@ -14,6 +23,10 @@ export interface LearnOptions { * - Terrain weight = how many hexes use it. * - Adjacency weight = how many edges join the pair. Pairs that never touch * in the example are left out, so they can never touch in generated maps. + * - Shape, patch size, line width, spacing, edge preference and layout come + * from measuring each terrain's patches (see measurePatches). + * - Line patches anchored to a map edge or another terrain become guaranteed + * features (e.g. a river from the edge to a lake). * * Cells that are missing (unpainted) are ignored, along with their edges. */ @@ -42,10 +55,24 @@ export function learnModel( } } - const shapes = measurePatches(map, opts.orientation, stagger); + const analysis = analysePatches(map, opts.orientation, stagger); const layouts = measureLayout(map); - const terrains = [...terrainCount] - .map(([name, weight]) => ({ name, weight, ...shapes.get(name), layout: layouts.get(name) })) + const terrains: TerrainEntry[] = [...terrainCount] + .map(([name, weight]) => { + const a = analysis.terrains.get(name); + const entry: TerrainEntry = { name, weight }; + if (a) { + entry.patch = a.patch; + entry.shape = a.shape; + if (a.turn !== undefined) entry.turn = a.turn; + if (a.width !== undefined) entry.width = a.width; + if (a.spacing !== undefined) entry.spacing = a.spacing; + if (a.edge !== undefined) entry.edge = a.edge; + } + const layout = layouts.get(name); + if (layout) entry.layout = layout; + return entry; + }) .sort((p, q) => q.weight - p.weight || p.name.localeCompare(q.name)); const order = new Map(terrains.map((t, i) => [t.name, i])); const adjacency = [...edgeCount.values()] @@ -56,55 +83,238 @@ export function learnModel( }) .sort((p, q) => order.get(p.a)! - order.get(q.a)! || q.weight - p.weight || p.b.localeCompare(q.b)); - return { name: opts.name, terrains, adjacency, meta: { ...(opts.meta ?? {}) } }; + const model: HexWfcModel = { + name: opts.name, + terrains, + adjacency, + exampleHexes: map.size, + meta: { ...(opts.meta ?? {}) }, + }; + if (analysis.features.length) model.features = analysis.features; + return model; } /** Thresholds for classifying patch shapes. Exported for tests and tuning. */ export const SHAPE_THRESHOLDS = { - /** Size-weighted mean patch below this many hexes → "none" (scattered). */ + /** Size-weighted mean patch below this many hexes → "scatter" (single hexes). */ + scatterPatchHexes: 1.5, + /** Size-weighted mean patch below this many hexes → "none". */ minPatchHexes: 2.5, /** Patch above this share of the map → "none" (it's the background). */ maxPatchShare: 0.3, - /** Long axis / short axis at or above this → "line". */ + /** Long axis / short axis at or above this → "line"... */ lineElongation: 2.2, + /** ...if also at most this many hexes thick. Thicker long patches (a sea + * along one edge) are bands, treated as blobs. */ + maxLineWidth: 3.5, + /** A thin patch whose second most common neighbouring terrain makes up at + * least this share of its border is a boundary (a shore between land and + * sea), not a line: it's left to the neighbour rules. */ + boundaryShare: 0.3, /** Mean same-terrain neighbours at or above this → "blob"; below → thin * (shores, rings), left to the neighbour rules. */ blobThickness: 3.5, + /** Line patches at least this many hexes long can become features. */ + featureMinHexes: 4, }; +interface Patch { + terrain: string; + cells: [number, number][]; + /** Principal axis (unit vector) and centroid of hex centres. */ + axis: [number, number]; + centre: [number, number]; + l1: number; + l2: number; + sameNeighbours: number; + /** Neighbouring terrains other than its own, with edge counts. */ + others: Map; +} + +export interface TerrainAnalysis { + patch: number; + shape: GrowthShape; + turn?: number; + width?: number; + spacing?: number; + edge?: number; +} + /** - * Measure each terrain's connected patches and turn them into a growth style. - * Only shape is used, never names, so it works for any palette. - * - * - patch: size-weighted mean patch size (Σs² / Σs, so one big lake counts - * for more than a few stray specks), as a fraction of all painted hexes. - * - elongation: √(λ1/λ2) of the covariance of hex centres, per patch. - * - thickness: mean number of same-terrain neighbours. + * Measure each terrain's patches and turn them into growth style and the + * other learned per-terrain values. Only shape is used, never names. */ export function measurePatches( cells: Map, orientation: Orientation, stagger: Stagger = "odd", -): Map { - const seen = new Set(); - const stats = new Map(); +): Map { + return analysePatches(cells, orientation, stagger).terrains; +} + +function analysePatches( + cells: Map, + orientation: Orientation, + stagger: Stagger, +): { terrains: Map; features: LineFeature[] } { + const patches = findPatches(cells, orientation, stagger); const total = cells.size; + const TH = SHAPE_THRESHOLDS; + + // Bounding box of the painted area, for edge detection. + let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; + for (const key of cells.keys()) { + const xy = parseCellKey(key); + if (!xy) continue; + minX = Math.min(minX, xy[0]); maxX = Math.max(maxX, xy[0]); + minY = Math.min(minY, xy[1]); maxY = Math.max(maxY, xy[1]); + } + const borderDist = ([x, y]: [number, number]) => Math.min(x - minX, maxX - x, y - minY, maxY - y); + + const byTerrain = new Map(); + for (const p of patches) { + const list = byTerrain.get(p.terrain); + if (list) list.push(p); + else byTerrain.set(p.terrain, [p]); + } + + // The background (largest share) is ignored when deciding what a line's end touches. + let background = ""; + let bgCount = -1; + const countOf = new Map(); + for (const t of cells.values()) countOf.set(t, (countOf.get(t) ?? 0) + 1); + for (const [t, n] of countOf) if (n > bgCount) { bgCount = n; background = t; } + + // Edge preference: share in the outer two rings vs overall. + const edgeRingTotal = [...cells.keys()].filter((k) => { + const xy = parseCellKey(k); + return xy && borderDist(xy) <= 1; + }).length; + const bigEnough = maxX - minX >= 5 && maxY - minY >= 5; + + const terrains = new Map(); + const lineTerrains = new Set(); + for (const [t, list] of byTerrain) { + let sumS = 0, sumS2 = 0, elongW = 0, thickW = 0, widthW = 0, weighted = 0; + const others = new Map(); + for (const p of list) { + for (const [u, n] of p.others) others.set(u, (others.get(u) ?? 0) + n); + const s = p.cells.length; + sumS += s; + sumS2 += s * s; + if (s >= 3) { + const elongation = Math.sqrt((p.l1 + 0.25) / (p.l2 + 0.25)); + // A uniform segment of length L has variance L²/12; centres are √3 apart. + const span = Math.sqrt(12 * p.l1) / Math.sqrt(3) + 1; + elongW += elongation * s; + thickW += (p.sameNeighbours / s) * s; + widthW += (s / span) * s; + weighted += s; + } + } + const meanPatch = sumS2 / sumS; + const share = total ? meanPatch / total : 0; + const a: TerrainAnalysis = { patch: Math.round(share * 10000) / 10000, shape: "none" }; + if (meanPatch < TH.scatterPatchHexes) a.shape = "scatter"; + else if (meanPatch < TH.minPatchHexes || share > TH.maxPatchShare || weighted === 0) a.shape = "none"; + else { + const elong = elongW / weighted; + const thick = thickW / weighted; + const width = widthW / weighted; + const border = [...others.values()].sort((x, y) => y - x); + const borderTotal = border.reduce((x, y) => x + y, 0); + const isBoundary = borderTotal > 0 && (border[1] ?? 0) / borderTotal >= TH.boundaryShare; + if (elong >= TH.lineElongation && width <= TH.maxLineWidth && isBoundary) { + a.shape = "none"; + } else if (elong >= TH.lineElongation && width <= TH.maxLineWidth) { + a.shape = "line"; + // Straighter patches (higher elongation) turn less. Heuristic. + a.turn = Math.round(Math.min(0.5, Math.max(0.05, 1.2 / elong)) * 100) / 100; + a.width = Math.round(Math.min(3, Math.max(1, width)) * 10) / 10; + lineTerrains.add(t); + } else if (thick >= TH.blobThickness || elong >= TH.lineElongation) { + a.shape = "blob"; + } + } + if (a.shape === "scatter" && list.length > 1) a.spacing = minSpacing(list, orientation, stagger); + if (bigEnough && edgeRingTotal > 0) { + const all = countOf.get(t) ?? 0; + const tShare = all / total; + let onEdge = 0; + for (const p of list) for (const c of p.cells) if (borderDist(c) <= 1) onEdge++; + const PSEUDO = 4; + const density = (onEdge + PSEUDO * tShare) / (edgeRingTotal + PSEUDO) / tShare; + a.edge = Math.round(Math.max(0.02, density) * 100) / 100; + } + terrains.set(t, a); + } + + // Features: line patches whose ends are anchored to the map edge or to a + // (non-background) terrain. + const featureCount = new Map(); + for (const p of patches) { + if (!lineTerrains.has(p.terrain) || p.cells.length < TH.featureMinHexes) continue; + const proj = (c: [number, number]) => { + const [px, py] = hexCenter(c[0], c[1], orientation, stagger); + return (px - p.centre[0]) * p.axis[0] + (py - p.centre[1]) * p.axis[1]; + }; + let lo = p.cells[0], hi = p.cells[0]; + for (const c of p.cells) { + if (proj(c) < proj(lo)) lo = c; + if (proj(c) > proj(hi)) hi = c; + } + const anchor = (end: [number, number]): string => { + if (borderDist(end) <= 1) return "edge"; + const near = new Map(); + for (const [k, t] of cells) { + if (t === p.terrain || t === background) continue; + const xy = parseCellKey(k); + if (xy && hexDistance(xy, end, orientation, stagger) <= 1) near.set(t, (near.get(t) ?? 0) + 1); + } + // Prefer a blob (a lake) over a thin terrain it passes through (its shore). + let best = "none", bestScore = 0; + for (const [t, n] of near) { + const sc = n + (terrains.get(t)?.shape === "blob" ? 100 : 0); + if (sc > bestScore) { bestScore = sc; best = t; } + } + return best; + }; + let from = anchor(lo), to = anchor(hi); + // A feature connects two things: edge to edge, or edge/terrain to terrain. + if (from === "none" || to === "none") continue; + // Prefer "edge" first, then a terrain, then "none". + const rank = (e: string) => (e === "edge" ? 0 : e === "none" ? 2 : 1); + if (rank(to) < rank(from) || (rank(to) === rank(from) && to < from)) [from, to] = [to, from]; + const key = `${p.terrain}\u0000${from}\u0000${to}`; + const f = featureCount.get(key); + if (f) f.count++; + else featureCount.set(key, { terrain: p.terrain, from, to, count: 1 }); + } + return { terrains, features: [...featureCount.values()] }; +} + +/** Flood-fill same-terrain patches and measure each one's shape. */ +function findPatches(cells: Map, orientation: Orientation, stagger: Stagger): Patch[] { + const seen = new Set(); + const out: Patch[] = []; for (const [start, t] of cells) { - if (seen.has(start)) continue; - // Flood-fill one patch. - const patch: [number, number][] = []; + if (seen.has(start) || !t) continue; + const list: [number, number][] = []; const stack = [start]; seen.add(start); let sameNeighbours = 0; + const others = new Map(); while (stack.length) { const key = stack.pop()!; const xy = parseCellKey(key); if (!xy) continue; - patch.push(xy); + list.push(xy); for (const [nx, ny] of hexNeighbors(xy[0], xy[1], orientation, stagger)) { const nk = cellKey(nx, ny); - if (cells.get(nk) !== t) continue; + const u = cells.get(nk); + if (u !== undefined && u !== t) others.set(u, (others.get(u) ?? 0) + 1); + if (u !== t) continue; sameNeighbours++; if (!seen.has(nk)) { seen.add(nk); @@ -112,58 +322,38 @@ export function measurePatches( } } } - const s = patch.length; - const st = stats.get(t) ?? { sumS: 0, sumS2: 0, elong: 0, thick: 0, weighted: 0 }; - st.sumS += s; - st.sumS2 += s * s; - if (s >= 3) { - // Principal axes of the patch. - let mx = 0, my = 0; - const pts = patch.map(([x, y]) => hexCenter(x, y, orientation, stagger)); - for (const [px, py] of pts) { mx += px; my += py; } - mx /= s; my /= s; - let sxx = 0, syy = 0, sxy = 0; - for (const [px, py] of pts) { - sxx += (px - mx) ** 2; syy += (py - my) ** 2; sxy += (px - mx) * (py - my); - } - sxx /= s; syy /= s; sxy /= s; - const tr = sxx + syy, det = sxx * syy - sxy * sxy; - const disc = Math.sqrt(Math.max(0, (tr * tr) / 4 - det)); - const l1 = tr / 2 + disc, l2 = Math.max(0, tr / 2 - disc); - const elongation = Math.sqrt((l1 + 0.25) / (l2 + 0.25)); - // Weight by size so big patches decide the style. - st.elong += elongation * s; - st.thick += (sameNeighbours / s) * s; - st.weighted += s; - } - stats.set(t, st); - } - - const out = new Map(); - const T = SHAPE_THRESHOLDS; - for (const [t, st] of stats) { - const meanPatch = st.sumS2 / st.sumS; - const share = total ? meanPatch / total : 0; - const patch = Math.round(share * 10000) / 10000; - if (meanPatch < T.minPatchHexes || share > T.maxPatchShare || st.weighted === 0) { - out.set(t, { patch, shape: "none" }); - continue; - } - const elong = st.elong / st.weighted; - const thick = st.thick / st.weighted; - if (elong >= T.lineElongation) { - // Straighter patches (higher elongation) turn less. Heuristic. - const turn = Math.round(Math.min(0.5, Math.max(0.05, 1.2 / elong)) * 100) / 100; - out.set(t, { patch, shape: "line", turn }); - } else if (thick >= T.blobThickness) { - out.set(t, { patch, shape: "blob" }); - } else { - out.set(t, { patch, shape: "none" }); + // Principal axes of the hex centres. + const pts = list.map(([x, y]) => hexCenter(x, y, orientation, stagger)); + const s = pts.length; + let mx = 0, my = 0; + for (const [px, py] of pts) { mx += px; my += py; } + mx /= s; my /= s; + let sxx = 0, syy = 0, sxy = 0; + for (const [px, py] of pts) { + sxx += (px - mx) ** 2; syy += (py - my) ** 2; sxy += (px - mx) * (py - my); } + sxx /= s; syy /= s; sxy /= s; + const tr = sxx + syy, det = sxx * syy - sxy * sxy; + const disc = Math.sqrt(Math.max(0, (tr * tr) / 4 - det)); + const l1 = tr / 2 + disc, l2 = Math.max(0, tr / 2 - disc); + // Eigenvector for l1. + let ax = sxy, ay = l1 - sxx; + if (Math.abs(ax) + Math.abs(ay) < 1e-9) [ax, ay] = sxx >= syy ? [1, 0] : [0, 1]; + const len = Math.hypot(ax, ay); + out.push({ terrain: t, cells: list, axis: [ax / len, ay / len], centre: [mx, my], l1, l2, sameNeighbours, others }); } return out; } +/** Smallest distance between two patches of the same scattered terrain (capped). */ +function minSpacing(list: Patch[], orientation: Orientation, stagger: Stagger): number { + const pts = list.slice(0, 400).map((p) => p.cells[0]); + let min = Infinity; + for (let i = 0; i < pts.length; i++) + for (let j = i + 1; j < pts.length; j++) min = Math.min(min, hexDistance(pts[i], pts[j], orientation, stagger)); + return Math.min(12, min); +} + /** * Where each terrain sits in the example: relative density in a 3×3 grid over * the painted area's bounding box (NW, N, NE, W, C, E, SW, S, SE). 1 means as diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index fa32b95f..7441158e 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -11,10 +11,14 @@ * How a terrain spreads when the solver places it: * - "blob": grows outward into a compact patch (lakes, forests); * - "line": pushes forward in a heading, turning now and then (ranges, ridges); + * - "scatter": single hexes dotted around (towns, ruins); kept apart by + * spacing and never removed by smoothing; * - "none": no growth; its shape comes from the neighbour rules alone - * (backgrounds, shores, scattered single hexes). + * (backgrounds, shores). */ -export type GrowthShape = "blob" | "line" | "none"; +export type GrowthShape = "blob" | "line" | "scatter" | "none"; + +export const GROWTH_SHAPES: readonly GrowthShape[] = ["blob", "line", "scatter", "none"]; export interface TerrainEntry { name: string; @@ -30,6 +34,18 @@ export interface TerrainEntry { shape?: GrowthShape; /** For "line": chance per step of turning (0–1). Missing = 0.2. */ turn?: number; + /** For "line": thickness in hexes (1–3). Missing = 1. */ + width?: number; + /** + * For "scatter": minimum distance in hexes between two hexes of this + * terrain, as seen in the example. Scaled with map size when solving. + */ + spacing?: number; + /** + * How common the terrain is along the map border compared with overall + * (1 = no preference, 3 = three times as common at the edge). + */ + edge?: number; /** * Where the terrain sat in the example, as relative density in a 3×3 grid * (row-major: NW, N, NE, W, C, E, SW, S, SE). 1 = as common as anywhere, @@ -42,16 +58,66 @@ export interface TerrainEntry { export const LAYOUT_BINS = ["NW", "N", "NE", "W", "C", "E", "SW", "S", "SE"] as const; /** - * Solver settings saved with a generator. Each maps to the SolveOptions - * field of the same name; options passed to solve() win over these. + * A guaranteed line feature, e.g. a river from a map edge to a lake. Placed + * before the solver runs, so it always exists. `from`/`to` are "edge", "none" + * (just stops) or a terrain name it must end at. + */ +export interface LineFeature { + terrain: string; + from: string; + to: string; + /** How many the example had. Scaled with map size when solving. */ + count: number; +} + +export type Symmetry = "none" | "left-right" | "top-bottom" | "both"; +export const SYMMETRIES: readonly Symmetry[] = ["none", "left-right", "top-bottom", "both"]; + +/** Min/max number of separate patches of a terrain (a town is a 1-hex patch). */ +export interface CountRange { + min?: number; + max?: number; +} + +/** + * Solver settings saved with a generator. Options passed to solve() win over + * these, and missing ones use DEFAULT_SETTINGS. */ export interface GeneratorSettings { + /** Multiplier on learned patch sizes. 0 turns growth off. */ featureSize?: number; + /** 0–1: keep terrain where it sat in the example (an ocean along the bottom stays there). */ directionalBias?: number; + /** How strongly decided neighbours steer each choice (clumping). */ neighbourInfluence?: number; + /** How hard the overall terrain mix is pulled toward the model's weights. */ frequencyFeedback?: number; + /** Randomness in which hex is decided next; lets enclosed features start. */ scatter?: number; + /** 0–1 share of each choice made by terrain weight alone (peppers rare terrain). */ randomness?: number; + /** 0–1: how strongly the border follows `edgeTerrain` (or the learned edge preference). */ + edgeStrength?: number; + /** Terrain the border should prefer ("" = as learned), e.g. water for islands. */ + edgeTerrain?: string; + /** Thickness of line terrains: 0 = as learned, otherwise 1–3. */ + lineWidth?: number; + /** 0–1: clean up lone specks and ragged edges after generating. */ + smoothing?: number; + /** Mirror the map. Symmetric where the rules allow. */ + symmetry?: Symmetry; + /** Multiplier on learned spacing between scattered terrain (towns). 0 = off. */ + spacing?: number; + /** Make all land (terrain not in `impassable`) one connected area. */ + connected?: boolean; + /** Terrains that count as impassable for `connected` (water, peaks, ...). */ + impassable?: string[]; + /** Per-terrain multiplier on weight, e.g. { Forest: 1.5, Water: 0.5 }. */ + mix?: Record; + /** Per-terrain min/max number of separate patches. */ + counts?: Record; + /** Lay down the model's guaranteed line features (rivers). */ + features?: boolean; } export const DEFAULT_SETTINGS: Required = { @@ -61,6 +127,17 @@ export const DEFAULT_SETTINGS: Required = { frequencyFeedback: 2, scatter: 3, randomness: 0.1, + edgeStrength: 0, + edgeTerrain: "", + lineWidth: 0, + smoothing: 0, + symmetry: "none", + spacing: 1, + connected: false, + impassable: [], + mix: {}, + counts: {}, + features: true, }; export interface AdjacencyEntry { @@ -74,6 +151,10 @@ export interface HexWfcModel { name: string; terrains: TerrainEntry[]; adjacency: AdjacencyEntry[]; + /** Guaranteed line features (rivers). */ + features?: LineFeature[]; + /** Number of painted hexes in the example. Used to scale counts and spacing. */ + exampleHexes?: number; /** Free-form string metadata (palette, source map, ...). Preserved by the file format. */ meta: Record; /** Saved solver settings. Missing fields use DEFAULT_SETTINGS. */ @@ -108,10 +189,12 @@ export function validateModel(model: HexWfcModel): string[] { problems.push(`Terrain "${t.name}" has an invalid weight`); if (t.patch !== undefined && !(t.patch >= 0 && t.patch <= 1)) problems.push(`Terrain "${t.name}" has a patch size outside 0–100%`); - if (t.shape !== undefined && !["blob", "line", "none"].includes(t.shape)) + if (t.shape !== undefined && !GROWTH_SHAPES.includes(t.shape)) problems.push(`Terrain "${t.name}" has unknown shape "${String(t.shape)}"`); if (t.turn !== undefined && !(t.turn >= 0 && t.turn <= 1)) problems.push(`Terrain "${t.name}" has a turn rate outside 0–1`); + if (t.width !== undefined && !(t.width >= 1 && t.width <= 3)) + problems.push(`Terrain "${t.name}" has a width outside 1–3`); if (t.layout !== undefined && (t.layout.length !== 9 || t.layout.some((v) => !(v >= 0)))) problems.push(`Terrain "${t.name}" needs 9 layout values ≥ 0`); } @@ -122,6 +205,12 @@ export function validateModel(model: HexWfcModel): string[] { if (!Number.isFinite(weight) || weight < 0) problems.push(`Adjacency row "${a} | ${b}" has an invalid weight`); } + for (const f of model.features ?? []) { + if (!names.has(f.terrain)) problems.push(`Feature uses unknown terrain "${f.terrain}"`); + for (const end of [f.from, f.to]) + if (end !== "edge" && end !== "none" && !names.has(end)) + problems.push(`Feature "${f.terrain}" ends at unknown terrain "${end}"`); + } const adj = adjacencyLookup(model); for (const t of model.terrains) { if (t.weight > 0 && !model.terrains.some((u) => adj(t.name, u.name) > 0)) @@ -131,16 +220,31 @@ export function validateModel(model: HexWfcModel): string[] { } /** - * Drop terrains that aren't in `allowed` (and their adjacency rows). Use it to - * fit a model to a palette that lacks some of its terrains. + * Drop terrains that aren't in `allowed` (and their adjacency rows and + * features). Use it to fit a model to a palette that lacks some terrains. */ export function restrictModel(model: HexWfcModel, allowed: Iterable): HexWfcModel { const keep = new Set(allowed); + const ok = (end: string) => end === "edge" || end === "none" || keep.has(end); return { ...model, terrains: model.terrains.filter((t) => keep.has(t.name)), adjacency: model.adjacency.filter((e) => keep.has(e.a) && keep.has(e.b)), + ...(model.features + ? { features: model.features.filter((f) => keep.has(f.terrain) && ok(f.from) && ok(f.to)) } + : {}), meta: { ...model.meta }, ...(model.settings ? { settings: { ...model.settings } } : {}), }; } + +/** Settings with defaults filled in; `override` wins over the model's saved ones. */ +export function resolveSettings(model: HexWfcModel, override: GeneratorSettings = {}): Required { + const out: Required = { ...DEFAULT_SETTINGS }; + for (const src of [model.settings ?? {}, override]) { + for (const [k, v] of Object.entries(src)) { + if (v !== undefined) (out as unknown as Record)[k] = v; + } + } + return out; +} diff --git a/packages/hex-wfc/src/post.ts b/packages/hex-wfc/src/post.ts new file mode 100644 index 00000000..320f7be4 --- /dev/null +++ b/packages/hex-wfc/src/post.ts @@ -0,0 +1,246 @@ +/** + * Passes that run on a finished map. Every change keeps all adjacency rules: + * a hex only changes to a terrain allowed next to all of its neighbours. + * Protected hexes (fixed / painted, and guaranteed features) never change. + */ + +import { hexNeighbors, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; +import { adjacencyLookup, type HexWfcModel, type CountRange } from "./model"; + +export interface GridInfo { + cols: number; + rows: number; + ox: number; + oy: number; + orientation: Orientation; + stagger: Stagger; +} + +const neighbourKeys = (key: string, grid: GridInfo, cells: Map): string[] => { + const xy = parseCellKey(key); + if (!xy) return []; + return hexNeighbors(xy[0], xy[1], grid.orientation, grid.stagger) + .map(([x, y]) => cellKey(x, y)) + .filter((k) => cells.has(k)); +}; + +/** Deterministic shuffle. */ +function shuffled(items: T[], rng: () => number): T[] { + const a = items.slice(); + for (let i = a.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + [a[i], a[j]] = [a[j], a[i]]; + } + return a; +} + +/** Can `key` become terrain u without breaking a rule with any neighbour? */ +function fits( + key: string, + u: string, + cells: Map, + grid: GridInfo, + adj: (a: string, b: string) => number, +): boolean { + return neighbourKeys(key, grid, cells).every((n) => adj(u, cells.get(n)!) > 0); +} + +/** + * Clean up lone specks and ragged edges: a hex with too few same-terrain + * neighbours takes its most common neighbouring terrain (if the rules allow). + * Strength 0–1 sets the number of passes and how lonely a hex must be. + * Scattered and line terrains are left alone (thin by nature). + * Returns the number of hexes changed. + */ +export function smooth( + cells: Map, + model: HexWfcModel, + grid: GridInfo, + strength: number, + protect: Set, + rng: () => number, +): number { + if (!(strength > 0)) return 0; + const adj = adjacencyLookup(model); + const keepShape = new Set(model.terrains.filter((t) => t.shape === "scatter" || t.shape === "line").map((t) => t.name)); + const passes = Math.ceil(Math.min(1, strength) * 3); + const lonely = strength >= 0.5 ? 1 : 0; // max same-terrain neighbours to count as a speck + let changed = 0; + for (let p = 0; p < passes; p++) { + let changedThisPass = 0; + for (const key of shuffled([...cells.keys()], rng)) { + const t = cells.get(key)!; + if (protect.has(key) || keepShape.has(t)) continue; + const ns = neighbourKeys(key, grid, cells); + let same = 0; + const tally = new Map(); + for (const n of ns) { + const u = cells.get(n)!; + if (u === t) same++; + else tally.set(u, (tally.get(u) ?? 0) + 1); + } + if (same > lonely) continue; + const candidates = [...tally].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); + for (const [u, n] of candidates) { + if (n < 2) break; // need a real majority to switch to + if (fits(key, u, cells, grid, adj)) { + cells.set(key, u); + changed++; + changedThisPass++; + break; + } + } + } + if (!changedThisPass) break; + } + return changed; +} + +/** Connected groups of hexes for which `inGroup` is true. */ +function components(cells: Map, grid: GridInfo, inGroup: (t: string) => boolean): string[][] { + const seen = new Set(); + const out: string[][] = []; + for (const [key, t] of cells) { + if (seen.has(key) || !inGroup(t)) continue; + const comp: string[] = []; + const stack = [key]; + seen.add(key); + while (stack.length) { + const k = stack.pop()!; + comp.push(k); + for (const n of neighbourKeys(k, grid, cells)) { + if (!seen.has(n) && inGroup(cells.get(n)!)) { + seen.add(n); + stack.push(n); + } + } + } + out.push(comp); + } + return out; +} + +/** + * Make all land (terrain not in `impassable`) one connected area by filling + * cut-off pockets with impassable terrain, working inward from their edges. + * Returns how many hexes changed and how many land hexes are still cut off + * (when the rules allowed no valid fill). + */ +export function connectLand( + cells: Map, + model: HexWfcModel, + grid: GridInfo, + impassable: Set, + protect: Set, +): { changed: number; stranded: number } { + const adj = adjacencyLookup(model); + const isLand = (t: string) => !impassable.has(t); + const blockers = model.terrains.filter((t) => impassable.has(t.name)).map((t) => t.name); + let changed = 0; + for (let round = 0; round < 50; round++) { + const land = components(cells, grid, isLand).sort((a, b) => b.length - a.length); + if (land.length <= 1) return { changed, stranded: 0 }; + let progress = false; + for (const pocket of land.slice(1)) { + for (const key of pocket) { + if (protect.has(key)) continue; + // Prefer the blocker most common around this hex. + const tally = new Map(); + for (const n of neighbourKeys(key, grid, cells)) { + const u = cells.get(n)!; + if (impassable.has(u)) tally.set(u, (tally.get(u) ?? 0) + 1); + } + const order = [...blockers].sort((a, b) => (tally.get(b) ?? 0) - (tally.get(a) ?? 0)); + for (const u of order) { + if (fits(key, u, cells, grid, adj)) { + cells.set(key, u); + changed++; + progress = true; + break; + } + } + } + } + if (!progress) break; + } + const land = components(cells, grid, isLand).sort((a, b) => b.length - a.length); + return { changed, stranded: land.slice(1).reduce((n, c) => n + c.length, 0) }; +} + +/** Number of separate patches per terrain. */ +export function countPatches(cells: Map, grid: GridInfo): Map { + const out = new Map(); + const seen = new Set(); + for (const [key, t] of cells) { + if (seen.has(key)) continue; + out.set(t, (out.get(t) ?? 0) + 1); + const stack = [key]; + seen.add(key); + while (stack.length) { + const k = stack.pop()!; + for (const n of neighbourKeys(k, grid, cells)) { + if (!seen.has(n) && cells.get(n) === t) { + seen.add(n); + stack.push(n); + } + } + } + } + return out; +} + +/** How far the patch counts are from the requested ranges (0 = all met). */ +export function countsPenalty(counted: Map, counts: Record): number { + let p = 0; + for (const [t, r] of Object.entries(counts)) { + const n = counted.get(t) ?? 0; + if (r.min !== undefined && n < r.min) p += r.min - n; + if (r.max !== undefined && n > r.max) p += n - r.max; + } + return p; +} + +/** + * Add single-hex patches of terrains below their minimum count, on hexes + * where the rules allow it and the hex isn't next to the same terrain. + * Doesn't take a hex from a terrain that would then drop below its own + * minimum. Returns the number of hexes changed. + */ +export function topUpCounts( + cells: Map, + model: HexWfcModel, + grid: GridInfo, + counts: Record, + protect: Set, + rng: () => number, +): number { + const adj = adjacencyLookup(model); + const known = new Set(model.terrains.map((t) => t.name)); + let changed = 0; + for (const [t, r] of Object.entries(counts)) { + if (r.min === undefined || !known.has(t)) continue; + let n = countPatches(cells, grid).get(t) ?? 0; + if (n >= r.min) continue; + for (const key of shuffled([...cells.keys()], rng)) { + if (n >= r.min) break; + const current = cells.get(key)!; + if (protect.has(key) || current === t) continue; + if (neighbourKeys(key, grid, cells).some((k) => cells.get(k) === t)) continue; + if (!fits(key, t, cells, grid, adj)) continue; + const own = counts[current]; + if (own?.min !== undefined) { + cells.set(key, t); + const after = countPatches(cells, grid).get(current) ?? 0; + if (after < own.min) { + cells.set(key, current); + continue; + } + } else { + cells.set(key, t); + } + changed++; + n++; + } + } + return changed; +} diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 613d80d8..8719d702 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -1,30 +1,39 @@ /** * Hex Wave Function Collapse (simple tiled model) with neighbour-weighted - * choices. + * choices, growth moves and map-level constraints. * * Hard rules: a pair with adjacency weight 0 can never touch (enforced by - * arc-consistency propagation plus backtracking). + * arc-consistency propagation plus backtracking). Post passes (smoothing, + * connected land, counts) only make changes that keep every rule. * - * Soft rules: when a hex is collapsed, each candidate terrain t is scored - * weight(t) × (geometric mean over decided neighbours u of adj(t,u) / Σ_v adj(t,v))^influence - * A model learned from a map with a lake therefore grows lake next to lake - * rather than scattering it. (A plain product over neighbours overcounts, - * because neighbours are correlated, and lets one terrain swallow the map.) - * The same scores drive the entropy used to pick the next hex. - * - * Two more terms keep the result looking like the example: + * Soft rules: each candidate terrain t for a hex is scored + * weight(t) × (geometric mean over decided neighbours u of P(u | t))^influence + * × layout and edge preferences + * A plain product over neighbours overcounts (neighbours are correlated) and + * lets one terrain swallow the map. The same scores drive the entropy used + * to pick the next hex. On top of that: * - frequency feedback nudges each choice toward the model's terrain mix; * - scatter adds randomness to the order hexes are decided in, so - * features start in many places instead of one frontier swallowing all. + * features start in many places instead of one frontier swallowing all; + * - growth moves let blob/line terrains spread from where a patch starts; + * - randomness mixes in plain weight-only picks (peppers rare terrain). * * Deterministic for a given model, options and seed. */ import { hexNeighbors, directionRing, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; -import { adjacencyLookup, DEFAULT_SETTINGS, type HexWfcModel } from "./model"; +import { + adjacencyLookup, + resolveSettings, + type HexWfcModel, + type GeneratorSettings, + type CountRange, +} from "./model"; import { mulberry32 } from "./rng"; +import { placeFeatures, placeEdgeBorder } from "./features"; +import { smooth, connectLand, countPatches, countsPenalty, topUpCounts, type GridInfo } from "./post"; -export interface SolveOptions { +export interface SolveOptions extends GeneratorSettings { cols: number; rows: number; /** Coordinate of the top-left hex. Stagger parity uses absolute coords, so this matters. */ @@ -34,49 +43,15 @@ export interface SolveOptions { /** Hexes that must keep their terrain, keyed "x_y" in absolute coords. */ fixed?: Map | Record; seed: number; - /** - * How strongly decided neighbours steer each choice (clumping). 0 uses only - * the hard rules and terrain weights, which gives speckled noise. Default 3. - */ - neighbourInfluence?: number; - /** - * How hard the solver steers the overall terrain mix toward the model's - * terrain weights. Without it, the most common terrain tends to swallow the - * map, because every new hex copies its neighbours. 0 turns it off. - * Default 2. - */ - frequencyFeedback?: number; - /** - * Randomness in which hex is decided next. Low values grow one region - * outward from a single start; higher values start features in many - * places, which lets enclosed features (a lake inside its shore) form. - * Default 3. - */ - scatter?: number; - /** - * Multiplier on each terrain's learned patch size (its "growth moves"). - * Patch sizes are stored as a share of the map, so they already scale with - * the grid; this adjusts on top: below 1 gives more, smaller features, - * above 1 fewer, bigger ones. 0 turns growth off. Default 1. - */ - featureSize?: number; - /** - * How strongly terrain keeps to where it sat in the example (its 3×3 - * layout). 0 = anywhere; 1 = e.g. an ocean along the bottom of the example - * stays along the bottom. Default 0. - */ - directionalBias?: number; - /** - * Share of each choice made by terrain weight alone, ignoring neighbours, - * layout and growth. Lets rare terrains (towns, ruins) pepper the map - * instead of only appearing where the example had them. Hard rules still - * apply. 0–1, default 0.1. - */ - randomness?: number; /** Backtracks allowed per attempt before restarting. Default 2000. */ maxBacktracks?: number; /** Fresh attempts after the first. Default 5. */ maxRestarts?: number; + /** + * Whole-map tries when counts or connected land are set; the best result + * is kept. Default 8. + */ + maxTries?: number; } export interface SolveStats { @@ -85,11 +60,23 @@ export interface SolveStats { decisions: number; /** Hexes placed by growth moves (blob/line spreading). */ grown: number; + /** Hexes changed by smoothing / connected land / count top-ups. */ + postChanges: number; + /** Whole-map tries (more than 1 when counts or connected land need it). */ + tries: number; ms: number; } export type SolveResult = - | { ok: true; cells: Map; stats: SolveStats } + | { + ok: true; + cells: Map; + /** Hexes laid down as guaranteed features (rivers), keyed "x_y". */ + featureCells: Set; + /** Soft goals that weren't fully met (counts, connected land, features). */ + warnings: string[]; + stats: SolveStats; + } | { ok: false; reason: "invalid-input" | "fixed-conflict" | "contradiction"; @@ -118,17 +105,134 @@ export function findViolation( return null; } +const emptyStats = (): SolveStats => ({ + attempts: 0, backtracks: 0, decisions: 0, grown: 0, postChanges: 0, tries: 0, ms: 0, +}); + +/** + * Generate a map. Lays down guaranteed features, runs the solver, then the + * post passes. When counts or connected land are requested, it makes several + * whole-map tries and keeps the best. + */ +export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { + const t0 = Date.now(); + const s = resolveSettings(model, opts); + const stagger = opts.stagger ?? "odd"; + const grid: GridInfo = { + cols: opts.cols, + rows: opts.rows, + ox: opts.offset?.x ?? 0, + oy: opts.offset?.y ?? 0, + orientation: opts.orientation, + stagger, + }; + + // Per-terrain mix multiplies the learned weights. + let working: HexWfcModel = { + ...model, + terrains: model.terrains.map((t) => ({ ...t, weight: t.weight * (s.mix[t.name] ?? 1) })), + }; + const features = s.features ? (model.features ?? []).filter((f) => f.count > 0) : []; + // Feature terrain is only laid down by the features, never by the solver. + const featureTerrains = new Set(features.map((f) => f.terrain)); + if (featureTerrains.size) + working = { ...working, terrains: working.terrains.map((t) => (featureTerrains.has(t.name) ? { ...t, weight: 0 } : t)) }; + + const hasCounts = Object.values(s.counts).some((c) => c.min !== undefined || c.max !== undefined); + const tries = hasCounts || s.connected ? Math.max(1, opts.maxTries ?? 8) : 1; + const masterRng = mulberry32(opts.seed ^ 0x9e3779b9); + const total = emptyStats(); + const impassable = new Set(s.impassable); + + type Candidate = { cells: Map; featureCells: Set; warnings: string[]; penalty: number }; + let best: Candidate | null = null; + let lastFail: SolveResult | null = null; + + for (let k = 0; k < tries; k++) { + total.tries++; + const seed = k === 0 ? opts.seed : Math.floor(masterRng() * 4294967296); + const rng = mulberry32(seed ^ 0x51ed270b); + const fixed = new Map(toCellMap(opts.fixed ?? {})); + const warnings: string[] = []; + const featureCells = new Set(); + for (const [key, t] of placeEdgeBorder(model, s, grid, fixed, rng)) { + fixed.set(key, t); + featureCells.add(key); + } + if (features.length) { + const placed = placeFeatures(model, features, s, grid, fixed, rng); + warnings.push(...placed.warnings); + for (const [key, t] of placed.cells) { + fixed.set(key, t); + featureCells.add(key); + } + } + + const core = solveOnce(working, { ...opts, fixed, seed }, s); + for (const key of ["attempts", "backtracks", "decisions", "grown"] as const) total[key] += core.stats[key]; + if (!core.ok) { + lastFail = core; + continue; + } + + const protect = new Set([...toCellMap(opts.fixed ?? {}).keys(), ...featureCells]); + const cells = core.cells; + total.postChanges += smooth(cells, model, grid, s.smoothing, protect, rng); + let penalty = 0; + if (s.connected && impassable.size) { + const { changed, stranded } = connectLand(cells, model, grid, impassable, protect); + total.postChanges += changed; + penalty += stranded; + if (stranded) warnings.push(`${stranded} land hexes are still cut off from the main landmass`); + } + if (hasCounts) penalty += countsPenalty(countPatches(cells, grid), s.counts); + + if (!best || penalty < best.penalty) best = { cells, featureCells, warnings, penalty }; + if (penalty === 0) break; + } + + if (!best) { + const fail = lastFail ?? { ok: false as const, reason: "contradiction" as const, message: "No valid map found", stats: total }; + fail.stats = { ...total, ms: Date.now() - t0 }; + return fail; + } + + if (hasCounts) { + const protect = new Set([...toCellMap(opts.fixed ?? {}).keys(), ...best.featureCells]); + total.postChanges += topUpCounts(best.cells, model, grid, s.counts, protect, mulberry32(opts.seed ^ 0x2545f491)); + const counted = countPatches(best.cells, grid); + for (const [t, range] of Object.entries(s.counts)) { + const n = counted.get(t) ?? 0; + if (range.min !== undefined && n < range.min) best.warnings.push(`Only ${n} ${t} (wanted at least ${range.min})`); + if (range.max !== undefined && n > range.max) best.warnings.push(`${n} ${t} (wanted at most ${range.max})`); + } + } + total.ms = Date.now() - t0; + return { ok: true, cells: best.cells, featureCells: best.featureCells, warnings: best.warnings, stats: total }; +} + /** Feedback never boosts or damps a terrain by more than this factor per choice. */ const FEEDBACK_CAP = 8; -export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { +type CoreResult = + | { ok: true; cells: Map; stats: SolveStats } + | { + ok: false; + reason: "invalid-input" | "fixed-conflict" | "contradiction"; + message: string; + at?: { x: number; y: number }; + stats: SolveStats; + }; + +/** One run of the collapse itself (with restarts and backtracking). */ +function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required): CoreResult { const t0 = Date.now(); - const stats: SolveStats = { attempts: 0, backtracks: 0, decisions: 0, grown: 0, ms: 0 }; + const stats = emptyStats(); const fail = ( reason: "invalid-input" | "fixed-conflict" | "contradiction", message: string, at?: { x: number; y: number }, - ): SolveResult => { + ): CoreResult => { stats.ms = Date.now() - t0; return { ok: false, reason, message, at, stats }; }; @@ -137,19 +241,18 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { const stagger = opts.stagger ?? "odd"; const ox = opts.offset?.x ?? 0; const oy = opts.offset?.y ?? 0; - // Options passed in win over settings saved with the model. - const saved = { ...DEFAULT_SETTINGS, ...model.settings }; - const influence = opts.neighbourInfluence ?? saved.neighbourInfluence; - const feedback = opts.frequencyFeedback ?? saved.frequencyFeedback; - const scatter = opts.scatter ?? saved.scatter; - const featureSize = opts.featureSize ?? saved.featureSize; - const bias = opts.directionalBias ?? saved.directionalBias; - const randomness = Math.min(1, Math.max(0, opts.randomness ?? saved.randomness)); + const influence = s.neighbourInfluence; + const feedback = s.frequencyFeedback; + const scatter = s.scatter; + const featureSize = s.featureSize; + const bias = s.directionalBias; + const randomness = Math.min(1, Math.max(0, s.randomness)); const terrains = [...new Set(model.terrains.map((t) => t.name))]; const T = terrains.length; if (!(cols > 0 && rows > 0)) return fail("invalid-input", "Grid must be at least 1×1"); if (T === 0) return fail("invalid-input", "The model has no terrains"); const tIndex = new Map(terrains.map((t, i) => [t, i])); + const entryOf = new Map(model.terrains.map((e) => [e.name, e])); const N = cols * rows; const W = (T + 31) >>> 5; // 32-bit words per domain bitset @@ -181,11 +284,13 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { } } - // Directional bias: per hex, log of each terrain's learned layout density - // at that position (bilinear between the 3×3 bin centres), times bias. - let logBias: Float32Array | null = null; + // Position preferences per hex: directional bias (learned 3×3 layout, + // bilinear between bin centres) and edge style (border preference that + // fades out over the outer ~15% of the map). + let logPos: Float32Array | null = null; + const ensurePos = () => (logPos ??= new Float32Array(N * T)); if (bias > 0 && model.terrains.some((e) => e.layout?.length === 9)) { - logBias = new Float32Array(N * T); + const pos = ensurePos(); const centre = [1 / 6, 1 / 2, 5 / 6]; const axis = (f: number): [number, number, number] => { if (f <= centre[0]) return [0, 0, 0]; @@ -202,7 +307,23 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { const [cy0, cy1, fy] = axis((Math.floor(c / cols) + 0.5) / rows); const top = lay[cy0 * 3 + cx0] * (1 - fx) + lay[cy0 * 3 + cx1] * fx; const bottom = lay[cy1 * 3 + cx0] * (1 - fx) + lay[cy1 * 3 + cx1] * fx; - logBias[c * T + t] = bias * Math.log(Math.max(0.02, top * (1 - fy) + bottom * fy)); + pos[c * T + t] += bias * Math.log(Math.max(0.02, top * (1 - fy) + bottom * fy)); + } + } + } + // Learned edge preference (soft). An explicit edge terrain is laid down as + // a fixed border before solving instead (see placeEdgeBorder). + if (s.edgeStrength > 0 && !s.edgeTerrain) { + const logEdge = new Float64Array(T); + for (let t = 0; t < T; t++) logEdge[t] = Math.log(Math.max(0.02, entryOf.get(terrains[t])?.edge ?? 1)); + if (logEdge.some((v) => v !== 0)) { + const pos = ensurePos(); + const depth = Math.max(2, 0.15 * Math.min(cols, rows)); + for (let c = 0; c < N; c++) { + const i = c % cols, j = Math.floor(c / cols); + const d = Math.min(i, cols - 1 - i, j, rows - 1 - j); + const f = Math.max(0, 1 - d / depth); + if (f > 0) for (let t = 0; t < T; t++) pos[c * T + t] += s.edgeStrength * f * logEdge[t]; } } } @@ -306,7 +427,7 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { /** Returns the cell whose domain emptied, or −1. */ const propagate = (seeds: number[]): number => { let head = 0, tail = 0, size = 0; - for (const s of seeds) if (!inQueue[s]) { inQueue[s] = 1; queue[tail++ % N] = s; size++; } + for (const sd of seeds) if (!inQueue[sd]) { inQueue[sd] = 1; queue[tail++ % N] = sd; size++; } while (size > 0) { const c = queue[head++ % N]; size--; @@ -341,58 +462,34 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { return -1; }; - // ── Scoring ────────────────────────────────────────────────────────────── - const scores = new Float64Array(T); - /** Fill `scores` with relative probabilities for an open cell; returns their sum. */ - const score = (c: number): number => { - const decided: number[] = []; - for (let d = 0; d < 6; d++) { - const n = nbr[c * 6 + d]; - if (n >= 0) { - const u = single(n); - if (u >= 0) decided.push(u); - } - } - let max = -Infinity; - for (let t = 0; t < T; t++) { - if (!has(c, t)) { scores[t] = -Infinity; continue; } - let s = logW[t] + (logBias ? logBias[c * T + t] : 0); - if (decided.length) { - let e = 0, same = 0; - for (const u of decided) if (u === t) same++; - const enclosed = growShape[t] !== 0 && same >= 3; - for (const u of decided) e += u === t && enclosed ? learnedSelf[t] : logP[t * T + u]; - s += e / decided.length; - } - scores[t] = s; - if (s > max) max = s; - } - let sum = 0; - for (let t = 0; t < T; t++) { - scores[t] = scores[t] === -Infinity ? 0 : Math.exp(scores[t] - max); - sum += scores[t]; - } - return sum; - }; - // ── Growth moves ───────────────────────────────────────────────────────── - // After the solver chooses a terrain for a hex, a "blob" or "line" terrain - // spreads into nearby open hexes. Every move is a normal place + propagate, - // undone on its own if it breaks a rule, so hard rules always hold. + // ── Growth setup ───────────────────────────────────────────────────────── + // After the solver chooses a terrain for a hex that starts a new patch, a + // "blob" or "line" terrain spreads into nearby open hexes. Every move is a + // normal place + propagate, undone on its own if it breaks a rule. const growShape = new Uint8Array(T); // 0 none, 1 blob, 2 line + const isScatter = new Uint8Array(T); // Learned self-adjacency of growth terrains, used only to fill holes: a hex // mostly surrounded by one growth terrain (e.g. a gap inside a lake) should // still become that terrain. const learnedSelf = new Float64Array(T); const growMoves = new Int32Array(T); const growTurn = new Float64Array(T); + const lineWidth = new Int32Array(T).fill(1); + const spacingOf = new Int32Array(T); // min hex distance between scattered hexes; 0/1 = none + const sizeScale = model.exampleHexes ? Math.sqrt(N / model.exampleHexes) : 1; for (const entry of model.terrains) { const t = tIndex.get(entry.name)!; + if (entry.shape === "scatter") { + isScatter[t] = 1; + if (entry.spacing && s.spacing > 0) spacingOf[t] = Math.max(1, Math.round(entry.spacing * s.spacing * sizeScale)); + } const shape = entry.shape === "blob" ? 1 : entry.shape === "line" ? 2 : 0; const moves = Math.min(Math.floor(N / 2), Math.round((entry.patch ?? 0) * N * featureSize) - 1); if (shape && moves > 0) { growShape[t] = shape; growMoves[t] = moves; growTurn[t] = entry.turn ?? 0.2; + lineWidth[t] = Math.max(1, Math.min(3, Math.round(s.lineWidth > 0 ? s.lineWidth : (entry.width ?? 1)))); // Growth owns this terrain's clumping. If the neighbour score also // rewarded "same terrain next door", every patch would keep spreading // past its learned size. Score self-adjacency at chance level instead. @@ -412,6 +509,59 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { } } } + const maxPatches = new Int32Array(T).fill(-1); + for (const [name, range] of Object.entries(s.counts) as [string, CountRange][]) { + const t = tIndex.get(name); + if (t !== undefined && range.max !== undefined) maxPatches[t] = range.max; + } + + // Mirror partners of a hex (relative to the grid), for symmetry. + const mirrorsOf = (c: number): number[] => { + if (s.symmetry === "none") return []; + const i = c % cols, j = Math.floor(c / cols); + const out: number[] = []; + const lr = s.symmetry === "left-right" || s.symmetry === "both"; + const tb = s.symmetry === "top-bottom" || s.symmetry === "both"; + if (lr) out.push(j * cols + (cols - 1 - i)); + if (tb) out.push((rows - 1 - j) * cols + i); + if (lr && tb) out.push((rows - 1 - j) * cols + (cols - 1 - i)); + return out.filter((m) => m !== c); + }; + + // ── Scoring ────────────────────────────────────────────────────────────── + const scores = new Float64Array(T); + /** Fill `scores` with relative probabilities for an open cell; returns their sum. */ + const score = (c: number): number => { + const decided: number[] = []; + for (let d = 0; d < 6; d++) { + const n = nbr[c * 6 + d]; + if (n >= 0) { + const u = single(n); + if (u >= 0) decided.push(u); + } + } + let max = -Infinity; + for (let t = 0; t < T; t++) { + if (!has(c, t)) { scores[t] = -Infinity; continue; } + let sc = logW[t] + (logPos ? logPos[c * T + t] : 0); + if (decided.length) { + let e = 0, same = 0; + for (const u of decided) if (u === t) same++; + const enclosed = growShape[t] !== 0 && same >= 3; + for (const u of decided) e += u === t && enclosed ? learnedSelf[t] : logP[t * T + u]; + sc += e / decided.length; + } + scores[t] = sc; + if (sc > max) max = sc; + } + let sum = 0; + for (let t = 0; t < T; t++) { + scores[t] = scores[t] === -Infinity ? 0 : Math.exp(scores[t] - max); + sum += scores[t]; + } + return sum; + }; + const ring = directionRing(orientation); const touchesTerrain = (c: number, t: number): boolean => { for (let d = 0; d < 6; d++) { @@ -420,17 +570,39 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { } return false; }; + /** Is there a decided hex of terrain t within `radius` steps of c? */ + const visit = new Int32Array(N); + let visitStamp = 0; + const nearTerrain = (c: number, t: number, radius: number): boolean => { + visitStamp++; + let frontier = [c]; + visit[c] = visitStamp; + for (let r = 0; r < radius; r++) { + const next: number[] = []; + for (const f of frontier) + for (let d = 0; d < 6; d++) { + const n = nbr[f * 6 + d]; + if (n < 0 || visit[n] === visitStamp) continue; + visit[n] = visitStamp; + if (single(n) === t) return true; + next.push(n); + } + frontier = next; + } + return false; + }; - /** Decide open cell c as t and propagate; undo just this move on contradiction. */ // Patches often stop short (rules, map edge, other patches), so track the // size patches actually reach this attempt and use that as the divisor. const patchesStarted = new Int32Array(T); const patchHexes = new Int32Array(T); const expectedPatch = (t: number) => patchesStarted[t] >= 3 ? Math.max(1, patchHexes[t] / patchesStarted[t]) : growMoves[t] + 1; + const patchCount = new Int32Array(T); // patches started this attempt (for max counts) - const tryPlace = (c: number, t: number): boolean => { - if (single(c) !== -1 || !has(c, t)) return false; + /** Decide open cell c as t and propagate; undo just this move on contradiction. */ + const tryPlaceOne = (c: number, t: number): boolean => { + if (c < 0 || single(c) !== -1 || !has(c, t)) return false; const mark = trailIdx.length; for (let w = 0; w < W; w++) setWord(c * W + w, t >>> 5 === w ? 1 << (t & 31) : 0); if (propagate([c]) >= 0) { @@ -440,6 +612,12 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { stats.grown++; return true; }; + /** tryPlaceOne plus the hex's mirror partners (symmetric where the rules allow). */ + const tryPlace = (c: number, t: number): boolean => { + if (!tryPlaceOne(c, t)) return false; + for (const m of mirrorsOf(c)) tryPlaceOne(m, t); + return true; + }; const growBlob = (seed: number, t: number, rng: () => number) => { let budget = growMoves[t]; @@ -460,11 +638,12 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { addNeighbours(seed); while (budget > 0 && frontier.length) { // Best of three random frontier hexes, favouring ones that touch more - // of the patch, keeps blobs compact without being perfectly round. - let bi = 0, bs = -1; + // of the patch (keeps blobs compact without being perfectly round) and + // ones where directional bias / edge style want this terrain. + let bi = 0, bs = -Infinity; for (let k = 0; k < 3; k++) { const i = Math.floor(rng() * frontier.length); - const sc = touching(frontier[i]) + rng(); + const sc = touching(frontier[i]) + rng() + (logPos ? logPos[frontier[i] * T + t] : 0); if (sc > bs) { bs = sc; bi = i; } } const n = frontier[bi]; @@ -483,7 +662,14 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { const growLine = (seed: number, t: number, rng: () => number) => { let budget = growMoves[t]; + const width = lineWidth[t]; + // Extra width: the hexes behind-left / behind-right of each step. + const widen = (c: number, h: number) => { + if (width >= 2 && budget > 0 && tryPlace(nbr[c * 6 + ring[(h + 2) % 6]], t)) budget--; + if (width >= 3 && budget > 0 && tryPlace(nbr[c * 6 + ring[(h + 4) % 6]], t)) budget--; + }; const h0 = Math.floor(rng() * 6); + widen(seed, h0); // Grow from both ends so the seed sits mid-line. const ends = [ { c: seed, h: h0, alive: true }, @@ -504,6 +690,7 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { end.h = hh; end.alive = true; budget--; + widen(n, hh); break; } } @@ -514,14 +701,16 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { const entropy = new Float64Array(N); const open = new Uint8Array(N); const noise = new Float64Array(N); + const saved = new Float64Array(T); for (let attempt = 0; attempt <= maxRestarts; attempt++) { stats.attempts++; const rng = mulberry32(Math.floor(masterRng() * 4294967296)); trailIdx = []; + trailVal = []; patchesStarted.fill(0); patchHexes.fill(0); - trailVal = []; + patchCount.fill(0); for (let c = 0; c < N; c++) noise[c] = rng() * scatter; for (let c = 0; c < N; c++) { const ft = fixedAt[c]; @@ -544,11 +733,11 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { let best = -1, bestH = Infinity, decidedCount = 0; placed.fill(0); for (let c = 0; c < N; c++) { - const s = single(c); - if (s >= 0) { placed[s]++; decidedCount++; } + const sg = single(c); + if (sg >= 0) { placed[sg]++; decidedCount++; } if (dirty[c]) { dirty[c] = 0; - open[c] = s === -1 ? 1 : 0; + open[c] = sg === -1 ? 1 : 0; if (open[c]) { const sum = score(c); let h = Math.log(sum); @@ -560,33 +749,43 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { } if (best < 0) break; // everything decided - // Frequency feedback is applied to the choice only, not to the entropy - // cache: it changes after every step, and rescoring every hex each - // step would make the solver quadratic in a much worse way. + // Frequency feedback, growth seed odds, spacing and counts apply to the + // choice only, not to the entropy cache: they change after every step, + // and rescoring every hex each step would be far slower. const contextSum = score(best); if (randomness > 0) { - // Mix in a context-free pick by terrain weight (still only among - // terrains the hard rules allow here). + // Mix in a pick that ignores neighbours: terrain weight plus position + // preferences (directional bias, edge style), still only among the + // terrains the hard rules allow here. + const base = (t: number) => Math.exp(logW[t] + (logPos ? logPos[best * T + t] : 0)); let baseSum = 0; - for (let t = 0; t < T; t++) if (scores[t] > 0) baseSum += Math.exp(logW[t]); + for (let t = 0; t < T; t++) if (scores[t] > 0) baseSum += base(t); for (let t = 0; t < T; t++) - if (scores[t] > 0) - scores[t] = (1 - randomness) * (scores[t] / contextSum) + (randomness * Math.exp(logW[t])) / baseSum; + if (scores[t] > 0) scores[t] = (1 - randomness) * (scores[t] / contextSum) + (randomness * base(t)) / baseSum; } + saved.set(scores); let sum = 0; for (let t = 0; t < T; t++) { if (scores[t] <= 0) continue; + const startsNew = !touchesTerrain(best, t); // Choosing a growth terrain here starts a whole patch, so it must // start (patch size) times less often. Otherwise coverage grows // with map size: patches scale with the map, and so would the // number of patches. - if (growShape[t] && !touchesTerrain(best, t)) scores[t] /= expectedPatch(t); - if (feedback > 0) { + if (growShape[t] && startsNew) scores[t] /= expectedPatch(t); + if (startsNew && maxPatches[t] >= 0 && patchCount[t] >= maxPatches[t]) scores[t] = 0; + if (spacingOf[t] > 1 && scores[t] > 0 && nearTerrain(best, t, spacingOf[t] - 1)) scores[t] = 0; + if (feedback > 0 && scores[t] > 0) { const ratio = Math.min(FEEDBACK_CAP, Math.max(1 / FEEDBACK_CAP, (share[t] * decidedCount + 1) / (placed[t] + 1))); scores[t] *= Math.pow(ratio, feedback); } sum += scores[t]; } + if (sum <= 0) { + // Spacing / counts ruled everything out here; fall back to the rules alone. + scores.set(saved); + for (let t = 0; t < T; t++) sum += scores[t]; + } let r = rng() * sum, choice = -1; for (let t = 0; t < T; t++) { if (scores[t] <= 0) continue; @@ -597,18 +796,24 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { stats.decisions++; stack.push([trailIdx.length, best, choice]); - for (let w = 0; w < W; w++) setWord(best * W + w, choice >>> 5 === w ? 1 << (choice & 31) : 0); // Grow only from a hex that starts a new patch. A hex joining an // existing patch of the same terrain must not trigger another full // growth, or the terrain cascades across the whole map. - const startsPatch = growShape[choice] !== 0 && !touchesTerrain(best, choice); + const startsPatch = !touchesTerrain(best, choice); + for (let w = 0; w < W; w++) setWord(best * W + w, choice >>> 5 === w ? 1 << (choice & 31) : 0); let contradiction = propagate([best]) >= 0; - if (!contradiction && startsPatch) { - const before = stats.grown; - if (growShape[choice] === 1) growBlob(best, choice, rng); - else growLine(best, choice, rng); - patchesStarted[choice]++; - patchHexes[choice] += 1 + stats.grown - before; + if (!contradiction) { + for (const m of mirrorsOf(best)) tryPlaceOne(m, choice); + if (startsPatch) { + patchCount[choice] += 1 + mirrorsOf(best).length; + if (growShape[choice]) { + const before = stats.grown; + if (growShape[choice] === 1) growBlob(best, choice, rng); + else growLine(best, choice, rng); + patchesStarted[choice]++; + patchHexes[choice] += 1 + stats.grown - before; + } + } } // Undo the last decision and ban that choice; repeat while the ban diff --git a/tests/hexWfc.test.ts b/tests/hexWfc.test.ts index fe8770ae..648fe2c0 100644 --- a/tests/hexWfc.test.ts +++ b/tests/hexWfc.test.ts @@ -3,7 +3,13 @@ import expect from "expect"; import { hexNeighbors, hexCenter, + hexDistance, directionRing, + countPatches, + encodeSetting, + decodeSetting, + type SolveOptions, + type GeneratorSettings, measurePatches, cellKey, learnModel, @@ -301,10 +307,10 @@ describe("growth: shape learning", () => { expect(Math.abs(small.patch - big.patch)).toBeLessThan(0.02); }); - it("treats single scattered hexes as no-growth", () => { + it("classifies single scattered hexes as scatter (no growth)", () => { const m = new Map(); for (let x = 0; x < 20; x++) for (let y = 0; y < 20; y++) m.set(cellKey(x, y), (x * 7 + y * 3) % 11 === 0 ? "Rock" : "Grass"); - expect(measurePatches(m, "pointy").get("Rock")?.shape).toBe("none"); + expect(measurePatches(m, "pointy").get("Rock")?.shape).toBe("scatter"); }); it("directionRing walks the neighbours clockwise in 60° steps", () => { @@ -480,3 +486,276 @@ describe("directional bias, randomness and saved settings", () => { expect(back.settings).toBeUndefined(); }); }); + +/** 40×40 example: a 1-wide river walked along hex neighbours from the top edge into a lake. */ +function riverExample(): Map { + const m = new Map(); + for (let x = 0; x < 40; x++) + for (let y = 0; y < 40; y++) { + const d = Math.hypot(x - 26, y - 28); + m.set(cellKey(x, y), d < 4.5 ? "Water" : d < 5.8 ? "Sand" : "Grass"); + } + let cur: [number, number] = [8, 0]; + for (let step = 0; step < 80; step++) { + m.set(cellKey(cur[0], cur[1]), "River"); + const ns = hexNeighbors(cur[0], cur[1], "flat", "odd"); + if (ns.some(([x, y]) => m.get(cellKey(x, y)) === "Water")) break; + const goal = [26 + Math.sin(step / 3) * 6, 28]; + ns.sort((a, b) => Math.hypot(a[0] - goal[0], a[1] - goal[1]) - Math.hypot(b[0] - goal[0], b[1] - goal[1])); + cur = ns.find(([x, y]) => m.get(cellKey(x, y)) !== "River" && x >= 0 && y >= 0)!; + } + return m; +} + +/** World example plus towns dotted on the grass. */ +function townsExample(): Map { + const m = worldExample(); + for (const [k, t] of m) { + const [x, y] = k.split("_").map(Number); + if (t === "Grass" && (x * 7 + y * 13) % 53 === 0) m.set(k, "Town"); + } + return m; +} + +const gridOf = (cols: number, rows: number) => ({ cols, rows, ox: 0, oy: 0, orientation: "flat" as const, stagger: "odd" as const }); + +describe("hex distance", () => { + it("is 1 for every neighbour and symmetric", () => { + for (const o of ["flat", "pointy"] as const) + for (const s of ["odd", "even"] as const) + for (const [x, y] of [[0, 0], [3, 4], [-2, 5], [7, -3]]) { + for (const n of hexNeighbors(x, y, o, s)) expect(hexDistance([x, y], n, o, s)).toBe(1); + expect(hexDistance([x, y], [x + 4, y + 1], o, s)).toBe(hexDistance([x + 4, y + 1], [x, y], o, s)); + } + }); +}); + +describe("learning: lines, boundaries, features, spacing", () => { + it("learns a river from the map edge into a lake as a guaranteed feature", () => { + const m = learnModel(riverExample(), { name: "river", orientation: "flat" }); + expect(m.terrains.find((t) => t.name === "River")?.shape).toBe("line"); + expect(m.features).toEqual([{ terrain: "River", from: "edge", to: "Water", count: 1 }]); + expect(m.exampleHexes).toBe(1600); + }); + + it("treats a shore between two terrains as a boundary, not a line or feature", () => { + const m = learnModel(coastExample(), { name: "coast", orientation: "flat" }); + expect(m.terrains.find((t) => t.name === "Sand")?.shape).toBe("none"); + expect(m.terrains.find((t) => t.name === "Ocean")?.shape).toBe("blob"); // thick band, not a line + expect(m.features ?? []).toEqual([]); + }); + + it("learns how far apart scattered towns are", () => { + const m = learnModel(townsExample(), { name: "towns", orientation: "flat" }); + const town = m.terrains.find((t) => t.name === "Town")!; + expect(town.shape).toBe("scatter"); + expect(town.spacing).toBeGreaterThanOrEqual(2); + }); +}); + +describe("controls", () => { + const world = learnModel(townsExample(), { name: "world", orientation: "flat" }); + const solveWorld = (extra: Partial = {}, seed = 4, cols = 36, rows = 24) => + solve(world, { cols, rows, orientation: "flat", seed, ...extra }); + + it("never breaks a learned rule, whatever the settings", () => { + const settings: Partial[] = [ + { smoothing: 1 }, + { symmetry: "both" }, + { edgeTerrain: "Water", edgeStrength: 1 }, + { edgeStrength: 1 }, + { counts: { Town: { min: 4, max: 4 }, Water: { min: 2 } } }, + { connected: true, impassable: ["Water", "Ridge"] }, + { lineWidth: 3, featureSize: 2 }, + { spacing: 2, randomness: 0.5 }, + { mix: { Forest: 3, Water: 0.2 }, directionalBias: 1 }, + ]; + for (const extra of settings) { + const r = solveWorld(extra); + expect(r.ok).toBe(true); + if (r.ok) expect(findViolation(world, r.cells, "flat")).toBeNull(); + } + }); + + it("guarantees the river: a connected line from the map edge to water", () => { + const m = learnModel(riverExample(), { name: "river", orientation: "flat" }); + for (const seed of [1, 2, 3]) { + const r = solve(m, { cols: 30, rows: 20, orientation: "flat", seed }); + expect(r.ok).toBe(true); + if (!r.ok) continue; + expect(findViolation(m, r.cells, "flat")).toBeNull(); + const river = [...r.cells].filter(([, t]) => t === "River").map(([k]) => k); + expect(river.length).toBeGreaterThan(5); + expect(countPatches(new Map(river.map((k) => [k, "River"])), gridOf(30, 20)).get("River")).toBe(1); + const onEdge = river.some((k) => { + const [x, y] = k.split("_").map(Number); + return x === 0 || y === 0 || x === 29 || y === 19; + }); + const touchesWater = river.some((k) => { + const [x, y] = k.split("_").map(Number); + return hexNeighbors(x, y, "flat").some(([nx, ny]) => r.cells.get(cellKey(nx, ny)) === "Water"); + }); + expect(onEdge && touchesWater).toBe(true); + } + const off = solve(m, { cols: 30, rows: 20, orientation: "flat", seed: 1, features: false }); + expect(off.ok).toBe(true); + if (off.ok) expect(off.featureCells.size).toBe(0); + }); + + it("edge terrain makes an island: the whole border is that terrain", () => { + const r = solveWorld({ edgeTerrain: "Water", edgeStrength: 1 }); + expect(r.ok).toBe(true); + if (!r.ok) return; + for (const [k, t] of r.cells) { + const [x, y] = k.split("_").map(Number); + if (x === 0 || y === 0 || x === 35 || y === 23) expect(t).toBe("Water"); + } + expect([...r.cells.values()].filter((t) => t === "Grass").length).toBeGreaterThan(100); + }); + + it("symmetry mirrors the map where the rules allow", () => { + const r = solveWorld({ symmetry: "left-right" }, 6, 31, 20); + expect(r.ok).toBe(true); + if (!r.ok) return; + let same = 0; + for (const [k, t] of r.cells) { + const [x, y] = k.split("_").map(Number); + if (r.cells.get(cellKey(30 - x, y)) === t) same++; + } + expect(same / r.cells.size).toBeGreaterThan(0.9); + }); + + it("smoothing leaves fewer lone specks", () => { + const specks = (cells: Map) => { + let n = 0; + for (const [k, t] of cells) { + if (t === "Town") continue; + const [x, y] = k.split("_").map(Number); + if (!hexNeighbors(x, y, "flat").some(([nx, ny]) => cells.get(cellKey(nx, ny)) === t)) n++; + } + return n; + }; + let rough = 0, smooth = 0; + for (const seed of [1, 2, 3]) { + const a = solveWorld({ smoothing: 0, randomness: 0.4 }, seed); + const b = solveWorld({ smoothing: 1, randomness: 0.4 }, seed); + if (a.ok && b.ok) { + rough += specks(a.cells); + smooth += specks(b.cells); + } + } + expect(smooth).toBeLessThan(rough); + }); + + it("counts: exact number of towns, at least two lakes", () => { + for (const seed of [1, 2]) { + const r = solveWorld({ counts: { Town: { min: 4, max: 4 }, Water: { min: 2 } } }, seed); + expect(r.ok).toBe(true); + if (!r.ok) continue; + const pc = countPatches(r.cells, gridOf(36, 24)); + expect(pc.get("Town")).toBe(4); + expect(pc.get("Water")).toBeGreaterThanOrEqual(2); + expect(r.warnings).toEqual([]); + } + }); + + it("spacing keeps towns apart", () => { + const towns = (cells: Map) => + [...cells].filter(([, t]) => t === "Town").map(([k]) => k.split("_").map(Number) as [number, number]); + const r = solveWorld({ spacing: 2, randomness: 0 }, 3, 40, 40); + expect(r.ok).toBe(true); + if (!r.ok) return; + const ts = towns(r.cells); + let min = Infinity; + for (let i = 0; i < ts.length; i++) + for (let j = i + 1; j < ts.length; j++) min = Math.min(min, hexDistance(ts[i], ts[j], "flat")); + expect(min).toBeGreaterThanOrEqual(3); + }); + + it("connected land fills cut-off pockets with impassable terrain", () => { + // Grass and Rock both touch everything; Rock is impassable. + const model: HexWfcModel = { + name: "rocks", meta: {}, + terrains: [{ name: "Grass", weight: 1 }, { name: "Rock", weight: 1 }], + adjacency: [ + { a: "Grass", b: "Grass", weight: 1 }, + { a: "Grass", b: "Rock", weight: 1 }, + { a: "Rock", b: "Rock", weight: 1 }, + ], + }; + const base = { cols: 20, rows: 20, orientation: "flat" as const, seed: 2, neighbourInfluence: 0 }; + const free = solve(model, base); + const tied = solve(model, { ...base, connected: true, impassable: ["Rock"] }); + expect(free.ok && tied.ok).toBe(true); + if (!free.ok || !tied.ok) return; + const landGroups = (cells: Map) => + countPatches(new Map([...cells].filter(([, t]) => t === "Grass")), gridOf(20, 20)).get("Grass") ?? 0; + expect(landGroups(free.cells)).toBeGreaterThan(1); + expect(landGroups(tied.cells)).toBe(1); + }); + + it("per-terrain mix shifts the terrain share", () => { + const forest = (extra: Partial) => { + let f = 0; + for (const seed of [1, 2, 3]) { + const r = solveWorld(extra, seed); + if (r.ok) f += [...r.cells.values()].filter((t) => t === "Forest").length; + } + return f; + }; + expect(forest({ mix: { Forest: 3 } })).toBeGreaterThan(forest({}) * 1.5); + }); + + it("line width makes ridges thicker", () => { + const thickness = (lineWidth: number) => { + let same = 0, n = 0; + for (const seed of [1, 2, 3]) { + const r = solveWorld({ lineWidth }, seed, 40, 30); + if (!r.ok) continue; + for (const [k, t] of r.cells) { + if (t !== "Ridge") continue; + const [x, y] = k.split("_").map(Number); + n++; + same += hexNeighbors(x, y, "flat").filter(([nx, ny]) => r.cells.get(cellKey(nx, ny)) === "Ridge").length; + } + } + return same / n; + }; + expect(thickness(3)).toBeGreaterThan(thickness(1)); + }); +}); + +describe("setting codec", () => { + it("round-trips every kind of setting through frontmatter text", () => { + const cases: [keyof GeneratorSettings, unknown][] = [ + ["featureSize", 1.25], + ["connected", true], + ["symmetry", "top-bottom"], + ["edgeTerrain", "Deep Sea"], + ["impassable", ["Water", "High peaks, north"]], + ["mix", { Forest: 1.5, "Deep Sea": 0.5 }], + ["counts", { Town: { min: 3, max: 3 }, Lake: { min: 1 }, Ruin: { min: 0, max: 2 }, Fort: { max: 1 } }], + ]; + for (const [field, value] of cases) { + const back = decodeSetting(field, String(encodeSetting(field, value))); + expect("value" in back ? back.value : back).toEqual(value); + } + }); + + it("explains malformed values", () => { + expect(decodeSetting("counts", "Town lots")).toHaveProperty("error"); + expect(decodeSetting("symmetry", "sideways")).toHaveProperty("error"); + expect(decodeSetting("mix", "Forest")).toHaveProperty("error"); + }); + + it("round-trips a model with features and settings", () => { + const m = learnModel(riverExample(), { name: "river", orientation: "flat" }); + m.settings = { + featureSize: 1.5, symmetry: "left-right", connected: true, impassable: ["Water"], + mix: { Grass: 0.8 }, counts: { Water: { min: 1 } }, edgeTerrain: "Water", edgeStrength: 0.5, features: false, + }; + const back = parseModelMarkdown(modelToMarkdown(m)); + expect(back.warnings).toEqual([]); + expect(back.model).toEqual(m); + }); +}); From 8a1ab911661995966947f5d79ba8e1f4bb213fc7 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 16:33:44 -0400 Subject: [PATCH 005/558] feat(worldgen): Generator tab with live preview, all solver controls, fill/regenerate map - src/worldgen/GeneratorTab.ts (Maps modal > Generator): learn from this map; pick a generator; live canvas preview with seed + re-roll + size; Shape (feature size, line width, smoothing, symmetry, edge style + strength), Placement (directional bias, spacing, randomness), Guarantees (features toggle, connected land + impassable chips), per-terrain table (mix slider, min/max patch counts), Advanced (clumping, mix strength, scatter), reset; every change saved to the generator file's frontmatter - Fill this map: "Fill unpainted hexes" keeps every painted hex; "Regenerate map" (click twice) keeps hexes with `locked: true` - New map tab: preview with seed/re-roll; Create uses the previewed seed - generators.ts: generateTerrain (palette fit, unknown fixed terrain kept), fillMap + writeTerrain (creates missing notes, syncs encounter links), readLockedHexes, paletteColors, saveGeneratorSettings via the library's setting codec (undefined clears a key) - preview.ts: canvas hex renderer with palette colours, feature outlines - tests: fill keeps painted / locked hexes, settings saved in text form Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/hex-wfc/src/format.ts | 4 +- packages/hex-wfc/src/solve.ts | 3 +- src/hex-map/MapModal.ts | 258 +++++------------- src/worldgen/GeneratorTab.ts | 447 +++++++++++++++++++++++++++++++ src/worldgen/generators.ts | 171 ++++++++++-- src/worldgen/preview.ts | 69 +++++ styles.css | 93 +++++++ tests/worldgenGenerators.test.ts | 129 +++++++-- 8 files changed, 938 insertions(+), 236 deletions(-) create mode 100644 src/worldgen/GeneratorTab.ts create mode 100644 src/worldgen/preview.ts diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index d1f986f4..dc182b58 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -127,7 +127,7 @@ export function decodeSetting(field: keyof GeneratorSettings, raw: string): { va return { error: "should be true or false" }; case "symmetry": return SYMMETRIES.includes(v as Symmetry) - ? { value: v as Symmetry } + ? { value: v } : { error: `should be one of ${SYMMETRIES.join(", ")}` }; case "string": return { value: v }; @@ -439,7 +439,7 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par } if (features.length) model.features = features; if (exampleHexes !== undefined) model.exampleHexes = exampleHexes; - if (Object.keys(settings).length) model.settings = settings as GeneratorSettings; + if (Object.keys(settings).length) model.settings = settings; model.name = name || fallbackName; return { model, warnings }; } diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 8719d702..1bd78785 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -27,7 +27,6 @@ import { resolveSettings, type HexWfcModel, type GeneratorSettings, - type CountRange, } from "./model"; import { mulberry32 } from "./rng"; import { placeFeatures, placeEdgeBorder } from "./features"; @@ -510,7 +509,7 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required this.close(), + rerender: () => { + this.activeTab = "Generator"; + this.render(); + }, + }).render(contentDivs.get("Generator")!); this.renderExportTab(contentDivs.get("Export")!); } @@ -450,23 +456,6 @@ export class MapModal extends HexmakerModal { } } - private async learnGenerator(rawName: string, btn: HTMLButtonElement): Promise { - btn.disabled = true; - const result = await saveGeneratorFromMap(this.plugin, this.view.activeMapName, rawName); - btn.disabled = false; - if ("error" in result) { - new Notice(result.error); - return; - } - const { model, file } = result; - new Notice( - `Saved generator "${model.name}": ${model.terrains.length} terrains, ${model.adjacency.length} neighbour pairs.`, - ); - this.selectedGeneratorPath = file.path; - this.activeTab = "Generator"; - this.render(); - } - /** Compute the folder where dropped bg images should land for a given map. */ private bgImportFolder(mapName: string): string { const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); @@ -584,7 +573,7 @@ export class MapModal extends HexmakerModal { // chosen palette are offered. el.createEl("label", { text: "Generator", cls: "duckmage-map-field-label" }); el.createEl("p", { - text: "Fill the new map with generated terrain, or leave it blank. Make one from a painted map on the properties tab.", + text: "Fill the new map with generated terrain, or leave it blank. Make generators and change their settings on the generator tab.", cls: "duckmage-map-origin-desc", }); const generatorRow = el.createDiv({ cls: "duckmage-region-row" }); @@ -608,10 +597,16 @@ export class MapModal extends HexmakerModal { fillGenerators(); }); - el.createEl("p", { - text: "Each generator's settings are on the generator tab.", - cls: "duckmage-map-origin-desc", - }); + // Preview of the generated terrain; Create uses exactly this seed. + const previewBox = el.createDiv({ cls: "duckmage-wfc-section" }); + const previewCanvas = previewBox.createEl("canvas", { cls: "duckmage-wfc-preview" }); + const previewStatus = previewBox.createEl("p", { cls: "duckmage-map-origin-desc" }); + const seedRow = previewBox.createDiv({ cls: "duckmage-region-row" }); + seedRow.createSpan({ text: "Seed", cls: "duckmage-map-origin-label" }); + const seedInput = seedRow.createEl("input", { type: "number", value: String(randomSeed()), cls: "duckmage-wfc-seed" }); + const rerollBtn = seedRow.createEl("button", { text: "Re-roll" }); + const previewBtn = seedRow.createEl("button", { text: "Preview" }); + previewBox.hide(); // Stagger offset el.createEl("label", { text: "Stagger offset", cls: "duckmage-map-field-label" }); @@ -681,6 +676,49 @@ export class MapModal extends HexmakerModal { bgClearBtn.disabled = false; }); + const selectedGenerator = () => generators.find((g) => g.file.path === generatorSelect.value) ?? null; + const runPreview = () => { + const g = selectedGenerator(); + if (!g) return; + const grid = { + cols: Math.max(1, Number(colsInput.value) || 20), + rows: Math.max(1, Number(rowsInput.value) || 16), + offset: { x: Number(originXInput.value) || 0, y: Number(originYInput.value) || 0 }, + stagger: staggerVal, + }; + const palette = this.plugin.getPaletteByName(paletteSelect.value)?.terrains.map((t) => t.name) ?? []; + const r = generateTerrain(this.plugin, g.model, palette, grid, Number(seedInput.value) >>> 0); + if (!r.ok) { + previewStatus.setText(`This generator couldn't fill the map: ${r.message}`); + return; + } + drawPreview(previewCanvas, r.cells, grid, this.plugin.settings.hexOrientation, paletteColors(this.plugin, paletteSelect.value), r.featureCells); + previewStatus.setText(r.warnings.length ? r.warnings.join("; ") : ""); + }; + let previewTimer: number | null = null; + const schedulePreview = () => { + previewBox.toggle(selectedGenerator() !== null); + if (!selectedGenerator()) return; + if (previewTimer !== null) window.clearTimeout(previewTimer); + if ((Number(colsInput.value) || 0) * (Number(rowsInput.value) || 0) > PREVIEW_AUTO_LIMIT) { + previewStatus.setText("Large map: use the preview button to see it."); + return; + } + previewTimer = window.setTimeout(() => { + previewTimer = null; + runPreview(); + }, 200); + }; + rerollBtn.addEventListener("click", () => { + seedInput.value = String(randomSeed()); + schedulePreview(); + }); + previewBtn.addEventListener("click", runPreview); + for (const input of [generatorSelect, paletteSelect, colsInput, rowsInput, originXInput, originYInput, seedInput]) + input.addEventListener("change", schedulePreview); + staggerBtn.addEventListener("click", schedulePreview); + presetsRow.addEventListener("click", schedulePreview); + // Create button const createRow = el.createDiv({ cls: "duckmage-region-row duckmage-map-create-row" }); const createBtn = createRow.createEl("button", { text: "Create", cls: "mod-cta" }); @@ -700,7 +738,8 @@ export class MapModal extends HexmakerModal { allInputs, pendingBgPath, pendingBgFile, - generators.find((g) => g.file.path === generatorSelect.value) ?? null, + selectedGenerator(), + Number(seedInput.value) >>> 0, ); createBtn.addEventListener("click", doCreate); nameInput.addEventListener("keydown", (e: KeyboardEvent) => { @@ -708,160 +747,6 @@ export class MapModal extends HexmakerModal { }); } - // ── Generator tab ───────────────────────────────────────────────────────── - - private renderGeneratorTab(el: HTMLElement): void { - el.empty(); - - // Learn from the active map - el.createEl("h4", { text: "Learn from this map" }); - el.createEl("p", { - text: "Make a wave function collapse generator from the terrain painted on this map. Terrains that never touch here never touch in generated maps, and lakes, ridges and forests keep their shape and relative size. Pick it on the new map tab.", - cls: "duckmage-map-origin-desc", - }); - const learnRow = el.createDiv({ cls: "duckmage-region-row" }); - const nameInput = learnRow.createEl("input", { - type: "text", - value: this.view.activeMapName, - placeholder: "generator-name", - }); - const learnBtn = learnRow.createEl("button", { text: "Generate solver from map", cls: "mod-cta" }); - learnBtn.addEventListener("click", () => void this.learnGenerator(nameInput.value, learnBtn)); - - // Settings of a saved generator - el.createEl("h4", { text: "Generator settings" }); - el.createEl("p", { - text: "Each generator keeps its own settings in its file. New maps made with it use them.", - cls: "duckmage-map-origin-desc", - }); - const pickRow = el.createDiv({ cls: "duckmage-region-row" }); - const select = pickRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); - const openBtn = pickRow.createEl("button", { text: "Open file" }); - const settingsEl = el.createDiv(); - let generators: GeneratorFile[] = []; - - const current = () => generators.find((g) => g.file.path === select.value); - const show = () => { - this.selectedGeneratorPath = select.value; - settingsEl.empty(); - const g = current(); - openBtn.disabled = !g; - if (!g) { - settingsEl.createEl("p", { - text: generators.length ? "Pick a generator." : "No generators yet. Paint a map, then use the button above.", - cls: "duckmage-map-origin-desc", - }); - return; - } - this.renderGeneratorSettings(settingsEl, g); - }; - openBtn.addEventListener("click", () => { - const g = current(); - if (!g) return; - this.close(); - void this.app.workspace.getLeaf("tab").openFile(g.file); - }); - select.addEventListener("change", show); - - select.createEl("option", { value: "", text: "Loading…" }); - openBtn.disabled = true; - void listGenerators(this.plugin).then((list) => { - generators = list; - select.empty(); - if (!list.length) select.createEl("option", { value: "", text: "No generators" }); - for (const g of list) { - const palette = g.model.meta.palette; - select.createEl("option", { - value: g.file.path, - text: palette ? `${g.model.name} (${palette})` : g.model.name, - }); - } - select.value = list.some((g) => g.file.path === this.selectedGeneratorPath) - ? this.selectedGeneratorPath - : (list[0]?.file.path ?? ""); - show(); - }); - } - - private renderGeneratorSettings(el: HTMLElement, g: GeneratorFile): void { - const { model } = g; - const byShape = (shape: string) => - model.terrains.filter((t) => (t.shape ?? "none") === shape).map((t) => t.name); - const parts = [`${model.terrains.length} terrains`]; - if (byShape("blob").length) parts.push(`blobs: ${byShape("blob").join(", ")}`); - if (byShape("line").length) parts.push(`lines: ${byShape("line").join(", ")}`); - if (model.meta["source-map"]) parts.push(`learned from ${model.meta["source-map"]}`); - el.createEl("p", { text: parts.join(" · "), cls: "duckmage-map-origin-desc" }); - - const sliders: { - field: keyof GeneratorSettings; - label: string; - hint: string; - min: number; - max: number; - step: number; - }[] = [ - { - field: "featureSize", label: "Feature size", min: 0, max: 3, step: 0.25, - hint: "Size of lakes, ranges and forests relative to the map. 1 = like the example map; lower = more, smaller features; 0 = no growth.", - }, - { - field: "directionalBias", label: "Directional bias", min: 0, max: 1, step: 0.05, - hint: "0 = features can go anywhere. 1 = they keep to where they were in the example, so an ocean along the bottom stays along the bottom.", - }, - { - field: "neighbourInfluence", label: "Clumping", min: 0, max: 6, step: 0.5, - hint: "How strongly each hex follows its neighbours. 0 gives speckled noise.", - }, - { - field: "frequencyFeedback", label: "Mix strength", min: 0, max: 4, step: 0.5, - hint: "How closely the overall terrain mix follows the example.", - }, - { - field: "randomness", label: "Randomness", min: 0, max: 1, step: 0.05, - hint: "Share of hexes chosen by plain chance, ignoring neighbours and layout. Lets rare terrain like towns pepper the map. Hard rules still apply.", - }, - { - field: "scatter", label: "Scatter", min: 0, max: 6, step: 0.5, - hint: "Randomness in where features start. Too low and one terrain can take over the map.", - }, - ]; - - const values: Required = { ...DEFAULT_SETTINGS, ...model.settings }; - const inputs = new Map(); - const save = (patch: GeneratorSettings) => { - model.settings = { ...model.settings, ...patch }; - saveGeneratorSettings(this.plugin, g.file, patch).catch((e: unknown) => { - new Notice(`Couldn't save generator settings: ${e instanceof Error ? e.message : String(e)}`); - }); - }; - - for (const def of sliders) { - el.createEl("label", { text: def.label, cls: "duckmage-map-field-label" }); - const row = el.createDiv({ cls: "duckmage-region-row" }); - const slider = row.createEl("input", { type: "range" }); - slider.min = String(def.min); - slider.max = String(def.max); - slider.step = String(def.step); - slider.value = String(values[def.field]); - const valueEl = row.createSpan({ text: String(values[def.field]) }); - el.createEl("p", { text: def.hint, cls: "duckmage-map-origin-desc" }); - inputs.set(def.field, [slider, valueEl]); - slider.addEventListener("input", () => valueEl.setText(slider.value)); - slider.addEventListener("change", () => save({ [def.field]: Number(slider.value) })); - } - - const resetRow = el.createDiv({ cls: "duckmage-region-row" }); - const resetBtn = resetRow.createEl("button", { text: "Reset to defaults" }); - resetBtn.addEventListener("click", () => { - for (const [field, [slider, valueEl]] of inputs) { - slider.value = String(DEFAULT_SETTINGS[field]); - valueEl.setText(slider.value); - } - save({ ...DEFAULT_SETTINGS }); - }); - } - // ── Delete ──────────────────────────────────────────────────────────────── private async deleteMap(name: string): Promise { @@ -962,6 +847,7 @@ export class MapModal extends HexmakerModal { bgImagePath: string | null, bgImageFile: File | null, generator: GeneratorFile | null, + seed: number, ): Promise { btn.setText("Generating…"); btn.disabled = true; @@ -977,9 +863,9 @@ export class MapModal extends HexmakerModal { let terrainAt: Map | undefined; if (generator) { const palette = this.plugin.getPaletteByName(paletteName)?.terrains.map((t) => t.name) ?? []; - const solved = generateMapTerrain( - this.plugin, generator.model, palette, cols, rows, - { x: initialX, y: initialY }, staggerOffset, randomSeed(), + const solved = generateTerrain( + this.plugin, generator.model, palette, + { cols, rows, offset: { x: initialX, y: initialY }, stagger: staggerOffset }, seed, ); if (!solved.ok) { new Notice(`Generator "${generator.model.name}" couldn't fill this map: ${solved.message}`); diff --git a/src/worldgen/GeneratorTab.ts b/src/worldgen/GeneratorTab.ts new file mode 100644 index 00000000..1ca64bd9 --- /dev/null +++ b/src/worldgen/GeneratorTab.ts @@ -0,0 +1,447 @@ +/** + * The "Generator" tab of the Maps modal: learn a generator from the active + * map, adjust a generator's settings (saved to its file's frontmatter) with a + * live preview, and fill or regenerate the active map with it. + */ + +import { App, Notice } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { HexMapView } from "../hex-map/HexMapView"; +import { + listGenerators, + saveGeneratorFromMap, + saveGeneratorSettings, + generateTerrain, + generatorFitsPalette, + paletteColors, + fillMap, + LOCK_KEY, + type GeneratorFile, +} from "./generators"; +import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; +import { + resolveSettings, + randomSeed, + SYMMETRIES, + type GeneratorSettings, + type Symmetry, + type CountRange, +} from "../../packages/hex-wfc/src"; + +export interface GeneratorTabHost { + close(): void; + /** Re-render the whole modal (e.g. after learning a new generator). */ + rerender(): void; +} + +const SYMMETRY_LABELS: Record = { + none: "None", + "left-right": "Left–right", + "top-bottom": "Top–bottom", + both: "Both", +}; + +export class GeneratorTab { + /** Survives re-renders of the modal. */ + static selectedPath = ""; + private seed = randomSeed(); + private previewCols = 30; + private previewRows = 20; + private previewTimer: number | null = null; + + constructor( + private app: App, + private plugin: HexmakerPlugin, + private view: HexMapView, + private host: GeneratorTabHost, + ) { + const map = plugin.getMap(view.activeMapName); + if (map && map.gridSize.cols * map.gridSize.rows <= PREVIEW_AUTO_LIMIT) { + this.previewCols = map.gridSize.cols; + this.previewRows = map.gridSize.rows; + } + } + + render(el: HTMLElement): void { + el.empty(); + el.addClass("duckmage-wfc-tab"); + this.renderLearn(el); + + el.createEl("h4", { text: "Generator settings" }); + el.createEl("p", { + text: "Each generator keeps its settings in its own file. New maps made with it use them.", + cls: "duckmage-map-origin-desc", + }); + const pickRow = el.createDiv({ cls: "duckmage-region-row" }); + const select = pickRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); + const openBtn = pickRow.createEl("button", { text: "Open file" }); + openBtn.disabled = true; + const body = el.createDiv(); + let generators: GeneratorFile[] = []; + const current = () => generators.find((g) => g.file.path === select.value); + + const show = () => { + GeneratorTab.selectedPath = select.value; + body.empty(); + const g = current(); + openBtn.disabled = !g; + if (g) this.renderGenerator(body, g); + else + body.createEl("p", { + text: generators.length ? "Pick a generator." : "No generators yet. Paint a map, then use the button above.", + cls: "duckmage-map-origin-desc", + }); + }; + select.addEventListener("change", show); + openBtn.addEventListener("click", () => { + const g = current(); + if (!g) return; + this.host.close(); + void this.app.workspace.getLeaf("tab").openFile(g.file); + }); + + select.createEl("option", { value: "", text: "Loading…" }); + void listGenerators(this.plugin).then((list) => { + generators = list; + select.empty(); + if (!list.length) select.createEl("option", { value: "", text: "No generators" }); + for (const g of list) { + const palette = g.model.meta.palette; + select.createEl("option", { value: g.file.path, text: palette ? `${g.model.name} (${palette})` : g.model.name }); + } + select.value = list.some((g) => g.file.path === GeneratorTab.selectedPath) + ? GeneratorTab.selectedPath + : (list[0]?.file.path ?? ""); + show(); + }); + } + + // ── Learn ──────────────────────────────────────────────────────────────── + + private renderLearn(el: HTMLElement): void { + el.createEl("h4", { text: "Learn from this map" }); + el.createEl("p", { + text: "Make a wave function collapse generator from the terrain painted on this map. Terrains that never touch here never touch in generated maps; lakes, ridges, forests and towns keep their shape and relative size; rivers that run from an edge into a lake are always placed.", + cls: "duckmage-map-origin-desc", + }); + const row = el.createDiv({ cls: "duckmage-region-row" }); + const nameInput = row.createEl("input", { type: "text", value: this.view.activeMapName, placeholder: "generator-name" }); + const btn = row.createEl("button", { text: "Generate solver from map", cls: "mod-cta" }); + btn.addEventListener("click", () => { + btn.disabled = true; + void saveGeneratorFromMap(this.plugin, this.view.activeMapName, nameInput.value).then((result) => { + btn.disabled = false; + if ("error" in result) { + new Notice(result.error); + return; + } + const { model, file } = result; + const extra = model.features?.length ? `, ${model.features.length} guaranteed feature(s)` : ""; + new Notice(`Saved generator "${model.name}": ${model.terrains.length} terrains, ${model.adjacency.length} neighbour pairs${extra}.`); + GeneratorTab.selectedPath = file.path; + this.host.rerender(); + }); + }); + } + + // ── One generator ──────────────────────────────────────────────────────── + + private renderGenerator(el: HTMLElement, g: GeneratorFile): void { + const { model } = g; + const colors = paletteColors(this.plugin, model.meta.palette); + const byShape = (shape: string) => model.terrains.filter((t) => (t.shape ?? "none") === shape).map((t) => t.name); + const parts = [`${model.terrains.length} terrains`]; + for (const [shape, label] of [["blob", "blobs"], ["line", "lines"], ["scatter", "scattered"]] as const) + if (byShape(shape).length) parts.push(`${label}: ${byShape(shape).join(", ")}`); + if (model.meta["source-map"]) parts.push(`learned from ${model.meta["source-map"]}`); + el.createEl("p", { text: parts.join(" · "), cls: "duckmage-map-origin-desc" }); + for (const w of g.warnings) el.createEl("p", { text: `⚠ ${w}`, cls: "duckmage-map-origin-desc" }); + + // Current settings, kept in sync with the file. + const s = () => resolveSettings(model); + const save = (patch: Partial>) => { + const next: Record = { ...(model.settings ?? {}) }; + for (const [k, v] of Object.entries(patch)) { + if (v === undefined) delete next[k]; + else next[k] = v; + } + model.settings = next; + saveGeneratorSettings(this.plugin, g.file, patch).catch((e: unknown) => { + new Notice(`Couldn't save generator settings: ${e instanceof Error ? e.message : String(e)}`); + }); + schedulePreview(); + }; + + // Preview + const previewBox = el.createDiv({ cls: "duckmage-wfc-section" }); + const canvas = previewBox.createEl("canvas", { cls: "duckmage-wfc-preview" }); + const status = previewBox.createEl("p", { cls: "duckmage-map-origin-desc" }); + const previewRow = previewBox.createDiv({ cls: "duckmage-region-row" }); + previewRow.createSpan({ text: "Seed", cls: "duckmage-map-origin-label" }); + const seedInput = previewRow.createEl("input", { type: "number", value: String(this.seed), cls: "duckmage-wfc-seed" }); + const rerollBtn = previewRow.createEl("button", { text: "Re-roll" }); + previewRow.createSpan({ text: "Size", cls: "duckmage-map-origin-label" }); + const colsInput = previewRow.createEl("input", { type: "number", value: String(this.previewCols), cls: "duckmage-wfc-num" }); + previewRow.createSpan({ text: "×" }); + const rowsInput = previewRow.createEl("input", { type: "number", value: String(this.previewRows), cls: "duckmage-wfc-num" }); + const previewBtn = previewRow.createEl("button", { text: "Preview" }); + + const runPreview = () => { + this.previewCols = Math.max(2, Math.min(200, Number(colsInput.value) || 30)); + this.previewRows = Math.max(2, Math.min(200, Number(rowsInput.value) || 20)); + this.seed = Number(seedInput.value) >>> 0; + const map = this.plugin.getMap(this.view.activeMapName); + const grid = { + cols: this.previewCols, + rows: this.previewRows, + offset: { x: 0, y: 0 }, + stagger: map?.staggerOffset ?? this.plugin.settings.staggerOffset ?? "odd", + }; + const palette = [...colors.keys()].length ? [...colors.keys()] : model.terrains.map((t) => t.name); + const r = generateTerrain(this.plugin, model, palette, grid, this.seed); + if (!r.ok) { + status.setText(`Couldn't generate: ${r.message}`); + return; + } + drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells); + const notes = r.warnings.length ? ` · ${r.warnings.join("; ")}` : ""; + status.setText(`${grid.cols}×${grid.rows} in ${r.stats.ms} ms${notes}`); + }; + const schedulePreview = () => { + if (this.previewTimer !== null) window.clearTimeout(this.previewTimer); + if (Number(colsInput.value) * Number(rowsInput.value) > PREVIEW_AUTO_LIMIT) { + status.setText("Large map: use the preview button to generate it."); + return; + } + this.previewTimer = window.setTimeout(() => { + this.previewTimer = null; + runPreview(); + }, 200); + }; + rerollBtn.addEventListener("click", () => { + seedInput.value = String(randomSeed()); + runPreview(); + }); + previewBtn.addEventListener("click", runPreview); + for (const input of [seedInput, colsInput, rowsInput]) input.addEventListener("change", schedulePreview); + + // Shape + this.heading(el, "Shape"); + this.slider(el, "Feature size", "Size of lakes, ranges and forests relative to the map. 1 = like the example; lower = more, smaller features; 0 = no growth.", 0, 3, 0.25, s().featureSize, (v) => save({ featureSize: v })); + this.slider(el, "Line width", "Thickness of ridges, ranges and rivers. 0 = as in the example.", 0, 3, 1, s().lineWidth, (v) => save({ lineWidth: v })); + this.slider(el, "Smoothing", "Clean up lone specks and ragged edges after generating.", 0, 1, 0.1, s().smoothing, (v) => save({ smoothing: v })); + this.select(el, "Symmetry", "Mirror the map. Symmetric wherever the rules allow.", + SYMMETRIES.map((v) => [v, SYMMETRY_LABELS[v]]), s().symmetry, (v) => save({ symmetry: v })); + this.select(el, "Edge style", "What the map border prefers. Pick a terrain such as water for islands, or follow the example map.", + [["", "As in the example"], ...model.terrains.map((t): [string, string] => [t.name, t.name])], + s().edgeTerrain, (v) => save({ edgeTerrain: v || undefined })); + this.slider(el, "Edge strength", "How strongly the border follows the edge style. 0 = off.", 0, 1, 0.05, s().edgeStrength, (v) => save({ edgeStrength: v })); + + // Placement + this.heading(el, "Placement"); + this.slider(el, "Directional bias", "0 = features can go anywhere. 1 = they keep to where they were in the example, so an ocean along the bottom stays along the bottom.", 0, 1, 0.05, s().directionalBias, (v) => save({ directionalBias: v })); + this.slider(el, "Spacing", "How far apart scattered terrain like towns stays, relative to the example. 0 = no spacing.", 0, 3, 0.25, s().spacing, (v) => save({ spacing: v })); + this.slider(el, "Randomness", "Share of hexes chosen by plain chance, ignoring neighbours. Lets rare terrain like towns pepper the map. Hard rules still apply.", 0, 1, 0.05, s().randomness, (v) => save({ randomness: v })); + + // Guarantees + this.heading(el, "Guarantees"); + if (model.features?.length) { + const list = model.features.map((f) => `${f.terrain}: ${f.from === "edge" ? "map edge" : f.from} → ${f.to === "edge" ? "map edge" : f.to}`).join(", "); + this.toggle(el, "Guaranteed features", `Always lay these down first: ${list}.`, s().features, (v) => save({ features: v })); + } else { + el.createEl("p", { + text: "No guaranteed features. Paint a river running from a map edge into a lake (or from edge to edge) in the example map to get one.", + cls: "duckmage-map-origin-desc", + }); + } + this.toggle(el, "Connected land", "Make all land one connected area, filling cut-off pockets with impassable terrain.", s().connected, (v) => save({ connected: v })); + el.createEl("label", { text: "Impassable terrain", cls: "duckmage-map-field-label" }); + const chips = el.createDiv({ cls: "duckmage-wfc-chips" }); + const impassable = new Set(s().impassable); + for (const t of model.terrains) { + const chip = chips.createEl("label", { cls: "duckmage-wfc-chip" }); + const cb = chip.createEl("input", { type: "checkbox" }); + cb.checked = impassable.has(t.name); + chip.createSpan({ text: t.name }); + cb.addEventListener("change", () => { + if (cb.checked) impassable.add(t.name); + else impassable.delete(t.name); + save({ impassable: [...impassable] }); + }); + } + + // Per terrain + this.heading(el, "Terrains"); + el.createEl("p", { + text: "Mix scales how common each terrain is. Min and max set how many separate patches to make (a town is a 1-hex patch); leave blank for no limit.", + cls: "duckmage-map-origin-desc", + }); + const table = el.createDiv({ cls: "duckmage-wfc-terrains" }); + const head = table.createDiv({ cls: "duckmage-wfc-terrain-row duckmage-wfc-terrain-head" }); + for (const h of ["Terrain", "Shape", "Mix", "Min", "Max"]) head.createSpan({ text: h }); + const mix = { ...s().mix }; + const counts: Record = Object.fromEntries(Object.entries(s().counts).map(([k, r]) => [k, { ...r }])); + for (const t of model.terrains) { + const row = table.createDiv({ cls: "duckmage-wfc-terrain-row" }); + const nameCell = row.createSpan({ cls: "duckmage-wfc-terrain-name" }); + const swatch = nameCell.createSpan({ cls: "duckmage-wfc-swatch" }); + swatch.setCssProps({ "--duckmage-wfc-swatch": colors.get(t.name) ?? "var(--background-modifier-border)" }); + nameCell.createSpan({ text: t.name }); + row.createSpan({ text: t.shape ?? "none", cls: "duckmage-map-origin-desc" }); + const mixCell = row.createSpan({ cls: "duckmage-wfc-mix" }); + const mixSlider = mixCell.createEl("input", { type: "range" }); + mixSlider.min = "0"; + mixSlider.max = "3"; + mixSlider.step = "0.25"; + mixSlider.value = String(mix[t.name] ?? 1); + const mixLabel = mixCell.createSpan({ text: `×${mixSlider.value}` }); + mixSlider.addEventListener("input", () => mixLabel.setText(`×${mixSlider.value}`)); + mixSlider.addEventListener("change", () => { + const v = Number(mixSlider.value); + if (v === 1) delete mix[t.name]; + else mix[t.name] = v; + save({ mix: Object.keys(mix).length ? { ...mix } : undefined }); + }); + for (const bound of ["min", "max"] as const) { + const input = row.createEl("input", { type: "number", cls: "duckmage-wfc-num", attr: { min: "0", placeholder: "–" } }); + const v = counts[t.name]?.[bound]; + input.value = v === undefined ? "" : String(v); + input.addEventListener("change", () => { + const range: CountRange = { ...(counts[t.name] ?? {}) }; + if (input.value === "") delete range[bound]; + else range[bound] = Math.max(0, Math.floor(Number(input.value) || 0)); + if (range.min === undefined && range.max === undefined) delete counts[t.name]; + else counts[t.name] = range; + save({ counts: Object.keys(counts).length ? { ...counts } : undefined }); + }); + } + } + + // Advanced tuning + const adv = el.createEl("details", { cls: "duckmage-wfc-section" }); + adv.createEl("summary", { text: "Advanced tuning" }); + this.slider(adv, "Clumping", "How strongly each hex follows its neighbours. 0 gives speckled noise.", 0, 6, 0.5, s().neighbourInfluence, (v) => save({ neighbourInfluence: v })); + this.slider(adv, "Mix strength", "How closely the overall terrain mix follows the example.", 0, 4, 0.5, s().frequencyFeedback, (v) => save({ frequencyFeedback: v })); + this.slider(adv, "Scatter", "Randomness in where features start. Too low and one terrain can take over the map.", 0, 6, 0.5, s().scatter, (v) => save({ scatter: v })); + + const resetRow = el.createDiv({ cls: "duckmage-region-row" }); + const resetBtn = resetRow.createEl("button", { text: "Reset settings to defaults" }); + resetBtn.addEventListener("click", () => { + const cleared: Partial> = {}; + for (const k of Object.keys(model.settings ?? {})) cleared[k as keyof GeneratorSettings] = undefined; + save(cleared); + this.host.rerender(); + }); + + this.renderFill(el, g, () => Number(seedInput.value) >>> 0); + schedulePreview(); + } + + // ── Fill the active map ────────────────────────────────────────────────── + + private renderFill(el: HTMLElement, g: GeneratorFile, seed: () => number): void { + this.heading(el, "Fill this map"); + const mapName = this.view.activeMapName; + const palette = this.plugin.getMapPalette(mapName).map((t) => t.name); + el.createEl("p", { + text: `Uses the preview's seed. "Fill unpainted hexes" keeps everything you've painted. "Regenerate" repaints the whole map except hexes whose note has "${LOCK_KEY}: true" in its properties.`, + cls: "duckmage-map-origin-desc", + }); + if (!generatorFitsPalette(g.model, palette)) + el.createEl("p", { + text: "⚠ This map's palette is missing some of the generator's terrains; those are left out.", + cls: "duckmage-map-origin-desc", + }); + const row = el.createDiv({ cls: "duckmage-region-row" }); + const fillBtn = row.createEl("button", { text: "Fill unpainted hexes", cls: "mod-cta" }); + const regenBtn = row.createEl("button", { text: "Regenerate map", cls: "mod-warning" }); + let confirming = false; + + const run = async (mode: "unpainted" | "regenerate", btn: HTMLButtonElement) => { + fillBtn.disabled = regenBtn.disabled = true; + const label = btn.textContent ?? ""; + const result = await fillMap(this.plugin, mapName, g.model, mode, seed(), (done, total) => + btn.setText(`Writing ${done} / ${total}…`), + ); + fillBtn.disabled = regenBtn.disabled = false; + btn.setText(label); + if ("error" in result) { + new Notice(`Couldn't fill the map: ${result.error}`); + return; + } + const notes = result.warnings.length ? ` (${result.warnings.join("; ")})` : ""; + new Notice(`Generator "${g.model.name}" set terrain on ${result.changed} hexes${notes}.`); + // Let the metadata cache catch up before redrawing. + window.setTimeout(() => this.plugin.refreshHexMap(), 300); + }; + fillBtn.addEventListener("click", () => void run("unpainted", fillBtn)); + regenBtn.addEventListener("click", () => { + if (!confirming) { + confirming = true; + regenBtn.setText("Click again to repaint the map"); + window.setTimeout(() => { + confirming = false; + regenBtn.setText("Regenerate map"); + }, 4000); + return; + } + confirming = false; + regenBtn.setText("Regenerate map"); + void run("regenerate", regenBtn); + }); + } + + // ── Small controls ─────────────────────────────────────────────────────── + + private heading(el: HTMLElement, text: string): void { + el.createEl("h5", { text, cls: "duckmage-wfc-heading" }); + } + + private slider( + el: HTMLElement, + label: string, + hint: string, + min: number, + max: number, + step: number, + value: number, + onChange: (v: number) => void, + ): void { + el.createEl("label", { text: label, cls: "duckmage-map-field-label" }); + const row = el.createDiv({ cls: "duckmage-region-row" }); + const input = row.createEl("input", { type: "range" }); + input.min = String(min); + input.max = String(max); + input.step = String(step); + input.value = String(value); + const valueEl = row.createSpan({ text: String(value) }); + el.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); + input.addEventListener("input", () => valueEl.setText(input.value)); + input.addEventListener("change", () => onChange(Number(input.value))); + } + + private select( + el: HTMLElement, + label: string, + hint: string, + options: [T, string][], + value: T, + onChange: (v: T) => void, + ): void { + el.createEl("label", { text: label, cls: "duckmage-map-field-label" }); + const sel = el.createDiv({ cls: "duckmage-region-row" }).createEl("select"); + for (const [v, text] of options) sel.createEl("option", { value: v, text }); + sel.value = value; + el.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); + sel.addEventListener("change", () => onChange(sel.value as T)); + } + + private toggle(el: HTMLElement, label: string, hint: string, value: boolean, onChange: (v: boolean) => void): void { + const row = el.createEl("label", { cls: "duckmage-region-row duckmage-wfc-toggle" }); + const cb = row.createEl("input", { type: "checkbox" }); + cb.checked = value; + row.createSpan({ text: label }); + el.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); + cb.addEventListener("change", () => onChange(cb.checked)); + } +} diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index 9f33df52..cc2bfb5d 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -1,17 +1,18 @@ /** * Hexmaker glue for the hex-wfc library: where generator files live, learning - * a generator from a painted map, and generating terrain for a new map. + * a generator from a painted map, generating terrain for a new map, and + * filling or regenerating an existing one. * * Generators are Markdown files (see packages/hex-wfc/src/format.ts) under * `{worldFolder}/generators`, so users can open and edit them by hand. A * palette can have any number of them (one learned from a lakes map, another * from a mountain range, ...). Each records the palette and map it came from - * in its frontmatter. + * in its frontmatter, along with its solver settings. */ import { TFile, TFolder } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; -import { getTerrainFromFile } from "../frontmatter"; +import { getFrontMatter, getTerrainFromFile, setTerrainInFile } from "../frontmatter"; import { normalizeFolder, slugify } from "../utils"; import { learnModel, @@ -21,12 +22,16 @@ import { restrictModel, solve, cellKey, - type HexWfcModel, + encodeSetting, SETTING_KEYS, + type HexWfcModel, type SolveResult, type GeneratorSettings, } from "../../packages/hex-wfc/src"; +/** Frontmatter key that keeps a hex's terrain when a map is regenerated. */ +export const LOCK_KEY = "locked"; + export interface GeneratorFile { file: TFile; model: HexWfcModel; @@ -85,6 +90,28 @@ export function readMapTerrain(plugin: HexmakerPlugin, mapName: string): Map { + const map = plugin.getMap(mapName); + const out = new Set(); + if (!map) return out; + const { cols, rows } = map.gridSize; + const { x: ox, y: oy } = map.gridOffset; + for (let x = ox; x < ox + cols; x++) { + for (let y = oy; y < oy + rows; y++) { + const fm = getFrontMatter(plugin.app, plugin.hexPath(x, y, mapName)) as Record | null; + if (fm?.[LOCK_KEY] === true) out.add(cellKey(x, y)); + } + } + return out; +} + +/** Palette colour per terrain name, for previews. */ +export function paletteColors(plugin: HexmakerPlugin, paletteName: string | undefined): Map { + const terrains = plugin.getPaletteByName(paletteName ?? "")?.terrains ?? plugin.settings.terrainPalettes[0]?.terrains ?? []; + return new Map(terrains.map((t) => [t.name, t.color])); +} + /** * Learn a generator from the map's painted hexes and save it as a new file. * Never overwrites: a name clash gets a numeric suffix. @@ -110,7 +137,6 @@ export async function saveGeneratorFromMap( meta: { palette: map.paletteName, "source-map": mapName, - "painted-hexes": String(cells.size), created: new Date().toISOString().slice(0, 10), }, }); @@ -135,43 +161,130 @@ export async function saveGeneratorFromMap( } /** - * Generate terrain for a whole new map. Terrains the palette lacks are dropped - * from the generator first. + * Save solver settings into a generator file's frontmatter. Only the + * frontmatter changes, so the tables and any notes the user wrote are kept. + * A value of `undefined` removes the setting (back to the default). */ -export function generateMapTerrain( +export async function saveGeneratorSettings( + plugin: HexmakerPlugin, + file: TFile, + settings: Partial>, +): Promise { + await plugin.app.fileManager.processFrontMatter(file, (fm: Record) => { + for (const [field, value] of Object.entries(settings) as [keyof GeneratorSettings, unknown][]) { + const key = SETTING_KEYS[field]; + if (value === undefined) delete fm[key]; + else fm[key] = encodeSetting(field, value); + } + }); +} + +export interface GridSpec { + cols: number; + rows: number; + offset: { x: number; y: number }; + stagger: "odd" | "even"; +} + +/** + * Run a generator on a grid. Terrains the palette lacks are dropped from the + * generator first. Fixed hexes whose terrain the generator doesn't know are + * kept, treated as allowed next to anything. + */ +export function generateTerrain( plugin: HexmakerPlugin, model: HexWfcModel, paletteTerrains: string[], - cols: number, - rows: number, - offset: { x: number; y: number }, - stagger: "odd" | "even", + grid: GridSpec, seed: number, - featureSize = 1, + fixed?: Map, ): SolveResult { - return solve(restrictModel(model, paletteTerrains), { - cols, - rows, - offset, + let fitted = restrictModel(model, paletteTerrains); + const unknown = new Set([...(fixed?.values() ?? [])].filter((t) => !fitted.terrains.some((e) => e.name === t))); + if (unknown.size) { + const all = [...fitted.terrains.map((t) => t.name), ...unknown]; + fitted = { + ...fitted, + terrains: [...fitted.terrains, ...[...unknown].map((name) => ({ name, weight: 0 }))], + adjacency: [ + ...fitted.adjacency, + ...[...unknown].flatMap((u) => all.map((b) => ({ a: u, b, weight: 1 }))), + ], + }; + } + return solve(fitted, { + cols: grid.cols, + rows: grid.rows, + offset: grid.offset, orientation: plugin.settings.hexOrientation, - stagger, + stagger: grid.stagger, seed, - featureSize, + fixed, }); } /** - * Save solver settings into a generator file's frontmatter. Only the - * frontmatter changes, so the tables and any notes the user wrote are kept. + * Fill an existing map with a generator. + * - "unpainted": only hexes without terrain change; every painted hex stays. + * - "regenerate": every hex may change except those marked `locked: true`. + * Returns the number of hexes written, plus any soft-goal warnings. */ -export async function saveGeneratorSettings( +export async function fillMap( plugin: HexmakerPlugin, - file: TFile, - settings: GeneratorSettings, + mapName: string, + model: HexWfcModel, + mode: "unpainted" | "regenerate", + seed: number, + onProgress?: (done: number, total: number) => void, +): Promise<{ changed: number; warnings: string[] } | { error: string }> { + const map = plugin.getMap(mapName); + if (!map) return { error: `Map "${mapName}" not found.` }; + const painted = readMapTerrain(plugin, mapName); + let fixed = painted; + if (mode === "regenerate") { + const locked = readLockedHexes(plugin, mapName); + fixed = new Map([...painted].filter(([k]) => locked.has(k))); + } + const palette = plugin.getMapPalette(mapName).map((t) => t.name); + const result = generateTerrain( + plugin, + model, + palette, + { cols: map.gridSize.cols, rows: map.gridSize.rows, offset: map.gridOffset, stagger: mapStagger(plugin, mapName) }, + seed, + fixed, + ); + if (!result.ok) return { error: result.message }; + const changes = [...result.cells].filter(([k, t]) => painted.get(k) !== t); + await writeTerrain(plugin, mapName, changes, onProgress); + return { changed: changes.length, warnings: result.warnings }; +} + +/** Write terrain to hex notes (creating missing ones) and keep encounter links in sync. */ +async function writeTerrain( + plugin: HexmakerPlugin, + mapName: string, + changes: [string, string][], + onProgress?: (done: number, total: number) => void, ): Promise { - await plugin.app.fileManager.processFrontMatter(file, (fm: Record) => { - for (const [field, value] of Object.entries(settings) as [keyof GeneratorSettings, number | undefined][]) { - if (value !== undefined) fm[SETTING_KEYS[field]] = value; - } - }); + const CHUNK = 20; + let done = 0; + for (let i = 0; i < changes.length; i += CHUNK) { + await Promise.all( + changes.slice(i, i + CHUNK).map(async ([key, terrain]) => { + const [x, y] = key.split("_").map(Number); + const path = plugin.hexPath(x, y, mapName); + const before = getTerrainFromFile(plugin.app, path); + if (plugin.app.vault.getAbstractFileByPath(path) instanceof TFile) { + await setTerrainInFile(plugin.app, path, terrain); + } else { + await plugin.createHexNote(x, y, mapName, undefined, terrain); + } + if (plugin.hasTerrainEncounterTable(terrain) || (before && plugin.hasTerrainEncounterTable(before))) + await plugin.syncHexEncounterTableLink(path, terrain); + done++; + }), + ); + onProgress?.(done, changes.length); + } } diff --git a/src/worldgen/preview.ts b/src/worldgen/preview.ts new file mode 100644 index 00000000..9a8dfc1e --- /dev/null +++ b/src/worldgen/preview.ts @@ -0,0 +1,69 @@ +/** + * Small canvas preview of a generated map, drawn with the palette colours. + * Used on the Generator and New map tabs before anything is written. + */ + +import { hexCenter, cellKey } from "../../packages/hex-wfc/src"; + +/** Above this many hexes the preview waits for an explicit click. */ +export const PREVIEW_AUTO_LIMIT = 4000; + +/** Stable fallback colour for terrains missing from the palette. */ +function hashColor(name: string): string { + let h = 0; + for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0; + return `hsl(${h % 360}, 45%, 55%)`; +} + +export function drawPreview( + canvas: HTMLCanvasElement, + cells: Map, + grid: { cols: number; rows: number; offset: { x: number; y: number }; stagger: "odd" | "even" }, + orientation: "flat" | "pointy", + colors: Map, + featureCells?: Set, + maxWidth = 420, +): void { + const { cols, rows, offset, stagger } = grid; + // Hex centres in unit space (neighbours √3 apart, circumradius 1). + const pts: [string, number, number][] = []; + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + for (let j = 0; j < rows; j++) + for (let i = 0; i < cols; i++) { + const x = offset.x + i, y = offset.y + j; + const [px, py] = hexCenter(x, y, orientation, stagger); + pts.push([cellKey(x, y), px, py]); + minX = Math.min(minX, px); maxX = Math.max(maxX, px); + minY = Math.min(minY, py); maxY = Math.max(maxY, py); + } + const spanX = maxX - minX + 2, spanY = maxY - minY + 2; + const scale = Math.max(1, Math.min(maxWidth / spanX, 14)); + canvas.width = Math.ceil(spanX * scale); + canvas.height = Math.ceil(spanY * scale); + const ctx = canvas.getContext("2d"); + if (!ctx) return; + ctx.clearRect(0, 0, canvas.width, canvas.height); + const corner = (k: number) => { + const a = (Math.PI / 3) * k + (orientation === "pointy" ? Math.PI / 6 : 0); + return [Math.cos(a), Math.sin(a)]; + }; + const corners = [0, 1, 2, 3, 4, 5].map(corner); + for (const [key, px, py] of pts) { + const t = cells.get(key); + const cx = (px - minX + 1) * scale, cy = (py - minY + 1) * scale; + ctx.beginPath(); + corners.forEach(([dx, dy], k) => { + const X = cx + dx * scale * 1.01, Y = cy + dy * scale * 1.01; + if (k === 0) ctx.moveTo(X, Y); + else ctx.lineTo(X, Y); + }); + ctx.closePath(); + ctx.fillStyle = t ? (colors.get(t) ?? hashColor(t)) : "rgba(127,127,127,0.15)"; + ctx.fill(); + if (featureCells?.has(key)) { + ctx.strokeStyle = "rgba(0,0,0,0.35)"; + ctx.lineWidth = Math.max(1, scale * 0.15); + ctx.stroke(); + } + } +} diff --git a/styles.css b/styles.css index f1107138..a9678bb4 100644 --- a/styles.css +++ b/styles.css @@ -5101,3 +5101,96 @@ tr:hover .duckmage-rt-entry-copy-btn:hover { font-variant-numeric: tabular-nums; color: var(--text-muted); } + +/* ── Maps modal: Generator tab (wave function collapse) ───────────────────── */ + +.duckmage-wfc-section { + margin: 0.75em 0; +} + +.duckmage-wfc-preview { + display: block; + max-width: 100%; + height: auto; + border-radius: var(--radius-s); + background: var(--background-secondary); +} + +.duckmage-wfc-heading { + margin: 1.2em 0 0.2em; + padding-bottom: 0.2em; + border-bottom: 1px solid var(--background-modifier-border); +} + +.duckmage-wfc-seed { + width: 120px; +} + +.duckmage-wfc-num { + width: 60px; +} + +.duckmage-wfc-toggle { + gap: 0.5em; + cursor: pointer; +} + +.duckmage-wfc-chips { + display: flex; + flex-wrap: wrap; + gap: 0.35em 0.75em; +} + +.duckmage-wfc-chip { + display: inline-flex; + align-items: center; + gap: 0.3em; + cursor: pointer; +} + +.duckmage-wfc-terrains { + display: grid; + gap: 0.25em; +} + +.duckmage-wfc-terrain-row { + display: grid; + grid-template-columns: minmax(8em, 1.5fr) 5em minmax(9em, 2fr) 4.5em 4.5em; + align-items: center; + gap: 0.5em; +} + +.duckmage-wfc-terrain-head { + font-size: 0.8em; + color: var(--text-muted); + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.duckmage-wfc-terrain-name { + display: inline-flex; + align-items: center; + gap: 0.4em; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.duckmage-wfc-swatch { + flex: none; + width: 0.9em; + height: 0.9em; + border-radius: 2px; + background: var(--duckmage-wfc-swatch, var(--background-modifier-border)); +} + +.duckmage-wfc-mix { + display: inline-flex; + align-items: center; + gap: 0.4em; +} + +.duckmage-wfc-mix input[type="range"] { + flex: 1; + min-width: 0; +} diff --git a/tests/worldgenGenerators.test.ts b/tests/worldgenGenerators.test.ts index b56ce2f8..888f38c0 100644 --- a/tests/worldgenGenerators.test.ts +++ b/tests/worldgenGenerators.test.ts @@ -6,17 +6,20 @@ import { generatorFitsPalette, listGenerators, readMapTerrain, + readLockedHexes, saveGeneratorFromMap, - generateMapTerrain, + saveGeneratorSettings, + generateTerrain, + fillMap, } from "../src/worldgen/generators"; -import { findViolation, type HexWfcModel } from "../packages/hex-wfc/src"; +import { findViolation, parseModelMarkdown, type HexWfcModel } from "../packages/hex-wfc/src"; import type HexmakerPlugin from "../src/HexmakerPlugin"; /** * In-memory vault + plugin stub. Hex notes are represented only by their - * terrain frontmatter; written files are kept as text. + * frontmatter (terrain, locked); other written files are kept as text. */ -function makePlugin(painted: Record) { +function makePlugin(painted: Record, locked: string[] = []) { const files = new Map(); const folders = new Set(); const fileObj = (path: string) => { @@ -26,16 +29,23 @@ function makePlugin(painted: Record) { return f; }; const hexPath = (x: number, y: number, map: string) => `world/hexes/${map}/${x}_${y}.md`; - const terrainByPath = new Map( - Object.entries(painted).map(([k, t]) => { - const [x, y] = k.split("_").map(Number); - return [hexPath(x, y, "sample"), t]; - }), - ); + const hexFm = new Map>(); + for (const [k, t] of Object.entries(painted)) { + const [x, y] = k.split("_").map(Number); + hexFm.set(hexPath(x, y, "sample"), { terrain: t }); + } + for (const k of locked) { + const [x, y] = k.split("_").map(Number); + const fm = hexFm.get(hexPath(x, y, "sample")) ?? {}; + fm.locked = true; + hexFm.set(hexPath(x, y, "sample"), fm); + } + const otherFm = new Map>(); + const created: string[] = []; const app = { vault: { getAbstractFileByPath: (p: string) => { - if (files.has(p) || terrainByPath.has(p)) return fileObj(p); + if (files.has(p) || hexFm.has(p)) return fileObj(p); if (folders.has(p)) return Object.create(TFolder.prototype) as TFolder; return null; }, @@ -49,23 +59,47 @@ function makePlugin(painted: Record) { }, metadataCache: { getFileCache: (f: TFile) => { - const terrain = terrainByPath.get(f.path); - return terrain ? { frontmatter: { terrain } } : null; + const fm = hexFm.get(f.path); + return fm ? { frontmatter: fm } : null; + }, + }, + fileManager: { + processFrontMatter: async (f: TFile, fn: (fm: Record) => void) => { + const store = hexFm.has(f.path) ? hexFm : otherFm; + const fm = store.get(f.path) ?? {}; + fn(fm); + store.set(f.path, fm); }, }, }; + const palette = ["Grass", "Sand", "Water"].map((name) => ({ name, color: "#000" })); const plugin = { app, settings: { worldFolder: "world", hexOrientation: "flat", staggerOffset: "odd", + terrainPalettes: [{ name: "Default", terrains: palette }], maps: [{ name: "sample", paletteName: "Default", gridSize: { cols: 12, rows: 10 }, gridOffset: { x: 0, y: 0 } }], }, getMap: (name: string) => plugin.settings.maps.find((m) => m.name === name), + getMapPalette: () => palette, + getPaletteByName: () => ({ name: "Default", terrains: palette }), hexPath, + createHexNote: async (x: number, y: number, map: string, _tpl?: string, terrain?: string) => { + const p = hexPath(x, y, map); + hexFm.set(p, terrain ? { terrain } : {}); + created.push(p); + return fileObj(p); + }, + hasTerrainEncounterTable: () => false, + syncHexEncounterTableLink: async () => {}, } as unknown as HexmakerPlugin; - return { plugin, files }; + const terrainAt = (k: string) => { + const [x, y] = k.split("_").map(Number); + return hexFm.get(hexPath(x, y, "sample"))?.terrain as string | undefined; + }; + return { plugin, files, otherFm, created, terrainAt }; } /** A 12×10 painted sample: a lake ringed by sand in grassland. */ @@ -79,15 +113,18 @@ function lakeSample(): Record { return out; } +const PALETTE = ["Grass", "Sand", "Water"]; + describe("worldgen generators", () => { it("stores generators under the world folder", () => { const { plugin } = makePlugin({}); expect(generatorsFolder(plugin)).toBe("world/generators"); }); - it("reads painted terrain from the map's hex notes", () => { - const { plugin } = makePlugin({ "0_0": "Grass", "3_4": "Water" }); + it("reads painted terrain and locked hexes from the map's notes", () => { + const { plugin } = makePlugin({ "0_0": "Grass", "3_4": "Water" }, ["3_4"]); expect([...readMapTerrain(plugin, "sample")]).toEqual([["0_0", "Grass"], ["3_4", "Water"]]); + expect([...readLockedHexes(plugin, "sample")]).toEqual(["3_4"]); }); it("learns from a map, saves a readable file, and lists it back", async () => { @@ -100,6 +137,7 @@ describe("worldgen generators", () => { expect(text).toContain("hex-wfc: 1"); expect(text).toContain("palette: Default"); expect(text).toContain("source-map: sample"); + expect(text).toContain("example-hexes: 120"); expect(text).toMatch(/\| (Water \| Sand|Sand \| Water) \|/); expect(text).not.toMatch(/\| (Water \| Grass|Grass \| Water) \|/); // never touched @@ -132,11 +170,68 @@ describe("worldgen generators", () => { const { plugin } = makePlugin(lakeSample()); const saved = await saveGeneratorFromMap(plugin, "sample", "lakes"); if ("error" in saved) throw new Error(saved.error); - const r = generateMapTerrain(plugin, saved.model, ["Grass", "Sand", "Water"], 30, 20, { x: 5, y: 5 }, "odd", 42); + const r = generateTerrain(plugin, saved.model, PALETTE, { cols: 30, rows: 20, offset: { x: 5, y: 5 }, stagger: "odd" }, 42); expect(r.ok).toBe(true); if (!r.ok) return; expect(r.cells.size).toBe(600); expect(r.cells.has("5_5")).toBe(true); expect(findViolation(saved.model, r.cells, "flat", "odd")).toBeNull(); }); + + it("keeps fixed hexes the generator doesn't know", async () => { + const { plugin } = makePlugin(lakeSample()); + const saved = await saveGeneratorFromMap(plugin, "sample", "lakes"); + if ("error" in saved) throw new Error(saved.error); + const r = generateTerrain(plugin, saved.model, PALETTE, { cols: 10, rows: 10, offset: { x: 0, y: 0 }, stagger: "odd" }, 1, new Map([["4_4", "Lava"]])); + expect(r.ok).toBe(true); + if (r.ok) expect(r.cells.get("4_4")).toBe("Lava"); + }); + + it("saves settings to frontmatter in their text form, and removes cleared ones", async () => { + const { plugin, otherFm } = makePlugin({}); + const file = Object.create(TFile.prototype) as TFile; + file.path = "world/generators/g.md"; + await saveGeneratorSettings(plugin, file, { featureSize: 1.5, counts: { Town: { min: 3, max: 3 } }, impassable: ["Water"] }); + expect(otherFm.get(file.path)).toEqual({ "feature-size": 1.5, counts: "Town 3", impassable: "Water" }); + await saveGeneratorSettings(plugin, file, { featureSize: undefined }); + expect(otherFm.get(file.path)).toEqual({ counts: "Town 3", impassable: "Water" }); + }); +}); + +describe("fill this map", () => { + /** A partly painted map: the lake sample's left half only. */ + const leftHalf = () => Object.fromEntries(Object.entries(lakeSample()).filter(([k]) => Number(k.split("_")[0]) < 6)); + + async function lakesModel(): Promise { + const { plugin } = makePlugin(lakeSample()); + const saved = await saveGeneratorFromMap(plugin, "sample", "lakes"); + if ("error" in saved) throw new Error(saved.error); + // Round-trip through the file format, as the UI does. + return parseModelMarkdown(await plugin.app.vault.cachedRead(saved.file)).model; + } + + it("fills unpainted hexes and keeps every painted one", async () => { + const model = await lakesModel(); + const painted = leftHalf(); + const { plugin, terrainAt, created } = makePlugin(painted); + const r = await fillMap(plugin, "sample", model, "unpainted", 7); + expect("error" in r).toBe(false); + for (const [k, t] of Object.entries(painted)) expect(terrainAt(k)).toBe(t); + for (let x = 6; x < 12; x++) for (let y = 0; y < 10; y++) expect(terrainAt(`${x}_${y}`)).toBeDefined(); + expect(created.length).toBe(60); // the right half had no notes yet + if (!("error" in r)) expect(r.changed).toBe(60); + }); + + it("regenerate repaints everything except locked hexes", async () => { + const model = await lakesModel(); + const painted = lakeSample(); + const locked = ["5_5", "0_0"]; + const { plugin, terrainAt } = makePlugin(painted, locked); + const r = await fillMap(plugin, "sample", model, "regenerate", 11); + expect("error" in r).toBe(false); + for (const k of locked) expect(terrainAt(k)).toBe(painted[k]); + const cells = new Map(); + for (let x = 0; x < 12; x++) for (let y = 0; y < 10; y++) cells.set(`${x}_${y}`, terrainAt(`${x}_${y}`)!); + expect(findViolation(model, cells, "flat")).toBeNull(); + }); }); From f443dba48ef9d8cc7d9bc85de7180c0c3abb9167 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 16:34:57 -0400 Subject: [PATCH 006/558] docs(hex-wfc): README for shapes, features, settings, file format Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/hex-wfc/README.md | 105 ++++++++++++++++++++++++++++--------- 1 file changed, 79 insertions(+), 26 deletions(-) diff --git a/packages/hex-wfc/README.md b/packages/hex-wfc/README.md index 306dea27..24041105 100644 --- a/packages/hex-wfc/README.md +++ b/packages/hex-wfc/README.md @@ -6,14 +6,50 @@ It works with any terrain names. Terrains are plain strings, so it doesn't matte It lives inside the [Hexmaker](https://github.com/sbuffkin/hexmaker) Obsidian plugin for now, but it doesn't depend on Hexmaker or Obsidian. The plan is to publish it as its own package. It has no build step yet: import the TypeScript sources directly, or bundle them. -## How it works - -- **Learning**: `learnModel` counts how often each terrain appears and how often each pair of terrains touches. If two terrains never touch in the example, they can never touch in generated maps. That includes a terrain next to itself. -- **Solving**: `solve` runs WFC with propagation, backtracking and restarts. Pairs with weight 0 are hard rules. Pair weights are also soft rules: each choice is scored from the neighbours that are already decided, so a lake in the example grows as a lake rather than scattering. `neighbourInfluence` sets how strong that effect is. -- **Growth**: learning also measures the shape of each terrain's patches. Compact patches (lakes, forests) become `blob`, stretched ones (ranges, ridges) become `line`, and backgrounds, shores and scattered hexes become `none`. When the solver starts a new patch of a `blob` or `line` terrain, it gets extra moves to spread: outward for blobs, forward with occasional turns for lines. Every move still obeys the hard rules. -- **Scale**: patch sizes are stored as a share of the map, not a hex count. A generator learned on a 50×50 map makes lakes and ranges of the same relative size on a 20×20 map, and the overall terrain mix stays close to the example's at any size. `featureSize` multiplies on top: below 1 gives more, smaller features, above 1 fewer, bigger ones. -- **Fixed hexes**: pass hexes that are already painted as `fixed`. They are never changed, and the rest of the map is filled around them. -- **Deterministic**: the same model, options and seed always give the same map. +## What it learns from an example map + +- **Rules**: how often each terrain appears and how often each pair touches. If two terrains never touch in the example, they can never touch in generated maps. That includes a terrain next to itself. +- **Shape** of each terrain's patches, using shape alone and never names: + - `blob`: compact patches, e.g. lakes and forests. + - `line`: thin and stretched, e.g. ridges and rivers. Width and turn rate are also learned. + - `scatter`: single hexes, e.g. towns. The smallest gap between them is also learned. + - `none`: backgrounds, and shores that run between two different terrains. +- **Size** of a typical patch, stored as a share of the map, so features scale with the map. +- **Layout**: where each terrain sat (a 3×3 grid), and how common it is along the map border. +- **Guaranteed features**: a line whose two ends are anchored becomes a feature that's always placed. Anchored means edge to edge, or edge to a lake. A river painted from the map edge into a lake is learned as "River: edge → Water". + +## What the solver does + +`solve` runs these steps in order: +1. Lays down the fixed parts first: + - an explicit edge terrain, e.g. a wavy water border for islands; + - the guaranteed features: a river is drawn as a wandering path, with a lake at its mouth. +2. Runs WFC with propagation, backtracking and restarts. +3. Applies post passes: smoothing, connected land, and topping up minimum counts. + +The rules are hard throughout: no setting ever produces a pair the example didn't allow. The same model, options and seed always give the same map. Pass hexes that are already painted as `fixed` and they're never changed. + +### Settings + +Settings can be passed to `solve` or saved in the model file: + +| Setting | What it does | +| --- | --- | +| `featureSize` | Multiplier on learned patch sizes. 0 turns growth off. | +| `lineWidth` | Thickness of line terrains: 0 = as learned, otherwise 1–3. | +| `smoothing` | 0–1. Cleans up lone specks and ragged edges. | +| `symmetry` | `none`, `left-right`, `top-bottom` or `both`. Symmetric wherever the rules allow. | +| `edgeTerrain`, `edgeStrength` | What the border prefers. Name a terrain for e.g. islands, or leave blank to follow the learned edge preference. | +| `directionalBias` | 0–1. Keeps terrain where it sat in the example. | +| `spacing` | Multiplier on the learned gap between scattered hexes (towns). | +| `randomness` | 0–1 share of choices made by weight alone, ignoring neighbours. Peppers rare terrain around the map. | +| `features` | Lay down the guaranteed features. | +| `connected`, `impassable` | Make all land one connected area, filling cut-off pockets with impassable terrain. | +| `mix` | Per-terrain weight multipliers, e.g. `{ Forest: 1.5 }`. | +| `counts` | Per-terrain min/max number of patches, e.g. `{ Town: { min: 3, max: 3 } }`. | +| `neighbourInfluence`, `frequencyFeedback`, `scatter` | Advanced tuning: clumping, how closely the terrain mix follows the example, and randomness in where features start. | + +`result.warnings` lists soft goals that weren't fully met, such as a count or a feature that didn't fit. ## Usage @@ -23,11 +59,11 @@ import { learnModel, solve, modelToMarkdown, parseModelMarkdown } from "hex-wfc" const painted = new Map([["0_0", "Water"], ["1_0", "Water"], ["2_0", "Grass"] /* ... */]); const model = learnModel(painted, { name: "lakes", orientation: "flat" }); -const result = solve(model, { cols: 30, rows: 20, orientation: "flat", seed: 42 }); +const result = solve(model, { cols: 30, rows: 20, orientation: "flat", seed: 42, smoothing: 0.5 }); if (result.ok) result.cells; // Map<"x_y", terrain> else console.warn(result.reason, result.message); -const text = modelToMarkdown(model); // save it +const text = modelToMarkdown(model); // save it const { model: again } = parseModelMarkdown(text); // load it ``` @@ -35,45 +71,62 @@ Coordinates are offset coordinates keyed as `"x_y"`. Flat-top grids stagger colu ## File format -Models save as Markdown with frontmatter and two tables, so you can edit them by hand: +Models save as Markdown with frontmatter and a few tables, so you can edit them by hand: ```markdown --- hex-wfc: 1 name: lakes +example-hexes: 2500 +feature-size: 1.5 +counts: "Town 3; Lake 1-" palette: Default --- ## Terrains -| Terrain | Weight | Patch % | Shape | Turn | -| --- | ---: | ---: | --- | ---: | -| Grass | 120 | 80 | none | | -| Water | 40 | 3.5 | blob | | -| Ridge | 10 | 1.2 | line | 0.2 | +| Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge | +| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: | +| Grass | 2100 | 87 | none | | | | 1.1 | +| Water | 80 | 3.4 | blob | | | | 0.2 | +| River | 40 | 1.6 | line | 0.25 | 1 | | | +| Town | 25 | 0.04 | scatter | | | 5 | | ## Adjacency | Terrain | Next to | Weight | | --- | --- | ---: | -| Grass | Grass | 300 | +| Grass | Grass | 3000 | | Grass | Water | 25 | -| Water | Water | 90 | +| River | Water | 3 | + +## Features + +| Terrain | From | To | Count | +| --- | --- | --- | ---: | +| River | edge | Water | 1 | ``` -- A pair that isn't listed, or has weight 0, can never touch. -- *Patch %*, *Shape* and *Turn* are optional. A file with only *Terrain* and *Weight* still works, without growth. -- Pairs work in both directions, so *A | B* also covers *B | A*. -- Extra frontmatter keys are kept in `model.meta`. +- **Adjacency:** a pair that isn't listed, or has weight 0, can never touch. Pairs work in both directions. +- **Optional parts:** every column after *Weight*, and the *Features* and *Layout* tables, are optional. A file with only *Terrain* and *Weight* still works. +- **Lists and maps in frontmatter** separate items with `; `, so terrain names can contain commas: `mix: "Forest 1.5; Water 0.5"`, `counts: "Town 3; Lake 1-; Ruin 0-2"`, `impassable: "Water; High peaks"`. +- **Other frontmatter keys** are kept in `model.meta`. ## Tuning -The defaults were tuned by eye and by comparing terrain mix across sizes. Run `dev/wfc-ascii.mts` and `dev/wfc-mix.mts` in the Hexmaker repo to check changes. Without `scatter`, enclosed features (a lake inside its shore) never start. Without growth-aware scoring, the most common terrain swallows the map. +The defaults were tuned by eye and by comparing the terrain mix across map sizes. To check changes, run the scripts in the Hexmaker repo's `dev/` folder: +- `wfc-mix.mts`: terrain mix at four sizes against the example. +- `wfc-ascii.mts`, `wfc-controls.mts`, `wfc-bias.mts` and `wfc-river.mts`: print sample maps. + +Three findings from tuning: +- **Scatter:** without it, enclosed features (a lake inside its shore) never start. +- **Growth-aware scoring:** without it, the most common terrain swallows the map. +- **Seed odds scaled by patch size:** without it, coverage grows with map size. ## Limits -- Growth gives ridges and ranges a direction, but nothing guarantees a feature exists or reaches anywhere in particular. A river that must run from a map edge to the sea needs a placed feature (planned). -- Learned `line` features are one hex wide, even if the example's are wider. -- The solver scans every cell on each step, so the cost grows with roughly the square of the map size. 60×60 takes well under a second. +- This is the simple tiled model plus growth. It learns blobs, lines and scatter well. It doesn't learn larger patterns, such as a castle surrounded by a moat surrounded by farmland, beyond what the pair rules imply. +- Guaranteed features are lines with anchored ends. Branching rivers (tributaries) aren't learned yet. +- The solver scans every cell on each step, so the cost grows with roughly the square of the map size. 60×60 takes about 0.15 s and 100×100 under a second. ## License From 47d94fce7e427e96259cb688cd9622d00ca1132f Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 16:53:36 -0400 Subject: [PATCH 007/558] feat(worldgen): learn and route path-tool rivers/roads; sturdier terrain features MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - hex-wfc paths.ts: learn path chains (type, what each end connects to: edge / terrain / "path" = joins another path of the type, e.g. a tributary / none; wiggle; length share; terrains it runs through) and route them after solving with Dijkstra over terrain preference + smooth noise; parents before branches; edge-to-edge must run most of the learned length; 1-hex stray chains ignored - Paths table in the generator file; SolveResult.paths - Terrain line features now need thin (≤1.5) minor (≤10%) terrains and must end in a blob or the edge; if features/edge border don't fit, the solve retries without them and warns instead of failing - Plugin: learning passes the map's path chains; previews draw paths in path-type colours; New map writes generated paths as path chains; Regenerate replaces the generator's path types (Fill leaves paths) - dev/wfc-vault-map.mts: learn + sample from a real vault map (read-only) Trained in Obsidian on the "bay-area" map: River edge→edge, River tributary path→shallows, Road Mountain Ridge→peak. Co-Authored-By: Claude Opus 5.5 (1M context) --- dev/wfc-vault-map.mts | 41 +++++ packages/hex-wfc/src/format.ts | 44 ++++- packages/hex-wfc/src/index.ts | 2 + packages/hex-wfc/src/learn.ts | 26 ++- packages/hex-wfc/src/model.ts | 29 ++- packages/hex-wfc/src/paths.ts | 312 +++++++++++++++++++++++++++++++++ packages/hex-wfc/src/solve.ts | 26 ++- src/hex-map/MapModal.ts | 16 +- src/worldgen/GeneratorTab.ts | 16 +- src/worldgen/generators.ts | 31 +++- src/worldgen/preview.ts | 18 ++ tests/hexWfc.test.ts | 64 +++++++ 12 files changed, 606 insertions(+), 19 deletions(-) create mode 100644 dev/wfc-vault-map.mts create mode 100644 packages/hex-wfc/src/paths.ts diff --git a/dev/wfc-vault-map.mts b/dev/wfc-vault-map.mts new file mode 100644 index 00000000..179ee5d0 --- /dev/null +++ b/dev/wfc-vault-map.mts @@ -0,0 +1,41 @@ +// Learn a generator from a real map in the vault (read-only) and print it plus +// a generated sample. Usage (from WSL, plugin root): +// npx tsx dev/wfc-vault-map.mts [seed] [cols] [rows] +import { readFileSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { learnModel, solve, modelToMarkdown, cellKey } from "../packages/hex-wfc/src"; +const vault = join(process.cwd(), "../../../.."); // plugin lives in /.obsidian/plugins/ +const pluginDir = existsSync("data.json") ? "." : join(vault, ".obsidian/plugins/duckmage-plugin"); +const data = JSON.parse(readFileSync(join(pluginDir, "data.json"), "utf8")); +const name = process.argv[2] ?? "bay-area"; +const map = data.maps.find((m: { name: string }) => m.name === name); +if (!map) throw new Error(`no map ${name}`); +const vaultRoot = join(pluginDir, "../../.."); +const cells = new Map(); +for (let x = map.gridOffset.x; x < map.gridOffset.x + map.gridSize.cols; x++) + for (let y = map.gridOffset.y; y < map.gridOffset.y + map.gridSize.rows; y++) { + const f = join(vaultRoot, data.hexFolder, name, `${x}_${y}.md`); + if (!existsSync(f)) continue; + const m = /^---[\s\S]*?\nterrain:\s*(.*)\n/.exec(readFileSync(f, "utf8")); + const t = m?.[1].trim().replace(/^"|"$/g, ""); + if (t) cells.set(cellKey(x, y), t); + } +const orientation = data.hexOrientation ?? "flat"; +const stagger = map.staggerOffset ?? data.staggerOffset ?? "odd"; +const model = learnModel(cells, { + name, orientation, stagger, + paths: map.pathChains.map((p: { typeName: string; hexes: string[] }) => ({ type: p.typeName, hexes: p.hexes })), + meta: { palette: map.paletteName, "source-map": name }, +}); +console.log(modelToMarkdown(model).split("\n").filter((l) => l.startsWith("|") || l.startsWith("##")).join("\n")); +const seed = Number(process.argv[3] ?? 1), cols = Number(process.argv[4] ?? map.gridSize.cols), rows = Number(process.argv[5] ?? map.gridSize.rows); +const glyphs = new Map(); +const g = (t: string) => { if (!glyphs.has(t)) glyphs.set(t, "abcdefghijklmnop"[glyphs.size]); return glyphs.get(t)!; }; +for (const t of model.terrains) g(t.name); +const r = solve(model, { cols, rows, orientation, stagger, seed }); +if (!r.ok) { console.log(r.message); process.exit(); } +const onPath = new Map(); +for (const p of r.paths) for (const h of p.hexes) onPath.set(h, p.type[0].toUpperCase()); +console.log(`\n${cols}x${rows}`, JSON.stringify(r.stats), r.warnings, [...glyphs].map(([t, c]) => `${c}=${t}`).join(" ")); +console.log("paths:", r.paths.map((p) => `${p.type}:${p.hexes.length} ${p.hexes[0]}→${p.hexes[p.hexes.length - 1]}`).join(", ")); +for (let y = 0; y < rows; y++) { let s = ""; for (let x = 0; x < cols; x++) { const k = cellKey(x, y); s += onPath.get(k) ?? g(r.cells.get(k)!); } console.log(s); } diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index dc182b58..02ce20cb 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -221,6 +221,9 @@ export function modelToMarkdown(model: HexWfcModel): string { " Order doesn't matter, so *A | B* also covers *B | A*.", "- **Features** (optional): lines that are always placed, e.g. a river from a map", " edge to a lake. *From* and *To* are `edge`, `none` or a terrain name.", + "- **Paths** (optional): paths drawn over the terrain (rivers, roads). *From* and", + " *To* are `edge`, `none`, `path` (joins another path of the same type, like a", + " tributary) or a terrain. *Through* is the share of the path on each terrain.", "- **Layout** (optional): where each terrain sat in the example map, in a 3×3", " grid. 1 means as common there as anywhere; 3 means three times as common.", "- Frontmatter settings (optional): `feature-size`, `directional-bias`, `clumping`,", @@ -253,6 +256,21 @@ export function modelToMarkdown(model: HexWfcModel): string { "", ] : []), + ...(model.paths?.length + ? [ + "## Paths", + "", + "| Path | From | To | Count | Turn | Length % | Through |", + "| --- | --- | --- | ---: | ---: | ---: | --- |", + ...model.paths.map( + (p) => + `| ${cell(p.type)} | ${cell(p.from)} | ${cell(p.to)} | ${num(p.count)} | ${num(p.turn)} | ${num(p.length * 100)} | ${cell( + Object.entries(p.through).map(([t, v]) => `${t} ${num(v * 100)}%`).join("; "), + )} |`, + ), + "", + ] + : []), ...(withLayout.length ? [ "## Layout", @@ -298,8 +316,8 @@ export function isModelMarkdown(text: string): boolean { return new RegExp(`^---\\r?\\n(?:.*\\r?\\n)*?${MARKER}\\s*:`).test(text); } -type Section = "terrains" | "adjacency" | "features" | "layout"; -const SECTIONS: readonly Section[] = ["terrains", "adjacency", "features", "layout"]; +type Section = "terrains" | "adjacency" | "features" | "paths" | "layout"; +const SECTIONS: readonly Section[] = ["terrains", "adjacency", "features", "paths", "layout"]; /** * Parse a model file. Throws if the text isn't a hex-wfc file at all; bad @@ -349,6 +367,7 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par let columns = new Map(); const model: HexWfcModel = { name: "", terrains: [], adjacency: [], meta }; const features: NonNullable = []; + const paths: NonNullable = []; const layouts = new Map(); const weightOf = (raw: string | undefined, where: string): number | null => { if (raw === undefined || raw === "") return 1; @@ -425,6 +444,26 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par continue; } features.push({ terrain: cells[0], from: col("from") ?? "none", to: col("to") ?? "none", count }); + } else if (section === "paths") { + const nums = ["count", "turn", "length %"].map((c) => Number(col(c) ?? (c === "count" ? "1" : "0"))); + if (nums.some((n) => !Number.isFinite(n) || n < 0)) { + warnings.push(`${where}: count, turn and length % should be numbers ≥ 0, row skipped`); + continue; + } + const through: Record = {}; + for (const item of (col("through") ?? "").split(";").map((x) => x.trim()).filter(Boolean)) { + const m = /^(.*\S)\s+([\d.]+)%?$/.exec(item); + if (m) through[m[1]] = Math.round(Number(m[2]) * 1000) / 100000; + } + paths.push({ + type: cells[0], + from: col("from") ?? "none", + to: col("to") ?? "none", + count: nums[0], + turn: nums[1], + length: Math.round(nums[2] * 1000) / 100000, + through, + }); } else { const values = LAYOUT_BINS.map((b) => Number(cells[columns.get(b.toLowerCase()) ?? -1])); if (values.every((v) => Number.isFinite(v) && v >= 0)) layouts.set(cells[0], values); @@ -438,6 +477,7 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par else warnings.push(`Layout row "${t}" isn't in the Terrains table, ignored`); } if (features.length) model.features = features; + if (paths.length) model.paths = paths; if (exampleHexes !== undefined) model.exampleHexes = exampleHexes; if (Object.keys(settings).length) model.settings = settings; model.name = name || fallbackName; diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index a1b861e6..b07e3e33 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -24,12 +24,14 @@ export { type GrowthShape, type GeneratorSettings, type LineFeature, + type PathFeature, type Symmetry, type CountRange, } from "./model"; export { learnModel, measurePatches, measureLayout, SHAPE_THRESHOLDS, type LearnOptions, type TerrainAnalysis } from "./learn"; export { solve, findViolation, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; export { countPatches, type GridInfo } from "./post"; +export { learnPaths, routePaths, type PathInput, type PathOutput } from "./paths"; export { modelToMarkdown, parseModelMarkdown, diff --git a/packages/hex-wfc/src/learn.ts b/packages/hex-wfc/src/learn.ts index 703c5143..da75f56f 100644 --- a/packages/hex-wfc/src/learn.ts +++ b/packages/hex-wfc/src/learn.ts @@ -9,12 +9,15 @@ import { type Stagger, } from "./grid"; import type { HexWfcModel, GrowthShape, LineFeature, TerrainEntry } from "./model"; +import { learnPaths, type PathInput } from "./paths"; export interface LearnOptions { name: string; orientation: Orientation; stagger?: Stagger; meta?: Record; + /** Paths drawn over the example (rivers, roads), learned as path features. */ + paths?: PathInput[]; } /** @@ -91,6 +94,10 @@ export function learnModel( meta: { ...(opts.meta ?? {}) }, }; if (analysis.features.length) model.features = analysis.features; + if (opts.paths?.length) { + const paths = learnPaths(opts.paths, map, opts.orientation, stagger); + if (paths.length) model.paths = paths; + } return model; } @@ -114,8 +121,12 @@ export const SHAPE_THRESHOLDS = { /** Mean same-terrain neighbours at or above this → "blob"; below → thin * (shores, rings), left to the neighbour rules. */ blobThickness: 3.5, - /** Line patches at least this many hexes long can become features. */ + /** Line patches at least this many hexes long can become features... */ featureMinHexes: 4, + /** ...if the terrain's lines are this thin (a painted river is ~1 wide)... */ + featureMaxWidth: 1.5, + /** ...and the terrain is a minor one (a share of the map at most this). */ + featureMaxShare: 0.1, }; interface Patch { @@ -194,6 +205,7 @@ function analysePatches( const terrains = new Map(); const lineTerrains = new Set(); + const featureTerrains = new Set(); for (const [t, list] of byTerrain) { let sumS = 0, sumS2 = 0, elongW = 0, thickW = 0, widthW = 0, weighted = 0; const others = new Map(); @@ -232,6 +244,7 @@ function analysePatches( a.turn = Math.round(Math.min(0.5, Math.max(0.05, 1.2 / elong)) * 100) / 100; a.width = Math.round(Math.min(3, Math.max(1, width)) * 10) / 10; lineTerrains.add(t); + if (width <= TH.featureMaxWidth && (countOf.get(t) ?? 0) / total <= TH.featureMaxShare) featureTerrains.add(t); } else if (thick >= TH.blobThickness || elong >= TH.lineElongation) { a.shape = "blob"; } @@ -253,7 +266,7 @@ function analysePatches( // (non-background) terrain. const featureCount = new Map(); for (const p of patches) { - if (!lineTerrains.has(p.terrain) || p.cells.length < TH.featureMinHexes) continue; + if (!featureTerrains.has(p.terrain) || p.cells.length < TH.featureMinHexes) continue; const proj = (c: [number, number]) => { const [px, py] = hexCenter(c[0], c[1], orientation, stagger); return (px - p.centre[0]) * p.axis[0] + (py - p.centre[1]) * p.axis[1]; @@ -271,11 +284,12 @@ function analysePatches( const xy = parseCellKey(k); if (xy && hexDistance(xy, end, orientation, stagger) <= 1) near.set(t, (near.get(t) ?? 0) + 1); } - // Prefer a blob (a lake) over a thin terrain it passes through (its shore). - let best = "none", bestScore = 0; + // A line only ends *in* a blob (a lake, a bay); passing a band of + // another terrain isn't an anchor. + let best = "none", bestN = 0; for (const [t, n] of near) { - const sc = n + (terrains.get(t)?.shape === "blob" ? 100 : 0); - if (sc > bestScore) { bestScore = sc; best = t; } + if (terrains.get(t)?.shape !== "blob") continue; + if (n > bestN) { bestN = n; best = t; } } return best; }; diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index 7441158e..e0f48b3a 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -70,6 +70,26 @@ export interface LineFeature { count: number; } +/** + * A path drawn on top of the terrain (a river or road made with a path tool), + * learned from the example's paths and routed over generated terrain. + * `from`/`to` are "edge", "none", "path" (joins another path of this type, + * like a tributary) or a terrain name. + */ +export interface PathFeature { + type: string; + from: string; + to: string; + /** How many the example had. Scaled with map size when routing. */ + count: number; + /** Share of steps that change direction (0–1). */ + turn: number; + /** Length as a share of the map's larger side. */ + length: number; + /** Share of the path's hexes on each terrain. */ + through: Record; +} + export type Symmetry = "none" | "left-right" | "top-bottom" | "both"; export const SYMMETRIES: readonly Symmetry[] = ["none", "left-right", "top-bottom", "both"]; @@ -116,7 +136,7 @@ export interface GeneratorSettings { mix?: Record; /** Per-terrain min/max number of separate patches. */ counts?: Record; - /** Lay down the model's guaranteed line features (rivers). */ + /** Lay down the model's guaranteed features and paths (rivers). */ features?: boolean; } @@ -151,8 +171,10 @@ export interface HexWfcModel { name: string; terrains: TerrainEntry[]; adjacency: AdjacencyEntry[]; - /** Guaranteed line features (rivers). */ + /** Guaranteed line features painted as terrain (rivers). */ features?: LineFeature[]; + /** Paths drawn over the terrain (rivers, roads), routed after solving. */ + paths?: PathFeature[]; /** Number of painted hexes in the example. Used to scale counts and spacing. */ exampleHexes?: number; /** Free-form string metadata (palette, source map, ...). Preserved by the file format. */ @@ -233,6 +255,9 @@ export function restrictModel(model: HexWfcModel, allowed: Iterable): He ...(model.features ? { features: model.features.filter((f) => keep.has(f.terrain) && ok(f.from) && ok(f.to)) } : {}), + ...(model.paths + ? { paths: model.paths.filter((p) => (p.from === "path" || ok(p.from)) && (p.to === "path" || ok(p.to))) } + : {}), meta: { ...model.meta }, ...(model.settings ? { settings: { ...model.settings } } : {}), }; diff --git a/packages/hex-wfc/src/paths.ts b/packages/hex-wfc/src/paths.ts new file mode 100644 index 00000000..fe61556e --- /dev/null +++ b/packages/hex-wfc/src/paths.ts @@ -0,0 +1,312 @@ +/** + * Path features: lines drawn on top of the terrain (rivers, roads) rather + * than painted as terrain. Learned from an example map's paths and routed + * over a generated map's terrain afterwards, so they never affect the + * terrain rules. + * + * Each learned path type records what its ends connect to ("edge", a terrain + * name, "path" = joins another path of the same type, as a tributary does, + * or "none"), how much it wiggles, how long it runs relative to the map, and + * which terrains it runs through. + */ + +import { hexNeighbors, hexDistance, directionRing, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; +import type { PathFeature } from "./model"; +import type { GridInfo } from "./post"; + +export interface PathInput { + /** Path type name, e.g. "River". */ + type: string; + /** Ordered hex keys "x_y". */ + hexes: string[]; +} + +export interface PathOutput { + type: string; + hexes: string[]; +} + +const MIN_PATH_HEXES = 3; + +/** Remove consecutive duplicates (repeat clicks). */ +function clean(hexes: string[]): string[] { + return hexes.filter((h, i) => i === 0 || h !== hexes[i - 1]); +} + +export function learnPaths( + paths: PathInput[], + cells: Map, + orientation: Orientation, + stagger: Stagger = "odd", +): PathFeature[] { + let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; + for (const k of cells.keys()) { + const xy = parseCellKey(k); + if (!xy) continue; + minX = Math.min(minX, xy[0]); maxX = Math.max(maxX, xy[0]); + minY = Math.min(minY, xy[1]); maxY = Math.max(maxY, xy[1]); + } + const span = Math.max(maxX - minX + 1, maxY - minY + 1, 1); + const onBorder = (xy: [number, number]) => + xy[0] <= minX || xy[0] >= maxX || xy[1] <= minY || xy[1] >= maxY; + const ring = directionRing(orientation); + + const usable = paths.map((p) => ({ type: p.type, hexes: clean(p.hexes) })).filter((p) => p.hexes.length >= MIN_PATH_HEXES); + const groups = new Map; hexes: number }>(); + + for (const [i, p] of usable.entries()) { + const others = new Set(); + for (const [j, q] of usable.entries()) if (j !== i && q.type === p.type) for (const h of q.hexes) others.add(h); + // Terrain the path mostly runs through, to tell a real destination apart. + const tally = new Map(); + for (const h of p.hexes) { + const t = cells.get(h); + if (t) tally.set(t, (tally.get(t) ?? 0) + 1); + } + const main = [...tally].sort((a, b) => b[1] - a[1])[0]?.[0]; + const anchor = (h: string): string => { + const xy = parseCellKey(h); + if (!xy) return "none"; + if (onBorder(xy)) return "edge"; + if (others.has(h)) return "path"; + const t = cells.get(h); + return t && t !== main ? t : "none"; + }; + let from = anchor(p.hexes[0]); + let to = anchor(p.hexes[p.hexes.length - 1]); + if (from === "none" && to === "none") continue; + // Order: a "path" anchor first (branches start from their parent), then + // "edge", then a terrain, then "none". + const rank = (e: string) => (e === "path" ? 0 : e === "edge" ? 1 : e === "none" ? 3 : 2); + if (rank(to) < rank(from) || (rank(to) === rank(from) && to < from)) [from, to] = [to, from]; + + // Wiggle: share of steps that change direction. + let turns = 0, steps = 0, prevDir = -1; + for (let k = 1; k < p.hexes.length; k++) { + const a = parseCellKey(p.hexes[k - 1]), b = parseCellKey(p.hexes[k]); + if (!a || !b) continue; + const ns = hexNeighbors(a[0], a[1], orientation, stagger); + const d = ns.findIndex(([x, y]) => x === b[0] && y === b[1]); + if (d < 0) continue; // not adjacent (a gap in the drawn path) + const dir = ring.indexOf(d); + if (prevDir >= 0) { + steps++; + if (dir !== prevDir) turns++; + } + prevDir = dir; + } + + const key = `${p.type}\u0000${from}\u0000${to}`; + let g = groups.get(key); + if (!g) { + g = { f: { type: p.type, from, to, count: 0, turn: 0, length: 0, through: {} }, turns: [], lengths: [], through: new Map(), hexes: 0 }; + groups.set(key, g); + } + g.f.count++; + g.turns.push(steps ? turns / steps : 0.2); + g.lengths.push(p.hexes.length / span); + for (const [t, n] of tally) g.through.set(t, (g.through.get(t) ?? 0) + n); + g.hexes += p.hexes.length; + } + + const round = (n: number, d = 100) => Math.round(n * d) / d; + return [...groups.values()].map(({ f, turns, lengths, through, hexes }) => ({ + ...f, + turn: round(turns.reduce((a, b) => a + b, 0) / turns.length), + length: round(lengths.reduce((a, b) => a + b, 0) / lengths.length), + through: Object.fromEntries([...through].sort((a, b) => b[1] - a[1]).map(([t, n]) => [t, round(n / hexes)])), + })); +} + +/** + * Route learned paths over a finished map. Each path is a cheapest route + * (Dijkstra) between its anchors, where hexes on terrains the example's path + * ran through are cheap, plus seeded noise for the learned wiggle. + */ +export function routePaths( + features: PathFeature[], + cells: Map, + grid: GridInfo, + rng: () => number, + sizeScale: number, +): { paths: PathOutput[]; warnings: string[] } { + const { cols, rows, ox, oy, orientation, stagger } = grid; + const N = cols * rows; + const keyOf = (c: number) => cellKey(ox + (c % cols), oy + Math.floor(c / cols)); + const idx = (x: number, y: number) => (y - oy) * cols + (x - ox); + const inGrid = (x: number, y: number) => x >= ox && x < ox + cols && y >= oy && y < oy + rows; + const nbr: number[][] = []; + for (let c = 0; c < N; c++) { + const x = ox + (c % cols), y = oy + Math.floor(c / cols); + nbr.push(hexNeighbors(x, y, orientation, stagger).filter(([nx, ny]) => inGrid(nx, ny)).map(([nx, ny]) => idx(nx, ny))); + } + const terrainOf = (c: number) => cells.get(keyOf(c)) ?? ""; + const share = new Map(); + for (const t of cells.values()) share.set(t, (share.get(t) ?? 0) + 1 / N); + const border = (c: number) => { + const i = c % cols, j = Math.floor(c / cols); + return i === 0 || j === 0 || i === cols - 1 || j === rows - 1; + }; + const sideOf = (c: number): number => { + const i = c % cols, j = Math.floor(c / cols); + const d = [j, cols - 1 - i, rows - 1 - j, i]; // N, E, S, W + return d.indexOf(Math.min(...d)); + }; + + const candidates = (anchor: string, taken: Set, avoidSide: number | null): number[] => { + const all: number[] = []; + for (let c = 0; c < N; c++) { + const ok = + anchor === "edge" ? border(c) && (avoidSide === null || sideOf(c) !== avoidSide) + : anchor === "path" ? taken.has(c) + : anchor === "none" ? !border(c) + : terrainOf(c) === anchor; + if (ok) all.push(c); + } + return all; + }; + + /** Cheapest route from `start` to the nearest target, avoiding `taken` (no braids). */ + const dijkstra = (cost: Float64Array, start: number, targets: Set, taken: Set): number[] | null => { + const dist = new Float64Array(N).fill(Infinity); + const prev = new Int32Array(N).fill(-1); + const heap = new MinHeap(); + dist[start] = 0; + heap.push(0, start); + while (heap.size) { + const [d, c] = heap.pop(); + if (d > dist[c]) continue; + if (targets.has(c)) { + const route: number[] = []; + for (let k = c; k >= 0; k = prev[k]) route.push(k); + return route.reverse(); + } + for (const n of nbr[c]) { + if (taken.has(n) && !targets.has(n)) continue; + const nd = d + cost[n]; + if (nd < dist[n]) { + dist[n] = nd; + prev[n] = c; + heap.push(nd, n); + } + } + } + return null; + }; + + const routeOne = (f: PathFeature, cost: Float64Array, taken: Set): number[] | null => { + const starts = candidates(f.from, taken, null).filter((c) => f.from === "path" || !taken.has(c)); + if (!starts.length) return null; + // A few random starts; keep the cheapest. + let start = starts[Math.floor(rng() * starts.length)]; + for (let t = 0; t < 6; t++) { + const c = starts[Math.floor(rng() * starts.length)]; + if (cost[c] < cost[start]) start = c; + } + const startSide = border(start) ? sideOf(start) : null; + let targets: Set; + if (f.to === "none") { + const want = Math.max(3, Math.round(f.length * Math.max(cols, rows))); + const sx = ox + (start % cols), sy = oy + Math.floor(start / cols); + const atLength: number[] = []; + for (let c = 0; c < N; c++) { + const d = hexDistance([sx, sy], [ox + (c % cols), oy + Math.floor(c / cols)], orientation, stagger); + if (Math.abs(d - want) <= 1) atLength.push(c); + } + targets = new Set(atLength.length ? [atLength[Math.floor(rng() * atLength.length)]] : []); + } else { + targets = new Set(candidates(f.to, taken, f.to === "edge" ? startSide : null)); + // Edge-to-edge: don't let it cut a corner; it should run at least most + // of the learned length. + if (f.to === "edge") { + const minLen = Math.round(0.6 * f.length * Math.max(cols, rows)); + const sx = ox + (start % cols), sy = oy + Math.floor(start / cols); + const far = [...targets].filter( + (c) => hexDistance([sx, sy], [ox + (c % cols), oy + Math.floor(c / cols)], orientation, stagger) >= minLen, + ); + if (far.length) targets = new Set(far); + } + } + if (f.to !== "path") for (const c of taken) targets.delete(c); + targets.delete(start); + if (!targets.size) return null; + const route = dijkstra(cost, start, targets, taken); + return route && route.length >= MIN_PATH_HEXES ? route : null; + }; + + const out: PathOutput[] = []; + const warnings: string[] = []; + const takenByType = new Map>(); + // Parents before branches. + const order = [...features].sort((a, b) => Number(a.from === "path") - Number(b.from === "path")); + + for (const f of order) { + // Cheap on terrains the example's path ran through (relative to how + // common they are), plus smooth noise so routes wiggle like the example. + const pref = (t: string) => Math.log(((f.through[t] ?? 0) + 0.01) / ((share.get(t) ?? 0) + 0.01)); + const noiseAmp = 0.5 + 3 * f.turn; + const phase = [rng(), rng(), rng()].map((v) => v * Math.PI * 2); + const freq = 0.6 + rng() * 0.6; + const cost = new Float64Array(N); + for (let c = 0; c < N; c++) { + const i = c % cols, j = Math.floor(c / cols); + const noise = (Math.sin(i * freq + phase[0]) * Math.cos(j * freq * 0.8 + phase[1]) + Math.sin((i + j) * freq * 0.7 + phase[2])) / 2; + cost[c] = Math.max(0.05, 1.5 - pref(terrainOf(c)) + noiseAmp * (0.5 + 0.5 * noise)); + } + + const count = Math.max(1, Math.round(f.count * sizeScale)); + const taken = takenByType.get(f.type) ?? new Set(); + takenByType.set(f.type, taken); + let made = 0; + for (let k = 0; k < count; k++) { + const route = routeOne(f, cost, taken); + if (!route) continue; + out.push({ type: f.type, hexes: route.map(keyOf) }); + for (const c of route) taken.add(c); + made++; + } + if (made < count) { + const end = (e: string) => (e === "edge" ? "a map edge" : e === "path" ? `another ${f.type}` : e); + warnings.push(`Placed ${made} of ${count} ${f.type} paths (${end(f.from)} to ${end(f.to)})`); + } + } + return { paths: out, warnings }; +} + +/** Minimal binary min-heap of [priority, value]. */ +class MinHeap { + private items: [number, number][] = []; + get size(): number { + return this.items.length; + } + push(priority: number, value: number): void { + const a = this.items; + a.push([priority, value]); + let i = a.length - 1; + while (i > 0) { + const p = (i - 1) >> 1; + if (a[p][0] <= a[i][0]) break; + [a[p], a[i]] = [a[i], a[p]]; + i = p; + } + } + pop(): [number, number] { + const a = this.items; + const top = a[0]; + const last = a.pop()!; + if (a.length) { + a[0] = last; + let i = 0; + for (;;) { + const l = 2 * i + 1, r = l + 1; + let m = i; + if (l < a.length && a[l][0] < a[m][0]) m = l; + if (r < a.length && a[r][0] < a[m][0]) m = r; + if (m === i) break; + [a[m], a[i]] = [a[i], a[m]]; + i = m; + } + } + return top; + } +} diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 1bd78785..0aaa56a0 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -30,6 +30,7 @@ import { } from "./model"; import { mulberry32 } from "./rng"; import { placeFeatures, placeEdgeBorder } from "./features"; +import { routePaths, type PathOutput } from "./paths"; import { smooth, connectLand, countPatches, countsPenalty, topUpCounts, type GridInfo } from "./post"; export interface SolveOptions extends GeneratorSettings { @@ -72,6 +73,8 @@ export type SolveResult = cells: Map; /** Hexes laid down as guaranteed features (rivers), keyed "x_y". */ featureCells: Set; + /** Paths routed over the terrain (rivers, roads drawn as paths). */ + paths: PathOutput[]; /** Soft goals that weren't fully met (counts, connected land, features). */ warnings: string[]; stats: SolveStats; @@ -167,7 +170,18 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { } } - const core = solveOnce(working, { ...opts, fixed, seed }, s); + let core = solveOnce(working, { ...opts, fixed, seed }, s); + if (!core.ok && featureCells.size) { + // The guaranteed features (or edge border) couldn't be fitted; try the + // map without them rather than failing outright. + const plain = new Map(toCellMap(opts.fixed ?? {})); + const retry = solveOnce(model, { ...opts, fixed: plain, seed }, s); + if (retry.ok) { + warnings.push("Guaranteed features or the edge border didn't fit this map, so they were left out"); + featureCells.clear(); + core = retry; + } + } for (const key of ["attempts", "backtracks", "decisions", "grown"] as const) total[key] += core.stats[key]; if (!core.ok) { lastFail = core; @@ -206,8 +220,16 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { if (range.max !== undefined && n > range.max) best.warnings.push(`${n} ${t} (wanted at most ${range.max})`); } } + let paths: PathOutput[] = []; + if (s.features && model.paths?.length) { + const N = grid.cols * grid.rows; + const scale = model.exampleHexes ? Math.sqrt(N / model.exampleHexes) : 1; + const routed = routePaths(model.paths, best.cells, grid, mulberry32(opts.seed ^ 0x7f4a7c15), scale); + paths = routed.paths; + best.warnings.push(...routed.warnings); + } total.ms = Date.now() - t0; - return { ok: true, cells: best.cells, featureCells: best.featureCells, warnings: best.warnings, stats: total }; + return { ok: true, cells: best.cells, featureCells: best.featureCells, paths, warnings: best.warnings, stats: total }; } /** Feedback never boosts or damps a terrain by more than this factor per choice. */ diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 156f3a76..02df59a1 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -12,6 +12,8 @@ import { generatorFitsPalette, generateTerrain, paletteColors, + pathColors, + toPathChains, type GeneratorFile, } from "../worldgen/generators"; import { GeneratorTab } from "../worldgen/GeneratorTab"; @@ -692,7 +694,7 @@ export class MapModal extends HexmakerModal { previewStatus.setText(`This generator couldn't fill the map: ${r.message}`); return; } - drawPreview(previewCanvas, r.cells, grid, this.plugin.settings.hexOrientation, paletteColors(this.plugin, paletteSelect.value), r.featureCells); + drawPreview(previewCanvas, r.cells, grid, this.plugin.settings.hexOrientation, paletteColors(this.plugin, paletteSelect.value), r.featureCells, r.paths, pathColors(this.plugin)); previewStatus.setText(r.warnings.length ? r.warnings.join("; ") : ""); }; let previewTimer: number | null = null; @@ -861,6 +863,7 @@ export class MapModal extends HexmakerModal { // Solve before creating anything, so a generator that can't fill the // map leaves no half-made map behind. let terrainAt: Map | undefined; + let generatedPaths: { type: string; hexes: string[] }[] = []; if (generator) { const palette = this.plugin.getPaletteByName(paletteName)?.terrains.map((t) => t.name) ?? []; const solved = generateTerrain( @@ -873,6 +876,7 @@ export class MapModal extends HexmakerModal { return; } terrainAt = solved.cells; + generatedPaths = solved.paths; } const result = await this.plugin.createNewMap( @@ -904,6 +908,16 @@ export class MapModal extends HexmakerModal { } } + if (generatedPaths.length) { + const newMap = this.plugin.getMap(result.name); + const { chains, missing } = toPathChains(this.plugin, generatedPaths); + if (newMap && chains.length) { + newMap.pathChains = [...newMap.pathChains, ...chains]; + await this.plugin.saveSettings(); + } + if (missing.length) new Notice(`No path type named ${missing.join(", ")}, so those paths were skipped.`); + } + if (resolvedBgPath) { const newMap = this.plugin.getMap(result.name); if (newMap) { diff --git a/src/worldgen/GeneratorTab.ts b/src/worldgen/GeneratorTab.ts index 1ca64bd9..a9eb10c4 100644 --- a/src/worldgen/GeneratorTab.ts +++ b/src/worldgen/GeneratorTab.ts @@ -14,6 +14,7 @@ import { generateTerrain, generatorFitsPalette, paletteColors, + pathColors, fillMap, LOCK_KEY, type GeneratorFile, @@ -153,6 +154,7 @@ export class GeneratorTab { const parts = [`${model.terrains.length} terrains`]; for (const [shape, label] of [["blob", "blobs"], ["line", "lines"], ["scatter", "scattered"]] as const) if (byShape(shape).length) parts.push(`${label}: ${byShape(shape).join(", ")}`); + if (model.paths?.length) parts.push(`paths: ${[...new Set(model.paths.map((p) => p.type))].join(", ")}`); if (model.meta["source-map"]) parts.push(`learned from ${model.meta["source-map"]}`); el.createEl("p", { text: parts.join(" · "), cls: "duckmage-map-origin-desc" }); for (const w of g.warnings) el.createEl("p", { text: `⚠ ${w}`, cls: "duckmage-map-origin-desc" }); @@ -203,7 +205,7 @@ export class GeneratorTab { status.setText(`Couldn't generate: ${r.message}`); return; } - drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells); + drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, r.paths, pathColors(this.plugin)); const notes = r.warnings.length ? ` · ${r.warnings.join("; ")}` : ""; status.setText(`${grid.cols}×${grid.rows} in ${r.stats.ms} ms${notes}`); }; @@ -245,12 +247,16 @@ export class GeneratorTab { // Guarantees this.heading(el, "Guarantees"); - if (model.features?.length) { - const list = model.features.map((f) => `${f.terrain}: ${f.from === "edge" ? "map edge" : f.from} → ${f.to === "edge" ? "map edge" : f.to}`).join(", "); + if (model.features?.length || model.paths?.length) { + const end = (e: string) => (e === "edge" ? "map edge" : e === "path" ? "joins another" : e); + const list = [ + ...(model.features ?? []).map((f) => `${f.terrain}: ${end(f.from)} → ${end(f.to)}`), + ...(model.paths ?? []).map((p) => `${p.type} path: ${end(p.from)} → ${end(p.to)}`), + ].join(", "); this.toggle(el, "Guaranteed features", `Always lay these down first: ${list}.`, s().features, (v) => save({ features: v })); } else { el.createEl("p", { - text: "No guaranteed features. Paint a river running from a map edge into a lake (or from edge to edge) in the example map to get one.", + text: "No guaranteed features. Draw a river (path or painted terrain) from a map edge into a lake, or from edge to edge, in the example map to get one.", cls: "duckmage-map-origin-desc", }); } @@ -344,7 +350,7 @@ export class GeneratorTab { const mapName = this.view.activeMapName; const palette = this.plugin.getMapPalette(mapName).map((t) => t.name); el.createEl("p", { - text: `Uses the preview's seed. "Fill unpainted hexes" keeps everything you've painted. "Regenerate" repaints the whole map except hexes whose note has "${LOCK_KEY}: true" in its properties.`, + text: `Uses the preview's seed. "Fill unpainted hexes" keeps everything you've painted and your paths. "Regenerate" repaints the whole map except hexes whose note has "${LOCK_KEY}: true" in its properties, and redraws the generator's path types (e.g. rivers).`, cls: "duckmage-map-origin-desc", }); if (!generatorFitsPalette(g.model, palette)) diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index cc2bfb5d..0834e85a 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -106,6 +106,24 @@ export function readLockedHexes(plugin: HexmakerPlugin, mapName: string): Set { + return new Map((plugin.settings.pathTypes ?? []).map((t) => [t.name, t.color])); +} + +/** + * Generated paths as map path chains. Path types the vault doesn't have are + * dropped (and named in the returned warning list). + */ +export function toPathChains( + plugin: HexmakerPlugin, + paths: { type: string; hexes: string[] }[], +): { chains: { typeName: string; hexes: string[] }[]; missing: string[] } { + const known = new Set((plugin.settings.pathTypes ?? []).map((t) => t.name)); + const missing = [...new Set(paths.map((p) => p.type).filter((t) => !known.has(t)))]; + return { chains: paths.filter((p) => known.has(p.type)).map((p) => ({ typeName: p.type, hexes: [...p.hexes] })), missing }; +} + /** Palette colour per terrain name, for previews. */ export function paletteColors(plugin: HexmakerPlugin, paletteName: string | undefined): Map { const terrains = plugin.getPaletteByName(paletteName ?? "")?.terrains ?? plugin.settings.terrainPalettes[0]?.terrains ?? []; @@ -134,6 +152,7 @@ export async function saveGeneratorFromMap( name, orientation: plugin.settings.hexOrientation, stagger: mapStagger(plugin, mapName), + paths: (map.pathChains ?? []).map((p) => ({ type: p.typeName, hexes: p.hexes })), meta: { palette: map.paletteName, "source-map": mapName, @@ -257,7 +276,17 @@ export async function fillMap( if (!result.ok) return { error: result.message }; const changes = [...result.cells].filter(([k, t]) => painted.get(k) !== t); await writeTerrain(plugin, mapName, changes, onProgress); - return { changed: changes.length, warnings: result.warnings }; + const warnings = [...result.warnings]; + // Regenerating also redraws the generator's path types (rivers, roads); + // other path types, and every path when only filling, are left alone. + if (mode === "regenerate" && model.paths?.length) { + const learned = new Set(model.paths.map((p) => p.type)); + const { chains, missing } = toPathChains(plugin, result.paths); + map.pathChains = [...(map.pathChains ?? []).filter((c) => !learned.has(c.typeName)), ...chains]; + if (missing.length) warnings.push(`No path type named ${missing.join(", ")}, so those paths were skipped`); + await plugin.saveSettings(); + } + return { changed: changes.length, warnings }; } /** Write terrain to hex notes (creating missing ones) and keep encounter links in sync. */ diff --git a/src/worldgen/preview.ts b/src/worldgen/preview.ts index 9a8dfc1e..f74979ba 100644 --- a/src/worldgen/preview.ts +++ b/src/worldgen/preview.ts @@ -22,6 +22,8 @@ export function drawPreview( orientation: "flat" | "pointy", colors: Map, featureCells?: Set, + paths: { type: string; hexes: string[] }[] = [], + pathColors: Map = new Map(), maxWidth = 420, ): void { const { cols, rows, offset, stagger } = grid; @@ -66,4 +68,20 @@ export function drawPreview( ctx.stroke(); } } + // Paths through hex centres. + const centre = new Map(pts.map(([key, px, py]) => [key, [(px - minX + 1) * scale, (py - minY + 1) * scale]])); + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + for (const p of paths) { + ctx.beginPath(); + p.hexes.forEach((h, i) => { + const c = centre.get(h); + if (!c) return; + if (i === 0) ctx.moveTo(c[0], c[1]); + else ctx.lineTo(c[0], c[1]); + }); + ctx.strokeStyle = pathColors.get(p.type) ?? "#2b6cb0"; + ctx.lineWidth = Math.max(1.5, scale * 0.35); + ctx.stroke(); + } } diff --git a/tests/hexWfc.test.ts b/tests/hexWfc.test.ts index 648fe2c0..a8ab2ced 100644 --- a/tests/hexWfc.test.ts +++ b/tests/hexWfc.test.ts @@ -759,3 +759,67 @@ describe("setting codec", () => { expect(back.model).toEqual(m); }); }); + +describe("paths drawn over the terrain", () => { + /** 30×20 grass map with a bay of water on the left, a river path edge-to-edge and a tributary into the bay. */ + function pathExample() { + const cells = new Map(); + for (let x = 0; x < 30; x++) for (let y = 0; y < 20; y++) cells.set(cellKey(x, y), x < 8 && y > 4 && y < 15 ? "Water" : "Grass"); + // Main river: straight down column 20, top edge to bottom edge. + const main = Array.from({ length: 20 }, (_, y) => cellKey(20, y)); + // Tributary: from the main river at (20,10) west to the bay (row 10). + const trib = Array.from({ length: 14 }, (_, i) => cellKey(20 - i, 10)); // ends at 7_10, in the bay + return { cells, paths: [{ type: "River", hexes: main }, { type: "River", hexes: trib }, { type: "River", hexes: ["3_3"] }] }; + } + + it("learns what each path's ends connect to, ignoring 1-hex stray paths", () => { + const { cells, paths } = pathExample(); + const m = learnModel(cells, { name: "p", orientation: "flat", paths }); + const sorted = (m.paths ?? []).map((p) => `${p.type}:${p.from}->${p.to}`).sort(); + expect(sorted).toEqual(["River:edge->edge", "River:path->Water"]); + const main = m.paths!.find((p) => p.from === "edge")!; + expect(main.through.Grass).toBe(1); + expect(main.length).toBeCloseTo(20 / 30, 2); + }); + + it("round-trips the Paths table", () => { + const { cells, paths } = pathExample(); + const m = learnModel(cells, { name: "p", orientation: "flat", paths }); + const back = parseModelMarkdown(modelToMarkdown(m)); + expect(back.warnings).toEqual([]); + expect(back.model.paths).toEqual(m.paths); + }); + + it("routes a main river edge to edge and a tributary from it into the water", () => { + const { cells, paths } = pathExample(); + const m = learnModel(cells, { name: "p", orientation: "flat", paths }); + for (const seed of [1, 2, 3]) { + const r = solve(m, { cols: 30, rows: 20, orientation: "flat", seed, directionalBias: 1 }); + expect(r.ok).toBe(true); + if (!r.ok) continue; + const adjacent = (a: string, b: string) => { + const [x, y] = a.split("_").map(Number); + return hexNeighbors(x, y, "flat").some(([nx, ny]) => cellKey(nx, ny) === b); + }; + for (const p of r.paths) for (let i = 1; i < p.hexes.length; i++) expect(adjacent(p.hexes[i - 1], p.hexes[i])).toBe(true); + const onEdge = (k: string) => { + const [x, y] = k.split("_").map(Number); + return x === 0 || y === 0 || x === 29 || y === 19; + }; + const main = r.paths.find((p) => onEdge(p.hexes[0]) && onEdge(p.hexes[p.hexes.length - 1])); + expect(main).toBeDefined(); + const trib = r.paths.find((p) => p !== main); + if (trib) { + expect(main!.hexes).toContain(trib.hexes[0]); + expect(r.cells.get(trib.hexes[trib.hexes.length - 1])).toBe("Water"); + } + } + }); + + it("features: false leaves paths out", () => { + const { cells, paths } = pathExample(); + const m = learnModel(cells, { name: "p", orientation: "flat", paths }); + const r = solve(m, { cols: 30, rows: 20, orientation: "flat", seed: 1, features: false }); + expect(r.ok && r.paths.length).toBe(0); + }); +}); From fc08c643619a43a8c41db083ad6feb9add2e4254 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 17:31:58 -0400 Subject: [PATCH 008/558] feat(worldgen): generator as its own page (region search, palette picker); simpler, terrain-neutral UI - Terrain generator is a full ItemView ('Open terrain generator' command) instead of a Maps-modal tab; region (map) search picks what to learn from and fill; palette selector filters generators and drives preview colours / generation - Fill section directly under the preview - Line width slider 1-3 (shown only when a terrain is line-shaped); spacing only when a terrain is scattered - Hints no longer assume terrain names (lakes, ranges, towns...); same for the help text written into generator files - Impassable terrain: searchable filter that adds removable chips - Guarantees/connected land: one short sentence each - Per-terrain table moved into the Advanced section - Preview warnings collapsed to a one-line count with details on hover Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/hex-wfc/src/format.ts | 24 +- src/HexmakerPlugin.ts | 8 + src/constants.ts | 1 + src/hex-map/MapModal.ts | 17 +- .../{GeneratorTab.ts => GeneratorPanel.ts} | 282 ++++++++++++------ src/worldgen/GeneratorView.ts | 39 +++ styles.css | 43 +++ 7 files changed, 300 insertions(+), 114 deletions(-) rename src/worldgen/{GeneratorTab.ts => GeneratorPanel.ts} (61%) create mode 100644 src/worldgen/GeneratorView.ts diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index 02ce20cb..3744aa37 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -209,21 +209,21 @@ export function modelToMarkdown(model: HexWfcModel): string { "", "A wave function collapse generator. You can edit the tables and settings by hand.", "", - "- **Terrains**: *Weight* is how common the terrain is. 0 means the solver never places it.", - " *Patch %* is the size of a typical patch as a share of the map, so features", - " scale with the map. *Shape* is how it spreads: `blob` (lakes, forests),", - " `line` (ranges, ridges), `scatter` (single hexes such as towns) or `none`", - " (backgrounds, shores). *Turn* is how often a `line` changes direction (0 to 1)", - " and *Width* its thickness (1 to 3). *Spacing* is the closest two `scatter` hexes", - " may be. *Edge* is how common the terrain is along the map border (1 = as anywhere).", + "- **Terrains**: *Weight* is how common the terrain is; 0 means the solver never places it.", + " *Patch %* is the size of a typical patch as a share of the map, so patches scale", + " with the map. *Shape* is how it spreads: `blob` (compact patches), `line` (long", + " thin runs), `scatter` (single hexes) or `none` (left to the neighbour rules).", + " *Turn* is how often a `line` changes direction (0 to 1) and *Width* its", + " thickness (1 to 3). *Spacing* is the closest two `scatter` hexes may be.", + " *Edge* is how common the terrain is along the map border (1 = as anywhere).", "- **Adjacency**: pairs that may touch, and how often (higher is more likely).", " A pair that isn't listed can never touch, including a terrain next to itself.", " Order doesn't matter, so *A | B* also covers *B | A*.", - "- **Features** (optional): lines that are always placed, e.g. a river from a map", - " edge to a lake. *From* and *To* are `edge`, `none` or a terrain name.", - "- **Paths** (optional): paths drawn over the terrain (rivers, roads). *From* and", - " *To* are `edge`, `none`, `path` (joins another path of the same type, like a", - " tributary) or a terrain. *Through* is the share of the path on each terrain.", + "- **Features** (optional): lines of terrain that are always placed. *From* and *To*", + " are `edge`, `none` or a terrain name.", + "- **Paths** (optional): paths drawn over the terrain. *From* and *To* are `edge`,", + " `none`, `path` (joins another path of the same type) or a terrain. *Through*", + " is the share of the path on each terrain.", "- **Layout** (optional): where each terrain sat in the example map, in a 3×3", " grid. 1 means as common there as anywhere; 3 means three times as common.", "- Frontmatter settings (optional): `feature-size`, `directional-bias`, `clumping`,", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 749e94f1..7b80967d 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -19,6 +19,7 @@ import { VIEW_TYPE_HEX_TABLE, VIEW_TYPE_RANDOM_TABLES, VIEW_TYPE_SETUP_WIZARD, + VIEW_TYPE_GENERATOR, } from "./constants"; import { SetupWizardView } from "./SetupWizardView"; import { normalizeFolder, makeTableTemplate, slugify } from "./utils"; @@ -37,6 +38,7 @@ import { getLinksInSection, removeLinkFromSection, } from "./sections"; +import { GeneratorView } from "./worldgen/GeneratorView"; export default class HexmakerPlugin extends Plugin { settings: HexmakerPluginSettings; availableIcons: string[] = []; @@ -85,6 +87,7 @@ export default class HexmakerPlugin extends Plugin { this.registerView(VIEW_TYPE_SETUP_WIZARD, (leaf) => new SetupWizardView(leaf, this)); this.registerView(VIEW_TYPE_HEX_MAP, (leaf) => new HexMapView(leaf, this)); + this.registerView(VIEW_TYPE_GENERATOR, (leaf) => new GeneratorView(leaf, this)); this.registerView( VIEW_TYPE_HEX_TABLE, (leaf) => new HexTableView(leaf, this), @@ -109,6 +112,11 @@ export default class HexmakerPlugin extends Plugin { .getLeaf() .setViewState({ type: VIEW_TYPE_HEX_TABLE }), }); + this.addCommand({ + id: "open-terrain-generator", + name: "Open terrain generator", + callback: () => void this.app.workspace.getLeaf("tab").setViewState({ type: VIEW_TYPE_GENERATOR, active: true }), + }); this.addCommand({ id: "open-random-tables", name: "Open random tables", diff --git a/src/constants.ts b/src/constants.ts index 7a0ae96e..9dd56bbe 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -8,6 +8,7 @@ export const VIEW_TYPE_HEX_MAP = "duckmage-hex-map"; export const VIEW_TYPE_HEX_TABLE = "duckmage-hex-table"; export const VIEW_TYPE_RANDOM_TABLES = "duckmage-random-tables"; export const VIEW_TYPE_SETUP_WIZARD = "duckmage-setup-wizard"; +export const VIEW_TYPE_GENERATOR = "duckmage-terrain-generator"; export const DEFAULT_TERRAIN_PALETTE: TerrainColor[] = [ // Sea diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 02df59a1..c1da9622 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -16,13 +16,12 @@ import { toPathChains, type GeneratorFile, } from "../worldgen/generators"; -import { GeneratorTab } from "../worldgen/GeneratorTab"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "../worldgen/preview"; import { randomSeed } from "../../packages/hex-wfc/src"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; -type ModalTab = "Maps" | "Properties" | "New map" | "Generator" | "Export"; +type ModalTab = "Maps" | "Properties" | "New map" | "Export"; function makeCheckbox( parent: HTMLElement, @@ -75,7 +74,7 @@ export class MapModal extends HexmakerModal { // Tab bar const tabBar = contentEl.createDiv({ cls: "duckmage-rt-mode-tabs duckmage-map-modal-tabs" }); - const tabNames: ModalTab[] = ["Maps", "Properties", "New map", "Generator", "Export"]; + const tabNames: ModalTab[] = ["Maps", "Properties", "New map", "Export"]; const contentDivs = new Map(); for (const tab of tabNames) { @@ -105,13 +104,6 @@ export class MapModal extends HexmakerModal { this.renderMapsTab(contentDivs.get("Maps")!); this.renderPropertiesTab(contentDivs.get("Properties")!); this.renderNewMapTab(contentDivs.get("New map")!); - new GeneratorTab(this.app, this.plugin, this.view, { - close: () => this.close(), - rerender: () => { - this.activeTab = "Generator"; - this.render(); - }, - }).render(contentDivs.get("Generator")!); this.renderExportTab(contentDivs.get("Export")!); } @@ -575,7 +567,7 @@ export class MapModal extends HexmakerModal { // chosen palette are offered. el.createEl("label", { text: "Generator", cls: "duckmage-map-field-label" }); el.createEl("p", { - text: "Fill the new map with generated terrain, or leave it blank. Make generators and change their settings on the generator tab.", + text: "Fill the new map with generated terrain, or leave it blank. Make generators and change their settings in the terrain generator.", cls: "duckmage-map-origin-desc", }); const generatorRow = el.createDiv({ cls: "duckmage-region-row" }); @@ -695,7 +687,8 @@ export class MapModal extends HexmakerModal { return; } drawPreview(previewCanvas, r.cells, grid, this.plugin.settings.hexOrientation, paletteColors(this.plugin, paletteSelect.value), r.featureCells, r.paths, pathColors(this.plugin)); - previewStatus.setText(r.warnings.length ? r.warnings.join("; ") : ""); + previewStatus.setText(r.warnings.length ? `${r.warnings.length} didn't fit (hover for details)` : ""); + previewStatus.setAttr("title", r.warnings.join("\n")); }; let previewTimer: number | null = null; const schedulePreview = () => { diff --git a/src/worldgen/GeneratorTab.ts b/src/worldgen/GeneratorPanel.ts similarity index 61% rename from src/worldgen/GeneratorTab.ts rename to src/worldgen/GeneratorPanel.ts index a9eb10c4..e167235c 100644 --- a/src/worldgen/GeneratorTab.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -1,11 +1,12 @@ /** - * The "Generator" tab of the Maps modal: learn a generator from the active - * map, adjust a generator's settings (saved to its file's frontmatter) with a - * live preview, and fill or regenerate the active map with it. + * The terrain generator page: pick a region (map) and palette, learn a + * generator from the region, adjust a generator's settings (saved to its + * file's frontmatter) with a live preview, and fill or regenerate the region. */ import { App, Notice } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; +import { VIEW_TYPE_HEX_MAP } from "../constants"; import type { HexMapView } from "../hex-map/HexMapView"; import { listGenerators, @@ -29,9 +30,8 @@ import { type CountRange, } from "../../packages/hex-wfc/src"; -export interface GeneratorTabHost { - close(): void; - /** Re-render the whole modal (e.g. after learning a new generator). */ +export interface GeneratorPanelHost { + /** Re-render the whole page (e.g. after learning a new generator). */ rerender(): void; } @@ -42,9 +42,11 @@ const SYMMETRY_LABELS: Record = { both: "Both", }; -export class GeneratorTab { - /** Survives re-renders of the modal. */ +export class GeneratorPanel { + /** Selections survive re-renders. */ static selectedPath = ""; + static mapName = ""; + static paletteName = ""; private seed = randomSeed(); private previewCols = 30; private previewRows = 20; @@ -53,93 +55,151 @@ export class GeneratorTab { constructor( private app: App, private plugin: HexmakerPlugin, - private view: HexMapView, - private host: GeneratorTabHost, + private host: GeneratorPanelHost, ) { - const map = plugin.getMap(view.activeMapName); + const maps = plugin.settings.maps; + if (!maps.some((m) => m.name === GeneratorPanel.mapName)) { + const active = (app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP)[0]?.view as HexMapView | undefined)?.activeMapName; + GeneratorPanel.mapName = active ?? plugin.settings.defaultMap ?? maps[0]?.name ?? ""; + } + if (!plugin.settings.terrainPalettes.some((p) => p.name === GeneratorPanel.paletteName)) + GeneratorPanel.paletteName = plugin.getMap(GeneratorPanel.mapName)?.paletteName ?? plugin.settings.terrainPalettes[0]?.name ?? ""; + const map = plugin.getMap(GeneratorPanel.mapName); if (map && map.gridSize.cols * map.gridSize.rows <= PREVIEW_AUTO_LIMIT) { this.previewCols = map.gridSize.cols; this.previewRows = map.gridSize.rows; } } + private get mapName(): string { + return GeneratorPanel.mapName; + } + + private paletteTerrains(): string[] { + return this.plugin.getPaletteByName(GeneratorPanel.paletteName)?.terrains.map((t) => t.name) ?? []; + } + render(el: HTMLElement): void { el.empty(); el.addClass("duckmage-wfc-tab"); + el.createEl("h3", { text: "Terrain generator" }); + this.renderRegion(el); this.renderLearn(el); - el.createEl("h4", { text: "Generator settings" }); - el.createEl("p", { - text: "Each generator keeps its settings in its own file. New maps made with it use them.", - cls: "duckmage-map-origin-desc", - }); + el.createEl("h4", { text: "Generator" }); const pickRow = el.createDiv({ cls: "duckmage-region-row" }); + pickRow.createSpan({ text: "Palette", cls: "duckmage-map-origin-label" }); + const paletteSelect = pickRow.createEl("select"); + for (const p of this.plugin.settings.terrainPalettes) paletteSelect.createEl("option", { value: p.name, text: p.name }); + paletteSelect.value = GeneratorPanel.paletteName; const select = pickRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); const openBtn = pickRow.createEl("button", { text: "Open file" }); openBtn.disabled = true; + el.createEl("p", { + text: "Generators whose terrains are all in this palette. Each keeps its settings in its own file.", + cls: "duckmage-map-origin-desc", + }); const body = el.createDiv(); let generators: GeneratorFile[] = []; const current = () => generators.find((g) => g.file.path === select.value); const show = () => { - GeneratorTab.selectedPath = select.value; + GeneratorPanel.selectedPath = select.value; body.empty(); const g = current(); openBtn.disabled = !g; if (g) this.renderGenerator(body, g); else body.createEl("p", { - text: generators.length ? "Pick a generator." : "No generators yet. Paint a map, then use the button above.", + text: generators.length ? "No generators for this palette yet." : "No generators yet. Pick a region above and learn from it.", cls: "duckmage-map-origin-desc", }); }; + const fill = () => { + const names = this.paletteTerrains(); + const fitting = generators.filter((g) => g.model.meta.palette === GeneratorPanel.paletteName || generatorFitsPalette(g.model, names)); + select.empty(); + if (!fitting.length) select.createEl("option", { value: "", text: "None" }); + for (const g of fitting) select.createEl("option", { value: g.file.path, text: g.model.name }); + select.value = fitting.some((g) => g.file.path === GeneratorPanel.selectedPath) + ? GeneratorPanel.selectedPath + : (fitting[0]?.file.path ?? ""); + show(); + }; select.addEventListener("change", show); + paletteSelect.addEventListener("change", () => { + GeneratorPanel.paletteName = paletteSelect.value; + fill(); + }); openBtn.addEventListener("click", () => { const g = current(); - if (!g) return; - this.host.close(); - void this.app.workspace.getLeaf("tab").openFile(g.file); + if (g) void this.app.workspace.getLeaf("tab").openFile(g.file); }); select.createEl("option", { value: "", text: "Loading…" }); void listGenerators(this.plugin).then((list) => { generators = list; - select.empty(); - if (!list.length) select.createEl("option", { value: "", text: "No generators" }); - for (const g of list) { - const palette = g.model.meta.palette; - select.createEl("option", { value: g.file.path, text: palette ? `${g.model.name} (${palette})` : g.model.name }); - } - select.value = list.some((g) => g.file.path === GeneratorTab.selectedPath) - ? GeneratorTab.selectedPath - : (list[0]?.file.path ?? ""); - show(); + fill(); + }); + } + + // ── Region ─────────────────────────────────────────────────────────────── + + /** Searchable list of maps; the chosen one is learned from and filled. */ + private renderRegion(el: HTMLElement): void { + el.createEl("h4", { text: "Region" }); + const search = el.createEl("input", { + type: "search", + cls: "duckmage-wfc-filter", + attr: { placeholder: "Search regions…" }, }); + const list = el.createDiv({ cls: "duckmage-wfc-chips duckmage-wfc-regions" }); + const render = () => { + list.empty(); + const q = search.value.trim().toLowerCase(); + const maps = this.plugin.settings.maps.filter((m) => !q || m.name.toLowerCase().includes(q)); + if (!maps.length) list.createSpan({ text: "No matching region", cls: "duckmage-map-origin-desc" }); + for (const m of maps.slice(0, 40)) { + const btn = list.createEl("button", { + cls: "duckmage-wfc-chip" + (m.name === this.mapName ? " is-selected" : ""), + attr: { title: `${m.gridSize.cols}×${m.gridSize.rows}, palette ${m.paletteName}` }, + }); + btn.createSpan({ text: m.name }); + btn.addEventListener("click", () => { + GeneratorPanel.mapName = m.name; + GeneratorPanel.paletteName = m.paletteName; + this.host.rerender(); + }); + } + }; + search.addEventListener("input", render); + render(); } // ── Learn ──────────────────────────────────────────────────────────────── private renderLearn(el: HTMLElement): void { - el.createEl("h4", { text: "Learn from this map" }); + el.createEl("h4", { text: `Learn from ${this.mapName || "a region"}` }); el.createEl("p", { - text: "Make a wave function collapse generator from the terrain painted on this map. Terrains that never touch here never touch in generated maps; lakes, ridges, forests and towns keep their shape and relative size; rivers that run from an edge into a lake are always placed.", + text: "Make a wave function collapse generator from the terrain and paths on this region. Terrains that never touch here never touch in generated maps, and each terrain keeps its shape and relative size.", cls: "duckmage-map-origin-desc", }); const row = el.createDiv({ cls: "duckmage-region-row" }); - const nameInput = row.createEl("input", { type: "text", value: this.view.activeMapName, placeholder: "generator-name" }); - const btn = row.createEl("button", { text: "Generate solver from map", cls: "mod-cta" }); + const nameInput = row.createEl("input", { type: "text", value: this.mapName, placeholder: "generator-name" }); + const btn = row.createEl("button", { text: "Generate solver from region", cls: "mod-cta" }); + btn.disabled = !this.mapName; btn.addEventListener("click", () => { btn.disabled = true; - void saveGeneratorFromMap(this.plugin, this.view.activeMapName, nameInput.value).then((result) => { + void saveGeneratorFromMap(this.plugin, this.mapName, nameInput.value).then((result) => { btn.disabled = false; if ("error" in result) { new Notice(result.error); return; } const { model, file } = result; - const extra = model.features?.length ? `, ${model.features.length} guaranteed feature(s)` : ""; - new Notice(`Saved generator "${model.name}": ${model.terrains.length} terrains, ${model.adjacency.length} neighbour pairs${extra}.`); - GeneratorTab.selectedPath = file.path; + new Notice(`Saved generator "${model.name}": ${model.terrains.length} terrains, ${model.adjacency.length} neighbour pairs.`); + GeneratorPanel.selectedPath = file.path; + GeneratorPanel.paletteName = model.meta.palette ?? GeneratorPanel.paletteName; this.host.rerender(); }); }); @@ -149,7 +209,7 @@ export class GeneratorTab { private renderGenerator(el: HTMLElement, g: GeneratorFile): void { const { model } = g; - const colors = paletteColors(this.plugin, model.meta.palette); + const colors = paletteColors(this.plugin, GeneratorPanel.paletteName); const byShape = (shape: string) => model.terrains.filter((t) => (t.shape ?? "none") === shape).map((t) => t.name); const parts = [`${model.terrains.length} terrains`]; for (const [shape, label] of [["blob", "blobs"], ["line", "lines"], ["scatter", "scattered"]] as const) @@ -192,22 +252,24 @@ export class GeneratorTab { this.previewCols = Math.max(2, Math.min(200, Number(colsInput.value) || 30)); this.previewRows = Math.max(2, Math.min(200, Number(rowsInput.value) || 20)); this.seed = Number(seedInput.value) >>> 0; - const map = this.plugin.getMap(this.view.activeMapName); + const map = this.plugin.getMap(this.mapName); const grid = { cols: this.previewCols, rows: this.previewRows, offset: { x: 0, y: 0 }, stagger: map?.staggerOffset ?? this.plugin.settings.staggerOffset ?? "odd", }; - const palette = [...colors.keys()].length ? [...colors.keys()] : model.terrains.map((t) => t.name); + const palette = this.paletteTerrains().length ? this.paletteTerrains() : model.terrains.map((t) => t.name); const r = generateTerrain(this.plugin, model, palette, grid, this.seed); if (!r.ok) { status.setText(`Couldn't generate: ${r.message}`); return; } drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, r.paths, pathColors(this.plugin)); - const notes = r.warnings.length ? ` · ${r.warnings.join("; ")}` : ""; + // Keep it to one line; the details are on hover. + const notes = r.warnings.length ? ` · ${r.warnings.length} didn't fit (hover for details)` : ""; status.setText(`${grid.cols}×${grid.rows} in ${r.stats.ms} ms${notes}`); + status.setAttr("title", r.warnings.join("\n")); }; const schedulePreview = () => { if (this.previewTimer !== null) window.clearTimeout(this.previewTimer); @@ -227,62 +289,47 @@ export class GeneratorTab { previewBtn.addEventListener("click", runPreview); for (const input of [seedInput, colsInput, rowsInput]) input.addEventListener("change", schedulePreview); + this.renderFill(el, g, () => Number(seedInput.value) >>> 0); + // Shape this.heading(el, "Shape"); - this.slider(el, "Feature size", "Size of lakes, ranges and forests relative to the map. 1 = like the example; lower = more, smaller features; 0 = no growth.", 0, 3, 0.25, s().featureSize, (v) => save({ featureSize: v })); - this.slider(el, "Line width", "Thickness of ridges, ranges and rivers. 0 = as in the example.", 0, 3, 1, s().lineWidth, (v) => save({ lineWidth: v })); + this.slider(el, "Feature size", "Size of each terrain's patches relative to the map. 1 = like the example; lower = more, smaller patches; 0 = no growth.", 0, 3, 0.25, s().featureSize, (v) => save({ featureSize: v })); + if (model.terrains.some((t) => t.shape === "line")) { + const learnedWidth = Math.max(1, Math.round(Math.max(...model.terrains.filter((t) => t.shape === "line").map((t) => t.width ?? 1)))); + this.slider(el, "Line width", "Thickness of line-shaped terrain, in hexes.", 1, 3, 1, s().lineWidth > 0 ? s().lineWidth : learnedWidth, (v) => save({ lineWidth: v })); + } this.slider(el, "Smoothing", "Clean up lone specks and ragged edges after generating.", 0, 1, 0.1, s().smoothing, (v) => save({ smoothing: v })); this.select(el, "Symmetry", "Mirror the map. Symmetric wherever the rules allow.", SYMMETRIES.map((v) => [v, SYMMETRY_LABELS[v]]), s().symmetry, (v) => save({ symmetry: v })); - this.select(el, "Edge style", "What the map border prefers. Pick a terrain such as water for islands, or follow the example map.", + this.select(el, "Edge style", "What the map border prefers: a terrain of your choice, or the example's border.", [["", "As in the example"], ...model.terrains.map((t): [string, string] => [t.name, t.name])], s().edgeTerrain, (v) => save({ edgeTerrain: v || undefined })); this.slider(el, "Edge strength", "How strongly the border follows the edge style. 0 = off.", 0, 1, 0.05, s().edgeStrength, (v) => save({ edgeStrength: v })); // Placement this.heading(el, "Placement"); - this.slider(el, "Directional bias", "0 = features can go anywhere. 1 = they keep to where they were in the example, so an ocean along the bottom stays along the bottom.", 0, 1, 0.05, s().directionalBias, (v) => save({ directionalBias: v })); - this.slider(el, "Spacing", "How far apart scattered terrain like towns stays, relative to the example. 0 = no spacing.", 0, 3, 0.25, s().spacing, (v) => save({ spacing: v })); - this.slider(el, "Randomness", "Share of hexes chosen by plain chance, ignoring neighbours. Lets rare terrain like towns pepper the map. Hard rules still apply.", 0, 1, 0.05, s().randomness, (v) => save({ randomness: v })); + this.slider(el, "Directional bias", "0 = terrain goes anywhere. 1 = it keeps to where it was in the example.", 0, 1, 0.05, s().directionalBias, (v) => save({ directionalBias: v })); + if (model.terrains.some((t) => t.shape === "scatter")) { + this.slider(el, "Spacing", "How far apart single-hex terrain stays, relative to the example. 0 = no spacing.", 0, 3, 0.25, s().spacing, (v) => save({ spacing: v })); + } + this.slider(el, "Randomness", "Share of hexes chosen by chance, ignoring neighbours, so rare terrain turns up here and there.", 0, 1, 0.05, s().randomness, (v) => save({ randomness: v })); // Guarantees this.heading(el, "Guarantees"); if (model.features?.length || model.paths?.length) { - const end = (e: string) => (e === "edge" ? "map edge" : e === "path" ? "joins another" : e); - const list = [ - ...(model.features ?? []).map((f) => `${f.terrain}: ${end(f.from)} → ${end(f.to)}`), - ...(model.paths ?? []).map((p) => `${p.type} path: ${end(p.from)} → ${end(p.to)}`), - ].join(", "); - this.toggle(el, "Guaranteed features", `Always lay these down first: ${list}.`, s().features, (v) => save({ features: v })); - } else { - el.createEl("p", { - text: "No guaranteed features. Draw a river (path or painted terrain) from a map edge into a lake, or from edge to edge, in the example map to get one.", - cls: "duckmage-map-origin-desc", - }); - } - this.toggle(el, "Connected land", "Make all land one connected area, filling cut-off pockets with impassable terrain.", s().connected, (v) => save({ connected: v })); - el.createEl("label", { text: "Impassable terrain", cls: "duckmage-map-field-label" }); - const chips = el.createDiv({ cls: "duckmage-wfc-chips" }); - const impassable = new Set(s().impassable); - for (const t of model.terrains) { - const chip = chips.createEl("label", { cls: "duckmage-wfc-chip" }); - const cb = chip.createEl("input", { type: "checkbox" }); - cb.checked = impassable.has(t.name); - chip.createSpan({ text: t.name }); - cb.addEventListener("change", () => { - if (cb.checked) impassable.add(t.name); - else impassable.delete(t.name); - save({ impassable: [...impassable] }); - }); + this.toggle(el, "Guaranteed features", "Always place the example's anchored lines and paths.", s().features, (v) => save({ features: v })); } + this.toggle(el, "Connected land", "Fill cut-off pockets so every passable hex connects.", s().connected, (v) => save({ connected: v })); + this.terrainFilter(el, "Impassable terrain", model.terrains.map((t) => t.name), colors, s().impassable, (list) => save({ impassable: list })); - // Per terrain - this.heading(el, "Terrains"); - el.createEl("p", { - text: "Mix scales how common each terrain is. Min and max set how many separate patches to make (a town is a 1-hex patch); leave blank for no limit.", + // Advanced: per-terrain controls and tuning + const adv = el.createEl("details", { cls: "duckmage-wfc-section" }); + adv.createEl("summary", { text: "Advanced" }); + adv.createEl("p", { + text: "Mix scales how common each terrain is. Min and max limit how many separate patches it forms; leave blank for no limit.", cls: "duckmage-map-origin-desc", }); - const table = el.createDiv({ cls: "duckmage-wfc-terrains" }); + const table = adv.createDiv({ cls: "duckmage-wfc-terrains" }); const head = table.createDiv({ cls: "duckmage-wfc-terrain-row duckmage-wfc-terrain-head" }); for (const h of ["Terrain", "Shape", "Mix", "Min", "Max"]) head.createSpan({ text: h }); const mix = { ...s().mix }; @@ -322,13 +369,9 @@ export class GeneratorTab { }); } } - - // Advanced tuning - const adv = el.createEl("details", { cls: "duckmage-wfc-section" }); - adv.createEl("summary", { text: "Advanced tuning" }); this.slider(adv, "Clumping", "How strongly each hex follows its neighbours. 0 gives speckled noise.", 0, 6, 0.5, s().neighbourInfluence, (v) => save({ neighbourInfluence: v })); this.slider(adv, "Mix strength", "How closely the overall terrain mix follows the example.", 0, 4, 0.5, s().frequencyFeedback, (v) => save({ frequencyFeedback: v })); - this.slider(adv, "Scatter", "Randomness in where features start. Too low and one terrain can take over the map.", 0, 6, 0.5, s().scatter, (v) => save({ scatter: v })); + this.slider(adv, "Scatter", "Randomness in where patches start. Too low and one terrain can take over the map.", 0, 6, 0.5, s().scatter, (v) => save({ scatter: v })); const resetRow = el.createDiv({ cls: "duckmage-region-row" }); const resetBtn = resetRow.createEl("button", { text: "Reset settings to defaults" }); @@ -339,18 +382,17 @@ export class GeneratorTab { this.host.rerender(); }); - this.renderFill(el, g, () => Number(seedInput.value) >>> 0); schedulePreview(); } // ── Fill the active map ────────────────────────────────────────────────── private renderFill(el: HTMLElement, g: GeneratorFile, seed: () => number): void { - this.heading(el, "Fill this map"); - const mapName = this.view.activeMapName; + this.heading(el, `Fill ${this.mapName || "region"}`); + const mapName = this.mapName; const palette = this.plugin.getMapPalette(mapName).map((t) => t.name); el.createEl("p", { - text: `Uses the preview's seed. "Fill unpainted hexes" keeps everything you've painted and your paths. "Regenerate" repaints the whole map except hexes whose note has "${LOCK_KEY}: true" in its properties, and redraws the generator's path types (e.g. rivers).`, + text: `Uses the preview's seed. "Fill unpainted hexes" keeps everything you've painted and your paths. "Regenerate" repaints the whole map, except hexes whose note has "${LOCK_KEY}: true" in its properties, and redraws the generator's path types.`, cls: "duckmage-map-origin-desc", }); if (!generatorFitsPalette(g.model, palette)) @@ -447,7 +489,67 @@ export class GeneratorTab { const cb = row.createEl("input", { type: "checkbox" }); cb.checked = value; row.createSpan({ text: label }); - el.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); + if (hint) el.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); cb.addEventListener("change", () => onChange(cb.checked)); } + /** + * Searchable terrain list: type to filter, click a match to add it; added + * terrains show as chips that can be removed. + */ + private terrainFilter( + el: HTMLElement, + label: string, + terrains: string[], + colors: Map, + selected: string[], + onChange: (list: string[]) => void, + ): void { + el.createEl("label", { text: label, cls: "duckmage-map-field-label" }); + const chosen = new Set(selected.filter((t) => terrains.includes(t))); + const chips = el.createDiv({ cls: "duckmage-wfc-chips" }); + const search = el.createEl("input", { type: "search", cls: "duckmage-wfc-filter", attr: { placeholder: "Search terrain to add…" } }); + const matches = el.createDiv({ cls: "duckmage-wfc-chips duckmage-wfc-matches" }); + const swatch = (parent: HTMLElement, t: string) => + parent.createSpan({ cls: "duckmage-wfc-swatch" }).setCssProps({ "--duckmage-wfc-swatch": colors.get(t) ?? "var(--background-modifier-border)" }); + + const render = () => { + chips.empty(); + if (!chosen.size) chips.createSpan({ text: "None", cls: "duckmage-map-origin-desc" }); + for (const t of chosen) { + const chip = chips.createSpan({ cls: "duckmage-wfc-chip is-selected" }); + swatch(chip, t); + chip.createSpan({ text: t }); + const remove = chip.createEl("button", { text: "×", cls: "duckmage-wfc-chip-remove", attr: { "aria-label": `Remove ${t}` } }); + remove.addEventListener("click", () => { + chosen.delete(t); + onChange([...chosen]); + render(); + }); + } + matches.empty(); + const q = search.value.trim().toLowerCase(); + if (!q) return; + const found = terrains.filter((t) => !chosen.has(t) && t.toLowerCase().includes(q)).slice(0, 12); + if (!found.length) matches.createSpan({ text: "No matching terrain", cls: "duckmage-map-origin-desc" }); + for (const t of found) { + const btn = matches.createEl("button", { cls: "duckmage-wfc-chip" }); + swatch(btn, t); + btn.createSpan({ text: t }); + btn.addEventListener("click", () => { + chosen.add(t); + search.value = ""; + onChange([...chosen]); + render(); + search.focus(); + }); + } + }; + search.addEventListener("input", render); + search.addEventListener("keydown", (e: KeyboardEvent) => { + if (e.key !== "Enter") return; + const first = matches.querySelector("button"); + if (first) first.click(); + }); + render(); + } } diff --git a/src/worldgen/GeneratorView.ts b/src/worldgen/GeneratorView.ts new file mode 100644 index 00000000..c4b93d73 --- /dev/null +++ b/src/worldgen/GeneratorView.ts @@ -0,0 +1,39 @@ +import { ItemView, type WorkspaceLeaf } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { VIEW_TYPE_GENERATOR } from "../constants"; +import { GeneratorPanel } from "./GeneratorPanel"; + +/** Full-page terrain generator (wave function collapse). */ +export class GeneratorView extends ItemView { + constructor( + leaf: WorkspaceLeaf, + private plugin: HexmakerPlugin, + ) { + super(leaf); + } + + getViewType(): string { + return VIEW_TYPE_GENERATOR; + } + + getDisplayText(): string { + return "Terrain generator"; + } + + getIcon(): string { + return "wand-sparkles"; + } + + async onOpen(): Promise { + this.render(); + } + + private render(): void { + this.contentEl.addClass("duckmage-wfc-page"); + new GeneratorPanel(this.app, this.plugin, { rerender: () => this.render() }).render(this.contentEl); + } + + async onClose(): Promise { + this.contentEl.empty(); + } +} diff --git a/styles.css b/styles.css index a9678bb4..b26ae083 100644 --- a/styles.css +++ b/styles.css @@ -5194,3 +5194,46 @@ tr:hover .duckmage-rt-entry-copy-btn:hover { flex: 1; min-width: 0; } + +.duckmage-wfc-filter { + width: 100%; + margin: 0.35em 0; +} + +.duckmage-wfc-matches:empty { + display: none; +} + +.duckmage-wfc-chip.is-selected { + padding: 0.1em 0.2em 0.1em 0.5em; + border-radius: var(--radius-s); + background: var(--background-modifier-hover); +} + +button.duckmage-wfc-chip { + padding: 0.15em 0.6em; + height: auto; +} + +.duckmage-wfc-chip-remove { + padding: 0 0.35em; + height: auto; + box-shadow: none; + background: transparent; + color: var(--text-muted); +} + +.duckmage-wfc-page { + padding: 1em 1.5em 3em; +} + +.duckmage-wfc-page .duckmage-wfc-tab { + max-width: 760px; + margin: 0 auto; +} + +.duckmage-wfc-regions { + max-height: 9em; + overflow-y: auto; + margin-bottom: 0.5em; +} From 7f2d8e711809d59911637b91f7f2e832d4219cde Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 17:42:22 -0400 Subject: [PATCH 009/558] fix(worldgen): edge 'as in the example' on by default; stricter line learning; Re-learn button; terse preview text - Learned edge preference now applies by default (edge-strength 1) and is doubled, so strength 1 reproduces the example's border mix: the-coast border mismatch 46 -> 16 pts, bay-area 49 -> 35 (dev/wfc-edge.mts) - Lines must be elongated >= 3, <= 2 hexes wide and a minor terrain (<= 10% of the map); hand-painted ragged patches no longer become 'lines' (the-coast ocean, evergreen heavy, ...) - Path patterns that join another path at both ends are not learned - Re-learn: re-reads the generator's source region, keeps its settings - Preview status: size, time and a hoverable warning count only; generator summary on one line with details on hover Co-Authored-By: Claude Opus 5.5 (1M context) --- dev/wfc-edge.mts | 40 +++++++++++++++++++++++++++++++ packages/hex-wfc/src/learn.ts | 11 +++++---- packages/hex-wfc/src/model.ts | 2 +- packages/hex-wfc/src/paths.ts | 3 +++ packages/hex-wfc/src/solve.ts | 4 +++- src/hex-map/MapModal.ts | 2 +- src/worldgen/GeneratorPanel.ts | 44 +++++++++++++++++++++++----------- src/worldgen/generators.ts | 25 +++++++++++++++++++ 8 files changed, 110 insertions(+), 21 deletions(-) create mode 100644 dev/wfc-edge.mts diff --git a/dev/wfc-edge.mts b/dev/wfc-edge.mts new file mode 100644 index 00000000..0aeeffc2 --- /dev/null +++ b/dev/wfc-edge.mts @@ -0,0 +1,40 @@ +// Border check: compare the share of each terrain on the outer 2 rings in a +// real vault map vs generated maps (learned edge, "as in the example"). +// Usage (from WSL, plugin root): npx tsx /dev/wfc-edge.mts [edgeStrength] +import { readFileSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { learnModel, solve, cellKey } from "../packages/hex-wfc/src"; +const data = JSON.parse(readFileSync("data.json", "utf8")); +const name = process.argv[2] ?? "the-coast"; +const strength = process.argv[3] === undefined ? undefined : Number(process.argv[3]); +const map = data.maps.find((m: { name: string }) => m.name === name); +const cells = new Map(); +for (let x = map.gridOffset.x; x < map.gridOffset.x + map.gridSize.cols; x++) + for (let y = map.gridOffset.y; y < map.gridOffset.y + map.gridSize.rows; y++) { + const f = join("../../..", data.hexFolder, name, `${x}_${y}.md`); + if (!existsSync(f)) continue; + const m = /^---[\s\S]*?\nterrain:\s*(.*)\n/.exec(readFileSync(f, "utf8")); + const t = m?.[1].trim().replace(/^"|"$/g, ""); + if (t) cells.set(cellKey(x, y), t); + } +const { cols, rows } = map.gridSize, ox = map.gridOffset.x, oy = map.gridOffset.y; +const ringShare = (c: Map, x0: number, y0: number) => { + const out: Record = {}; let n = 0; + for (const [k, t] of c) { const [x, y] = k.split("_").map(Number); const d = Math.min(x - x0, x0 + cols - 1 - x, y - y0, y0 + rows - 1 - y); if (d <= 1) { out[t] = (out[t] ?? 0) + 1; n++; } } + for (const t in out) out[t] = Math.round((1000 * out[t]) / n) / 10; + return out; +}; +const model = learnModel(cells, { name, orientation: data.hexOrientation, stagger: map.staggerOffset ?? "odd" }); +const ex = ringShare(cells, ox, oy); +const gen: Record = {}; +const seeds = [1, 2, 3, 4, 5, 6]; +for (const seed of seeds) { + const r = solve(model, { cols, rows, orientation: data.hexOrientation, stagger: map.staggerOffset ?? "odd", seed, features: false, ...(strength === undefined ? {} : { edgeStrength: strength }) }); + if (!r.ok) continue; + for (const [t, v] of Object.entries(ringShare(r.cells, 0, 0))) gen[t] = (gen[t] ?? 0) + v / seeds.length; +} +const top = Object.entries(ex).sort((a, b) => b[1] - a[1]).slice(0, 8); +let err = 0; +for (const t of new Set([...Object.keys(ex), ...Object.keys(gen)])) err += Math.abs((ex[t] ?? 0) - (gen[t] ?? 0)); +console.log(`edge strength ${strength ?? "default"}: border mismatch ${err.toFixed(0)} pts`); +for (const [t, v] of top) console.log(" ", t.padEnd(20), `example ${v.toFixed(1)}%`.padEnd(16), `generated ${(gen[t] ?? 0).toFixed(1)}%`); diff --git a/packages/hex-wfc/src/learn.ts b/packages/hex-wfc/src/learn.ts index da75f56f..2d419df6 100644 --- a/packages/hex-wfc/src/learn.ts +++ b/packages/hex-wfc/src/learn.ts @@ -110,10 +110,12 @@ export const SHAPE_THRESHOLDS = { /** Patch above this share of the map → "none" (it's the background). */ maxPatchShare: 0.3, /** Long axis / short axis at or above this → "line"... */ - lineElongation: 2.2, + lineElongation: 3, /** ...if also at most this many hexes thick. Thicker long patches (a sea * along one edge) are bands, treated as blobs. */ - maxLineWidth: 3.5, + maxLineWidth: 2, + /** ...and the terrain isn't a major one (share of the map at most this). */ + maxLineShare: 0.1, /** A thin patch whose second most common neighbouring terrain makes up at * least this share of its border is a boundary (a shore between land and * sea), not a line: it's left to the neighbour rules. */ @@ -236,9 +238,10 @@ function analysePatches( const border = [...others.values()].sort((x, y) => y - x); const borderTotal = border.reduce((x, y) => x + y, 0); const isBoundary = borderTotal > 0 && (border[1] ?? 0) / borderTotal >= TH.boundaryShare; - if (elong >= TH.lineElongation && width <= TH.maxLineWidth && isBoundary) { + const thinLine = elong >= TH.lineElongation && width <= TH.maxLineWidth && (countOf.get(t) ?? 0) / total <= TH.maxLineShare; + if (thinLine && isBoundary) { a.shape = "none"; - } else if (elong >= TH.lineElongation && width <= TH.maxLineWidth) { + } else if (thinLine) { a.shape = "line"; // Straighter patches (higher elongation) turn less. Heuristic. a.turn = Math.round(Math.min(0.5, Math.max(0.05, 1.2 / elong)) * 100) / 100; diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index e0f48b3a..0d75126c 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -147,7 +147,7 @@ export const DEFAULT_SETTINGS: Required = { frequencyFeedback: 2, scatter: 3, randomness: 0.1, - edgeStrength: 0, + edgeStrength: 1, edgeTerrain: "", lineWidth: 0, smoothing: 0, diff --git a/packages/hex-wfc/src/paths.ts b/packages/hex-wfc/src/paths.ts index fe61556e..253ebda4 100644 --- a/packages/hex-wfc/src/paths.ts +++ b/packages/hex-wfc/src/paths.ts @@ -75,6 +75,9 @@ export function learnPaths( let from = anchor(p.hexes[0]); let to = anchor(p.hexes[p.hexes.length - 1]); if (from === "none" && to === "none") continue; + // Joins at both ends (a link between two branches) isn't something to + // reproduce on its own. + if (from === "path" && to === "path") continue; // Order: a "path" anchor first (branches start from their parent), then // "edge", then a terrain, then "none". const rank = (e: string) => (e === "path" ? 0 : e === "edge" ? 1 : e === "none" ? 3 : 2); diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 0aaa56a0..6cfc317e 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -336,7 +336,9 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required 0 && !s.edgeTerrain) { const logEdge = new Float64Array(T); - for (let t = 0; t < T; t++) logEdge[t] = Math.log(Math.max(0.02, entryOf.get(terrains[t])?.edge ?? 1)); + // Doubled so strength 1 roughly reproduces the example's border mix + // (measured on real maps with dev/wfc-edge.mts). + for (let t = 0; t < T; t++) logEdge[t] = 2 * Math.log(Math.max(0.02, entryOf.get(terrains[t])?.edge ?? 1)); if (logEdge.some((v) => v !== 0)) { const pos = ensurePos(); const depth = Math.max(2, 0.15 * Math.min(cols, rows)); diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index c1da9622..4fa90a74 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -687,7 +687,7 @@ export class MapModal extends HexmakerModal { return; } drawPreview(previewCanvas, r.cells, grid, this.plugin.settings.hexOrientation, paletteColors(this.plugin, paletteSelect.value), r.featureCells, r.paths, pathColors(this.plugin)); - previewStatus.setText(r.warnings.length ? `${r.warnings.length} didn't fit (hover for details)` : ""); + previewStatus.setText(r.warnings.length ? `⚠ ${r.warnings.length}` : ""); previewStatus.setAttr("title", r.warnings.join("\n")); }; let previewTimer: number | null = null; diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index e167235c..0bb28db6 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -17,6 +17,7 @@ import { paletteColors, pathColors, fillMap, + relearnGenerator, LOCK_KEY, type GeneratorFile, } from "./generators"; @@ -95,10 +96,8 @@ export class GeneratorPanel { const select = pickRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); const openBtn = pickRow.createEl("button", { text: "Open file" }); openBtn.disabled = true; - el.createEl("p", { - text: "Generators whose terrains are all in this palette. Each keeps its settings in its own file.", - cls: "duckmage-map-origin-desc", - }); + const relearnBtn = pickRow.createEl("button", { text: "Re-learn", attr: { title: "Learn again from the region it came from, keeping its settings" } }); + relearnBtn.disabled = true; const body = el.createDiv(); let generators: GeneratorFile[] = []; const current = () => generators.find((g) => g.file.path === select.value); @@ -108,6 +107,7 @@ export class GeneratorPanel { body.empty(); const g = current(); openBtn.disabled = !g; + relearnBtn.disabled = !g?.model.meta["source-map"]; if (g) this.renderGenerator(body, g); else body.createEl("p", { @@ -135,6 +135,20 @@ export class GeneratorPanel { const g = current(); if (g) void this.app.workspace.getLeaf("tab").openFile(g.file); }); + relearnBtn.addEventListener("click", () => { + const g = current(); + if (!g) return; + relearnBtn.disabled = true; + void relearnGenerator(this.plugin, g).then((r) => { + if ("error" in r) { + new Notice(r.error); + relearnBtn.disabled = false; + return; + } + new Notice(`Re-learned "${g.model.name}" from ${g.model.meta["source-map"]}.`); + this.host.rerender(); + }); + }); select.createEl("option", { value: "", text: "Loading…" }); void listGenerators(this.plugin).then((list) => { @@ -210,14 +224,17 @@ export class GeneratorPanel { private renderGenerator(el: HTMLElement, g: GeneratorFile): void { const { model } = g; const colors = paletteColors(this.plugin, GeneratorPanel.paletteName); + // One short line; the per-shape breakdown is on hover. const byShape = (shape: string) => model.terrains.filter((t) => (t.shape ?? "none") === shape).map((t) => t.name); - const parts = [`${model.terrains.length} terrains`]; - for (const [shape, label] of [["blob", "blobs"], ["line", "lines"], ["scatter", "scattered"]] as const) - if (byShape(shape).length) parts.push(`${label}: ${byShape(shape).join(", ")}`); - if (model.paths?.length) parts.push(`paths: ${[...new Set(model.paths.map((p) => p.type))].join(", ")}`); - if (model.meta["source-map"]) parts.push(`learned from ${model.meta["source-map"]}`); - el.createEl("p", { text: parts.join(" · "), cls: "duckmage-map-origin-desc" }); - for (const w of g.warnings) el.createEl("p", { text: `⚠ ${w}`, cls: "duckmage-map-origin-desc" }); + const detail = (["blob", "line", "scatter", "none"] as const) + .filter((shape) => byShape(shape).length) + .map((shape) => `${shape}: ${byShape(shape).join(", ")}`); + if (model.paths?.length) detail.push(`paths: ${[...new Set(model.paths.map((p) => p.type))].join(", ")}`); + const summary = el.createEl("p", { + text: `${model.terrains.length} terrains${model.meta["source-map"] ? ` · from ${model.meta["source-map"]}` : ""}${g.warnings.length ? ` · ⚠ ${g.warnings.length}` : ""}`, + cls: "duckmage-map-origin-desc", + }); + summary.setAttr("title", [...detail, ...g.warnings].join("\n")); // Current settings, kept in sync with the file. const s = () => resolveSettings(model); @@ -266,9 +283,8 @@ export class GeneratorPanel { return; } drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, r.paths, pathColors(this.plugin)); - // Keep it to one line; the details are on hover. - const notes = r.warnings.length ? ` · ${r.warnings.length} didn't fit (hover for details)` : ""; - status.setText(`${grid.cols}×${grid.rows} in ${r.stats.ms} ms${notes}`); + // Short: size and time, plus a hoverable count if anything didn't fit. + status.setText(`${grid.cols}×${grid.rows} · ${r.stats.ms} ms${r.warnings.length ? ` · ⚠ ${r.warnings.length}` : ""}`); status.setAttr("title", r.warnings.join("\n")); }; const schedulePreview = () => { diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index 0834e85a..8b58cd32 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -317,3 +317,28 @@ async function writeTerrain( onProgress?.(done, changes.length); } } + +/** + * Re-learn a generator from the region it came from (its `source-map`), + * keeping its name, settings and other metadata. Rewrites the file. + */ +export async function relearnGenerator( + plugin: HexmakerPlugin, + g: GeneratorFile, +): Promise<{ model: HexWfcModel } | { error: string }> { + const mapName = g.model.meta["source-map"]; + const map = mapName ? plugin.getMap(mapName) : undefined; + if (!mapName || !map) return { error: `The region this generator came from (${mapName ?? "unknown"}) no longer exists.` }; + const cells = readMapTerrain(plugin, mapName); + if (cells.size < 2) return { error: `Region "${mapName}" has no painted terrain to learn from.` }; + const model = learnModel(cells, { + name: g.model.name, + orientation: plugin.settings.hexOrientation, + stagger: mapStagger(plugin, mapName), + paths: (map.pathChains ?? []).map((p) => ({ type: p.typeName, hexes: p.hexes })), + meta: { ...g.model.meta, palette: map.paletteName, created: new Date().toISOString().slice(0, 10) }, + }); + if (g.model.settings) model.settings = { ...g.model.settings }; + await plugin.app.vault.modify(g.file, modelToMarkdown(model)); + return { model }; +} From 0d9217b3a39e54246a43846fbe135b50d02e683a Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 17:47:31 -0400 Subject: [PATCH 010/558] feat(worldgen): Create map from the preview Replaces the Preview button (the preview already refreshes; Re-roll previews large maps) with a name field and Create map, which creates a new map identical to the preview: same size, seed, palette, terrain and paths, then opens it in the hex map view (plugin.showMap). Co-Authored-By: Claude Opus 5.5 (1M context) --- src/HexmakerPlugin.ts | 11 ++++++ src/worldgen/GeneratorPanel.ts | 63 ++++++++++++++++++++++++++++------ 2 files changed, 64 insertions(+), 10 deletions(-) diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 7b80967d..65561c8c 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -376,6 +376,17 @@ export default class HexmakerPlugin extends Plugin { void this.app.workspace.getLeaf().setViewState({ type: VIEW_TYPE_HEX_MAP }); } + /** Show a map in the hex map view, opening the view if it isn't open. */ + async showMap(name: string): Promise { + let leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP)[0]; + if (!leaf) { + leaf = this.app.workspace.getLeaf("tab"); + await leaf.setViewState({ type: VIEW_TYPE_HEX_MAP, active: true }); + } + await this.app.workspace.revealLeaf(leaf); + (leaf.view as HexMapView).switchMapFromModal(name); + } + openSetupWizard(): void { void this.app.workspace.getLeaf("tab").setViewState({ type: VIEW_TYPE_SETUP_WIZARD }); } diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 0bb28db6..d52c7753 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -18,6 +18,7 @@ import { pathColors, fillMap, relearnGenerator, + toPathChains, LOCK_KEY, type GeneratorFile, } from "./generators"; @@ -263,19 +264,24 @@ export class GeneratorPanel { const colsInput = previewRow.createEl("input", { type: "number", value: String(this.previewCols), cls: "duckmage-wfc-num" }); previewRow.createSpan({ text: "×" }); const rowsInput = previewRow.createEl("input", { type: "number", value: String(this.previewRows), cls: "duckmage-wfc-num" }); - const previewBtn = previewRow.createEl("button", { text: "Preview" }); + const createRow = previewBox.createDiv({ cls: "duckmage-region-row" }); + const newNameInput = createRow.createEl("input", { type: "text", attr: { placeholder: "Name for the new map" } }); + const createBtn = createRow.createEl("button", { text: "Create map", cls: "mod-cta" }); - const runPreview = () => { - this.previewCols = Math.max(2, Math.min(200, Number(colsInput.value) || 30)); - this.previewRows = Math.max(2, Math.min(200, Number(rowsInput.value) || 20)); - this.seed = Number(seedInput.value) >>> 0; + const previewGrid = () => { const map = this.plugin.getMap(this.mapName); - const grid = { - cols: this.previewCols, - rows: this.previewRows, + return { + cols: Math.max(2, Math.min(200, Number(colsInput.value) || 30)), + rows: Math.max(2, Math.min(200, Number(rowsInput.value) || 20)), offset: { x: 0, y: 0 }, stagger: map?.staggerOffset ?? this.plugin.settings.staggerOffset ?? "odd", }; + }; + const runPreview = () => { + const grid = previewGrid(); + this.previewCols = grid.cols; + this.previewRows = grid.rows; + this.seed = Number(seedInput.value) >>> 0; const palette = this.paletteTerrains().length ? this.paletteTerrains() : model.terrains.map((t) => t.name); const r = generateTerrain(this.plugin, model, palette, grid, this.seed); if (!r.ok) { @@ -290,7 +296,7 @@ export class GeneratorPanel { const schedulePreview = () => { if (this.previewTimer !== null) window.clearTimeout(this.previewTimer); if (Number(colsInput.value) * Number(rowsInput.value) > PREVIEW_AUTO_LIMIT) { - status.setText("Large map: use the preview button to generate it."); + status.setText("Large map: re-roll to preview it."); return; } this.previewTimer = window.setTimeout(() => { @@ -302,7 +308,44 @@ export class GeneratorPanel { seedInput.value = String(randomSeed()); runPreview(); }); - previewBtn.addEventListener("click", runPreview); + // Create a new map that is exactly the preview: same size, seed, palette and paths. + createBtn.addEventListener("click", () => { + const grid = previewGrid(); + const seed = Number(seedInput.value) >>> 0; + const palette = this.paletteTerrains().length ? this.paletteTerrains() : model.terrains.map((t) => t.name); + const r = generateTerrain(this.plugin, model, palette, grid, seed); + if (!r.ok) { + new Notice(`Couldn't generate: ${r.message}`); + return; + } + createBtn.disabled = true; + void this.plugin + .createNewMap( + newNameInput.value.trim() || `${model.name}-${seed}`, + grid.cols, grid.rows, GeneratorPanel.paletteName, 0, 0, grid.stagger, + (done, total) => createBtn.setText(`Creating ${done} / ${total}…`), + r.cells, + ) + .then(async (result) => { + createBtn.disabled = false; + createBtn.setText("Create map"); + if ("error" in result) { + new Notice(result.error); + return; + } + const { chains, missing } = toPathChains(this.plugin, r.paths); + const created = this.plugin.getMap(result.name); + if (created && chains.length) { + created.pathChains = [...created.pathChains, ...chains]; + await this.plugin.saveSettings(); + } + if (missing.length) new Notice(`No path type named ${missing.join(", ")}, so those paths were skipped.`); + new Notice(`Created map "${result.name}".`); + GeneratorPanel.mapName = result.name; + await this.plugin.showMap(result.name); + this.host.rerender(); + }); + }); for (const input of [seedInput, colsInput, rowsInput]) input.addEventListener("change", schedulePreview); this.renderFill(el, g, () => Number(seedInput.value) >>> 0); From 66777c961a46b40d7057f4c85e357d3c0bce2997 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 17:53:33 -0400 Subject: [PATCH 011/558] feat(worldgen): right-click a region in the Maps list to create a generator from it Learns the generator (name = region, never overwrites), then opens the terrain generator page with that region, palette and generator selected (plugin.openTerrainGenerator, also used by the command; refreshes the page if it's already open). Co-Authored-By: Claude Opus 5.5 (1M context) --- src/HexmakerPlugin.ts | 20 +++++++++++++++++++- src/hex-map/MapModal.ts | 32 +++++++++++++++++++++++++++++++- src/worldgen/GeneratorView.ts | 6 ++++++ 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 65561c8c..3d70a95e 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -39,6 +39,7 @@ import { removeLinkFromSection, } from "./sections"; import { GeneratorView } from "./worldgen/GeneratorView"; +import { GeneratorPanel } from "./worldgen/GeneratorPanel"; export default class HexmakerPlugin extends Plugin { settings: HexmakerPluginSettings; availableIcons: string[] = []; @@ -115,7 +116,7 @@ export default class HexmakerPlugin extends Plugin { this.addCommand({ id: "open-terrain-generator", name: "Open terrain generator", - callback: () => void this.app.workspace.getLeaf("tab").setViewState({ type: VIEW_TYPE_GENERATOR, active: true }), + callback: () => void this.openTerrainGenerator(), }); this.addCommand({ id: "open-random-tables", @@ -376,6 +377,23 @@ export default class HexmakerPlugin extends Plugin { void this.app.workspace.getLeaf().setViewState({ type: VIEW_TYPE_HEX_MAP }); } + /** + * Open the terrain generator page (or bring it forward), optionally with a + * region and generator selected. + */ + async openTerrainGenerator(select: { mapName?: string; generatorPath?: string; paletteName?: string } = {}): Promise { + if (select.mapName) GeneratorPanel.mapName = select.mapName; + if (select.paletteName) GeneratorPanel.paletteName = select.paletteName; + if (select.generatorPath) GeneratorPanel.selectedPath = select.generatorPath; + const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_GENERATOR)[0]; + if (existing) { + await this.app.workspace.revealLeaf(existing); + (existing.view as GeneratorView).refresh(); + return; + } + await this.app.workspace.getLeaf("tab").setViewState({ type: VIEW_TYPE_GENERATOR, active: true }); + } + /** Show a map in the hex map view, opening the view if it isn't open. */ async showMap(name: string): Promise { let leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP)[0]; diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 4fa90a74..27a54aff 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -1,4 +1,4 @@ -import { App, Notice, TFolder } from "obsidian"; +import { App, Menu, Notice, TFolder } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { HexMapView } from "./HexMapView"; @@ -10,6 +10,7 @@ import { FileLinkSuggestModal } from "./FileLinkSuggestModal"; import { listGenerators, generatorFitsPalette, + saveGeneratorFromMap, generateTerrain, paletteColors, pathColors, @@ -250,6 +251,17 @@ export class MapModal extends HexmakerModal { const li = list.createEl("li", { cls: "duckmage-region-item duckmage-map-list-item" + (isActive ? " is-active" : ""), }); + li.addEventListener("contextmenu", (e: MouseEvent) => { + e.preventDefault(); + const menu = new Menu(); + menu.addItem((item) => + item + .setTitle(`Create generator from ${map.name}`) + .setIcon("wand-sparkles") + .onClick(() => void this.createGeneratorFrom(map.name)), + ); + menu.showAtMouseEvent(e); + }); if (isConfirming) { li.addClass("duckmage-map-item-confirming"); @@ -742,6 +754,24 @@ export class MapModal extends HexmakerModal { }); } + // ── Generator ───────────────────────────────────────────────────────────── + + /** Learn a generator from a region and open it in the terrain generator. */ + private async createGeneratorFrom(mapName: string): Promise { + const result = await saveGeneratorFromMap(this.plugin, mapName, mapName); + if ("error" in result) { + new Notice(result.error); + return; + } + new Notice(`Created generator "${result.model.name}" from ${mapName}.`); + this.close(); + await this.plugin.openTerrainGenerator({ + mapName, + generatorPath: result.file.path, + paletteName: result.model.meta.palette, + }); + } + // ── Delete ──────────────────────────────────────────────────────────────── private async deleteMap(name: string): Promise { diff --git a/src/worldgen/GeneratorView.ts b/src/worldgen/GeneratorView.ts index c4b93d73..ce8864ca 100644 --- a/src/worldgen/GeneratorView.ts +++ b/src/worldgen/GeneratorView.ts @@ -28,6 +28,12 @@ export class GeneratorView extends ItemView { this.render(); } + /** Re-render, e.g. after the selected region or generator changed. */ + refresh(): void { + this.contentEl.empty(); + this.render(); + } + private render(): void { this.contentEl.addClass("duckmage-wfc-page"); new GeneratorPanel(this.app, this.plugin, { rerender: () => this.render() }).render(this.contentEl); From 43fbea94da8ef57486804b20fcc9e316a96f6cda Mon Sep 17 00:00:00 2001 From: nyxsys Date: Tue, 6 Oct 2026 18:05:33 -0400 Subject: [PATCH 012/558] feat(worldgen): drop the Fill section from the generator page (fillMap kept for use elsewhere) Co-Authored-By: Claude Opus 5.5 (1M context) --- src/worldgen/GeneratorPanel.ts | 59 +--------------------------------- 1 file changed, 1 insertion(+), 58 deletions(-) diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index d52c7753..551fdadc 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -1,7 +1,7 @@ /** * The terrain generator page: pick a region (map) and palette, learn a * generator from the region, adjust a generator's settings (saved to its - * file's frontmatter) with a live preview, and fill or regenerate the region. + * file's frontmatter) with a live preview, and create a new map from it. */ import { App, Notice } from "obsidian"; @@ -16,10 +16,8 @@ import { generatorFitsPalette, paletteColors, pathColors, - fillMap, relearnGenerator, toPathChains, - LOCK_KEY, type GeneratorFile, } from "./generators"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; @@ -348,7 +346,6 @@ export class GeneratorPanel { }); for (const input of [seedInput, colsInput, rowsInput]) input.addEventListener("change", schedulePreview); - this.renderFill(el, g, () => Number(seedInput.value) >>> 0); // Shape this.heading(el, "Shape"); @@ -444,60 +441,6 @@ export class GeneratorPanel { schedulePreview(); } - // ── Fill the active map ────────────────────────────────────────────────── - - private renderFill(el: HTMLElement, g: GeneratorFile, seed: () => number): void { - this.heading(el, `Fill ${this.mapName || "region"}`); - const mapName = this.mapName; - const palette = this.plugin.getMapPalette(mapName).map((t) => t.name); - el.createEl("p", { - text: `Uses the preview's seed. "Fill unpainted hexes" keeps everything you've painted and your paths. "Regenerate" repaints the whole map, except hexes whose note has "${LOCK_KEY}: true" in its properties, and redraws the generator's path types.`, - cls: "duckmage-map-origin-desc", - }); - if (!generatorFitsPalette(g.model, palette)) - el.createEl("p", { - text: "⚠ This map's palette is missing some of the generator's terrains; those are left out.", - cls: "duckmage-map-origin-desc", - }); - const row = el.createDiv({ cls: "duckmage-region-row" }); - const fillBtn = row.createEl("button", { text: "Fill unpainted hexes", cls: "mod-cta" }); - const regenBtn = row.createEl("button", { text: "Regenerate map", cls: "mod-warning" }); - let confirming = false; - - const run = async (mode: "unpainted" | "regenerate", btn: HTMLButtonElement) => { - fillBtn.disabled = regenBtn.disabled = true; - const label = btn.textContent ?? ""; - const result = await fillMap(this.plugin, mapName, g.model, mode, seed(), (done, total) => - btn.setText(`Writing ${done} / ${total}…`), - ); - fillBtn.disabled = regenBtn.disabled = false; - btn.setText(label); - if ("error" in result) { - new Notice(`Couldn't fill the map: ${result.error}`); - return; - } - const notes = result.warnings.length ? ` (${result.warnings.join("; ")})` : ""; - new Notice(`Generator "${g.model.name}" set terrain on ${result.changed} hexes${notes}.`); - // Let the metadata cache catch up before redrawing. - window.setTimeout(() => this.plugin.refreshHexMap(), 300); - }; - fillBtn.addEventListener("click", () => void run("unpainted", fillBtn)); - regenBtn.addEventListener("click", () => { - if (!confirming) { - confirming = true; - regenBtn.setText("Click again to repaint the map"); - window.setTimeout(() => { - confirming = false; - regenBtn.setText("Regenerate map"); - }, 4000); - return; - } - confirming = false; - regenBtn.setText("Regenerate map"); - void run("regenerate", regenBtn); - }); - } - // ── Small controls ─────────────────────────────────────────────────────── private heading(el: HTMLElement, text: string): void { From 3a35b03eb31777c0477817a2f20a86b4bb5396b5 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Wed, 7 Oct 2026 07:35:34 -0400 Subject: [PATCH 013/558] test: run the hex-wfc and generator tests Co-Authored-By: Claude Opus 5.5 (1M context) --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index a763a408..d82be639 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,8 @@ "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json versions.json", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/hexWfc.test.ts tests/worldgenGenerators.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/hexWfc.test.ts tests/worldgenGenerators.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts" From b58acdf4029c7dd78a70bfec21b8e31762f4f47d Mon Sep 17 00:00:00 2001 From: nyxsys Date: Wed, 7 Oct 2026 20:22:26 -0400 Subject: [PATCH 014/558] feat(worldgen): sticky preview, terrain share readout, split smoothing, drag-to-change and seed lock - The generator page is two columns: controls on the left, and the preview (with seed, size and Create map) in a right column that sticks to the top while the controls scroll. Narrow panes stack it above the controls. - The terrain table (no longer a collapsed "Advanced" section) shows each terrain's share of the example and of the preview, plus the change its mix and min/max make (same seed, run without them; cached until other settings change). Guaranteed line features are tagged, since mix barely moves them. Clumping moved to Shape, Scatter to Placement. - Smoothing is split into Edge smoothing (bumps/notches on patches, lone hexes untouched), Remove small patches (size in hexes) and Keep rare terrain (share of the example below which nothing is smoothed away). Generators with only the old `smoothing` key keep roughly the same effect (cleanupStrengths); any change to the new sliders replaces it. - Size and seed inputs change by dragging up/down, previewing as they go. - Lock seed: Re-roll becomes Regenerate and keeps the seed, so settings can be compared on large maps that don't auto-preview. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- packages/hex-wfc/src/format.ts | 9 +- packages/hex-wfc/src/index.ts | 4 +- packages/hex-wfc/src/model.ts | 17 +++- packages/hex-wfc/src/post.ts | 131 ++++++++++++++++++++++----- packages/hex-wfc/src/solve.ts | 28 +++++- src/worldgen/GeneratorPanel.ts | 160 ++++++++++++++++++++++++++------- src/worldgen/preview.ts | 4 +- src/worldgen/scrub.ts | 74 +++++++++++++++ src/worldgen/shares.ts | 47 ++++++++++ styles.css | 85 +++++++++++++++++- tests/hexWfcCleanup.test.ts | 116 ++++++++++++++++++++++++ tests/worldgenScrub.test.ts | 17 ++++ tests/worldgenShares.test.ts | 53 +++++++++++ 14 files changed, 687 insertions(+), 62 deletions(-) create mode 100644 src/worldgen/scrub.ts create mode 100644 src/worldgen/shares.ts create mode 100644 tests/hexWfcCleanup.test.ts create mode 100644 tests/worldgenScrub.test.ts create mode 100644 tests/worldgenShares.test.ts diff --git a/package.json b/package.json index d82be639..8672efc5 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,8 @@ "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json versions.json", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/hexWfc.test.ts tests/worldgenGenerators.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/hexWfc.test.ts tests/worldgenGenerators.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts" diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index 3744aa37..4404c6ad 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -46,6 +46,9 @@ export const SETTING_KEYS: Record = { edgeTerrain: "edge-terrain", lineWidth: "line-width", smoothing: "smoothing", + edgeSmoothing: "edge-smoothing", + speckSize: "speck-size", + keepRare: "keep-rare", symmetry: "symmetry", spacing: "spacing", connected: "connected", @@ -66,6 +69,9 @@ const SETTING_KINDS: Record = { edgeTerrain: "string", lineWidth: "number", smoothing: "number", + edgeSmoothing: "number", + speckSize: "number", + keepRare: "number", symmetry: "symmetry", spacing: "number", connected: "boolean", @@ -228,7 +234,8 @@ export function modelToMarkdown(model: HexWfcModel): string { " grid. 1 means as common there as anywhere; 3 means three times as common.", "- Frontmatter settings (optional): `feature-size`, `directional-bias`, `clumping`,", " `mix-strength`, `scatter`, `randomness`, `edge-strength`, `edge-terrain`,", - " `line-width`, `smoothing`, `symmetry`, `spacing`, `connected`, `impassable`,", + " `line-width`, `edge-smoothing`, `speck-size`, `keep-rare`, `symmetry`, `spacing`,", + " `connected`, `impassable`,", " `mix`, `counts` and `features`.", "", "## Terrains", diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index b07e3e33..05cdf7dd 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -29,8 +29,8 @@ export { type CountRange, } from "./model"; export { learnModel, measurePatches, measureLayout, SHAPE_THRESHOLDS, type LearnOptions, type TerrainAnalysis } from "./learn"; -export { solve, findViolation, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; -export { countPatches, type GridInfo } from "./post"; +export { solve, findViolation, cleanupStrengths, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; +export { countPatches, smoothEdges, removeSpecks, untouchableTerrains, type GridInfo } from "./post"; export { learnPaths, routePaths, type PathInput, type PathOutput } from "./paths"; export { modelToMarkdown, diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index 0d75126c..b8988dd0 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -122,8 +122,20 @@ export interface GeneratorSettings { edgeTerrain?: string; /** Thickness of line terrains: 0 = as learned, otherwise 1–3. */ lineWidth?: number; - /** 0–1: clean up lone specks and ragged edges after generating. */ + /** + * Legacy single knob (0–1): lone specks, plus ragged edges from 0.5. Used + * only while `edgeSmoothing` and `speckSize` are both 0. + */ smoothing?: number; + /** 0–1: trim one-hex protrusions and notches on patch edges. Leaves lone hexes alone. */ + edgeSmoothing?: number; + /** Remove patches of this many hexes or fewer (0 = off). */ + speckSize?: number; + /** + * 0–1 share of the example: terrains rarer than this are never smoothed or + * removed, so the odd rare hex survives. 0 = off. + */ + keepRare?: number; /** Mirror the map. Symmetric where the rules allow. */ symmetry?: Symmetry; /** Multiplier on learned spacing between scattered terrain (towns). 0 = off. */ @@ -151,6 +163,9 @@ export const DEFAULT_SETTINGS: Required = { edgeTerrain: "", lineWidth: 0, smoothing: 0, + edgeSmoothing: 0, + speckSize: 0, + keepRare: 0, symmetry: "none", spacing: 1, connected: false, diff --git a/packages/hex-wfc/src/post.ts b/packages/hex-wfc/src/post.ts index 320f7be4..1a6f2067 100644 --- a/packages/hex-wfc/src/post.ts +++ b/packages/hex-wfc/src/post.ts @@ -46,43 +46,62 @@ function fits( } /** - * Clean up lone specks and ragged edges: a hex with too few same-terrain - * neighbours takes its most common neighbouring terrain (if the rules allow). - * Strength 0–1 sets the number of passes and how lonely a hex must be. - * Scattered and line terrains are left alone (thin by nature). + * Terrains the clean-up passes never touch: scattered and line terrains + * (thin by nature), plus any terrain whose share of the example is below + * `keepRare`, so the odd rare hex survives smoothing. + */ +export function untouchableTerrains(model: HexWfcModel, keepRare = 0): Set { + const total = model.terrains.reduce((sum, t) => sum + Math.max(0, t.weight), 0) || 1; + return new Set( + model.terrains + .filter((t) => t.shape === "scatter" || t.shape === "line" || (keepRare > 0 && Math.max(0, t.weight) / total < keepRare)) + .map((t) => t.name), + ); +} + +/** Neighbour terrains around `key`, most common first, and how many match its own. */ +function neighbourTally(key: string, cells: Map, grid: GridInfo) { + const t = cells.get(key)!; + let same = 0; + const tally = new Map(); + for (const n of neighbourKeys(key, grid, cells)) { + const u = cells.get(n)!; + if (u === t) same++; + else tally.set(u, (tally.get(u) ?? 0) + 1); + } + return { same, others: [...tally].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) }; +} + +/** + * Tidy patch edges. A hex that belongs to a patch but sticks out of it + * (one same-terrain neighbour) or, from strength 0.5, sits in a notch (two) + * takes the surrounding terrain when that terrain outnumbers its own by two + * and the rules allow. Lone hexes (no same-terrain neighbour) are left to + * `removeSpecks`. Strength 0–1 also sets the number of passes (1–3). * Returns the number of hexes changed. */ -export function smooth( +export function smoothEdges( cells: Map, model: HexWfcModel, grid: GridInfo, strength: number, protect: Set, + keep: Set, rng: () => number, ): number { if (!(strength > 0)) return 0; const adj = adjacencyLookup(model); - const keepShape = new Set(model.terrains.filter((t) => t.shape === "scatter" || t.shape === "line").map((t) => t.name)); const passes = Math.ceil(Math.min(1, strength) * 3); - const lonely = strength >= 0.5 ? 1 : 0; // max same-terrain neighbours to count as a speck + const maxSame = strength >= 0.5 ? 2 : 1; let changed = 0; for (let p = 0; p < passes; p++) { let changedThisPass = 0; for (const key of shuffled([...cells.keys()], rng)) { - const t = cells.get(key)!; - if (protect.has(key) || keepShape.has(t)) continue; - const ns = neighbourKeys(key, grid, cells); - let same = 0; - const tally = new Map(); - for (const n of ns) { - const u = cells.get(n)!; - if (u === t) same++; - else tally.set(u, (tally.get(u) ?? 0) + 1); - } - if (same > lonely) continue; - const candidates = [...tally].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); - for (const [u, n] of candidates) { - if (n < 2) break; // need a real majority to switch to + if (protect.has(key) || keep.has(cells.get(key)!)) continue; + const { same, others } = neighbourTally(key, cells, grid); + if (same < 1 || same > maxSame) continue; + for (const [u, n] of others) { + if (n < same + 2) break; if (fits(key, u, cells, grid, adj)) { cells.set(key, u); changed++; @@ -96,6 +115,76 @@ export function smooth( return changed; } +/** + * Remove small patches: every patch of `maxSize` hexes or fewer is filled in + * from outside, hex by hex, with its most common neighbouring terrain the + * rules allow (at least two neighbours of it for a lone hex). Hexes that + * can't change are left. Returns the number of hexes changed. + */ +export function removeSpecks( + cells: Map, + model: HexWfcModel, + grid: GridInfo, + maxSize: number, + protect: Set, + keep: Set, +): number { + if (!(maxSize >= 1)) return 0; + const adj = adjacencyLookup(model); + let changed = 0; + for (let round = 0; round < 3; round++) { + let changedThisRound = 0; + for (const patch of patchesOf(cells, grid)) { + if (patch.keys.length > maxSize || keep.has(patch.terrain)) continue; + const inPatch = new Set(patch.keys); + for (const key of patch.keys) { + if (protect.has(key) || cells.get(key) !== patch.terrain) continue; + const tally = new Map(); + for (const n of neighbourKeys(key, grid, cells)) { + const u = cells.get(n)!; + if (!inPatch.has(n) && u !== patch.terrain) tally.set(u, (tally.get(u) ?? 0) + 1); + } + const others = [...tally].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); + for (const [u, n] of others) { + if (patch.keys.length === 1 && n < 2) break; + if (fits(key, u, cells, grid, adj)) { + cells.set(key, u); + changed++; + changedThisRound++; + break; + } + } + } + } + if (!changedThisRound) break; + } + return changed; +} + +/** Every same-terrain patch on the map. */ +function patchesOf(cells: Map, grid: GridInfo): { terrain: string; keys: string[] }[] { + const out: { terrain: string; keys: string[] }[] = []; + const seen = new Set(); + for (const [key, t] of cells) { + if (seen.has(key)) continue; + const keys: string[] = []; + const stack = [key]; + seen.add(key); + while (stack.length) { + const k = stack.pop()!; + keys.push(k); + for (const n of neighbourKeys(k, grid, cells)) { + if (!seen.has(n) && cells.get(n) === t) { + seen.add(n); + stack.push(n); + } + } + } + out.push({ terrain: t, keys }); + } + return out; +} + /** Connected groups of hexes for which `inGroup` is true. */ function components(cells: Map, grid: GridInfo, inGroup: (t: string) => boolean): string[][] { const seen = new Set(); diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 6cfc317e..3e0744e5 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -31,7 +31,28 @@ import { import { mulberry32 } from "./rng"; import { placeFeatures, placeEdgeBorder } from "./features"; import { routePaths, type PathOutput } from "./paths"; -import { smooth, connectLand, countPatches, countsPenalty, topUpCounts, type GridInfo } from "./post"; +import { + smoothEdges, + removeSpecks, + untouchableTerrains, + connectLand, + countPatches, + countsPenalty, + topUpCounts, + type GridInfo, +} from "./post"; + +/** + * Edge smoothing and speck size to apply. A generator saved before these were + * split only has the legacy `smoothing` knob: any value removed lone specks, + * and 0.5 or more also tidied edges. + */ +export function cleanupStrengths(s: Required): { edges: number; speckSize: number } { + if (s.edgeSmoothing > 0 || s.speckSize > 0 || !(s.smoothing > 0)) { + return { edges: s.edgeSmoothing, speckSize: Math.floor(s.speckSize) }; + } + return { edges: s.smoothing >= 0.5 ? s.smoothing : 0, speckSize: 1 }; +} export interface SolveOptions extends GeneratorSettings { cols: number; @@ -190,7 +211,10 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { const protect = new Set([...toCellMap(opts.fixed ?? {}).keys(), ...featureCells]); const cells = core.cells; - total.postChanges += smooth(cells, model, grid, s.smoothing, protect, rng); + const keep = untouchableTerrains(model, s.keepRare); + const { edges, speckSize } = cleanupStrengths(s); + total.postChanges += smoothEdges(cells, model, grid, edges, protect, keep, rng); + total.postChanges += removeSpecks(cells, model, grid, speckSize, protect, keep); let penalty = 0; if (s.connected && impassable.size) { const { changed, stranded } = connectLand(cells, model, grid, impassable, protect); diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 551fdadc..437870ac 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -4,7 +4,7 @@ * file's frontmatter) with a live preview, and create a new map from it. */ -import { App, Notice } from "obsidian"; +import { App, Notice, setIcon } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import { VIEW_TYPE_HEX_MAP } from "../constants"; import type { HexMapView } from "../hex-map/HexMapView"; @@ -21,8 +21,11 @@ import { type GeneratorFile, } from "./generators"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; +import { makeScrubbable } from "./scrub"; +import { exampleShares, formatShare, formatShareChange, hasTerrainTweaks, terrainShares, withoutTerrainTweaks } from "./shares"; import { resolveSettings, + cleanupStrengths, randomSeed, SYMMETRIES, type GeneratorSettings, @@ -47,6 +50,7 @@ export class GeneratorPanel { static selectedPath = ""; static mapName = ""; static paletteName = ""; + static seedLocked = false; private seed = randomSeed(); private previewCols = 30; private previewRows = 20; @@ -79,9 +83,14 @@ export class GeneratorPanel { return this.plugin.getPaletteByName(GeneratorPanel.paletteName)?.terrains.map((t) => t.name) ?? []; } - render(el: HTMLElement): void { - el.empty(); - el.addClass("duckmage-wfc-tab"); + render(root: HTMLElement): void { + root.empty(); + root.addClass("duckmage-wfc-tab"); + // Controls on the left; the preview sits in a column that stays in view + // while the controls scroll (stacked above them on narrow panes). + const layout = root.createDiv({ cls: "duckmage-wfc-layout" }); + const el = layout.createDiv({ cls: "duckmage-wfc-main" }); + const side = layout.createDiv({ cls: "duckmage-wfc-side" }); el.createEl("h3", { text: "Terrain generator" }); this.renderRegion(el); this.renderLearn(el); @@ -104,15 +113,16 @@ export class GeneratorPanel { const show = () => { GeneratorPanel.selectedPath = select.value; body.empty(); + side.empty(); const g = current(); openBtn.disabled = !g; relearnBtn.disabled = !g?.model.meta["source-map"]; - if (g) this.renderGenerator(body, g); - else - body.createEl("p", { - text: generators.length ? "No generators for this palette yet." : "No generators yet. Pick a region above and learn from it.", - cls: "duckmage-map-origin-desc", - }); + if (g) this.renderGenerator(body, side, g); + else { + const text = generators.length ? "No generators for this palette yet." : "No generators yet. Pick a region and learn from it."; + body.createEl("p", { text, cls: "duckmage-map-origin-desc" }); + side.createEl("p", { text: "Pick a generator to preview it here.", cls: "duckmage-map-origin-desc" }); + } }; const fill = () => { const names = this.paletteTerrains(); @@ -220,7 +230,7 @@ export class GeneratorPanel { // ── One generator ──────────────────────────────────────────────────────── - private renderGenerator(el: HTMLElement, g: GeneratorFile): void { + private renderGenerator(el: HTMLElement, side: HTMLElement, g: GeneratorFile): void { const { model } = g; const colors = paletteColors(this.plugin, GeneratorPanel.paletteName); // One short line; the per-shape breakdown is on hover. @@ -250,14 +260,31 @@ export class GeneratorPanel { schedulePreview(); }; - // Preview - const previewBox = el.createDiv({ cls: "duckmage-wfc-section" }); + // Preview (in the sticky side column) + const previewBox = side.createDiv({ cls: "duckmage-wfc-section" }); + previewBox.createEl("h4", { text: "Preview" }); const canvas = previewBox.createEl("canvas", { cls: "duckmage-wfc-preview" }); const status = previewBox.createEl("p", { cls: "duckmage-map-origin-desc" }); const previewRow = previewBox.createDiv({ cls: "duckmage-region-row" }); previewRow.createSpan({ text: "Seed", cls: "duckmage-map-origin-label" }); const seedInput = previewRow.createEl("input", { type: "number", value: String(this.seed), cls: "duckmage-wfc-seed" }); - const rerollBtn = previewRow.createEl("button", { text: "Re-roll" }); + // Locked: the button regenerates with the same seed, so a settings change + // can be compared on the same map (large maps don't preview on their own). + const lockBtn = previewRow.createEl("button", { cls: "clickable-icon duckmage-wfc-lock" }); + const rerollBtn = previewRow.createEl("button"); + const showLock = () => { + const locked = GeneratorPanel.seedLocked; + setIcon(lockBtn, locked ? "lock" : "lock-open"); + lockBtn.toggleClass("is-active", locked); + lockBtn.setAttr("aria-pressed", String(locked)); + lockBtn.setAttr("aria-label", locked ? "Seed locked: regenerate keeps it" : "Lock the seed"); + rerollBtn.setText(locked ? "Regenerate" : "Re-roll"); + }; + lockBtn.addEventListener("click", () => { + GeneratorPanel.seedLocked = !GeneratorPanel.seedLocked; + showLock(); + schedulePreview(); + }); previewRow.createSpan({ text: "Size", cls: "duckmage-map-origin-label" }); const colsInput = previewRow.createEl("input", { type: "number", value: String(this.previewCols), cls: "duckmage-wfc-num" }); previewRow.createSpan({ text: "×" }); @@ -275,6 +302,36 @@ export class GeneratorPanel { stagger: map?.staggerOffset ?? this.plugin.settings.staggerOffset ?? "odd", }; }; + // Share readouts in the Advanced table, filled in further down. + const shareCells = new Map(); + let baseline: { key: string; shares: Map } | null = null; + /** + * Shares in the preview vs the same seed without per-terrain mix/counts, + * so the table shows what those settings change. The untweaked run is + * cached until something other than mix/counts changes. + */ + const updateShares = (cells: Map, grid: ReturnType, palette: string[]) => { + const now = terrainShares(cells); + let before = now; + if (hasTerrainTweaks(model)) { + const plain = withoutTerrainTweaks(model); + const key = JSON.stringify([this.seed, grid, palette, plain.settings]); + if (baseline?.key !== key) { + const b = generateTerrain(this.plugin, plain, palette, grid, this.seed); + baseline = { key, shares: b.ok ? terrainShares(b.cells) : now }; + } + before = baseline.shares; + } + for (const [name, cell] of shareCells) { + const n = now.get(name) ?? 0, b = before.get(name) ?? 0; + cell.now.setText(formatShare(n)); + const change = formatShareChange(n, b); + cell.change.setText(change); + cell.change.toggleClass("is-up", change.startsWith("+")); + cell.change.toggleClass("is-down", change.startsWith("−")); + cell.change.setAttr("title", change ? `${formatShare(b)} without its mix and min/max settings` : ""); + } + }; const runPreview = () => { const grid = previewGrid(); this.previewCols = grid.cols; @@ -286,7 +343,11 @@ export class GeneratorPanel { status.setText(`Couldn't generate: ${r.message}`); return; } - drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, r.paths, pathColors(this.plugin)); + // Draw at the side column's device-pixel width so it stays sharp when stretched. + const dpr = activeWindow.devicePixelRatio || 1; + drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, r.paths, pathColors(this.plugin), + Math.max(420, side.clientWidth) * dpr, 40 * dpr); + updateShares(r.cells, grid, palette); // Short: size and time, plus a hoverable count if anything didn't fit. status.setText(`${grid.cols}×${grid.rows} · ${r.stats.ms} ms${r.warnings.length ? ` · ⚠ ${r.warnings.length}` : ""}`); status.setAttr("title", r.warnings.join("\n")); @@ -294,7 +355,9 @@ export class GeneratorPanel { const schedulePreview = () => { if (this.previewTimer !== null) window.clearTimeout(this.previewTimer); if (Number(colsInput.value) * Number(rowsInput.value) > PREVIEW_AUTO_LIMIT) { - status.setText("Large map: re-roll to preview it."); + status.setText(GeneratorPanel.seedLocked + ? "Large map: press Regenerate to see your changes on this seed." + : "Large map: re-roll to preview it, or lock the seed to compare settings."); return; } this.previewTimer = window.setTimeout(() => { @@ -303,9 +366,10 @@ export class GeneratorPanel { }, 200); }; rerollBtn.addEventListener("click", () => { - seedInput.value = String(randomSeed()); + if (!GeneratorPanel.seedLocked) seedInput.value = String(randomSeed()); runPreview(); }); + showLock(); // Create a new map that is exactly the preview: same size, seed, palette and paths. createBtn.addEventListener("click", () => { const grid = previewGrid(); @@ -345,16 +409,34 @@ export class GeneratorPanel { }); }); for (const input of [seedInput, colsInput, rowsInput]) input.addEventListener("change", schedulePreview); + // Drag up/down on size and seed; the preview follows while dragging. + makeScrubbable(colsInput, { min: 2, max: 200, pxPerStep: 4 }); + makeScrubbable(rowsInput, { min: 2, max: 200, pxPerStep: 4 }); + makeScrubbable(seedInput, { min: 0, max: 0xffffffff, pxPerStep: 8 }); + for (const input of [seedInput, colsInput, rowsInput]) { + input.addEventListener("input", () => { + if (input.hasClass("is-scrubbing")) schedulePreview(); + }); + } // Shape this.heading(el, "Shape"); this.slider(el, "Feature size", "Size of each terrain's patches relative to the map. 1 = like the example; lower = more, smaller patches; 0 = no growth.", 0, 3, 0.25, s().featureSize, (v) => save({ featureSize: v })); + this.slider(el, "Clumping", "How strongly each hex follows its neighbours. 0 gives speckled noise.", 0, 6, 0.5, s().neighbourInfluence, (v) => save({ neighbourInfluence: v })); if (model.terrains.some((t) => t.shape === "line")) { const learnedWidth = Math.max(1, Math.round(Math.max(...model.terrains.filter((t) => t.shape === "line").map((t) => t.width ?? 1)))); this.slider(el, "Line width", "Thickness of line-shaped terrain, in hexes.", 1, 3, 1, s().lineWidth > 0 ? s().lineWidth : learnedWidth, (v) => save({ lineWidth: v })); } - this.slider(el, "Smoothing", "Clean up lone specks and ragged edges after generating.", 0, 1, 0.1, s().smoothing, (v) => save({ smoothing: v })); + // Clean-up after generating. Older generators only have one "smoothing" + // value; the sliders start from what it meant, and any change replaces it. + const cleanup = cleanupStrengths(s()); + this.slider(el, "Edge smoothing", "Trim one-hex bumps and notches along the edges of patches. Lone hexes are left alone.", 0, 1, 0.1, cleanup.edges, + (v) => save({ edgeSmoothing: v, speckSize: cleanupStrengths(s()).speckSize, smoothing: undefined })); + this.slider(el, "Remove small patches", "Fill in patches of this many hexes or fewer with the terrain around them. 0 = keep all.", 0, 6, 1, cleanup.speckSize, + (v) => save({ speckSize: v, edgeSmoothing: cleanupStrengths(s()).edges, smoothing: undefined })); + this.slider(el, "Keep rare terrain", "Terrains under this share of the example (%) are never smoothed or removed, so the odd rare hex survives.", 0, 20, 1, + Math.round(s().keepRare * 100), (v) => save({ keepRare: v / 100 })); this.select(el, "Symmetry", "Mirror the map. Symmetric wherever the rules allow.", SYMMETRIES.map((v) => [v, SYMMETRY_LABELS[v]]), s().symmetry, (v) => save({ symmetry: v })); this.select(el, "Edge style", "What the map border prefers: a terrain of your choice, or the example's border.", @@ -365,6 +447,7 @@ export class GeneratorPanel { // Placement this.heading(el, "Placement"); this.slider(el, "Directional bias", "0 = terrain goes anywhere. 1 = it keeps to where it was in the example.", 0, 1, 0.05, s().directionalBias, (v) => save({ directionalBias: v })); + this.slider(el, "Scatter", "Randomness in where patches start. Too low and one terrain can take over the map.", 0, 6, 0.5, s().scatter, (v) => save({ scatter: v })); if (model.terrains.some((t) => t.shape === "scatter")) { this.slider(el, "Spacing", "How far apart single-hex terrain stays, relative to the example. 0 = no spacing.", 0, 3, 0.25, s().spacing, (v) => save({ spacing: v })); } @@ -378,25 +461,37 @@ export class GeneratorPanel { this.toggle(el, "Connected land", "Fill cut-off pockets so every passable hex connects.", s().connected, (v) => save({ connected: v })); this.terrainFilter(el, "Impassable terrain", model.terrains.map((t) => t.name), colors, s().impassable, (list) => save({ impassable: list })); - // Advanced: per-terrain controls and tuning - const adv = el.createEl("details", { cls: "duckmage-wfc-section" }); - adv.createEl("summary", { text: "Advanced" }); - adv.createEl("p", { - text: "Mix scales how common each terrain is. Min and max limit how many separate patches it forms; leave blank for no limit.", + // Terrain mix: per-terrain controls and what they do to the preview + this.heading(el, "Terrain mix"); + el.createEl("p", { + text: "Mix scales how common each terrain is. Min and max limit how many separate patches it forms; leave blank for no limit. Example is each terrain's share of the region it was learned from; Map is its share of the preview, with the change your mix and min/max make to it.", cls: "duckmage-map-origin-desc", }); - const table = adv.createDiv({ cls: "duckmage-wfc-terrains" }); + const table = el.createDiv({ cls: "duckmage-wfc-terrains" }); const head = table.createDiv({ cls: "duckmage-wfc-terrain-row duckmage-wfc-terrain-head" }); - for (const h of ["Terrain", "Shape", "Mix", "Min", "Max"]) head.createSpan({ text: h }); + const headings: [string, string][] = [ + ["Terrain", ""], + ["Mix", ""], + ["Min", "Fewest separate patches"], + ["Max", "Most separate patches"], + ["Example", "Share of the region this generator was learned from"], + ["Map", "Share of the preview; the change is what mix and min/max add or remove (same seed)"], + ]; + for (const [h, title] of headings) head.createSpan({ text: h, attr: title ? { title } : {} }); + const example = exampleShares(model); const mix = { ...s().mix }; const counts: Record = Object.fromEntries(Object.entries(s().counts).map(([k, r]) => [k, { ...r }])); for (const t of model.terrains) { const row = table.createDiv({ cls: "duckmage-wfc-terrain-row" }); - const nameCell = row.createSpan({ cls: "duckmage-wfc-terrain-name" }); + // Guaranteed line features are laid down before the solver runs, so + // mix barely changes how much of them there is. + const isFeature = model.features?.some((f) => f.terrain === t.name) ?? false; + const title = `${t.name} (${t.shape ?? "no"} shape)` + (isFeature ? ". Placed as a guaranteed feature, so mix has little effect." : ""); + const nameCell = row.createSpan({ cls: "duckmage-wfc-terrain-name", attr: { title } }); const swatch = nameCell.createSpan({ cls: "duckmage-wfc-swatch" }); swatch.setCssProps({ "--duckmage-wfc-swatch": colors.get(t.name) ?? "var(--background-modifier-border)" }); nameCell.createSpan({ text: t.name }); - row.createSpan({ text: t.shape ?? "none", cls: "duckmage-map-origin-desc" }); + if (isFeature) nameCell.createSpan({ text: "feature", cls: "duckmage-wfc-tag" }); const mixCell = row.createSpan({ cls: "duckmage-wfc-mix" }); const mixSlider = mixCell.createEl("input", { type: "range" }); mixSlider.min = "0"; @@ -424,10 +519,15 @@ export class GeneratorPanel { save({ counts: Object.keys(counts).length ? { ...counts } : undefined }); }); } + row.createSpan({ text: formatShare(example.get(t.name) ?? 0), cls: "duckmage-wfc-share" }); + const mapCell = row.createSpan({ cls: "duckmage-wfc-share" }); + shareCells.set(t.name, { + now: mapCell.createSpan({ text: "–" }), + change: mapCell.createSpan({ cls: "duckmage-wfc-share-change" }), + }); } - this.slider(adv, "Clumping", "How strongly each hex follows its neighbours. 0 gives speckled noise.", 0, 6, 0.5, s().neighbourInfluence, (v) => save({ neighbourInfluence: v })); - this.slider(adv, "Mix strength", "How closely the overall terrain mix follows the example.", 0, 4, 0.5, s().frequencyFeedback, (v) => save({ frequencyFeedback: v })); - this.slider(adv, "Scatter", "Randomness in where patches start. Too low and one terrain can take over the map.", 0, 6, 0.5, s().scatter, (v) => save({ scatter: v })); + + this.slider(el, "Mix strength", "How closely the overall terrain mix follows the example.", 0, 4, 0.5, s().frequencyFeedback, (v) => save({ frequencyFeedback: v })); const resetRow = el.createDiv({ cls: "duckmage-region-row" }); const resetBtn = resetRow.createEl("button", { text: "Reset settings to defaults" }); diff --git a/src/worldgen/preview.ts b/src/worldgen/preview.ts index f74979ba..158f3ed6 100644 --- a/src/worldgen/preview.ts +++ b/src/worldgen/preview.ts @@ -25,6 +25,8 @@ export function drawPreview( paths: { type: string; hexes: string[] }[] = [], pathColors: Map = new Map(), maxWidth = 420, + /** Largest hex size in canvas pixels (keeps tiny maps from ballooning). */ + maxScale = 14, ): void { const { cols, rows, offset, stagger } = grid; // Hex centres in unit space (neighbours √3 apart, circumradius 1). @@ -39,7 +41,7 @@ export function drawPreview( minY = Math.min(minY, py); maxY = Math.max(maxY, py); } const spanX = maxX - minX + 2, spanY = maxY - minY + 2; - const scale = Math.max(1, Math.min(maxWidth / spanX, 14)); + const scale = Math.max(1, Math.min(maxWidth / spanX, maxScale)); canvas.width = Math.ceil(spanX * scale); canvas.height = Math.ceil(spanY * scale); const ctx = canvas.getContext("2d"); diff --git a/src/worldgen/scrub.ts b/src/worldgen/scrub.ts new file mode 100644 index 00000000..05aa9fb2 --- /dev/null +++ b/src/worldgen/scrub.ts @@ -0,0 +1,74 @@ +/** + * Drag up or down on a number input to change it (like a DCC "scrubber"). + * A plain click still focuses the input for typing. + */ + +export interface ScrubOptions { + min: number; + max: number; + step?: number; + /** Pixels of drag per step. */ + pxPerStep?: number; +} + +/** Value after dragging `dy` pixels (negative = up = bigger) from `start`. */ +export function scrubValue(start: number, dy: number, { min, max, step = 1, pxPerStep = 6 }: ScrubOptions): number { + const v = start + Math.round(-dy / pxPerStep) * step; + return Math.max(min, Math.min(max, v)); +} + +/** Movement before a press counts as a drag rather than a click. */ +const DRAG_THRESHOLD = 3; + +/** + * Make `input` scrubbable. Fires "input" on every step and "change" when the + * drag ends, the same events typing would fire. + */ +export function makeScrubbable(input: HTMLInputElement, opts: ScrubOptions): void { + input.addClass("duckmage-scrub"); + input.setAttr("title", "Drag up or down to change, or click to type"); + let startY = 0; + let startValue = 0; + let dragging = false; + let pressed = false; + + input.addEventListener("pointerdown", (e: PointerEvent) => { + if (e.button !== 0 || input.ownerDocument.activeElement === input) return; + pressed = true; + dragging = false; + startY = e.clientY; + startValue = Number(input.value) || 0; + try { + input.setPointerCapture(e.pointerId); + } catch { + // Not an active pointer (e.g. a synthetic event); dragging still works inside the input. + } + // Don't focus yet: a drag shouldn't leave a text cursor behind. + e.preventDefault(); + }); + input.addEventListener("pointermove", (e: PointerEvent) => { + if (!pressed) return; + const dy = e.clientY - startY; + if (!dragging && Math.abs(dy) < DRAG_THRESHOLD) return; + dragging = true; + input.addClass("is-scrubbing"); + const next = String(scrubValue(startValue, dy, opts)); + if (next !== input.value) { + input.value = next; + input.dispatchEvent(new Event("input", { bubbles: true })); + } + }); + const end = (e: PointerEvent) => { + if (!pressed) return; + pressed = false; + if (input.hasPointerCapture(e.pointerId)) input.releasePointerCapture(e.pointerId); + input.removeClass("is-scrubbing"); + if (dragging) input.dispatchEvent(new Event("change", { bubbles: true })); + else { + input.focus(); + input.select(); + } + }; + input.addEventListener("pointerup", end); + input.addEventListener("pointercancel", end); +} diff --git a/src/worldgen/shares.ts b/src/worldgen/shares.ts new file mode 100644 index 00000000..ad2dbf1c --- /dev/null +++ b/src/worldgen/shares.ts @@ -0,0 +1,47 @@ +/** + * Terrain shares for the generator page: how much of a map each terrain + * covers, so the Advanced table can show what a mix or count change does. + */ + +import type { HexWfcModel } from "../../packages/hex-wfc/src"; + +/** Fraction of hexes (0–1) per terrain in a generated map. */ +export function terrainShares(cells: Map): Map { + const counts = new Map(); + for (const t of cells.values()) counts.set(t, (counts.get(t) ?? 0) + 1); + const total = cells.size || 1; + return new Map([...counts].map(([t, n]) => [t, n / total])); +} + +/** The learned mix: each terrain's weight as a fraction of all weights. */ +export function exampleShares(model: HexWfcModel): Map { + const total = model.terrains.reduce((sum, t) => sum + Math.max(0, t.weight), 0) || 1; + return new Map(model.terrains.map((t) => [t.name, Math.max(0, t.weight) / total])); +} + +/** True when the model has per-terrain mix or count settings. */ +export function hasTerrainTweaks(model: HexWfcModel): boolean { + const s = model.settings ?? {}; + return Object.keys(s.mix ?? {}).length > 0 || Object.keys(s.counts ?? {}).length > 0; +} + +/** The same model with per-terrain mix and counts dropped (everything else kept). */ +export function withoutTerrainTweaks(model: HexWfcModel): HexWfcModel { + const settings = { ...(model.settings ?? {}) }; + delete settings.mix; + delete settings.counts; + return { ...model, settings }; +} + +/** "12%", or "<1%" for a terrain that's present but rare. */ +export function formatShare(share: number): string { + if (share > 0 && share < 0.005) return "<1%"; + return `${Math.round(share * 100)}%`; +} + +/** Change in percentage points, e.g. "+6", "−3", or "" when it rounds to 0. */ +export function formatShareChange(now: number, before: number): string { + const d = Math.round((now - before) * 100); + if (d === 0) return ""; + return d > 0 ? `+${d}` : `−${-d}`; +} diff --git a/styles.css b/styles.css index b26ae083..e611ef93 100644 --- a/styles.css +++ b/styles.css @@ -5155,7 +5155,8 @@ tr:hover .duckmage-rt-entry-copy-btn:hover { .duckmage-wfc-terrain-row { display: grid; - grid-template-columns: minmax(8em, 1.5fr) 5em minmax(9em, 2fr) 4.5em 4.5em; + /* Terrain, Mix, Min, Max, Example, Map */ + grid-template-columns: minmax(7em, 1.3fr) minmax(8em, 2fr) 3.75em 3.75em 3.5em 5.5em; align-items: center; gap: 0.5em; } @@ -5228,8 +5229,67 @@ button.duckmage-wfc-chip { } .duckmage-wfc-page .duckmage-wfc-tab { - max-width: 760px; + max-width: 1280px; margin: 0 auto; + container-type: inline-size; +} + +/* Controls left, preview right. The preview column sticks to the top of the + scrolling view so changes made far down the page are visible right away. */ +.duckmage-wfc-layout { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(280px, 42%); + gap: 2em; + align-items: start; +} + +.duckmage-wfc-side { + position: sticky; + top: 0; + max-height: 100vh; + overflow-y: auto; +} + +.duckmage-wfc-side .duckmage-wfc-preview { + width: 100%; +} + +/* Narrow panes: one column, preview first and not sticky. */ +@container (max-width: 760px) { + .duckmage-wfc-layout { + grid-template-columns: minmax(0, 1fr); + } + + .duckmage-wfc-side { + position: static; + max-height: none; + order: -1; + } +} + +.duckmage-wfc-share { + text-align: right; + font-variant-numeric: tabular-nums; +} + +.duckmage-wfc-tag { + flex: none; + font-size: 0.75em; + color: var(--text-faint); +} + +.duckmage-wfc-share-change { + margin-left: 0.35em; + font-size: 0.85em; + color: var(--text-muted); +} + +.duckmage-wfc-share-change.is-up { + color: var(--color-green); +} + +.duckmage-wfc-share-change.is-down { + color: var(--color-red); } .duckmage-wfc-regions { @@ -5237,3 +5297,24 @@ button.duckmage-wfc-chip { overflow-y: auto; margin-bottom: 0.5em; } + +/* Drag-to-change number inputs (src/worldgen/scrub.ts). Spinners are hidden: + dragging replaces them, and a click focuses the field for typing. */ +.duckmage-scrub:not(:focus) { + cursor: ns-resize; +} + +.duckmage-scrub::-webkit-inner-spin-button, +.duckmage-scrub::-webkit-outer-spin-button { + -webkit-appearance: none; + margin: 0; +} + +.duckmage-scrub.is-scrubbing { + cursor: ns-resize; + border-color: var(--interactive-accent); +} + +.duckmage-wfc-lock.is-active { + color: var(--interactive-accent); +} diff --git a/tests/hexWfcCleanup.test.ts b/tests/hexWfcCleanup.test.ts new file mode 100644 index 00000000..36aac208 --- /dev/null +++ b/tests/hexWfcCleanup.test.ts @@ -0,0 +1,116 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + cellKey, + cleanupStrengths, + hexNeighbors, + removeSpecks, + resolveSettings, + smoothEdges, + untouchableTerrains, + type HexWfcModel, +} from "../packages/hex-wfc/src"; + +/** + * The clean-up passes that replaced the single "smoothing" knob: edge + * smoothing, small-patch removal, and keeping rare terrain. + */ + +const grid = { cols: 12, rows: 12, ox: 0, oy: 0, orientation: "flat" as const, stagger: "odd" as const }; +const names = ["Grass", "Forest", "Water", "Gem"]; +// Every pair may touch, so only the passes' own rules decide what changes. +const model: HexWfcModel = { + name: "t", + meta: {}, + terrains: [ + { name: "Grass", weight: 80 }, + { name: "Forest", weight: 10 }, + { name: "Water", weight: 9 }, + { name: "Gem", weight: 1 }, + ], + adjacency: names.flatMap((a) => names.map((b) => ({ a, b, weight: 1 }))), +}; +const rng = () => 0.5; +const neighbours = (k: string) => { + const [x, y] = k.split("_").map(Number); + return hexNeighbors(x, y, "flat", "odd").map(([nx, ny]) => cellKey(nx, ny)); +}; + +/** All grass, with a 7-hex water blob around 3_3, a 2-hex forest, a lone forest and a lone gem. */ +function sample(): Map { + const cells = new Map(); + for (let x = 0; x < grid.cols; x++) for (let y = 0; y < grid.rows; y++) cells.set(cellKey(x, y), "Grass"); + for (const k of [cellKey(3, 3), ...neighbours(cellKey(3, 3))]) cells.set(k, "Water"); + cells.set(cellKey(8, 2), "Forest"); + cells.set(cellKey(8, 3), "Forest"); + cells.set(cellKey(8, 8), "Forest"); + cells.set(cellKey(3, 9), "Gem"); + return cells; +} + +const count = (cells: Map, t: string) => [...cells.values()].filter((v) => v === t).length; + +describe("removeSpecks", () => { + it("fills patches up to the size and keeps bigger ones", () => { + const cells = sample(); + removeSpecks(cells, model, grid, 2, new Set(), new Set()); + expect(count(cells, "Forest")).toBe(0); + expect(count(cells, "Gem")).toBe(0); + expect(count(cells, "Water")).toBe(7); + }); + + it("size 1 only clears lone hexes", () => { + const cells = sample(); + removeSpecks(cells, model, grid, 1, new Set(), new Set()); + expect(count(cells, "Forest")).toBe(2); + expect(count(cells, "Gem")).toBe(0); + }); + + it("leaves kept terrains and protected hexes", () => { + const cells = sample(); + removeSpecks(cells, model, grid, 3, new Set([cellKey(8, 8)]), new Set(["Gem"])); + expect(cells.get(cellKey(3, 9))).toBe("Gem"); + expect(cells.get(cellKey(8, 8))).toBe("Forest"); + expect(cells.get(cellKey(8, 2))).toBe("Grass"); + }); +}); + +describe("smoothEdges", () => { + it("trims a one-hex bump but leaves lone hexes to removeSpecks", () => { + const cells = sample(); + const blob = new Set([cellKey(3, 3), ...neighbours(cellKey(3, 3))]); + // A grass hex touching exactly one blob hex becomes a one-hex bump. + const bump = [...cells.keys()].find( + (k) => !blob.has(k) && neighbours(k).filter((n) => blob.has(n)).length === 1 && neighbours(k).length === 6, + )!; + cells.set(bump, "Water"); + smoothEdges(cells, model, grid, 0.4, new Set(), new Set(), rng); + expect(cells.get(bump)).toBe("Grass"); + expect(count(cells, "Water")).toBe(7); + expect(cells.get(cellKey(8, 8))).toBe("Forest"); + expect(cells.get(cellKey(3, 9))).toBe("Gem"); + }); +}); + +describe("untouchableTerrains", () => { + it("keeps terrains under the rare share, plus scatter and line shapes", () => { + expect([...untouchableTerrains(model, 0)]).toEqual([]); + expect([...untouchableTerrains(model, 0.05)]).toEqual(["Gem"]); + expect([...untouchableTerrains(model, 0.095)].sort()).toEqual(["Gem", "Water"]); + const shaped: HexWfcModel = { ...model, terrains: model.terrains.map((t) => (t.name === "Forest" ? { ...t, shape: "line" } : t)) }; + expect([...untouchableTerrains(shaped, 0)]).toEqual(["Forest"]); + }); +}); + +describe("cleanupStrengths", () => { + const at = (settings: HexWfcModel["settings"]) => cleanupStrengths(resolveSettings({ ...model, settings })); + it("maps the legacy smoothing knob", () => { + expect(at({})).toEqual({ edges: 0, speckSize: 0 }); + expect(at({ smoothing: 0.3 })).toEqual({ edges: 0, speckSize: 1 }); + expect(at({ smoothing: 0.7 })).toEqual({ edges: 0.7, speckSize: 1 }); + }); + it("uses the split settings once any is set", () => { + expect(at({ smoothing: 0.7, edgeSmoothing: 0.4 })).toEqual({ edges: 0.4, speckSize: 0 }); + expect(at({ speckSize: 3 })).toEqual({ edges: 0, speckSize: 3 }); + }); +}); diff --git a/tests/worldgenScrub.test.ts b/tests/worldgenScrub.test.ts new file mode 100644 index 00000000..dfa1c091 --- /dev/null +++ b/tests/worldgenScrub.test.ts @@ -0,0 +1,17 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { scrubValue } from "../src/worldgen/scrub"; + +describe("scrubValue", () => { + const opts = { min: 2, max: 200, pxPerStep: 4 }; + it("dragging up raises the value, down lowers it", () => { + expect(scrubValue(30, -40, opts)).toBe(40); + expect(scrubValue(30, 40, opts)).toBe(20); + expect(scrubValue(30, 1, opts)).toBe(30); + }); + it("clamps to the range and honours the step", () => { + expect(scrubValue(30, -4000, opts)).toBe(200); + expect(scrubValue(30, 4000, opts)).toBe(2); + expect(scrubValue(10, -12, { min: 0, max: 100, step: 5, pxPerStep: 6 })).toBe(20); + }); +}); diff --git a/tests/worldgenShares.test.ts b/tests/worldgenShares.test.ts new file mode 100644 index 00000000..bfd56753 --- /dev/null +++ b/tests/worldgenShares.test.ts @@ -0,0 +1,53 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + exampleShares, + formatShare, + formatShareChange, + hasTerrainTweaks, + terrainShares, + withoutTerrainTweaks, +} from "../src/worldgen/shares"; +import type { HexWfcModel } from "../packages/hex-wfc/src"; + +const model: HexWfcModel = { + name: "m", + meta: {}, + terrains: [ + { name: "Grass", weight: 3 }, + { name: "Mountain", weight: 1 }, + { name: "Never", weight: 0 }, + ], + adjacency: [], + settings: { mix: { Mountain: 2 }, counts: { Mountain: { min: 1 } }, randomness: 0.3 }, +}; + +describe("generator terrain shares", () => { + it("measures each terrain's share of a map", () => { + const cells = new Map([["0_0", "Grass"], ["1_0", "Grass"], ["2_0", "Grass"], ["3_0", "Mountain"]]); + expect(Object.fromEntries(terrainShares(cells))).toEqual({ Grass: 0.75, Mountain: 0.25 }); + expect(terrainShares(new Map()).size).toBe(0); + }); + + it("reads the learned mix from the weights", () => { + expect(Object.fromEntries(exampleShares(model))).toEqual({ Grass: 0.75, Mountain: 0.25, Never: 0 }); + }); + + it("drops only mix and counts for the comparison run", () => { + expect(hasTerrainTweaks(model)).toBe(true); + const plain = withoutTerrainTweaks(model); + expect(plain.settings).toEqual({ randomness: 0.3 }); + expect(hasTerrainTweaks(plain)).toBe(false); + expect(model.settings?.mix).toEqual({ Mountain: 2 }); + expect(hasTerrainTweaks({ ...model, settings: { mix: {}, counts: {} } })).toBe(false); + }); + + it("formats shares and changes in percentage points", () => { + expect(formatShare(0.104)).toBe("10%"); + expect(formatShare(0.003)).toBe("<1%"); + expect(formatShare(0)).toBe("0%"); + expect(formatShareChange(0.16, 0.1)).toBe("+6"); + expect(formatShareChange(0.07, 0.1)).toBe("−3"); + expect(formatShareChange(0.101, 0.1)).toBe(""); + }); +}); From a33e212fad9b5a1b743c26a5d920adde5375d17a Mon Sep 17 00:00:00 2001 From: nyxsys Date: Wed, 7 Oct 2026 20:46:09 -0400 Subject: [PATCH 015/558] feat(worldgen): default impassable terrain to shallows, ocean and trench Generators that have never saved an impassable list now treat their terrains named shallows/ocean/trench (any case) as impassable, so "Connected land" works without setup. A saved list, including an empty one, still wins. Applied in generateTerrain and shown on the page via generatorSettings(). Co-Authored-By: Claude Opus 5.5 --- src/worldgen/GeneratorPanel.ts | 4 ++-- src/worldgen/generators.ts | 22 ++++++++++++++++++++++ tests/worldgenGenerators.test.ts | 25 +++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 437870ac..a9afad51 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -13,6 +13,7 @@ import { saveGeneratorFromMap, saveGeneratorSettings, generateTerrain, + generatorSettings, generatorFitsPalette, paletteColors, pathColors, @@ -24,7 +25,6 @@ import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; import { makeScrubbable } from "./scrub"; import { exampleShares, formatShare, formatShareChange, hasTerrainTweaks, terrainShares, withoutTerrainTweaks } from "./shares"; import { - resolveSettings, cleanupStrengths, randomSeed, SYMMETRIES, @@ -246,7 +246,7 @@ export class GeneratorPanel { summary.setAttr("title", [...detail, ...g.warnings].join("\n")); // Current settings, kept in sync with the file. - const s = () => resolveSettings(model); + const s = () => generatorSettings(model); const save = (patch: Partial>) => { const next: Record = { ...(model.settings ?? {}) }; for (const [k, v] of Object.entries(patch)) { diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index 8b58cd32..36cf13ae 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -27,6 +27,7 @@ import { type HexWfcModel, type SolveResult, type GeneratorSettings, + resolveSettings, } from "../../packages/hex-wfc/src"; /** Frontmatter key that keeps a hex's terrain when a map is regenerated. */ @@ -205,6 +206,26 @@ export interface GridSpec { stagger: "odd" | "even"; } +/** Terrain names treated as impassable until a generator sets its own list. */ +export const DEFAULT_IMPASSABLE = ["shallows", "ocean", "trench"]; + +/** + * Impassable terrains for a generator that has never saved the setting: its + * terrains named like DEFAULT_IMPASSABLE (any case), so "Connected land" + * works out of the box. Once the generator saves a list (even an empty one), + * that list is used instead. + */ +export function defaultImpassable(model: HexWfcModel): string[] | undefined { + if (model.settings?.impassable !== undefined) return undefined; + return model.terrains.map((t) => t.name).filter((n) => DEFAULT_IMPASSABLE.includes(n.toLowerCase())); +} + +/** Saved settings with the plugin's defaults filled in (see defaultImpassable). */ +export function generatorSettings(model: HexWfcModel): Required { + const impassable = defaultImpassable(model); + return resolveSettings(model, impassable ? { impassable } : {}); +} + /** * Run a generator on a grid. Terrains the palette lacks are dropped from the * generator first. Fixed hexes whose terrain the generator doesn't know are @@ -239,6 +260,7 @@ export function generateTerrain( stagger: grid.stagger, seed, fixed, + ...(defaultImpassable(model) ? { impassable: defaultImpassable(model) } : {}), }); } diff --git a/tests/worldgenGenerators.test.ts b/tests/worldgenGenerators.test.ts index 888f38c0..4b42b0f8 100644 --- a/tests/worldgenGenerators.test.ts +++ b/tests/worldgenGenerators.test.ts @@ -11,6 +11,8 @@ import { saveGeneratorSettings, generateTerrain, fillMap, + defaultImpassable, + generatorSettings, } from "../src/worldgen/generators"; import { findViolation, parseModelMarkdown, type HexWfcModel } from "../packages/hex-wfc/src"; import type HexmakerPlugin from "../src/HexmakerPlugin"; @@ -235,3 +237,26 @@ describe("fill this map", () => { expect(findViolation(model, cells, "flat")).toBeNull(); }); }); + +describe("default impassable terrain", () => { + const base: HexWfcModel = { + name: "d", + meta: {}, + terrains: ["Grass", "Shallows", "ocean", "TRENCH", "Hills"].map((name) => ({ name, weight: 1 })), + adjacency: [], + }; + + it("uses the generator's shallows, ocean and trench, in any case", () => { + expect(defaultImpassable(base)).toEqual(["Shallows", "ocean", "TRENCH"]); + expect(generatorSettings(base).impassable).toEqual(["Shallows", "ocean", "TRENCH"]); + }); + + it("only covers terrains the generator has", () => { + expect(defaultImpassable({ ...base, terrains: [{ name: "Grass", weight: 1 }] })).toEqual([]); + }); + + it("steps aside once the generator saves its own list, even an empty one", () => { + expect(defaultImpassable({ ...base, settings: { impassable: ["Hills"] } })).toBeUndefined(); + expect(generatorSettings({ ...base, settings: { impassable: [] } }).impassable).toEqual([]); + }); +}); From 64e4fb90236858bdbdb73540e025ccc8a7590327 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Wed, 7 Oct 2026 21:03:45 -0400 Subject: [PATCH 016/558] feat(worldgen): Paths section with per-route on/off, count, wiggle, length, follow and draw-as MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The learned path count scales with map size (√ of hexes vs the example), so big maps quickly got far too many roads/rivers, with no way to tune them. - Library: GeneratorSettings.paths (per route, keyed "Type: from > to") with off / count (exact; unset = learned, scaled) / wiggle / length / follow / as, and drawPaths (unset follows the old `features` flag). routePaths applies them and reports per-route auto/wanted/placed (SolveResult.pathRoutes). Frontmatter: `draw-paths`, and `paths: "Road: edge > peak = count 2, wiggle 1.5, as Trade road"`. - Generator page: a Paths section with a Draw paths toggle and one card per route: on/off, Count (blank = "Auto (n)"; drag or scroll to change, live preview), draw-as path type, Placed "n of m" (orange when short), and Wiggle / Length / Follow terrain sliders. Hovering a card highlights its paths on the preview. "Guaranteed features" now covers terrain lines only. - Create map, Fill (regenerate) and the New map modal draw each route as its chosen path type. - Every number field on the page (seed, size, terrain min/max, path count) changes with the mouse wheel as well as by dragging. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- packages/hex-wfc/src/format.ts | 39 ++++++++- packages/hex-wfc/src/index.ts | 6 +- packages/hex-wfc/src/model.ts | 32 ++++++- packages/hex-wfc/src/paths.ts | 45 +++++++--- packages/hex-wfc/src/solve.ts | 22 ++++- src/hex-map/MapModal.ts | 4 +- src/worldgen/GeneratorPanel.ts | 149 +++++++++++++++++++++++++++++++-- src/worldgen/generators.ts | 18 ++-- src/worldgen/preview.ts | 9 +- src/worldgen/scrub.ts | 58 ++++++++++--- styles.css | 66 +++++++++++++++ tests/hexWfcPathTweaks.test.ts | 137 ++++++++++++++++++++++++++++++ 13 files changed, 540 insertions(+), 49 deletions(-) create mode 100644 tests/hexWfcPathTweaks.test.ts diff --git a/package.json b/package.json index 4ca35eb6..419956d0 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,8 @@ "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json versions.json", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index 4404c6ad..3ddb2a44 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -25,6 +25,7 @@ import { type GrowthShape, type Symmetry, type CountRange, + type PathTweak, type TerrainEntry, } from "./model"; @@ -32,7 +33,7 @@ export const FORMAT_VERSION = 1; const MARKER = "hex-wfc"; const EXAMPLE_KEY = "example-hexes"; -type SettingKind = "number" | "string" | "symmetry" | "boolean" | "list" | "mix" | "counts"; +type SettingKind = "number" | "string" | "symmetry" | "boolean" | "list" | "mix" | "counts" | "paths"; /** Frontmatter key for each saved solver setting. */ export const SETTING_KEYS: Record = { @@ -56,6 +57,8 @@ export const SETTING_KEYS: Record = { mix: "mix", counts: "counts", features: "features", + drawPaths: "draw-paths", + paths: "paths", }; const SETTING_KINDS: Record = { @@ -79,6 +82,8 @@ const SETTING_KINDS: Record = { mix: "mix", counts: "counts", features: "boolean", + drawPaths: "boolean", + paths: "paths", }; const num = (n: number) => String(Math.round(n * 1000) / 1000); @@ -109,6 +114,17 @@ export function encodeSetting(field: keyof GeneratorSettings, value: unknown): s return `${t} ${r.min ?? ""}-${r.max ?? ""}`; }) .join("; "); + case "paths": + return Object.entries(value as Record) + .map(([route, t]) => { + const opts: string[] = []; + if (t.off) opts.push("off"); + for (const k of ["count", "wiggle", "length", "follow"] as const) if (t[k] !== undefined) opts.push(`${k} ${num(t[k])}`); + if (t.as) opts.push(`as ${t.as}`); + return `${route} = ${opts.join(", ")}`; + }) + .filter((e) => !e.endsWith("= ")) + .join("; "); default: return String(value); } @@ -167,6 +183,24 @@ export function decodeSetting(field: keyof GeneratorSettings, raw: string): { va } return { value: out }; } + case "paths": { + const out: Record = {}; + for (const item of items()) { + const eq = item.indexOf(" = "); + if (eq < 0) return { error: `has "${item}"; write it like "Road: edge > peak = count 2, wiggle 1.5"` }; + const route = item.slice(0, eq).trim(); + const tweak: PathTweak = {}; + for (const part of item.slice(eq + 3).split(",").map((x) => x.trim()).filter(Boolean)) { + const m = /^(count|wiggle|length|follow) (\S+)$/.exec(part); + if (part === "off") tweak.off = true; + else if (part.startsWith("as ")) tweak.as = part.slice(3).trim(); + else if (m && Number.isFinite(Number(m[2])) && Number(m[2]) >= 0) tweak[m[1] as "count"] = Number(m[2]); + else return { error: `has "${part}" for ${route}; use off, count N, wiggle N, length N, follow N or as ` }; + } + out[route] = tweak; + } + return { value: out }; + } } } @@ -236,7 +270,8 @@ export function modelToMarkdown(model: HexWfcModel): string { " `mix-strength`, `scatter`, `randomness`, `edge-strength`, `edge-terrain`,", " `line-width`, `edge-smoothing`, `speck-size`, `keep-rare`, `symmetry`, `spacing`,", " `connected`, `impassable`,", - " `mix`, `counts` and `features`.", + " `mix`, `counts`, `features`, `draw-paths` and `paths` (per route, e.g.", + " `Road: edge > peak = count 2, wiggle 1.5, as Trade road`).", "", "## Terrains", "", diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index 05cdf7dd..5d0835c9 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -27,11 +27,13 @@ export { type PathFeature, type Symmetry, type CountRange, + type PathTweak, + pathRouteKey, } from "./model"; export { learnModel, measurePatches, measureLayout, SHAPE_THRESHOLDS, type LearnOptions, type TerrainAnalysis } from "./learn"; -export { solve, findViolation, cleanupStrengths, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; +export { solve, findViolation, cleanupStrengths, pathsEnabled, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; export { countPatches, smoothEdges, removeSpecks, untouchableTerrains, type GridInfo } from "./post"; -export { learnPaths, routePaths, type PathInput, type PathOutput } from "./paths"; +export { learnPaths, routePaths, type PathInput, type PathOutput, type RouteStat } from "./paths"; export { modelToMarkdown, parseModelMarkdown, diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index b8988dd0..a481ad34 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -94,6 +94,27 @@ export type Symmetry = "none" | "left-right" | "top-bottom" | "both"; export const SYMMETRIES: readonly Symmetry[] = ["none", "left-right", "top-bottom", "both"]; /** Min/max number of separate patches of a terrain (a town is a 1-hex patch). */ +/** Adjustments to one learned path route; anything unset is as learned. */ +export interface PathTweak { + /** Never place this route. */ + off?: boolean; + /** Exact number to place. Unset = learned count scaled to the map size. */ + count?: number; + /** Multiplier on how much it meanders. 0 = as straight as the terrain allows. */ + wiggle?: number; + /** Multiplier on its length (routes ending in "none", and edge-to-edge). */ + length?: number; + /** Multiplier on how strongly it keeps to the terrains it ran through. 0 = ignores terrain. */ + follow?: number; + /** Path type to draw it as on the map, instead of its learned type. */ + as?: string; +} + +/** Key that identifies a learned path route, e.g. "Road: edge > peak". */ +export function pathRouteKey(p: { type: string; from: string; to: string }): string { + return `${p.type}: ${p.from} > ${p.to}`; +} + export interface CountRange { min?: number; max?: number; @@ -148,8 +169,15 @@ export interface GeneratorSettings { mix?: Record; /** Per-terrain min/max number of separate patches. */ counts?: Record; - /** Lay down the model's guaranteed features and paths (rivers). */ + /** Lay down the model's guaranteed features (terrain lines such as a river painted as terrain). */ features?: boolean; + /** + * Draw the learned paths (roads, rivers drawn as paths) over the terrain. + * Unset: follows `features`, as before the two were split. + */ + drawPaths?: boolean; + /** Per-route adjustments, keyed by pathRouteKey(). */ + paths?: Record; } export const DEFAULT_SETTINGS: Required = { @@ -173,6 +201,8 @@ export const DEFAULT_SETTINGS: Required = { mix: {}, counts: {}, features: true, + drawPaths: true, + paths: {}, }; export interface AdjacencyEntry { diff --git a/packages/hex-wfc/src/paths.ts b/packages/hex-wfc/src/paths.ts index 253ebda4..35431320 100644 --- a/packages/hex-wfc/src/paths.ts +++ b/packages/hex-wfc/src/paths.ts @@ -11,7 +11,7 @@ */ import { hexNeighbors, hexDistance, directionRing, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; -import type { PathFeature } from "./model"; +import { pathRouteKey, type PathFeature, type PathTweak } from "./model"; import type { GridInfo } from "./post"; export interface PathInput { @@ -23,9 +23,21 @@ export interface PathInput { export interface PathOutput { type: string; + /** The learned route it came from (pathRouteKey). */ + route: string; hexes: string[]; } +/** How one learned route fared on a map. */ +export interface RouteStat { + route: string; + /** Learned count scaled to this map: what "auto" means. */ + auto: number; + /** How many were asked for (0 when the route is off). */ + wanted: number; + placed: number; +} + const MIN_PATH_HEXES = 3; /** Remove consecutive duplicates (repeat clicks). */ @@ -132,7 +144,8 @@ export function routePaths( grid: GridInfo, rng: () => number, sizeScale: number, -): { paths: PathOutput[]; warnings: string[] } { + tweaks: Record = {}, +): { paths: PathOutput[]; warnings: string[]; routes: RouteStat[] } { const { cols, rows, ox, oy, orientation, stagger } = grid; const N = cols * rows; const keyOf = (c: number) => cellKey(ox + (c % cols), oy + Math.floor(c / cols)); @@ -243,11 +256,16 @@ export function routePaths( // Parents before branches. const order = [...features].sort((a, b) => Number(a.from === "path") - Number(b.from === "path")); - for (const f of order) { + const routes: RouteStat[] = []; + for (const learned of order) { + const route = pathRouteKey(learned); + const tw = tweaks[route] ?? {}; + const f: PathFeature = { ...learned, length: learned.length * (tw.length ?? 1) }; + const follow = tw.follow ?? 1; // Cheap on terrains the example's path ran through (relative to how // common they are), plus smooth noise so routes wiggle like the example. - const pref = (t: string) => Math.log(((f.through[t] ?? 0) + 0.01) / ((share.get(t) ?? 0) + 0.01)); - const noiseAmp = 0.5 + 3 * f.turn; + const pref = (t: string) => follow * Math.log(((f.through[t] ?? 0) + 0.01) / ((share.get(t) ?? 0) + 0.01)); + const noiseAmp = (0.5 + 3 * f.turn) * (tw.wiggle ?? 1); const phase = [rng(), rng(), rng()].map((v) => v * Math.PI * 2); const freq = 0.6 + rng() * 0.6; const cost = new Float64Array(N); @@ -257,23 +275,28 @@ export function routePaths( cost[c] = Math.max(0.05, 1.5 - pref(terrainOf(c)) + noiseAmp * (0.5 + 0.5 * noise)); } - const count = Math.max(1, Math.round(f.count * sizeScale)); + const auto = Math.max(1, Math.round(f.count * sizeScale)); + const count = tw.off ? 0 : Math.max(0, Math.round(tw.count ?? auto)); + const stat: RouteStat = { route, auto, wanted: count, placed: 0 }; + routes.push(stat); + if (!count) continue; const taken = takenByType.get(f.type) ?? new Set(); takenByType.set(f.type, taken); let made = 0; for (let k = 0; k < count; k++) { - const route = routeOne(f, cost, taken); - if (!route) continue; - out.push({ type: f.type, hexes: route.map(keyOf) }); - for (const c of route) taken.add(c); + const path = routeOne(f, cost, taken); + if (!path) continue; + out.push({ type: f.type, route: stat.route, hexes: path.map(keyOf) }); + for (const c of path) taken.add(c); made++; } + stat.placed = made; if (made < count) { const end = (e: string) => (e === "edge" ? "a map edge" : e === "path" ? `another ${f.type}` : e); warnings.push(`Placed ${made} of ${count} ${f.type} paths (${end(f.from)} to ${end(f.to)})`); } } - return { paths: out, warnings }; + return { paths: out, warnings, routes }; } /** Minimal binary min-heap of [priority, value]. */ diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 3e0744e5..82c7b556 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -30,7 +30,7 @@ import { } from "./model"; import { mulberry32 } from "./rng"; import { placeFeatures, placeEdgeBorder } from "./features"; -import { routePaths, type PathOutput } from "./paths"; +import { routePaths, type PathOutput, type RouteStat } from "./paths"; import { smoothEdges, removeSpecks, @@ -96,6 +96,8 @@ export type SolveResult = featureCells: Set; /** Paths routed over the terrain (rivers, roads drawn as paths). */ paths: PathOutput[]; + /** Per learned route: how many were wanted and placed. */ + pathRoutes: RouteStat[]; /** Soft goals that weren't fully met (counts, connected land, features). */ warnings: string[]; stats: SolveStats; @@ -245,15 +247,27 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { } } let paths: PathOutput[] = []; - if (s.features && model.paths?.length) { + let pathRoutes: RouteStat[] = []; + if (pathsEnabled(model, opts) && model.paths?.length) { const N = grid.cols * grid.rows; const scale = model.exampleHexes ? Math.sqrt(N / model.exampleHexes) : 1; - const routed = routePaths(model.paths, best.cells, grid, mulberry32(opts.seed ^ 0x7f4a7c15), scale); + const routed = routePaths(model.paths, best.cells, grid, mulberry32(opts.seed ^ 0x7f4a7c15), scale, s.paths); paths = routed.paths; + pathRoutes = routed.routes; best.warnings.push(...routed.warnings); } total.ms = Date.now() - t0; - return { ok: true, cells: best.cells, featureCells: best.featureCells, paths, warnings: best.warnings, stats: total }; + return { ok: true, cells: best.cells, featureCells: best.featureCells, paths, pathRoutes, warnings: best.warnings, stats: total }; +} + +/** + * Whether learned paths are drawn. `drawPaths` decides when set; generators + * saved before it existed only had `features`, which used to cover paths too. + */ +export function pathsEnabled(model: HexWfcModel, override: GeneratorSettings = {}): boolean { + const own = override.drawPaths ?? model.settings?.drawPaths; + if (own !== undefined) return own; + return override.features ?? model.settings?.features ?? true; } /** Feedback never boosts or damps a terrain by more than this factor per choice. */ diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 27a54aff..d5f480cf 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -886,7 +886,7 @@ export class MapModal extends HexmakerModal { // Solve before creating anything, so a generator that can't fill the // map leaves no half-made map behind. let terrainAt: Map | undefined; - let generatedPaths: { type: string; hexes: string[] }[] = []; + let generatedPaths: { type: string; route?: string; hexes: string[] }[] = []; if (generator) { const palette = this.plugin.getPaletteByName(paletteName)?.terrains.map((t) => t.name) ?? []; const solved = generateTerrain( @@ -933,7 +933,7 @@ export class MapModal extends HexmakerModal { if (generatedPaths.length) { const newMap = this.plugin.getMap(result.name); - const { chains, missing } = toPathChains(this.plugin, generatedPaths); + const { chains, missing } = toPathChains(this.plugin, generatedPaths, generator?.model); if (newMap && chains.length) { newMap.pathChains = [...newMap.pathChains, ...chains]; await this.plugin.saveSettings(); diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index a9afad51..44fca481 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -14,6 +14,7 @@ import { saveGeneratorSettings, generateTerrain, generatorSettings, + drawnPathType, generatorFitsPalette, paletteColors, pathColors, @@ -26,6 +27,10 @@ import { makeScrubbable } from "./scrub"; import { exampleShares, formatShare, formatShareChange, hasTerrainTweaks, terrainShares, withoutTerrainTweaks } from "./shares"; import { cleanupStrengths, + pathsEnabled, + pathRouteKey, + type PathTweak, + type RouteStat, randomSeed, SYMMETRIES, type GeneratorSettings, @@ -332,6 +337,26 @@ export class GeneratorPanel { cell.change.setAttr("title", change ? `${formatShare(b)} without its mix and min/max settings` : ""); } }; + // Path rows (filled in further down) and the last drawn preview, so + // hovering a row can redraw it with that route highlighted. + const pathRows = new Map(); + let lastDraw: ((highlight?: string) => void) | null = null; + let hoveredRoute: string | undefined; + const updatePathRows = (stats: RouteStat[]) => { + const byRoute = new Map(stats.map((st) => [st.route, st])); + for (const [route, row] of pathRows) { + const st = byRoute.get(route); + row.auto = st?.auto ?? row.auto; + row.count.placeholder = `Auto (${row.auto})`; + if (!st || !pathsEnabled(model) || st.wanted === 0) { + row.placed.setText("Off"); + row.placed.removeClass("is-short"); + continue; + } + row.placed.setText(`${st.placed} of ${st.wanted}`); + row.placed.toggleClass("is-short", st.placed < st.wanted); + } + }; const runPreview = () => { const grid = previewGrid(); this.previewCols = grid.cols; @@ -343,11 +368,17 @@ export class GeneratorPanel { status.setText(`Couldn't generate: ${r.message}`); return; } - // Draw at the side column's device-pixel width so it stays sharp when stretched. - const dpr = activeWindow.devicePixelRatio || 1; - drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, r.paths, pathColors(this.plugin), - Math.max(420, side.clientWidth) * dpr, 40 * dpr); + // Paths are coloured as the map path type they'll become. + const paths = r.paths.map((p) => ({ ...p, type: drawnPathType(model, p) })); + lastDraw = (highlight?: string) => { + // Draw at the side column's device-pixel width so it stays sharp when stretched. + const dpr = activeWindow.devicePixelRatio || 1; + drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, paths, pathColors(this.plugin), + Math.max(420, side.clientWidth) * dpr, 40 * dpr, highlight); + }; + lastDraw(hoveredRoute); updateShares(r.cells, grid, palette); + updatePathRows(r.pathRoutes); // Short: size and time, plus a hoverable count if anything didn't fit. status.setText(`${grid.cols}×${grid.rows} · ${r.stats.ms} ms${r.warnings.length ? ` · ⚠ ${r.warnings.length}` : ""}`); status.setAttr("title", r.warnings.join("\n")); @@ -395,7 +426,7 @@ export class GeneratorPanel { new Notice(result.error); return; } - const { chains, missing } = toPathChains(this.plugin, r.paths); + const { chains, missing } = toPathChains(this.plugin, r.paths, model); const created = this.plugin.getMap(result.name); if (created && chains.length) { created.pathChains = [...created.pathChains, ...chains]; @@ -455,8 +486,8 @@ export class GeneratorPanel { // Guarantees this.heading(el, "Guarantees"); - if (model.features?.length || model.paths?.length) { - this.toggle(el, "Guaranteed features", "Always place the example's anchored lines and paths.", s().features, (v) => save({ features: v })); + if (model.features?.length) { + this.toggle(el, "Guaranteed features", "Always place the example's anchored terrain lines (such as a river painted as terrain). Drawn paths have their own section below.", s().features, (v) => save({ features: v })); } this.toggle(el, "Connected land", "Fill cut-off pockets so every passable hex connects.", s().connected, (v) => save({ connected: v })); this.terrainFilter(el, "Impassable terrain", model.terrains.map((t) => t.name), colors, s().impassable, (list) => save({ impassable: list })); @@ -510,6 +541,7 @@ export class GeneratorPanel { const input = row.createEl("input", { type: "number", cls: "duckmage-wfc-num", attr: { min: "0", placeholder: "–" } }); const v = counts[t.name]?.[bound]; input.value = v === undefined ? "" : String(v); + makeScrubbable(input, { min: 0, max: 99, pxPerStep: 8 }); input.addEventListener("change", () => { const range: CountRange = { ...(counts[t.name] ?? {}) }; if (input.value === "") delete range[bound]; @@ -529,6 +561,109 @@ export class GeneratorPanel { this.slider(el, "Mix strength", "How closely the overall terrain mix follows the example.", 0, 4, 0.5, s().frequencyFeedback, (v) => save({ frequencyFeedback: v })); + // Paths: one row per learned route (type + what its ends connect to) + if (model.paths?.length) { + this.heading(el, "Paths"); + el.createEl("p", { + text: "Roads and rivers drawn over the terrain. Count is how many of each route to draw; leave it blank for the learned amount for this map size (drag or scroll on it). Hover a row to highlight its paths on the preview.", + cls: "duckmage-map-origin-desc", + }); + const tweaks: Record = Object.fromEntries(Object.entries(s().paths).map(([k, t]) => [k, { ...t }])); + const saveTweak = (route: string, patch: Partial) => { + const t: PathTweak = { ...(tweaks[route] ?? {}), ...patch }; + for (const k of Object.keys(t) as (keyof PathTweak)[]) if (t[k] === undefined || t[k] === false) delete t[k]; + if (Object.keys(t).length) tweaks[route] = t; + else delete tweaks[route]; + save({ paths: Object.keys(tweaks).length ? { ...tweaks } : undefined }); + }; + const table = el.createDiv({ cls: "duckmage-wfc-paths" }); + this.toggle(table, "Draw paths", "", pathsEnabled(model), (v) => { + save({ drawPaths: v }); + table.toggleClass("is-off", !v); + }); + table.toggleClass("is-off", !pathsEnabled(model)); + const mapTypes = (this.plugin.settings.pathTypes ?? []).map((t) => t.name); + const typeColors = pathColors(this.plugin); + for (const f of model.paths) { + const route = pathRouteKey(f); + const end = (e: string) => (e === "edge" ? "map edge" : e === "path" ? `a ${f.type}` : e === "none" ? "anywhere" : e); + const tw = tweaks[route] ?? {}; + const row = table.createDiv({ cls: "duckmage-wfc-path-row" + (tw.off ? " is-off" : "") }); + row.addEventListener("mouseenter", () => { + hoveredRoute = route; + lastDraw?.(route); + }); + row.addEventListener("mouseleave", () => { + hoveredRoute = undefined; + lastDraw?.(); + }); + + // Line 1: on, name, route, count, becomes, placed + const top = row.createDiv({ cls: "duckmage-wfc-path-top" }); + const on = top.createEl("input", { type: "checkbox", attr: { "aria-label": `Draw ${f.type} (${end(f.from)} to ${end(f.to)})` } }); + on.checked = !tw.off; + on.addEventListener("change", () => { + row.toggleClass("is-off", !on.checked); + saveTweak(route, { off: !on.checked || undefined }); + }); + const name = top.createSpan({ cls: "duckmage-wfc-terrain-name" }); + name.createSpan({ cls: "duckmage-wfc-swatch" }).setCssProps({ + "--duckmage-wfc-swatch": typeColors.get(tw.as ?? f.type) ?? "var(--background-modifier-border)", + }); + name.createSpan({ text: f.type }); + top.createSpan({ text: `${end(f.from)} → ${end(f.to)}`, cls: "duckmage-map-origin-desc duckmage-wfc-path-route" }); + + const countWrap = top.createSpan({ cls: "duckmage-wfc-path-count" }); + countWrap.createSpan({ text: "Count", cls: "duckmage-map-origin-label" }); + const count = countWrap.createEl("input", { type: "number", cls: "duckmage-wfc-num", attr: { min: "0", placeholder: "Auto" } }); + count.value = tw.count === undefined ? "" : String(tw.count); + const rowState = { placed: top.createSpan({ cls: "duckmage-wfc-path-placed", text: "–" }), count, auto: 1 }; + makeScrubbable(count, { min: 0, max: 99, pxPerStep: 8, initial: () => rowState.auto }); + count.addEventListener("input", () => { + if (count.hasClass("is-scrubbing")) { + tweaks[route] = { ...(tweaks[route] ?? {}), count: Number(count.value) }; + model.settings = { ...(model.settings ?? {}), paths: { ...tweaks } }; + schedulePreview(); + } + }); + count.addEventListener("change", () => { + saveTweak(route, { count: count.value === "" ? undefined : Math.max(0, Math.floor(Number(count.value) || 0)) }); + }); + + const asWrap = top.createSpan({ cls: "duckmage-wfc-path-as" }); + asWrap.createSpan({ text: "As", cls: "duckmage-map-origin-label" }); + const asSel = asWrap.createEl("select", { attr: { title: "Path type it is drawn as on the map" } }); + const learnedKnown = mapTypes.includes(f.type); + asSel.createEl("option", { value: "", text: learnedKnown ? f.type : `${f.type} (no such type: skipped)` }); + for (const t of mapTypes) if (t !== f.type) asSel.createEl("option", { value: t, text: t }); + asSel.value = tw.as && mapTypes.includes(tw.as) ? tw.as : ""; + asSel.addEventListener("change", () => saveTweak(route, { as: asSel.value || undefined })); + top.appendChild(rowState.placed); + pathRows.set(route, rowState); + + // Line 2: shape of the route + const knobs = row.createDiv({ cls: "duckmage-wfc-path-knobs" }); + const knob = (label: string, title: string, key: "wiggle" | "length" | "follow", max: number) => { + const cell = knobs.createSpan({ cls: "duckmage-wfc-mix", attr: { title } }); + cell.createSpan({ text: label, cls: "duckmage-map-origin-label" }); + const slider = cell.createEl("input", { type: "range" }); + slider.min = "0"; + slider.max = String(max); + slider.step = "0.25"; + slider.value = String(tw[key] ?? 1); + const valueLabel = cell.createSpan({ text: `×${slider.value}` }); + slider.addEventListener("input", () => valueLabel.setText(`×${slider.value}`)); + slider.addEventListener("change", () => { + const v = Number(slider.value); + saveTweak(route, { [key]: v === 1 ? undefined : v }); + }); + }; + knob("Wiggle", "How much it meanders. 0 = as straight as the terrain allows.", "wiggle", 3); + if (f.to === "none" || f.to === "edge") knob("Length", "How long it runs, relative to the example.", "length", 3); + knob("Follow terrain", "How strongly it keeps to the terrains it ran through in the example. 0 = ignores terrain.", "follow", 3); + } + } + const resetRow = el.createDiv({ cls: "duckmage-region-row" }); const resetBtn = resetRow.createEl("button", { text: "Reset settings to defaults" }); resetBtn.addEventListener("click", () => { diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index 36cf13ae..e81e2051 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -28,6 +28,7 @@ import { type SolveResult, type GeneratorSettings, resolveSettings, + pathRouteKey, } from "../../packages/hex-wfc/src"; /** Frontmatter key that keeps a hex's terrain when a map is regenerated. */ @@ -118,11 +119,18 @@ export function pathColors(plugin: HexmakerPlugin): Map { */ export function toPathChains( plugin: HexmakerPlugin, - paths: { type: string; hexes: string[] }[], + paths: { type: string; route?: string; hexes: string[] }[], + model?: HexWfcModel, ): { chains: { typeName: string; hexes: string[] }[]; missing: string[] } { const known = new Set((plugin.settings.pathTypes ?? []).map((t) => t.name)); - const missing = [...new Set(paths.map((p) => p.type).filter((t) => !known.has(t)))]; - return { chains: paths.filter((p) => known.has(p.type)).map((p) => ({ typeName: p.type, hexes: [...p.hexes] })), missing }; + const typed = paths.map((p) => ({ typeName: drawnPathType(model, p), hexes: [...p.hexes] })); + const missing = [...new Set(typed.map((p) => p.typeName).filter((t) => !known.has(t)))]; + return { chains: typed.filter((p) => known.has(p.typeName)), missing }; +} + +/** The map path type a generated path is drawn as: its route's "as", else its learned type. */ +export function drawnPathType(model: HexWfcModel | undefined, p: { type: string; route?: string }): string { + return (p.route && model?.settings?.paths?.[p.route]?.as) || p.type; } /** Palette colour per terrain name, for previews. */ @@ -302,8 +310,8 @@ export async function fillMap( // Regenerating also redraws the generator's path types (rivers, roads); // other path types, and every path when only filling, are left alone. if (mode === "regenerate" && model.paths?.length) { - const learned = new Set(model.paths.map((p) => p.type)); - const { chains, missing } = toPathChains(plugin, result.paths); + const learned = new Set(model.paths.map((p) => drawnPathType(model, { type: p.type, route: pathRouteKey(p) }))); + const { chains, missing } = toPathChains(plugin, result.paths, model); map.pathChains = [...(map.pathChains ?? []).filter((c) => !learned.has(c.typeName)), ...chains]; if (missing.length) warnings.push(`No path type named ${missing.join(", ")}, so those paths were skipped`); await plugin.saveSettings(); diff --git a/src/worldgen/preview.ts b/src/worldgen/preview.ts index 158f3ed6..736ef4d4 100644 --- a/src/worldgen/preview.ts +++ b/src/worldgen/preview.ts @@ -22,11 +22,13 @@ export function drawPreview( orientation: "flat" | "pointy", colors: Map, featureCells?: Set, - paths: { type: string; hexes: string[] }[] = [], + paths: { type: string; route?: string; hexes: string[] }[] = [], pathColors: Map = new Map(), maxWidth = 420, /** Largest hex size in canvas pixels (keeps tiny maps from ballooning). */ maxScale = 14, + /** Route to emphasise (others are dimmed), e.g. while its table row is hovered. */ + highlightRoute?: string, ): void { const { cols, rows, offset, stagger } = grid; // Hex centres in unit space (neighbours √3 apart, circumradius 1). @@ -75,6 +77,8 @@ export function drawPreview( ctx.lineCap = "round"; ctx.lineJoin = "round"; for (const p of paths) { + const lit = !highlightRoute || p.route === highlightRoute; + ctx.globalAlpha = lit ? 1 : 0.2; ctx.beginPath(); p.hexes.forEach((h, i) => { const c = centre.get(h); @@ -83,7 +87,8 @@ export function drawPreview( else ctx.lineTo(c[0], c[1]); }); ctx.strokeStyle = pathColors.get(p.type) ?? "#2b6cb0"; - ctx.lineWidth = Math.max(1.5, scale * 0.35); + ctx.lineWidth = Math.max(1.5, scale * 0.35) * (highlightRoute && lit ? 1.8 : 1); ctx.stroke(); } + ctx.globalAlpha = 1; } diff --git a/src/worldgen/scrub.ts b/src/worldgen/scrub.ts index 05aa9fb2..964cd238 100644 --- a/src/worldgen/scrub.ts +++ b/src/worldgen/scrub.ts @@ -1,6 +1,6 @@ /** - * Drag up or down on a number input to change it (like a DCC "scrubber"). - * A plain click still focuses the input for typing. + * Number inputs you can drag up/down or scroll over to change (like a DCC + * "scrubber"). A plain click still focuses the input for typing. */ export interface ScrubOptions { @@ -9,6 +9,8 @@ export interface ScrubOptions { step?: number; /** Pixels of drag per step. */ pxPerStep?: number; + /** Value to start from when the field is blank (e.g. a shown "auto" value). */ + initial?: () => number; } /** Value after dragging `dy` pixels (negative = up = bigger) from `start`. */ @@ -17,16 +19,34 @@ export function scrubValue(start: number, dy: number, { min, max, step = 1, pxPe return Math.max(min, Math.min(max, v)); } +/** Value after one wheel notch: scrolling up adds a step, down takes one away. */ +export function wheelValue(start: number, deltaY: number, { min, max, step = 1 }: ScrubOptions): number { + if (deltaY === 0) return start; + return Math.max(min, Math.min(max, start + (deltaY < 0 ? step : -step))); +} + /** Movement before a press counts as a drag rather than a click. */ const DRAG_THRESHOLD = 3; +/** Quiet time after the last wheel notch before "change" fires (one save per burst). */ +const WHEEL_SETTLE_MS = 350; /** - * Make `input` scrubbable. Fires "input" on every step and "change" when the - * drag ends, the same events typing would fire. + * Make `input` scrubbable by dragging and by the mouse wheel while hovered. + * Fires "input" on every step and "change" when the drag (or a burst of + * wheel notches) ends, the same events typing would fire. */ export function makeScrubbable(input: HTMLInputElement, opts: ScrubOptions): void { input.addClass("duckmage-scrub"); - input.setAttr("title", "Drag up or down to change, or click to type"); + input.setAttr("title", "Drag up/down or scroll to change, or click to type"); + const current = () => (input.value === "" && opts.initial ? opts.initial() : Number(input.value) || 0); + const set = (v: number) => { + const next = String(v); + if (next === input.value) return false; + input.value = next; + input.dispatchEvent(new Event("input", { bubbles: true })); + return true; + }; + let startY = 0; let startValue = 0; let dragging = false; @@ -37,7 +57,7 @@ export function makeScrubbable(input: HTMLInputElement, opts: ScrubOptions): voi pressed = true; dragging = false; startY = e.clientY; - startValue = Number(input.value) || 0; + startValue = current(); try { input.setPointerCapture(e.pointerId); } catch { @@ -52,11 +72,7 @@ export function makeScrubbable(input: HTMLInputElement, opts: ScrubOptions): voi if (!dragging && Math.abs(dy) < DRAG_THRESHOLD) return; dragging = true; input.addClass("is-scrubbing"); - const next = String(scrubValue(startValue, dy, opts)); - if (next !== input.value) { - input.value = next; - input.dispatchEvent(new Event("input", { bubbles: true })); - } + set(scrubValue(startValue, dy, opts)); }); const end = (e: PointerEvent) => { if (!pressed) return; @@ -71,4 +87,24 @@ export function makeScrubbable(input: HTMLInputElement, opts: ScrubOptions): voi }; input.addEventListener("pointerup", end); input.addEventListener("pointercancel", end); + + // Wheel over the field: one step per notch. The page doesn't scroll while + // the pointer is on the field; everywhere else it scrolls as usual. + let settle: number | null = null; + input.addEventListener( + "wheel", + (e: WheelEvent) => { + e.preventDefault(); + input.addClass("is-scrubbing"); + set(wheelValue(current(), e.deltaY, opts)); + const win = input.ownerDocument.defaultView ?? activeWindow; + if (settle !== null) win.clearTimeout(settle); + settle = win.setTimeout(() => { + settle = null; + input.removeClass("is-scrubbing"); + input.dispatchEvent(new Event("change", { bubbles: true })); + }, WHEEL_SETTLE_MS); + }, + { passive: false }, + ); } diff --git a/styles.css b/styles.css index e611ef93..7911c4f9 100644 --- a/styles.css +++ b/styles.css @@ -5318,3 +5318,69 @@ button.duckmage-wfc-chip { .duckmage-wfc-lock.is-active { color: var(--interactive-accent); } + +/* Generator page: Paths table. Each route is a two-line card: on/name/route/ + count/type/placed, then its shape sliders. */ +.duckmage-wfc-paths { + display: grid; + gap: 0.4em; +} + +.duckmage-wfc-path-row { + padding: 0.4em 0.5em; + border-radius: var(--radius-s); + border: 1px solid var(--background-modifier-border); +} + +.duckmage-wfc-path-row:hover { + background: var(--background-modifier-hover); +} + +.duckmage-wfc-paths.is-off .duckmage-wfc-path-row, +.duckmage-wfc-path-row.is-off .duckmage-wfc-path-knobs, +.duckmage-wfc-path-row.is-off .duckmage-wfc-path-count, +.duckmage-wfc-path-row.is-off .duckmage-wfc-path-as { + opacity: 0.45; +} + +.duckmage-wfc-path-top { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.4em 0.8em; +} + +.duckmage-wfc-path-route { + flex: 1; + min-width: 8em; + margin: 0; +} + +.duckmage-wfc-path-count, +.duckmage-wfc-path-as { + display: inline-flex; + align-items: center; + gap: 0.35em; +} + +.duckmage-wfc-path-count .duckmage-wfc-num { + width: 6.5em; +} + +.duckmage-wfc-path-placed { + min-width: 4.5em; + text-align: right; + font-variant-numeric: tabular-nums; + color: var(--text-muted); +} + +.duckmage-wfc-path-placed.is-short { + color: var(--color-orange); +} + +.duckmage-wfc-path-knobs { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(11em, 1fr)); + gap: 0.25em 1em; + margin-top: 0.35em; +} diff --git a/tests/hexWfcPathTweaks.test.ts b/tests/hexWfcPathTweaks.test.ts new file mode 100644 index 00000000..da7e00c7 --- /dev/null +++ b/tests/hexWfcPathTweaks.test.ts @@ -0,0 +1,137 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + cellKey, + decodeSetting, + encodeSetting, + hexNeighbors, + learnModel, + modelToMarkdown, + parseModelMarkdown, + pathRouteKey, + pathsEnabled, + solve, + type HexWfcModel, + type PathTweak, + type SolveOptions, +} from "../packages/hex-wfc/src"; +import { drawnPathType } from "../src/worldgen/generators"; +import { wheelValue } from "../src/worldgen/scrub"; + +/** + * Per-route path settings on the generator page: on/off, exact count, + * wiggle, length, follow terrain and "draw as". + */ + +/** 30×20 grass map with a bay on the left, a river edge to edge and a tributary into the bay. */ +function riverModel(): HexWfcModel { + const cells = new Map(); + for (let x = 0; x < 30; x++) for (let y = 0; y < 20; y++) cells.set(cellKey(x, y), x < 8 && y > 4 && y < 15 ? "Water" : "Grass"); + const main = Array.from({ length: 20 }, (_, y) => cellKey(20, y)); + const trib = Array.from({ length: 14 }, (_, i) => cellKey(20 - i, 10)); + return learnModel(cells, { name: "p", orientation: "flat", paths: [{ type: "River", hexes: main }, { type: "River", hexes: trib }] }); +} + +const model = riverModel(); +const mainRoute = pathRouteKey(model.paths!.find((p) => p.from === "edge")!); +const tribRoute = pathRouteKey(model.paths!.find((p) => p.from === "path")!); +const run = (paths: Record, extra: Partial = {}, seed = 1, cols = 30, rows = 20) => { + const r = solve(model, { cols, rows, orientation: "flat", seed, directionalBias: 1, paths, ...extra }); + if (!r.ok) throw new Error(r.message); + return r; +}; + +/** Share of steps along the paths that change direction. */ +function turniness(paths: { hexes: string[] }[]): number { + let turns = 0, steps = 0; + for (const p of paths) { + let prev = -1; + for (let i = 1; i < p.hexes.length; i++) { + const [x, y] = p.hexes[i - 1].split("_").map(Number); + const d = hexNeighbors(x, y, "flat").findIndex(([nx, ny]) => cellKey(nx, ny) === p.hexes[i]); + if (prev >= 0) { + steps++; + if (d !== prev) turns++; + } + prev = d; + } + } + return steps ? turns / steps : 0; +} + +describe("path route keys", () => { + it("name a route by type and ends", () => { + expect(mainRoute).toBe("River: edge > edge"); + expect(tribRoute).toBe("River: path > Water"); + }); +}); + +describe("path tweaks", () => { + it("off leaves a route out and reports it as not wanted", () => { + const r = run({ [tribRoute]: { off: true } }); + expect(r.paths.every((p) => p.route === mainRoute)).toBe(true); + expect(r.pathRoutes.find((s) => s.route === tribRoute)).toMatchObject({ wanted: 0, placed: 0 }); + expect(r.warnings.some((w) => w.includes("path"))).toBe(false); + }); + + it("count places exactly that many, and reports the auto count", () => { + const r = run({ [mainRoute]: { count: 3 }, [tribRoute]: { off: true } }, {}, 2, 60, 40); + const stat = r.pathRoutes.find((s) => s.route === mainRoute)!; + expect(stat.wanted).toBe(3); + expect(stat.placed).toBe(r.paths.length); + expect(stat.placed).toBeGreaterThanOrEqual(2); + expect(stat.auto).toBeGreaterThanOrEqual(1); + expect(run({ [mainRoute]: { count: 0 } }).paths.filter((p) => p.route === mainRoute)).toEqual([]); + }); + + it("wiggle 0 runs straighter than wiggle 3", () => { + let straight = 0, wiggly = 0; + for (const seed of [1, 2, 3, 4]) { + straight += turniness(run({ [mainRoute]: { wiggle: 0 }, [tribRoute]: { off: true } }, {}, seed).paths); + wiggly += turniness(run({ [mainRoute]: { wiggle: 3 }, [tribRoute]: { off: true } }, {}, seed).paths); + } + expect(straight).toBeLessThan(wiggly); + }); + + it("draw-paths off places no paths; unset follows the old features flag", () => { + expect(run({}, { drawPaths: false }).paths).toEqual([]); + expect(pathsEnabled(model)).toBe(true); + expect(pathsEnabled({ ...model, settings: { features: false } })).toBe(false); + expect(pathsEnabled({ ...model, settings: { features: false, drawPaths: true } })).toBe(true); + }); + + it("draws a route as another path type when asked", () => { + const m: HexWfcModel = { ...model, settings: { paths: { [mainRoute]: { as: "Trade road" } } } }; + expect(drawnPathType(m, { type: "River", route: mainRoute })).toBe("Trade road"); + expect(drawnPathType(m, { type: "River", route: tribRoute })).toBe("River"); + expect(drawnPathType(undefined, { type: "River" })).toBe("River"); + }); +}); + +describe("path settings in frontmatter", () => { + it("round-trip through the codec and the generator file", () => { + const paths: Record = { + [mainRoute]: { count: 2, wiggle: 1.5, as: "Trade road" }, + [tribRoute]: { off: true, follow: 0 }, + }; + const back = decodeSetting("paths", String(encodeSetting("paths", paths))); + expect("value" in back ? back.value : back).toEqual(paths); + const file = parseModelMarkdown(modelToMarkdown({ ...model, settings: { paths, drawPaths: false } })); + expect(file.warnings).toEqual([]); + expect(file.model.settings).toMatchObject({ paths, drawPaths: false }); + }); + + it("explains a bad option", () => { + expect(decodeSetting("paths", "River: edge > edge = speed 3")).toHaveProperty("error"); + expect(decodeSetting("paths", "River count 3")).toHaveProperty("error"); + }); +}); + +describe("wheelValue", () => { + it("scroll up adds a step, down takes one away, within the range", () => { + expect(wheelValue(3, -100, { min: 0, max: 9 })).toBe(4); + expect(wheelValue(3, 100, { min: 0, max: 9 })).toBe(2); + expect(wheelValue(0, 100, { min: 0, max: 9 })).toBe(0); + expect(wheelValue(9, -100, { min: 0, max: 9 })).toBe(9); + }); +}); From 7d3ea78a87a47ecf97ac6edf88739242483e640b Mon Sep 17 00:00:00 2001 From: nyxsys Date: Wed, 7 Oct 2026 22:39:40 -0400 Subject: [PATCH 017/558] feat(worldgen): generator saves, version stamps with per-version examples; fix blank first render of new maps Saves - Save button on the generator page writes generators/saves/.md: settings, seed, size, palette, the generated terrain (run-length grid) and paths, plus a full copy of the generator. Load puts the settings back on the generator (recreating it from the copy if it's gone), restores seed/size and locks the seed. If this version generates a different map from the same inputs, the preview and Create map use the saved map. - Format in src/worldgen/saveFormat.ts (pure); vault I/O in saves.ts. The saves folder is excluded from the generator list, and isModelMarkdown now only looks at frontmatter. Versions - Generator files (every write), saves, new maps (createdWith) and data.json (savedWith) record the plugin version. The version is compiled in from manifest.json (esbuild define): Obsidian keeps the manifest from startup, which went stale after an in-place update and stamped 1.5.3. - tests/fixtures/compat// holds an example generator, save and map per version; tests/compat.test.ts loads them all with current code. `npm run version` now writes the new version's set (compat:snapshot). - Map normalisation moved to migrateMapData (src/compat.ts). New maps rendered mostly blank - Create map writes every hex note then opens the map at once; Obsidian indexes the notes over the next tens of seconds, and the active view never re-rendered, so it stayed blank (reproduced: 65 of 950 hexes). Terrain the plugin just wrote is now read from memory until indexed (frontmatter.ts, used by the map render): 950 of 950 painted on first render. - Each new hex is one write: its encounter-table link is put in the note text before creation instead of a read + rewrite afterwards. (Creation time is dominated by the disk: ~19 ms per file on this machine.) Also: the generator page's narrow-pane layout never applied (both classes sit on one element); it now stacks at <760px with the preview pinned on top. Co-Authored-By: Claude Opus 5.5 --- esbuild.config.mjs | 5 + package.json | 7 +- packages/hex-wfc/src/format.ts | 3 +- src/HexmakerPlugin.ts | 49 +++-- src/compat.ts | 62 ++++++ src/frontmatter.ts | 26 ++- src/hex-map/HexMapView.ts | 5 +- src/sections.ts | 36 ++-- src/types.ts | 4 + src/worldgen/GeneratorPanel.ts | 160 +++++++++++++- src/worldgen/generators.ts | 13 +- src/worldgen/saveFormat.ts | 260 +++++++++++++++++++++++ src/worldgen/saves.ts | 101 +++++++++ styles.css | 27 ++- tests/compat.test.ts | 108 ++++++++++ tests/compat/examples.ts | 93 ++++++++ tests/compat/snapshot.ts | 27 +++ tests/fixtures/compat/1.5.5/generator.md | 86 ++++++++ tests/fixtures/compat/1.5.5/map.json | 46 ++++ tests/fixtures/compat/1.5.5/save.md | 163 ++++++++++++++ tests/pendingTerrain.test.ts | 60 ++++++ tests/worldgenGenerators.test.ts | 5 +- 22 files changed, 1293 insertions(+), 53 deletions(-) create mode 100644 src/compat.ts create mode 100644 src/worldgen/saveFormat.ts create mode 100644 src/worldgen/saves.ts create mode 100644 tests/compat.test.ts create mode 100644 tests/compat/examples.ts create mode 100644 tests/compat/snapshot.ts create mode 100644 tests/fixtures/compat/1.5.5/generator.md create mode 100644 tests/fixtures/compat/1.5.5/map.json create mode 100644 tests/fixtures/compat/1.5.5/save.md create mode 100644 tests/pendingTerrain.test.ts diff --git a/esbuild.config.mjs b/esbuild.config.mjs index da33b777..9f6ae4e5 100644 --- a/esbuild.config.mjs +++ b/esbuild.config.mjs @@ -4,6 +4,7 @@ import { createRequire } from "module"; const require = createRequire(import.meta.url); const pkg = require("./package.json"); +const manifest = require("./manifest.json"); const fs = require("fs"); const production = process.argv[2] === "production"; @@ -32,6 +33,10 @@ const context = await esbuild.context({ treeShaking: true, outfile: `${outDir}/${outFile}`, loader: { ".md": "text", ".png": "dataurl" }, + // The version stamped on files the plugin writes (src/compat.ts). Taken from + // manifest.json at build time: Obsidian keeps the manifest it read at startup, + // so plugin.manifest.version can be stale after an update without a restart. + define: { __HEXMAKER_VERSION__: JSON.stringify(manifest.version) }, }); if (prod) { diff --git a/package.json b/package.json index 419956d0..f31f6a0a 100644 --- a/package.json +++ b/package.json @@ -6,9 +6,10 @@ "scripts": { "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", - "version": "node version-bump.mjs && git add manifest.json versions.json", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", + "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", + "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index 3ddb2a44..c703d07f 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -355,7 +355,8 @@ export interface ParseResult { } export function isModelMarkdown(text: string): boolean { - return new RegExp(`^---\\r?\\n(?:.*\\r?\\n)*?${MARKER}\\s*:`).test(text); + // Only the frontmatter counts: stop at its closing "---". + return new RegExp(`^---\\r?\\n(?:(?!---).*\\r?\\n)*?${MARKER}\\s*:`).test(text); } type Section = "terrains" | "adjacency" | "features" | "paths" | "layout"; diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 3d70a95e..f825f854 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -32,11 +32,13 @@ import type { TerrainPalette, } from "./types"; import DEFAULT_HEX_TEMPLATE from "./defaultHexTemplate.md"; -import { getTerrainFromFile, setTerrainInFile, setSubmapInFile, withFrontmatterField } from "./frontmatter"; +import { migrateMapData, pluginVersion } from "./compat"; +import { getTerrainFromFile, setTerrainInFile, setSubmapInFile, withFrontmatterField, notePendingTerrain, clearPendingTerrain } from "./frontmatter"; import { addLinkToSection, getLinksInSection, removeLinkFromSection, + insertLinkInSection, } from "./sections"; import { GeneratorView } from "./worldgen/GeneratorView"; import { GeneratorPanel } from "./worldgen/GeneratorPanel"; @@ -47,6 +49,8 @@ export default class HexmakerPlugin extends Plugin { async onload() { await this.loadSettings(); + // Notes written by this plugin are read from memory until indexed (see frontmatter.ts). + this.registerEvent(this.app.metadataCache.on("changed", (file) => clearPendingTerrain(file.path))); // Defer until vault metadata cache is ready; calling before layout-ready // returns null for all vault paths so custom icons are silently dropped. this.app.workspace.onLayoutReady(() => { @@ -371,7 +375,9 @@ export default class HexmakerPlugin extends Plugin { ); } - onunload() {} + onunload() { + clearPendingTerrain(); + } private openHexMap(): void { void this.app.workspace.getLeaf().setViewState({ type: VIEW_TYPE_HEX_MAP }); @@ -431,11 +437,7 @@ export default class HexmakerPlugin extends Plugin { ? this.settings.maps : []; - for (const r of this.settings.maps) { - if (!r.paletteName) r.paletteName = DEFAULT_PALETTE_NAME; - if (!r.gridOffset) r.gridOffset = { x: 0, y: 0 }; - if (!Array.isArray(r.pathChains)) r.pathChains = []; - } + this.settings.maps = this.settings.maps.map((r) => migrateMapData(r, DEFAULT_PALETTE_NAME)); // Ensure terrainPalettes is valid if ( !Array.isArray(this.settings.terrainPalettes) || @@ -474,6 +476,7 @@ export default class HexmakerPlugin extends Plugin { } async saveSettings() { + this.settings.savedWith = pluginVersion(this); await this.saveData(this.settings); // Settings hold map-level state (paths, palette, grid size, overlays). // A save made from one view/window leaves sibling map views stale — @@ -859,9 +862,15 @@ export default class HexmakerPlugin extends Plugin { */ /** Whether `{tablesFolder}/terrain/encounters/{terrain}.md` exists. */ hasTerrainEncounterTable(terrain: string): boolean { + return this.terrainEncounterTable(terrain) !== null; + } + + /** The terrain's encounters table file, if it has one. */ + terrainEncounterTable(terrain: string): TFile | null { const tablesFolder = normalizeFolder(this.settings.tablesFolder); const subfolder = tablesFolder ? `${tablesFolder}/terrain` : "terrain"; - return this.app.vault.getAbstractFileByPath(`${subfolder}/encounters/${terrain}.md`) instanceof TFile; + const file = this.app.vault.getAbstractFileByPath(`${subfolder}/encounters/${terrain}.md`); + return file instanceof TFile ? file : null; } async syncHexEncounterTableLink( @@ -1113,7 +1122,16 @@ export default class HexmakerPlugin extends Plugin { .replace(/\{\{x\}\}/g, String(x)) .replace(/\{\{y\}\}/g, String(y)) .replace(/\{\{title\}\}/g, `Hex ${x}, ${y}`); - if (terrain) content = withFrontmatterField(content, "terrain", terrain); + if (terrain) { + content = withFrontmatterField(content, "terrain", terrain); + // Add the terrain's encounter-table link now rather than reading the + // note back and rewriting it after it's created. + const table = this.terrainEncounterTable(terrain); + if (table) { + const linkText = `[[${this.app.metadataCache.fileToLinktext(table, path)}]]`; + content = insertLinkInSection(content, "Encounters Table", linkText); + } + } const hexBase = normalizeFolder(this.settings.hexFolder); const mapFolder = hexBase ? `${hexBase}/${mapName}` : mapName; @@ -1127,7 +1145,9 @@ export default class HexmakerPlugin extends Plugin { } try { - return await this.app.vault.create(path, content); + const file = await this.app.vault.create(path, content); + if (terrain) notePendingTerrain(path, terrain); + return file; } catch { // A concurrent worker may have created this file between our existence check and // this create call. If the file now exists, use it rather than treating it as an error. @@ -1212,6 +1232,7 @@ export default class HexmakerPlugin extends Plugin { gridOffset: { x: initialX, y: initialY }, pathChains: [], staggerOffset, + createdWith: pluginVersion(this), }); await this.saveSettings(); @@ -1255,12 +1276,8 @@ export default class HexmakerPlugin extends Plugin { const path = this.hexPath(x, y, mapName); if (!this.app.vault.getAbstractFileByPath(path)) { const terrain = terrainAt?.get(`${x}_${y}`); - const result = await this.createHexNote(x, y, mapName, template, terrain); - if (result) { - created++; - if (terrain && this.hasTerrainEncounterTable(terrain)) - await this.syncHexEncounterTableLink(path, terrain); - } + // createHexNote writes the terrain and its encounter link in one go. + if (await this.createHexNote(x, y, mapName, template, terrain)) created++; } done++; }), diff --git a/src/compat.ts b/src/compat.ts new file mode 100644 index 00000000..33e0334b --- /dev/null +++ b/src/compat.ts @@ -0,0 +1,62 @@ +/** + * Versions and backwards compatibility for things the plugin writes to disk. + * + * Every generator file, generator save and map records the plugin version + * that wrote it, so a later version can load it "as best it can" and, if a + * format ever changes, migrate by version. One example of each per released + * version lives in tests/fixtures/compat// and is loaded by + * tests/compat.test.ts; `npm run version` snapshots the new version's set. + * + * Pure (no Obsidian imports), so tests and the snapshot script can use it. + */ + +import type { MapData } from "./types"; + +/** Frontmatter key recording the plugin version that last wrote a file. */ +export const VERSION_KEY = "hexmaker-version"; + +/** Set by esbuild from manifest.json (see esbuild.config.mjs); absent in tests. */ +declare const __HEXMAKER_VERSION__: string | undefined; + +/** + * The plugin version this build is, or the manifest Obsidian loaded, or + * "unknown" (tests, stubs). The build constant comes first because Obsidian + * keeps the manifest from startup, which is stale after an in-place update. + */ +export function pluginVersion(plugin: { manifest?: { version?: string } }): string { + if (typeof __HEXMAKER_VERSION__ === "string") return __HEXMAKER_VERSION__; + return plugin.manifest?.version ?? "unknown"; +} + +/** + * Compare dotted versions ("1.5.10" > "1.5.9"). Unknown or malformed + * versions sort first, so they're treated as the oldest. + */ +export function compareVersions(a: string | undefined, b: string | undefined): number { + const parts = (v: string | undefined) => (v && /^\d+(\.\d+)*$/.test(v) ? v.split(".").map(Number) : null); + const pa = parts(a), pb = parts(b); + if (!pa || !pb) return pa ? 1 : pb ? -1 : 0; + for (let i = 0; i < Math.max(pa.length, pb.length); i++) { + const d = (pa[i] ?? 0) - (pb[i] ?? 0); + if (d) return d; + } + return 0; +} + +/** Default palette for maps saved before maps had one. */ +export const LEGACY_PALETTE_NAME = "Default"; + +/** + * Bring a map entry from data.json (any version) up to the current shape. + * Fills fields older versions didn't have; never drops unknown fields, so a + * map saved by a newer version survives a round trip through an older one. + */ +export function migrateMapData(raw: unknown, defaultPalette = LEGACY_PALETTE_NAME): MapData { + const r = (raw && typeof raw === "object" ? { ...(raw as Record) } : {}) as Partial & Record; + if (typeof r.name !== "string") r.name = String(r.name ?? "map"); + if (!r.paletteName) r.paletteName = defaultPalette; + if (!r.gridSize || typeof r.gridSize !== "object") r.gridSize = { cols: 0, rows: 0 }; + if (!r.gridOffset) r.gridOffset = { x: 0, y: 0 }; + if (!Array.isArray(r.pathChains)) r.pathChains = []; + return r as MapData; +} diff --git a/src/frontmatter.ts b/src/frontmatter.ts index 17763270..891463a2 100644 --- a/src/frontmatter.ts +++ b/src/frontmatter.ts @@ -100,8 +100,32 @@ export function gmIconsFromFm(fm: Frontmatter | null | undefined): string[] { return typeof legacy === "string" ? [legacy] : []; } +/** + * Terrain of hex notes this plugin just wrote whose frontmatter Obsidian + * hasn't indexed yet. Creating a map writes thousands of notes and opens it + * straight away; without this the first render shows most hexes blank and + * nothing re-renders when the index catches up. Cleared per note when its + * metadata arrives (HexmakerPlugin listens for "changed"). + */ +const pendingTerrain = new Map(); + +export function notePendingTerrain(path: string, terrain: string): void { + pendingTerrain.set(path, terrain); +} + +export function clearPendingTerrain(path?: string): void { + if (path === undefined) pendingTerrain.clear(); + else pendingTerrain.delete(path); +} + +/** Terrain of a just-written note that isn't indexed yet, if any. */ +export function pendingTerrainOf(path: string): string | null { + return pendingTerrain.get(path) ?? null; +} + export function getTerrainFromFile(app: App, path: string): string | null { - return terrainFromFm(getFrontMatter(app, path)); + const fm = getFrontMatter(app, path); + return fm ? terrainFromFm(fm) : pendingTerrainOf(path); } export async function setTerrainInFile( diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index adcc692b..8e993aae 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -6,6 +6,7 @@ import { getIconOverrideFromFile, getFrontMatter, terrainFromFm, + pendingTerrainOf, iconOverrideFromFm, gmIconsFromFm, setGmIconsInFile, @@ -3217,9 +3218,11 @@ export class HexMapView extends ItemView { // getFileCache three times per hex (~11.5k redundant lookups on a // 3843-hex map). const fm = getFrontMatter(this.app, path); + // A note this plugin just wrote may not be indexed yet (new maps write + // thousands at once); its terrain is held in memory until it is. const terrainKey = terrainOverrides?.has(path) ? terrainOverrides.get(path)! - : terrainFromFm(fm); + : fm ? terrainFromFm(fm) : pendingTerrainOf(path); const terrainEntry = terrainKey != null ? paletteByName.get(terrainKey) : undefined; const hexEl = parent.createDiv({ diff --git a/src/sections.ts b/src/sections.ts index 752ee29c..54c84a27 100644 --- a/src/sections.ts +++ b/src/sections.ts @@ -5,21 +5,27 @@ import { escapeRegex } from "./textUtils"; export async function addLinkToSection(app: App, filePath: string, section: string, linkText: string): Promise { const file = app.vault.getAbstractFileByPath(filePath); if (!(file instanceof TFile)) return; - await app.vault.process(file, (content) => { - const headingRegex = new RegExp(`^###\\s+${escapeRegex(section)}\\s*$`, "mi"); - const match = headingRegex.exec(content); - if (!match) { - return content.trimEnd() + `\n\n### ${section}\n\n${linkText}\n`; - } - const afterHeading = match.index + match[0].length; - const nextBoundaryMatch = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); - const sectionEnd = nextBoundaryMatch ? afterHeading + nextBoundaryMatch.index : content.length; - const sectionContent = content.slice(afterHeading, sectionEnd); - if (sectionContent.includes(linkText)) return content; - const trimmedSection = sectionContent.trimEnd(); - const insertAt = afterHeading + trimmedSection.length; - return content.slice(0, insertAt) + "\n\n" + linkText + content.slice(insertAt); - }); + await app.vault.process(file, (content) => insertLinkInSection(content, section, linkText)); +} + +/** + * Note text with `linkText` added under the "### section" heading (the + * heading is appended if missing). Unchanged if the link is already there. + */ +export function insertLinkInSection(content: string, section: string, linkText: string): string { + const headingRegex = new RegExp(`^###\\s+${escapeRegex(section)}\\s*$`, "mi"); + const match = headingRegex.exec(content); + if (!match) { + return content.trimEnd() + `\n\n### ${section}\n\n${linkText}\n`; + } + const afterHeading = match.index + match[0].length; + const nextBoundaryMatch = /\n(?:#{1,6} |-{3,})/m.exec(content.slice(afterHeading)); + const sectionEnd = nextBoundaryMatch ? afterHeading + nextBoundaryMatch.index : content.length; + const sectionContent = content.slice(afterHeading, sectionEnd); + if (sectionContent.includes(linkText)) return content; + const trimmedSection = sectionContent.trimEnd(); + const insertAt = afterHeading + trimmedSection.length; + return content.slice(0, insertAt) + "\n\n" + linkText + content.slice(insertAt); } /** Remove a wiki-link from under the named ### section. Removes the whole line containing it. */ diff --git a/src/types.ts b/src/types.ts index 273798ec..494a3773 100644 --- a/src/types.ts +++ b/src/types.ts @@ -50,6 +50,8 @@ export interface MapBackgroundImage { export interface MapData { name: string; + /** Plugin version that created the map (see src/compat.ts). */ + createdWith?: string; paletteName: string; terrainType?: string; // terrain name from the map's palette; used as submap center dot color gridSize: { cols: number; rows: number }; @@ -103,6 +105,8 @@ export interface TerrainColor { export interface HexmakerPluginSettings { mySetting: string; + /** Plugin version that last saved data.json (see src/compat.ts). */ + savedWith?: string; worldFolder: string; hexFolder: string; townsFolder: string; diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 44fca481..1aebc8d2 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -24,6 +24,9 @@ import { } from "./generators"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; import { makeScrubbable } from "./scrub"; +import { listSaves, writeSave, readSave, applySave } from "./saves"; +import { SAVE_FORMAT, type GeneratorSave } from "./saveFormat"; +import { compareVersions, pluginVersion } from "../compat"; import { exampleShares, formatShare, formatShareChange, hasTerrainTweaks, terrainShares, withoutTerrainTweaks } from "./shares"; import { cleanupStrengths, @@ -56,6 +59,12 @@ export class GeneratorPanel { static mapName = ""; static paletteName = ""; static seedLocked = false; + /** + * The save last loaded. While the page still shows its generator, seed and + * size (and no setting has changed), the preview and Create map use the + * saved map, even if this version would generate a different one. + */ + static loadedSave: GeneratorSave | null = null; private seed = randomSeed(); private previewCols = 30; private previewRows = 20; @@ -78,6 +87,12 @@ export class GeneratorPanel { this.previewCols = map.gridSize.cols; this.previewRows = map.gridSize.rows; } + const loaded = GeneratorPanel.loadedSave; + if (loaded) { + this.seed = loaded.seed; + this.previewCols = loaded.cols; + this.previewRows = loaded.rows; + } } private get mapName(): string { @@ -252,7 +267,11 @@ export class GeneratorPanel { // Current settings, kept in sync with the file. const s = () => generatorSettings(model); + // A just-loaded save's settings win over a possibly stale read of the file. + const isThisGenerator = (sv: GeneratorSave) => sv.generatorPath === g.file.path || sv.generatorName === model.name; + if (GeneratorPanel.loadedSave && isThisGenerator(GeneratorPanel.loadedSave)) model.settings = { ...GeneratorPanel.loadedSave.settings }; const save = (patch: Partial>) => { + GeneratorPanel.loadedSave = null; const next: Record = { ...(model.settings ?? {}) }; for (const [k, v] of Object.entries(patch)) { if (v === undefined) delete next[k]; @@ -298,6 +317,28 @@ export class GeneratorPanel { const newNameInput = createRow.createEl("input", { type: "text", attr: { placeholder: "Name for the new map" } }); const createBtn = createRow.createEl("button", { text: "Create map", cls: "mod-cta" }); + // Saves: keep a generated map and its settings without creating a map. + const savesBox = previewBox.createDiv({ cls: "duckmage-wfc-saves" }); + savesBox.createEl("h5", { text: "Saves", cls: "duckmage-wfc-heading" }); + const saveRow = savesBox.createDiv({ cls: "duckmage-region-row" }); + const saveNameInput = saveRow.createEl("input", { type: "text", attr: { placeholder: "Save name (optional)" } }); + const saveBtn = saveRow.createEl("button", { text: "Save", attr: { title: "Save these settings, seed and size with the generated map" } }); + const loadRow = savesBox.createDiv({ cls: "duckmage-region-row" }); + const loadSelect = loadRow.createEl("select", { cls: "duckmage-wfc-save-select" }); + const loadBtn = loadRow.createEl("button", { text: "Load" }); + const fillSaves = () => { + const current = pluginVersion(this.plugin); + const saves = listSaves(this.plugin); + loadSelect.empty(); + if (!saves.length) loadSelect.createEl("option", { value: "", text: "No saves yet" }); + for (const sv of saves) { + const other = compareVersions(sv.version, current) !== 0 ? ` · v${sv.version}` : ""; + loadSelect.createEl("option", { value: sv.file.path, text: `${sv.name} · ${sv.generator} · seed ${sv.seed} · ${sv.size}${other}` }); + } + loadBtn.disabled = !saves.length; + }; + fillSaves(); + const previewGrid = () => { const map = this.plugin.getMap(this.mapName); return { @@ -357,6 +398,15 @@ export class GeneratorPanel { row.placed.toggleClass("is-short", st.placed < st.wanted); } }; + /** The loaded save, while the page shows exactly its generator, seed and size. */ + const showingSave = (): GeneratorSave | null => { + const sv = GeneratorPanel.loadedSave; + if (!sv || !isThisGenerator(sv)) return null; + if (sv.seed !== Number(seedInput.value) >>> 0 || sv.cols !== Number(colsInput.value) || sv.rows !== Number(rowsInput.value)) return null; + return sv; + }; + /** What the preview shows now, for Save. */ + let shown: { cells: Map; paths: { type: string; route?: string; hexes: string[] }[] } | null = null; const runPreview = () => { const grid = previewGrid(); this.previewCols = grid.cols; @@ -368,19 +418,33 @@ export class GeneratorPanel { status.setText(`Couldn't generate: ${r.message}`); return; } + // A loaded save shows its own map if this version generates a different one. + let cells = r.cells; + let rawPaths: { type: string; route?: string; hexes: string[] }[] = r.paths; + let saveNote = ""; + const sv = showingSave(); + if (sv) { + if (sameCells(sv.cells, r.cells)) saveNote = ` · save "${sv.name}"`; + else { + cells = sv.cells; + rawPaths = sv.paths; + saveNote = ` · saved map "${sv.name}" (from v${sv.version}; this version generates it differently)`; + } + } else GeneratorPanel.loadedSave = null; + shown = { cells, paths: rawPaths }; // Paths are coloured as the map path type they'll become. - const paths = r.paths.map((p) => ({ ...p, type: drawnPathType(model, p) })); + const paths = rawPaths.map((p) => ({ ...p, type: drawnPathType(model, p) })); lastDraw = (highlight?: string) => { // Draw at the side column's device-pixel width so it stays sharp when stretched. const dpr = activeWindow.devicePixelRatio || 1; - drawPreview(canvas, r.cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, paths, pathColors(this.plugin), + drawPreview(canvas, cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, paths, pathColors(this.plugin), Math.max(420, side.clientWidth) * dpr, 40 * dpr, highlight); }; lastDraw(hoveredRoute); - updateShares(r.cells, grid, palette); + updateShares(cells, grid, palette); updatePathRows(r.pathRoutes); // Short: size and time, plus a hoverable count if anything didn't fit. - status.setText(`${grid.cols}×${grid.rows} · ${r.stats.ms} ms${r.warnings.length ? ` · ⚠ ${r.warnings.length}` : ""}`); + status.setText(`${grid.cols}×${grid.rows} · ${r.stats.ms} ms${r.warnings.length ? ` · ⚠ ${r.warnings.length}` : ""}${saveNote}`); status.setAttr("title", r.warnings.join("\n")); }; const schedulePreview = () => { @@ -396,6 +460,78 @@ export class GeneratorPanel { runPreview(); }, 200); }; + saveBtn.addEventListener("click", () => { + if (!shown) { + new Notice("Generate a preview first (re-roll or regenerate)."); + return; + } + const grid = previewGrid(); + const snapshot = shown; + saveBtn.disabled = true; + void (async () => { + try { + const saved: GeneratorSave = { + name: saveNameInput.value.trim() || `${model.name}-${this.seed}`, + version: pluginVersion(this.plugin), + format: SAVE_FORMAT, + created: new Date().toISOString().slice(0, 10), + generatorName: model.name, + generatorPath: g.file.path, + palette: GeneratorPanel.paletteName, + seed: this.seed, + cols: grid.cols, + rows: grid.rows, + stagger: grid.stagger, + orientation: this.plugin.settings.hexOrientation, + settings: { ...(model.settings ?? {}) }, + cells: snapshot.cells, + paths: snapshot.paths, + generatorMarkdown: await this.app.vault.read(g.file), + }; + const file = await writeSave(this.plugin, saved); + GeneratorPanel.loadedSave = { ...saved, name: file.basename }; + saveNameInput.value = ""; + new Notice(`Saved "${file.basename}".`); + // The new file may not be in the metadata cache yet. + window.setTimeout(fillSaves, 300); + } catch (e) { + new Notice(`Couldn't save: ${e instanceof Error ? e.message : String(e)}`); + } finally { + saveBtn.disabled = false; + } + })(); + }); + loadBtn.addEventListener("click", () => { + const file = this.app.vault.getFileByPath(loadSelect.value); + if (!file) return; + loadBtn.disabled = true; + void (async () => { + const read = await readSave(this.plugin, file); + if ("error" in read) { + new Notice(`Couldn't load "${file.basename}": ${read.error}`); + loadBtn.disabled = false; + return; + } + const { save: sv, warnings } = read; + const applied = await applySave(this.plugin, sv); + if ("error" in applied) { + new Notice(applied.error); + loadBtn.disabled = false; + return; + } + GeneratorPanel.loadedSave = { ...sv, generatorPath: applied.file.path }; + GeneratorPanel.selectedPath = applied.file.path; + if (this.plugin.settings.terrainPalettes.some((p) => p.name === sv.palette)) GeneratorPanel.paletteName = sv.palette; + GeneratorPanel.seedLocked = true; + const notes = [ + applied.recreated ? `recreated generator "${applied.file.basename}" from the save` : "", + compareVersions(sv.version, pluginVersion(this.plugin)) !== 0 ? `saved with v${sv.version}` : "", + ...warnings, + ].filter(Boolean); + new Notice(`Loaded "${sv.name}"${notes.length ? ` (${notes.join("; ")})` : ""}.`); + this.host.rerender(); + })(); + }); rerollBtn.addEventListener("click", () => { if (!GeneratorPanel.seedLocked) seedInput.value = String(randomSeed()); runPreview(); @@ -406,11 +542,14 @@ export class GeneratorPanel { const grid = previewGrid(); const seed = Number(seedInput.value) >>> 0; const palette = this.paletteTerrains().length ? this.paletteTerrains() : model.terrains.map((t) => t.name); - const r = generateTerrain(this.plugin, model, palette, grid, seed); - if (!r.ok) { - new Notice(`Couldn't generate: ${r.message}`); + const generated = generateTerrain(this.plugin, model, palette, grid, seed); + if (!generated.ok) { + new Notice(`Couldn't generate: ${generated.message}`); return; } + // While a loaded save is shown, create exactly the saved map. + const sv = showingSave(); + const r = sv ? { ...generated, cells: sv.cells, paths: sv.paths } : generated; createBtn.disabled = true; void this.plugin .createNewMap( @@ -790,3 +929,10 @@ export class GeneratorPanel { render(); } } + +/** Same terrain on every hex. */ +function sameCells(a: Map, b: Map): boolean { + if (a.size !== b.size) return false; + for (const [k, t] of a) if (b.get(k) !== t) return false; + return true; +} diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index e81e2051..acf4b352 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -14,6 +14,7 @@ import { TFile, TFolder } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import { getFrontMatter, getTerrainFromFile, setTerrainInFile } from "../frontmatter"; import { normalizeFolder, slugify } from "../utils"; +import { VERSION_KEY, pluginVersion } from "../compat"; import { learnModel, modelToMarkdown, @@ -45,12 +46,18 @@ export function generatorsFolder(plugin: HexmakerPlugin): string { return world ? `${world}/generators` : "generators"; } +/** Where generator saves (presets with their generated map) are kept. */ +export function savesFolder(plugin: HexmakerPlugin): string { + return `${generatorsFolder(plugin)}/saves`; +} + /** Every generator file in the generators folder (sub-folders included). */ export async function listGenerators(plugin: HexmakerPlugin): Promise { const folder = generatorsFolder(plugin); + const saves = savesFolder(plugin) + "/"; const files = plugin.app.vault .getMarkdownFiles() - .filter((f) => f.path.startsWith(folder + "/") && !f.basename.startsWith("_")); + .filter((f) => f.path.startsWith(folder + "/") && !f.path.startsWith(saves) && !f.basename.startsWith("_")); const out: GeneratorFile[] = []; for (const file of files) { const text = await plugin.app.vault.cachedRead(file); @@ -166,6 +173,7 @@ export async function saveGeneratorFromMap( palette: map.paletteName, "source-map": mapName, created: new Date().toISOString().slice(0, 10), + [VERSION_KEY]: pluginVersion(plugin), }, }); if (model.adjacency.length === 0) @@ -204,6 +212,7 @@ export async function saveGeneratorSettings( if (value === undefined) delete fm[key]; else fm[key] = encodeSetting(field, value); } + fm[VERSION_KEY] = pluginVersion(plugin); }); } @@ -366,7 +375,7 @@ export async function relearnGenerator( orientation: plugin.settings.hexOrientation, stagger: mapStagger(plugin, mapName), paths: (map.pathChains ?? []).map((p) => ({ type: p.typeName, hexes: p.hexes })), - meta: { ...g.model.meta, palette: map.paletteName, created: new Date().toISOString().slice(0, 10) }, + meta: { ...g.model.meta, palette: map.paletteName, created: new Date().toISOString().slice(0, 10), [VERSION_KEY]: pluginVersion(plugin) }, }); if (g.model.settings) model.settings = { ...g.model.settings }; await plugin.app.vault.modify(g.file, modelToMarkdown(model)); diff --git a/src/worldgen/saveFormat.ts b/src/worldgen/saveFormat.ts new file mode 100644 index 00000000..e914b350 --- /dev/null +++ b/src/worldgen/saveFormat.ts @@ -0,0 +1,260 @@ +/** + * Generator saves: a quick save of everything on the generator page (the + * generator's settings, seed, size and palette) plus the map it produced, + * so a generated map can be kept and reloaded without creating a map. + * + * A save is a Markdown note in the generators/saves folder: + * + * --- + * hexmaker-save: 1 <- SAVE_FORMAT + * hexmaker-version: 1.5.5 <- plugin version that wrote it + * name: bay-area-12345 + * generator: bay-area + * generator-path: world/generators/bay-area.md + * palette: Default + * seed: 12345 + * size: 38x25 + * stagger: odd + * orientation: flat + * created: 2026-10-08 + * --- + * ## Settings ~~~~json the generator's settings when saved + * ## Terrain ~~~~hexmaker-terrain legend + one run-length row per line + * ## Paths ~~~~json [{ type, route, hexes }] + * ## Generator ~~~~hex-wfc the whole generator file, so the save loads + * even if the generator was changed, re-learned or deleted + * + * The stored terrain is the source of truth: if a later version generates a + * different map from the same inputs, loading still shows (and creates) the + * saved one. Pure: no Obsidian imports. + */ + +import { VERSION_KEY } from "../compat"; +import type { GeneratorSettings } from "../../packages/hex-wfc/src"; + +export const SAVE_FORMAT = 1; +export const SAVE_MARKER = "hexmaker-save"; +/** Code fence for embedded blocks; four tildes so the generator's own content can't close it. */ +const FENCE = "~~~~"; + +export interface GeneratorSave { + name: string; + /** Plugin version that wrote the save ("unknown" if it didn't say). */ + version: string; + format: number; + created: string; + generatorName: string; + generatorPath: string; + palette: string; + seed: number; + cols: number; + rows: number; + stagger: "odd" | "even"; + orientation: "flat" | "pointy"; + settings: GeneratorSettings; + /** Terrain per hex, keyed "x_y" (grid starts at 0_0). */ + cells: Map; + paths: { type: string; route?: string; hexes: string[] }[]; + /** The generator file's full text when saved. */ + generatorMarkdown: string; +} + +// ── Terrain grid ────────────────────────────────────────────────────────── + +/** + * Encode a cols×rows grid as a legend line plus one line per row of legend + * indexes, run-length encoded: "0*5 2 1*3". "-" is an unpainted hex. + */ +export function encodeCells(cells: Map, cols: number, rows: number): string { + const legend: string[] = []; + const index = new Map(); + const lines: string[] = []; + for (let y = 0; y < rows; y++) { + const tokens: string[] = []; + let prev = "", run = 0; + const flush = () => { + if (run) tokens.push(run > 1 ? `${prev}*${run}` : prev); + }; + for (let x = 0; x < cols; x++) { + const t = cells.get(`${x}_${y}`); + let tok = "-"; + if (t !== undefined) { + if (!index.has(t)) { + index.set(t, legend.length); + legend.push(t); + } + tok = String(index.get(t)); + } + if (tok === prev) run++; + else { + flush(); + prev = tok; + run = 1; + } + } + flush(); + lines.push(tokens.join(" ")); + } + return [`legend: ${legend.join("; ")}`, ...lines].join("\n"); +} + +export function decodeCells(text: string, cols: number, rows: number): { cells: Map } | { error: string } { + const lines = text.split(/\r?\n/); + const head = lines.shift() ?? ""; + if (!head.startsWith("legend:")) return { error: "the terrain block has no legend line" }; + const legend = head.slice("legend:".length).split(";").map((s) => s.trim()).filter((s) => s !== ""); + const cells = new Map(); + for (let y = 0; y < rows; y++) { + let x = 0; + for (const tok of (lines[y] ?? "").trim().split(/\s+/).filter(Boolean)) { + const m = /^(-|\d+)(?:\*(\d+))?$/.exec(tok); + if (!m) return { error: `row ${y + 1} has "${tok}"` }; + const n = m[2] ? Number(m[2]) : 1; + for (let k = 0; k < n; k++, x++) { + if (m[1] === "-") continue; + const t = legend[Number(m[1])]; + if (t === undefined) return { error: `row ${y + 1} uses terrain #${m[1]}, which isn't in the legend` }; + cells.set(`${x}_${y}`, t); + } + } + if (x !== cols) return { error: `row ${y + 1} has ${x} hexes, expected ${cols}` }; + } + return { cells }; +} + +// ── Whole file ──────────────────────────────────────────────────────────── + +const yaml = (v: string | number) => + typeof v === "number" || /^[A-Za-z0-9_][A-Za-z0-9 _./()-]*$/.test(v) ? String(v) : JSON.stringify(v); + +export function serializeSave(s: GeneratorSave): string { + const fm = [ + `${SAVE_MARKER}: ${SAVE_FORMAT}`, + `${VERSION_KEY}: ${yaml(s.version)}`, + `name: ${yaml(s.name)}`, + `generator: ${yaml(s.generatorName)}`, + `generator-path: ${yaml(s.generatorPath)}`, + `palette: ${yaml(s.palette)}`, + `seed: ${s.seed}`, + `size: ${s.cols}x${s.rows}`, + `stagger: ${s.stagger}`, + `orientation: ${s.orientation}`, + `created: ${yaml(s.created)}`, + ]; + const block = (lang: string, body: string) => `${FENCE}${lang}\n${body.replace(/\s+$/, "")}\n${FENCE}`; + return [ + "---", + ...fm, + "---", + "", + `# ${s.name}`, + "", + `Generator save from **${s.generatorName}**: seed ${s.seed}, ${s.cols}×${s.rows}. Load it from the terrain generator page.`, + "", + "## Settings", + "", + block("json", JSON.stringify(s.settings, null, 2)), + "", + "## Terrain", + "", + block("hexmaker-terrain", encodeCells(s.cells, s.cols, s.rows)), + "", + "## Paths", + "", + block("json", JSON.stringify(s.paths)), + "", + "## Generator", + "", + block("hex-wfc", s.generatorMarkdown), + "", + ].join("\n"); +} + +export function isSaveMarkdown(text: string): boolean { + return new RegExp(`^---\\r?\\n(?:(?!---).*\\r?\\n)*?${SAVE_MARKER}\\s*:`).test(text); +} + +function isSavedPath(p: unknown): p is GeneratorSave["paths"][number] { + if (!p || typeof p !== "object") return false; + const o = p as Record; + return typeof o.type === "string" && Array.isArray(o.hexes) && o.hexes.every((h) => typeof h === "string"); +} + +/** The body of the fenced block under "## heading". */ +function section(text: string, heading: string): string | undefined { + const re = new RegExp(`^## ${heading}\\s*\\r?\\n[\\s\\S]*?^${FENCE}[^\\n]*\\r?\\n([\\s\\S]*?)^${FENCE}\\s*$`, "m"); + return re.exec(text)?.[1]?.replace(/\r?\n$/, ""); +} + +/** + * Read a save written by any version. Later formats should add a migration + * here keyed on `format` (and `hexmaker-version` if needed) rather than + * changing how older files are read. + */ +export function parseSave(text: string, fallbackName = "save"): { save: GeneratorSave; warnings: string[] } | { error: string } { + const fmMatch = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text); + if (!fmMatch) return { error: "no frontmatter" }; + const fm: Record = {}; + for (const line of fmMatch[1].split(/\r?\n/)) { + const m = /^([\w-]+):\s*(.*)$/.exec(line); + if (!m) continue; + let v = m[2].trim(); + if (v.startsWith('"')) { + try { + v = String(JSON.parse(v)); + } catch { + v = v.slice(1, -1); + } + } + fm[m[1]] = v; + } + const format = Number(fm[SAVE_MARKER]); + if (!Number.isFinite(format)) return { error: "not a generator save" }; + const warnings: string[] = []; + if (format > SAVE_FORMAT) warnings.push(`Saved in a newer format (${format}); loading what this version understands`); + + const size = /^(\d+)\s*x\s*(\d+)$/i.exec(fm.size ?? ""); + if (!size) return { error: `bad size "${fm.size ?? ""}"` }; + const cols = Number(size[1]), rows = Number(size[2]); + + const terrain = section(text, "Terrain"); + if (terrain === undefined) return { error: "no Terrain block" }; + const decoded = decodeCells(terrain, cols, rows); + if ("error" in decoded) return { error: `terrain: ${decoded.error}` }; + + let settings: GeneratorSettings = {}; + try { + settings = JSON.parse(section(text, "Settings") ?? "{}") as GeneratorSettings; + } catch { + warnings.push("The settings block couldn't be read, so the generator's own settings are used"); + } + let paths: GeneratorSave["paths"] = []; + try { + const raw = JSON.parse(section(text, "Paths") ?? "[]") as unknown; + if (Array.isArray(raw)) paths = (raw as unknown[]).filter(isSavedPath); + } catch { + warnings.push("The paths block couldn't be read, so the save has no paths"); + } + + return { + save: { + name: fm.name || fallbackName, + version: fm[VERSION_KEY] || "unknown", + format, + created: fm.created ?? "", + generatorName: fm.generator ?? "", + generatorPath: fm["generator-path"] ?? "", + palette: fm.palette ?? "", + seed: Number(fm.seed) >>> 0, + cols, + rows, + stagger: fm.stagger === "even" ? "even" : "odd", + orientation: fm.orientation === "pointy" ? "pointy" : "flat", + settings, + cells: decoded.cells, + paths, + generatorMarkdown: section(text, "Generator") ?? "", + }, + warnings, + }; +} diff --git a/src/worldgen/saves.ts b/src/worldgen/saves.ts new file mode 100644 index 00000000..1b4796d7 --- /dev/null +++ b/src/worldgen/saves.ts @@ -0,0 +1,101 @@ +/** + * Generator saves in the vault: list, write, read, and load one back onto its + * generator. The file format is in saveFormat.ts. + */ + +import { TFile, TFolder } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { slugify } from "../utils"; +import { VERSION_KEY } from "../compat"; +import { generatorsFolder, savesFolder, listGenerators, saveGeneratorSettings, type GeneratorFile } from "./generators"; +import { parseSave, serializeSave, SAVE_MARKER, type GeneratorSave } from "./saveFormat"; +import { parseModelMarkdown, SETTING_KEYS, type GeneratorSettings } from "../../packages/hex-wfc/src"; + +/** A save as listed (frontmatter only; the file is parsed on load). */ +export interface SaveEntry { + file: TFile; + name: string; + generator: string; + seed: string; + size: string; + version: string; +} + +/** A frontmatter value as text, or `fallback` if it isn't a plain value. */ +const text = (v: unknown, fallback: string): string => + typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? String(v) : fallback; + +export function listSaves(plugin: HexmakerPlugin): SaveEntry[] { + const folder = savesFolder(plugin) + "/"; + return plugin.app.vault + .getMarkdownFiles() + .filter((f) => f.path.startsWith(folder) && !f.basename.startsWith("_")) + .map((file) => ({ file, fm: plugin.app.metadataCache.getFileCache(file)?.frontmatter })) + .filter(({ fm }) => fm?.[SAVE_MARKER] !== undefined) + .map(({ file, fm }) => ({ + file, + name: text(fm?.name, file.basename), + generator: text(fm?.generator, ""), + seed: text(fm?.seed, ""), + size: text(fm?.size, ""), + version: text(fm?.[VERSION_KEY], "unknown"), + })) + .sort((a, b) => b.file.stat.mtime - a.file.stat.mtime); +} + +async function ensureFolder(plugin: HexmakerPlugin, path: string): Promise { + if (plugin.app.vault.getAbstractFileByPath(path) instanceof TFolder) return; + try { + await plugin.app.vault.createFolder(path); + } catch { + /* exists */ + } +} + +/** Write a save. Never overwrites: a name clash gets a numeric suffix. */ +export async function writeSave(plugin: HexmakerPlugin, save: GeneratorSave): Promise { + const folder = savesFolder(plugin); + await ensureFolder(plugin, generatorsFolder(plugin)); + await ensureFolder(plugin, folder); + const base = slugify(save.name) || "save"; + let name = base; + for (let n = 2; plugin.app.vault.getAbstractFileByPath(`${folder}/${name}.md`); n++) name = `${base}-${n}`; + return plugin.app.vault.create(`${folder}/${name}.md`, serializeSave({ ...save, name })); +} + +export async function readSave(plugin: HexmakerPlugin, file: TFile): Promise<{ save: GeneratorSave; warnings: string[] } | { error: string }> { + return parseSave(await plugin.app.vault.read(file), file.basename); +} + +/** + * Put a save's settings back on its generator, so the page shows what was + * saved. The generator is found by path, then by name; if it's gone, it is + * recreated from the copy inside the save. Returns the generator file. + */ +export async function applySave( + plugin: HexmakerPlugin, + save: GeneratorSave, +): Promise<{ file: TFile; recreated: boolean } | { error: string }> { + const generators = await listGenerators(plugin); + let g: GeneratorFile | undefined = + generators.find((x) => x.file.path === save.generatorPath) ?? generators.find((x) => x.model.name === save.generatorName); + let recreated = false; + if (!g) { + if (!save.generatorMarkdown) return { error: `Generator "${save.generatorName}" no longer exists and the save has no copy of it.` }; + const folder = generatorsFolder(plugin); + await ensureFolder(plugin, folder); + const base = slugify(save.generatorName) || "generator"; + let path = `${folder}/${base}.md`; + for (let n = 2; plugin.app.vault.getAbstractFileByPath(path); n++) path = `${folder}/${base}-${n}.md`; + const file = await plugin.app.vault.create(path, save.generatorMarkdown); + const { model, warnings } = parseModelMarkdown(save.generatorMarkdown, file.basename); + g = { file, model, warnings }; + recreated = true; + } + // Replace the generator's settings with the saved ones (keys the save + // doesn't have go back to their defaults). + const patch: Partial> = {}; + for (const k of Object.keys(SETTING_KEYS) as (keyof GeneratorSettings)[]) patch[k] = save.settings[k]; + await saveGeneratorSettings(plugin, g.file, patch); + return { file: g.file, recreated }; +} diff --git a/styles.css b/styles.css index 7911c4f9..ba379b8a 100644 --- a/styles.css +++ b/styles.css @@ -5228,10 +5228,15 @@ button.duckmage-wfc-chip { padding: 1em 1.5em 3em; } -.duckmage-wfc-page .duckmage-wfc-tab { +/* The view's content element carries both classes. It is the container the + narrow-pane @container rule below measures. */ +.duckmage-wfc-page.duckmage-wfc-tab { + container-type: inline-size; +} + +.duckmage-wfc-page .duckmage-wfc-layout { max-width: 1280px; margin: 0 auto; - container-type: inline-size; } /* Controls left, preview right. The preview column sticks to the top of the @@ -5254,16 +5259,28 @@ button.duckmage-wfc-chip { width: 100%; } -/* Narrow panes: one column, preview first and not sticky. */ +/* Narrow panes: one column, with the preview pinned to the top (capped in + height so the controls keep most of the pane; its own rows scroll). */ @container (max-width: 760px) { .duckmage-wfc-layout { grid-template-columns: minmax(0, 1fr); + gap: 1em; } .duckmage-wfc-side { - position: static; - max-height: none; order: -1; + z-index: 2; + max-height: 45vh; + padding-bottom: 0.5em; + background: var(--background-primary); + border-bottom: 1px solid var(--background-modifier-border); + } + + .duckmage-wfc-side .duckmage-wfc-preview { + width: auto; + max-width: 100%; + max-height: 28vh; + margin: 0 auto; } } diff --git a/tests/compat.test.ts b/tests/compat.test.ts new file mode 100644 index 00000000..91c3ad82 --- /dev/null +++ b/tests/compat.test.ts @@ -0,0 +1,108 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import * as path from "node:path"; +import { isModelMarkdown, parseModelMarkdown, solve } from "../packages/hex-wfc/src"; +import { compareVersions, migrateMapData, VERSION_KEY } from "../src/compat"; +import { isSaveMarkdown, parseSave, serializeSave, decodeCells, encodeCells } from "../src/worldgen/saveFormat"; +import { exampleFiles } from "./compat/examples"; + +/** + * Every released version leaves an example generator, save and map in + * tests/fixtures/compat// (written by `npm run version`). The + * current code must still load all of them. If one breaks, add a migration + * keyed on the file's version instead of editing the old example. + */ + +const root = process.cwd(); +const compatDir = path.join(root, "tests", "fixtures", "compat"); +// Checkouts on Windows may turn the examples CRLF; the files were written LF. +const read = (...p: string[]) => readFileSync(path.join(...p), "utf8").replace(/ +/g, " +"); +const versions = existsSync(compatDir) + ? readdirSync(compatDir).filter((d) => /^\d+(\.\d+)*$/.test(d)).sort(compareVersions) + : []; +const current = (JSON.parse(read(root, "manifest.json")) as { version: string }).version; + +describe("compat examples", () => { + it("exist for the current version (npm run version writes them)", () => { + expect(versions).toContain(current); + }); + + for (const version of versions) { + describe(version, () => { + const dir = path.join(compatDir, version); + + it("generator loads and still generates", () => { + const text = read(dir, "generator.md"); + expect(isModelMarkdown(text)).toBe(true); + const { model, warnings } = parseModelMarkdown(text, "example"); + expect(warnings).toEqual([]); + expect(model.meta[VERSION_KEY]).toBe(version); + expect(model.terrains.length).toBeGreaterThan(1); + const r = solve(model, { cols: 14, rows: 10, orientation: "flat", seed: 1 }); + expect(r.ok).toBe(true); + }); + + it("save loads with its map, settings and generator copy", () => { + const text = read(dir, "save.md"); + expect(isSaveMarkdown(text)).toBe(true); + expect(isModelMarkdown(text)).toBe(false); + const parsed = parseSave(text); + if ("error" in parsed) throw new Error(parsed.error); + const { save, warnings } = parsed; + expect(warnings).toEqual([]); + expect(save.version).toBe(version); + expect(save.cells.size).toBe(save.cols * save.rows); + expect(Object.keys(save.settings).length).toBeGreaterThan(0); + expect(parseModelMarkdown(save.generatorMarkdown, "copy").warnings).toEqual([]); + }); + + it("map entry migrates to the current shape", () => { + const map = migrateMapData(JSON.parse(read(dir, "map.json"))); + expect(map.createdWith).toBe(version); + expect(map.gridSize.cols).toBeGreaterThan(0); + expect(Array.isArray(map.pathChains)).toBe(true); + expect(map.paletteName).toBeTruthy(); + }); + }); + } +}); + +describe("save format", () => { + it("round-trips a save written now", () => { + const text = exampleFiles("9.9.9")["save.md"]; + const parsed = parseSave(text); + if ("error" in parsed) throw new Error(parsed.error); + expect(serializeSave(parsed.save)).toBe(text); + }); + + it("run-length encodes the terrain grid, including unpainted hexes", () => { + const cells = new Map([["0_0", "Grass"], ["1_0", "Grass"], ["2_0", "Water"], ["0_1", "Water"], ["2_1", "Grass"]]); + const text = encodeCells(cells, 3, 2); + expect(text).toBe("legend: Grass; Water\n0*2 1\n1 - 0"); + const back = decodeCells(text, 3, 2); + expect("cells" in back && [...back.cells].sort()).toEqual([...cells].sort()); + }); + + it("explains a damaged terrain block", () => { + expect(decodeCells("legend: Grass\n0*2", 3, 1)).toHaveProperty("error"); + expect(decodeCells("legend: Grass\n0 5 0", 3, 1)).toHaveProperty("error"); + }); +}); + +describe("compareVersions", () => { + it("orders dotted versions numerically, unknown first", () => { + expect(compareVersions("1.5.10", "1.5.9")).toBeGreaterThan(0); + expect(compareVersions("1.5.5", "1.5.5")).toBe(0); + expect(compareVersions("unknown", "1.0.0")).toBeLessThan(0); + }); +}); + +describe("migrateMapData", () => { + it("fills what old map entries lack and keeps unknown fields", () => { + const m = migrateMapData({ name: "old", gridSize: { cols: 3, rows: 2 }, futureField: 1 }); + expect(m).toMatchObject({ paletteName: "Default", gridOffset: { x: 0, y: 0 }, pathChains: [], futureField: 1 }); + }); +}); diff --git a/tests/compat/examples.ts b/tests/compat/examples.ts new file mode 100644 index 00000000..7cd615fd --- /dev/null +++ b/tests/compat/examples.ts @@ -0,0 +1,93 @@ +/** + * The example generator, save and map written for each released version + * (tests/fixtures/compat//). Built from a fixed little map so every + * version's set is comparable. Used by snapshot.ts; read back by + * tests/compat.test.ts with the current code. + */ + +import { cellKey, learnModel, modelToMarkdown, pathRouteKey, solve, type HexWfcModel } from "../../packages/hex-wfc/src"; +import { VERSION_KEY } from "../../src/compat"; +import { serializeSave } from "../../src/worldgen/saveFormat"; +import type { MapData } from "../../src/types"; + +const COLS = 14, ROWS = 10, SEED = 7; + +/** A lake, a forest band and hills, with a road edge to edge and a river into the lake. */ +function exampleMap() { + const cells = new Map(); + for (let x = 0; x < COLS; x++) { + for (let y = 0; y < ROWS; y++) { + const dx = x - 4, dy = y - 5; + let t = "grass"; + if (dx * dx + dy * dy < 6) t = "shallows"; + else if (x >= 10) t = "forest"; + else if (y <= 1) t = "hills"; + cells.set(cellKey(x, y), t); + } + } + const road = Array.from({ length: COLS }, (_, x) => cellKey(x, 8)); + const river = Array.from({ length: 5 }, (_, i) => cellKey(4, i)).concat(cellKey(4, 5)); + return { cells, paths: [{ type: "Road", hexes: road }, { type: "River", hexes: river }] }; +} + +export function exampleGenerator(version: string): HexWfcModel { + const { cells, paths } = exampleMap(); + const model = learnModel(cells, { + name: "compat-example", + orientation: "flat", + paths, + meta: { palette: "Default", "source-map": "compat-example", created: "2026-10-08", [VERSION_KEY]: version }, + }); + const road = model.paths?.find((p) => p.type === "Road"); + // Exercise every kind of saved setting, so a format change shows up here. + model.settings = { + featureSize: 1.25, + randomness: 0.2, + edgeSmoothing: 0.5, + speckSize: 1, + keepRare: 0.05, + impassable: ["shallows"], + connected: true, + mix: { forest: 1.5 }, + counts: { shallows: { min: 1, max: 2 } }, + drawPaths: true, + ...(road ? { paths: { [pathRouteKey(road)]: { count: 1, wiggle: 0.5, as: "Road" } } } : {}), + }; + return model; +} + +export function exampleFiles(version: string): { "generator.md": string; "save.md": string; "map.json": string } { + const model = exampleGenerator(version); + const generatorMarkdown = modelToMarkdown(model); + const solved = solve(model, { cols: COLS, rows: ROWS, orientation: "flat", stagger: "odd", seed: SEED }); + if (!solved.ok) throw new Error(`example generator failed: ${solved.message}`); + const save = serializeSave({ + name: "compat-example-7", + version, + format: 1, + created: "2026-10-08", + generatorName: model.name, + generatorPath: "world/generators/compat-example.md", + palette: "Default", + seed: SEED, + cols: COLS, + rows: ROWS, + stagger: "odd", + orientation: "flat", + settings: model.settings ?? {}, + cells: solved.cells, + paths: solved.paths, + generatorMarkdown, + }); + const map: MapData = { + name: "compat-example", + createdWith: version, + paletteName: "Default", + gridSize: { cols: COLS, rows: ROWS }, + gridOffset: { x: 0, y: 0 }, + pathChains: solved.paths.map((p) => ({ typeName: p.type, hexes: p.hexes })), + staggerOffset: "odd", + showCoords: true, + }; + return { "generator.md": generatorMarkdown, "save.md": save, "map.json": JSON.stringify(map, null, 2) + "\n" }; +} diff --git a/tests/compat/snapshot.ts b/tests/compat/snapshot.ts new file mode 100644 index 00000000..4f30d651 --- /dev/null +++ b/tests/compat/snapshot.ts @@ -0,0 +1,27 @@ +/** + * Write this version's compatibility examples (generator, save, map) to + * tests/fixtures/compat//. Run by `npm run version` on + * every bump, or by hand with `npm run compat:snapshot`. + * + * Never overwrites an existing version's set: those files are the record of + * what that version wrote, and tests/compat.test.ts checks the current code + * still reads them. Pass --force only to regenerate the set for an + * unreleased version. + */ + +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import * as path from "node:path"; +import { exampleFiles } from "./examples"; + +const root = process.cwd(); +const version = (JSON.parse(readFileSync(path.join(root, "manifest.json"), "utf8")) as { version: string }).version; +const dir = path.join(root, "tests", "fixtures", "compat", version); +const force = process.argv.includes("--force"); + +if (existsSync(dir) && !force) { + console.log(`Compat examples for ${version} already exist; leaving them as they are.`); +} else { + mkdirSync(dir, { recursive: true }); + for (const [name, text] of Object.entries(exampleFiles(version))) writeFileSync(path.join(dir, name), text); + console.log(`Wrote compat examples for ${version} to ${path.relative(root, dir)}.`); +} diff --git a/tests/fixtures/compat/1.5.5/generator.md b/tests/fixtures/compat/1.5.5/generator.md new file mode 100644 index 00000000..ca5301ac --- /dev/null +++ b/tests/fixtures/compat/1.5.5/generator.md @@ -0,0 +1,86 @@ +--- +hex-wfc: 1 +name: compat-example +example-hexes: 140 +feature-size: 1.25 +randomness: 0.2 +edge-smoothing: 0.5 +speck-size: 1 +keep-rare: 0.05 +connected: true +impassable: "shallows" +mix: "forest 1.5" +counts: "shallows 1-2" +draw-paths: true +paths: "Road: edge > edge = count 1, wiggle 0.5, as Road" +palette: Default +source-map: compat-example +created: 2026-10-08 +hexmaker-version: 1.5.5 +--- + +# compat-example + +A wave function collapse generator. You can edit the tables and settings by hand. + +- **Terrains**: *Weight* is how common the terrain is; 0 means the solver never places it. + *Patch %* is the size of a typical patch as a share of the map, so patches scale + with the map. *Shape* is how it spreads: `blob` (compact patches), `line` (long + thin runs), `scatter` (single hexes) or `none` (left to the neighbour rules). + *Turn* is how often a `line` changes direction (0 to 1) and *Width* its + thickness (1 to 3). *Spacing* is the closest two `scatter` hexes may be. + *Edge* is how common the terrain is along the map border (1 = as anywhere). +- **Adjacency**: pairs that may touch, and how often (higher is more likely). + A pair that isn't listed can never touch, including a terrain next to itself. + Order doesn't matter, so *A | B* also covers *B | A*. +- **Features** (optional): lines of terrain that are always placed. *From* and *To* + are `edge`, `none` or a terrain name. +- **Paths** (optional): paths drawn over the terrain. *From* and *To* are `edge`, + `none`, `path` (joins another path of the same type) or a terrain. *Through* + is the share of the path on each terrain. +- **Layout** (optional): where each terrain sat in the example map, in a 3×3 + grid. 1 means as common there as anywhere; 3 means three times as common. +- Frontmatter settings (optional): `feature-size`, `directional-bias`, `clumping`, + `mix-strength`, `scatter`, `randomness`, `edge-strength`, `edge-terrain`, + `line-width`, `edge-smoothing`, `speck-size`, `keep-rare`, `symmetry`, `spacing`, + `connected`, `impassable`, + `mix`, `counts`, `features`, `draw-paths` and `paths` (per route, e.g. + `Road: edge > peak = count 2, wiggle 1.5, as Trade road`). + +## Terrains + +| Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge | +| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: | +| grass | 59 | 42.14 | none | | | | 0.95 | +| forest | 40 | 28.57 | blob | | | | 1.21 | +| shallows | 21 | 15 | blob | | | | 0.05 | +| hills | 20 | 14.29 | blob | | | | 1.71 | + +## Adjacency + +| Terrain | Next to | Weight | +| --- | --- | ---: | +| grass | grass | 125 | +| grass | shallows | 34 | +| grass | hills | 19 | +| grass | forest | 15 | +| forest | forest | 93 | +| forest | hills | 4 | +| shallows | shallows | 46 | +| hills | hills | 37 | + +## Paths + +| Path | From | To | Count | Turn | Length % | Through | +| --- | --- | --- | ---: | ---: | ---: | --- | +| Road | edge | edge | 1 | 1 | 100 | grass 71%; forest 29% | +| River | edge | none | 1 | 0 | 43 | shallows 50%; hills 33%; grass 17% | + +## Layout + +| Terrain | NW | N | NE | W | C | E | SW | S | SE | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| grass | 0.96 | 1.06 | 0.2 | 0.96 | 1.33 | 0.25 | 1.83 | 1.96 | 0.25 | +| forest | 0.17 | 0.17 | 3 | 0.21 | 0.21 | 2.88 | 0.21 | 0.21 | 2.88 | +| shallows | 0.72 | 0.44 | 0.2 | 3.37 | 2.32 | 0.25 | 0.91 | 0.56 | 0.25 | +| hills | 3.08 | 3.08 | 0.2 | 0.21 | 0.21 | 0.25 | 0.21 | 0.21 | 0.25 | diff --git a/tests/fixtures/compat/1.5.5/map.json b/tests/fixtures/compat/1.5.5/map.json new file mode 100644 index 00000000..8ec2634e --- /dev/null +++ b/tests/fixtures/compat/1.5.5/map.json @@ -0,0 +1,46 @@ +{ + "name": "compat-example", + "createdWith": "1.5.5", + "paletteName": "Default", + "gridSize": { + "cols": 14, + "rows": 10 + }, + "gridOffset": { + "x": 0, + "y": 0 + }, + "pathChains": [ + { + "typeName": "Road", + "hexes": [ + "6_9", + "7_8", + "7_7", + "7_6", + "7_5", + "6_5", + "5_4", + "4_4", + "3_3", + "2_4", + "1_3", + "0_3" + ] + }, + { + "typeName": "River", + "hexes": [ + "5_0", + "6_1", + "7_1", + "8_2", + "9_1", + "10_1", + "11_0" + ] + } + ], + "staggerOffset": "odd", + "showCoords": true +} diff --git a/tests/fixtures/compat/1.5.5/save.md b/tests/fixtures/compat/1.5.5/save.md new file mode 100644 index 00000000..7c029c6a --- /dev/null +++ b/tests/fixtures/compat/1.5.5/save.md @@ -0,0 +1,163 @@ +--- +hexmaker-save: 1 +hexmaker-version: 1.5.5 +name: compat-example-7 +generator: compat-example +generator-path: world/generators/compat-example.md +palette: Default +seed: 7 +size: 14x10 +stagger: odd +orientation: flat +created: 2026-10-08 +--- + +# compat-example-7 + +Generator save from **compat-example**: seed 7, 14×10. Load it from the terrain generator page. + +## Settings + +~~~~json +{ + "featureSize": 1.25, + "randomness": 0.2, + "edgeSmoothing": 0.5, + "speckSize": 1, + "keepRare": 0.05, + "impassable": [ + "shallows" + ], + "connected": true, + "mix": { + "forest": 1.5 + }, + "counts": { + "shallows": { + "min": 1, + "max": 2 + } + }, + "drawPaths": true, + "paths": { + "Road: edge > edge": { + "count": 1, + "wiggle": 0.5, + "as": "Road" + } + } +} +~~~~ + +## Terrain + +~~~~hexmaker-terrain +legend: hills; forest; grass; shallows +0*7 1*7 +0*7 1*7 +0*7 1*7 +2*2 0 2 0*3 1*7 +2*3 3 2*3 1*7 +2 3*5 2*2 1*6 +2 3*6 2 1*6 +2*2 3 2 3*3 2 1*6 +2*8 1*6 +2*8 1*6 +~~~~ + +## Paths + +~~~~json +[{"type":"Road","route":"Road: edge > edge","hexes":["6_9","7_8","7_7","7_6","7_5","6_5","5_4","4_4","3_3","2_4","1_3","0_3"]},{"type":"River","route":"River: edge > none","hexes":["5_0","6_1","7_1","8_2","9_1","10_1","11_0"]}] +~~~~ + +## Generator + +~~~~hex-wfc +--- +hex-wfc: 1 +name: compat-example +example-hexes: 140 +feature-size: 1.25 +randomness: 0.2 +edge-smoothing: 0.5 +speck-size: 1 +keep-rare: 0.05 +connected: true +impassable: "shallows" +mix: "forest 1.5" +counts: "shallows 1-2" +draw-paths: true +paths: "Road: edge > edge = count 1, wiggle 0.5, as Road" +palette: Default +source-map: compat-example +created: 2026-10-08 +hexmaker-version: 1.5.5 +--- + +# compat-example + +A wave function collapse generator. You can edit the tables and settings by hand. + +- **Terrains**: *Weight* is how common the terrain is; 0 means the solver never places it. + *Patch %* is the size of a typical patch as a share of the map, so patches scale + with the map. *Shape* is how it spreads: `blob` (compact patches), `line` (long + thin runs), `scatter` (single hexes) or `none` (left to the neighbour rules). + *Turn* is how often a `line` changes direction (0 to 1) and *Width* its + thickness (1 to 3). *Spacing* is the closest two `scatter` hexes may be. + *Edge* is how common the terrain is along the map border (1 = as anywhere). +- **Adjacency**: pairs that may touch, and how often (higher is more likely). + A pair that isn't listed can never touch, including a terrain next to itself. + Order doesn't matter, so *A | B* also covers *B | A*. +- **Features** (optional): lines of terrain that are always placed. *From* and *To* + are `edge`, `none` or a terrain name. +- **Paths** (optional): paths drawn over the terrain. *From* and *To* are `edge`, + `none`, `path` (joins another path of the same type) or a terrain. *Through* + is the share of the path on each terrain. +- **Layout** (optional): where each terrain sat in the example map, in a 3×3 + grid. 1 means as common there as anywhere; 3 means three times as common. +- Frontmatter settings (optional): `feature-size`, `directional-bias`, `clumping`, + `mix-strength`, `scatter`, `randomness`, `edge-strength`, `edge-terrain`, + `line-width`, `edge-smoothing`, `speck-size`, `keep-rare`, `symmetry`, `spacing`, + `connected`, `impassable`, + `mix`, `counts`, `features`, `draw-paths` and `paths` (per route, e.g. + `Road: edge > peak = count 2, wiggle 1.5, as Trade road`). + +## Terrains + +| Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge | +| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: | +| grass | 59 | 42.14 | none | | | | 0.95 | +| forest | 40 | 28.57 | blob | | | | 1.21 | +| shallows | 21 | 15 | blob | | | | 0.05 | +| hills | 20 | 14.29 | blob | | | | 1.71 | + +## Adjacency + +| Terrain | Next to | Weight | +| --- | --- | ---: | +| grass | grass | 125 | +| grass | shallows | 34 | +| grass | hills | 19 | +| grass | forest | 15 | +| forest | forest | 93 | +| forest | hills | 4 | +| shallows | shallows | 46 | +| hills | hills | 37 | + +## Paths + +| Path | From | To | Count | Turn | Length % | Through | +| --- | --- | --- | ---: | ---: | ---: | --- | +| Road | edge | edge | 1 | 1 | 100 | grass 71%; forest 29% | +| River | edge | none | 1 | 0 | 43 | shallows 50%; hills 33%; grass 17% | + +## Layout + +| Terrain | NW | N | NE | W | C | E | SW | S | SE | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| grass | 0.96 | 1.06 | 0.2 | 0.96 | 1.33 | 0.25 | 1.83 | 1.96 | 0.25 | +| forest | 0.17 | 0.17 | 3 | 0.21 | 0.21 | 2.88 | 0.21 | 0.21 | 2.88 | +| shallows | 0.72 | 0.44 | 0.2 | 3.37 | 2.32 | 0.25 | 0.91 | 0.56 | 0.25 | +| hills | 3.08 | 3.08 | 0.2 | 0.21 | 0.21 | 0.25 | 0.21 | 0.21 | 0.25 | +~~~~ diff --git a/tests/pendingTerrain.test.ts b/tests/pendingTerrain.test.ts new file mode 100644 index 00000000..0f78b947 --- /dev/null +++ b/tests/pendingTerrain.test.ts @@ -0,0 +1,60 @@ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { TFile, type App } from "obsidian"; +import { clearPendingTerrain, getTerrainFromFile, notePendingTerrain, pendingTerrainOf } from "../src/frontmatter"; +import { insertLinkInSection } from "../src/sections"; + +/** + * Regression: creating a map writes every hex note and opens the map + * straight away. Obsidian indexes the notes over the next seconds (tens of + * seconds on a large vault), so the first render read no terrain for most + * hexes, and nothing re-rendered afterwards: the map stayed mostly blank. + * Terrain the plugin just wrote is now read from memory until indexed. + */ + +const PATH = "world/hexes/m/1_2.md"; + +/** App whose metadata cache has (or hasn't yet) indexed one note. */ +function appWith(frontmatter: Record | undefined): App { + const file = Object.create(TFile.prototype) as TFile; + file.path = PATH; + return { + vault: { getAbstractFileByPath: (p: string) => (p === PATH ? file : null) }, + metadataCache: { getFileCache: () => (frontmatter ? { frontmatter } : null) }, + } as unknown as App; +} + +describe("terrain of notes not indexed yet", () => { + afterEach(() => clearPendingTerrain()); + + it("is read from memory until the metadata cache has the note", () => { + notePendingTerrain(PATH, "Forest"); + expect(getTerrainFromFile(appWith(undefined), PATH)).toBe("Forest"); + expect(pendingTerrainOf(PATH)).toBe("Forest"); + }); + + it("the indexed frontmatter wins once it's there", () => { + notePendingTerrain(PATH, "Forest"); + expect(getTerrainFromFile(appWith({ terrain: "Water" }), PATH)).toBe("Water"); + }); + + it("is forgotten when cleared (on the note's metadata change)", () => { + notePendingTerrain(PATH, "Forest"); + clearPendingTerrain(PATH); + expect(getTerrainFromFile(appWith(undefined), PATH)).toBeNull(); + }); +}); + +describe("insertLinkInSection", () => { + it("adds the link under an existing heading, once", () => { + const note = "---\nterrain: grass\n---\n\n### Encounters Table\n\n### Notes\n"; + const once = insertLinkInSection(note, "Encounters Table", "[[grass]]"); + expect(once).toMatch(/### Encounters Table\n+\[\[grass\]\]/); + expect(once.indexOf("[[grass]]")).toBeLessThan(once.indexOf("### Notes")); + expect(insertLinkInSection(once, "Encounters Table", "[[grass]]")).toBe(once); + }); + + it("appends the heading when the note doesn't have it", () => { + expect(insertLinkInSection("# Hex\n", "Encounters Table", "[[grass]]")).toBe("# Hex\n\n### Encounters Table\n\n[[grass]]\n"); + }); +}); diff --git a/tests/worldgenGenerators.test.ts b/tests/worldgenGenerators.test.ts index 4b42b0f8..459c7cb6 100644 --- a/tests/worldgenGenerators.test.ts +++ b/tests/worldgenGenerators.test.ts @@ -194,9 +194,10 @@ describe("worldgen generators", () => { const file = Object.create(TFile.prototype) as TFile; file.path = "world/generators/g.md"; await saveGeneratorSettings(plugin, file, { featureSize: 1.5, counts: { Town: { min: 3, max: 3 } }, impassable: ["Water"] }); - expect(otherFm.get(file.path)).toEqual({ "feature-size": 1.5, counts: "Town 3", impassable: "Water" }); + // Every write also stamps the plugin version ("unknown" in this stub). + expect(otherFm.get(file.path)).toEqual({ "feature-size": 1.5, counts: "Town 3", impassable: "Water", "hexmaker-version": "unknown" }); await saveGeneratorSettings(plugin, file, { featureSize: undefined }); - expect(otherFm.get(file.path)).toEqual({ counts: "Town 3", impassable: "Water" }); + expect(otherFm.get(file.path)).toEqual({ counts: "Town 3", impassable: "Water", "hexmaker-version": "unknown" }); }); }); From 8b09ebb8280fffe0422493a3cd85e2672570edfc Mon Sep 17 00:00:00 2001 From: nyxsys Date: Wed, 7 Oct 2026 22:41:03 -0400 Subject: [PATCH 018/558] test: fix the CRLF normalisation in compat.test.ts (escapes were mangled in 7d3ea78) Co-Authored-By: Claude Opus 5.5 --- tests/compat.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/compat.test.ts b/tests/compat.test.ts index 91c3ad82..a1ab8e5a 100644 --- a/tests/compat.test.ts +++ b/tests/compat.test.ts @@ -17,9 +17,7 @@ import { exampleFiles } from "./compat/examples"; const root = process.cwd(); const compatDir = path.join(root, "tests", "fixtures", "compat"); // Checkouts on Windows may turn the examples CRLF; the files were written LF. -const read = (...p: string[]) => readFileSync(path.join(...p), "utf8").replace(/ -/g, " -"); +const read = (...p: string[]) => readFileSync(path.join(...p), "utf8").replace(/\r\n/g, "\n"); const versions = existsSync(compatDir) ? readdirSync(compatDir).filter((d) => /^\d+(\.\d+)*$/.test(d)).sort(compareVersions) : []; From 2d3c7ee7bbe1abfc24a5755ed1bee8780fb8958b Mon Sep 17 00:00:00 2001 From: nyxsys Date: Thu, 8 Oct 2026 06:37:49 -0400 Subject: [PATCH 019/558] fix(hex-map): changing a tool's choice no longer turns the tool off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The terrain button and every right-click "Switch …" entry exited the tool before opening its picker, so closing the picker without picking (Escape, clicking away, or after only changing the brush size) left no tool active and you had to go back to the toolbar. - Pickers now only change the tool when something is picked; dismissing one leaves the tool, its choice, brush size and erase state as they were (handleTerrainButton, openIconPicker, and a `keep` flag on the table, submap, token and path handlers used by the right-click menu). - Picking a different tool properly leaves the old one first (leaveOtherToolFor commits its pending stroke). - Faction and region tools get the missing "Switch faction/region" entry. - Terrain/icon erase toggles say "Paint mode" instead of "Link mode". - Switching to icons no longer resets the terrain brush to 1×: the brush only applies to terrain (getBrushHexes). - A new path type starts a new chain instead of continuing the old one. tests/toolSwitch.test.ts guards the pattern. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/hex-map/HexMapView.ts | 81 +++++++++++++++++++++++++++------------ tests/toolSwitch.test.ts | 47 +++++++++++++++++++++++ 3 files changed, 106 insertions(+), 26 deletions(-) create mode 100644 tests/toolSwitch.test.ts diff --git a/package.json b/package.json index f31f6a0a..d6a9145c 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 8e993aae..38baddbb 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -1341,35 +1341,33 @@ export class HexMapView extends ItemView { if (mode === "terrain") { onSwitch = () => this.handleTerrainButton(); switchLabel = "Switch terrain"; - extra.push({ label: erasing ? "Link mode" : "Erase mode", onClick: toggleEraseMode }); + extra.push({ label: erasing ? "Paint mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "icon") { - onSwitch = () => { this.exitIconMode(); this.handleIconButton(); }; + onSwitch = () => this.openIconPicker(); switchLabel = "Switch icon"; - extra.push({ label: erasing ? "Link mode" : "Erase mode", onClick: toggleEraseMode }); + extra.push({ label: erasing ? "Paint mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "tableLink") { - onSwitch = () => { this.exitTableLinkMode(); this.handleTableLinkButton(); }; + onSwitch = () => this.handleTableLinkButton(true); switchLabel = "Switch table"; extra.push({ label: erasing ? "Link mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "submapLink") { - onSwitch = () => { this.exitSubmapLinkMode(); this.handleSubmapLinkButton(); }; + onSwitch = () => this.handleSubmapLinkButton(true); switchLabel = "Switch submap"; extra.push({ label: erasing ? "Link mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "factionLink") { + onSwitch = () => this.handleFactionLinkButton(); + switchLabel = "Switch faction"; extra.push({ label: erasing ? "Link mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "regionLink") { + onSwitch = () => this.handleRegionLinkButton(); + switchLabel = "Switch region"; extra.push({ label: erasing ? "Link mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "path") { - onSwitch = () => { - this.exitPathMode(); - this.drawingMode = null; - this.updateToolbarButtonStates(); - this.updatePathOverlay(); - this.handlePathButton(); - }; + onSwitch = () => this.handlePathButton(true); switchLabel = "Switch path type"; extra.push({ label: erasing ? "Draw mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "placeToken") { - onSwitch = () => { this.exitTokenMode(); this.handleTokenButton(); }; + onSwitch = () => this.handleTokenButton(true); switchLabel = "Switch token"; } // swap: no picker → onSwitch stays null, menu shows only "Exit tool" @@ -1377,6 +1375,15 @@ export class HexMapView extends ItemView { new PainterContextMenu(onSwitch, () => this.exitCurrentMode(), switchLabel, extra).open(clientX, clientY); } + /** + * Called when a picker's choice switches to tool `next`: properly leave a + * different active tool first (commits its pending stroke). Staying in the + * same tool keeps its state. + */ + private leaveOtherToolFor(next: NonNullable): void { + if (this.drawingMode !== null && this.drawingMode !== next) this.exitCurrentMode(); + } + private exitCurrentMode(): void { this.isErasingMode = false; if (this.drawingMode === "terrain") this.exitTerrainMode(); @@ -1406,7 +1413,11 @@ export class HexMapView extends ItemView { } private handleTerrainButton(): void { - if (this.drawingMode === "terrain") this.exitTerrainMode(); + // Keep the current tool while the picker is open: closing it without a + // pick (Escape, clicking away, or after only changing the brush size) + // must leave painting exactly as it was. It used to exit terrain mode + // here first, so any of those turned the tool off. + if (this.drawingMode === "terrain") this.commitTerrainStroke(); // Show crosshair on the viewport while the picker is open this.viewportEl?.addClass("duckmage-terrain-picking"); @@ -1418,6 +1429,7 @@ export class HexMapView extends ItemView { this.plugin.getMapPalette(this.activeMapName), (terrainName: string | null) => { this.viewportEl?.removeClass("duckmage-terrain-picking"); + this.leaveOtherToolFor("terrain"); this.drawingMode = "terrain"; this.isErasingMode = false; this.terrainPickMode = false; @@ -1428,6 +1440,7 @@ export class HexMapView extends ItemView { () => { // Eyedropper: enter terrain mode in pick-from-map state this.viewportEl?.removeClass("duckmage-terrain-picking"); + this.leaveOtherToolFor("terrain"); this.drawingMode = "terrain"; this.isErasingMode = false; this.terrainPickMode = true; @@ -1458,16 +1471,26 @@ export class HexMapView extends ItemView { private handleIconButton(): void { if (this.drawingMode === "icon") { this.exitIconMode(); return; } + this.openIconPicker(); + } + + /** + * Pick an icon to paint. Like the terrain picker, the current tool stays + * active until an icon is actually picked, so dismissing it changes nothing. + */ + private openIconPicker(): void { new IconPickerModal( this.app, this.plugin, (iconName: string | null, gmOnly: boolean) => { + this.leaveOtherToolFor("icon"); this.drawingMode = "icon"; this.isErasingMode = false; this.paintIconName = iconName; this.paintIconGmOnly = gmOnly; this.paintTerrainName = null; - this.paintBrushSize = 1; + // The terrain brush size is kept: icons always paint one hex + // (getBrushHexes), so switching to icons and back doesn't reset it. // Auto-enable the GM layer when the user picks a GM-only paint — // otherwise their painted icons are silently invisible because the // layer is hidden. Mirrors the showFactionOverlay-on-paint @@ -1501,8 +1524,9 @@ export class HexMapView extends ItemView { this.updateToolbarButtonStates(); } - private handleTableLinkButton(): void { - if (this.drawingMode === "tableLink") { this.exitTableLinkMode(); return; } + /** `keep`: opened from the tool's own right-click menu; stay in the tool unless something is picked. */ + private handleTableLinkButton(keep = false): void { + if (!keep && this.drawingMode === "tableLink") { this.exitTableLinkMode(); return; } new FolderTreePickerModal( this.app, this.plugin, @@ -1511,6 +1535,7 @@ export class HexMapView extends ItemView { "Filter tables…", "No tables found.", (file) => { + this.leaveOtherToolFor("tableLink"); this.drawingMode = "tableLink"; this.isErasingMode = false; this.paintTablePath = file.path; @@ -1532,13 +1557,14 @@ export class HexMapView extends ItemView { this.updateToolbarButtonStates(); } - private handleSubmapLinkButton(): void { - if (this.drawingMode === "submapLink") { this.exitSubmapLinkMode(); return; } + private handleSubmapLinkButton(keep = false): void { + if (!keep && this.drawingMode === "submapLink") { this.exitSubmapLinkMode(); return; } new SubmapPickerModal( this.app, this.plugin, undefined, (mapName) => { + this.leaveOtherToolFor("submapLink"); this.drawingMode = "submapLink"; this.isErasingMode = false; this.paintSubmapName = mapName; @@ -1558,6 +1584,7 @@ export class HexMapView extends ItemView { private handleFactionLinkButton(): void { new FactionPickerModal(this.app, this.plugin, (filePath) => { + this.leaveOtherToolFor("factionLink"); this.drawingMode = "factionLink"; this.isErasingMode = false; this.paintFactionPath = filePath; @@ -1579,6 +1606,7 @@ export class HexMapView extends ItemView { private handleRegionLinkButton(): void { new GeoRegionPickerModal(this.app, this.plugin, (filePath) => { + this.leaveOtherToolFor("regionLink"); this.drawingMode = "regionLink"; this.isErasingMode = false; this.paintRegionPath = filePath; @@ -1604,8 +1632,8 @@ export class HexMapView extends ItemView { this.updateToolbarButtonStates(); } - private handleTokenButton(): void { - if (this.drawingMode === "placeToken") { + private handleTokenButton(keep = false): void { + if (!keep && this.drawingMode === "placeToken") { this.exitTokenMode(); return; } @@ -1616,6 +1644,7 @@ export class HexMapView extends ItemView { "", {}, (notePath, data) => { + this.leaveOtherToolFor("placeToken"); this.pendingTokenNotePath = notePath; this.pendingTokenPlaceData = { icon: data.icon, shape: data.shape, size: data.size, color: data.color, border: data.border, description: data.description }; this.drawingMode = "placeToken"; @@ -3590,7 +3619,8 @@ export class HexMapView extends ItemView { private getBrushHexes(x: number, y: number): [number, number][] { const center: [number, number] = [x, y]; - if (this.paintBrushSize === 1) return [center]; + // Only terrain paints with a brush; every other tool works on one hex. + if (this.paintBrushSize === 1 || this.drawingMode !== "terrain") return [center]; const nb = hexNeighbors(x, y, this.plugin.settings.hexOrientation, this.getActiveStagger()); // nb[2] and nb[3] are always adjacent to each other AND to center in both // orientations (verified from offset tables), forming a compact triangle. @@ -4455,8 +4485,8 @@ export class HexMapView extends ItemView { } } - private handlePathButton(): void { - if (this.drawingMode === "path") { + private handlePathButton(keep = false): void { + if (!keep && this.drawingMode === "path") { this.exitPathMode(); this.drawingMode = null; this.updateToolbarButtonStates(); @@ -4468,6 +4498,9 @@ export class HexMapView extends ItemView { this.plugin, this.activePathTypeName, (typeName) => { + this.leaveOtherToolFor("path"); + // A new type starts a new chain rather than continuing the old one. + this.exitPathMode(); this.activePathTypeName = typeName; this.drawingMode = "path"; this.isErasingMode = false; diff --git a/tests/toolSwitch.test.ts b/tests/toolSwitch.test.ts new file mode 100644 index 00000000..59c668b0 --- /dev/null +++ b/tests/toolSwitch.test.ts @@ -0,0 +1,47 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; + +/** + * Regression guard: switching terrain (or any tool's choice) must not turn + * the tool off. The terrain button and the right-click "Switch …" entries + * used to exit the tool and then open its picker, so closing the picker + * without picking (Escape, clicking away, after only changing brush size) + * left no tool active. Pickers now overwrite the tool's state only when + * something is picked. + */ + +const src = readFileSync(path.join(process.cwd(), "src", "hex-map", "HexMapView.ts"), "utf8").replace(/\r\n/g, "\n"); + +/** Source of the method `name` (up to its closing brace at two-space indent). */ +function method(name: string): string { + const start = src.indexOf(` private ${name}(`); + expect(start).toBeGreaterThan(-1); + return src.slice(start, src.indexOf("\n }\n", start)); +} + +describe("switching a tool's choice keeps the tool", () => { + it("the terrain picker doesn't exit terrain mode before opening", () => { + expect(method("handleTerrainButton")).not.toMatch(/exitTerrainMode\(\)/); + }); + + it("right-click Switch entries never exit the tool first", () => { + const menu = method("showPainterContextMenu"); + const switches = [...menu.matchAll(/onSwitch = ([^;]+);/g)].map((m) => m[1]); + expect(switches.length).toBeGreaterThanOrEqual(8); + for (const s of switches) expect(s).not.toMatch(/exit\w*Mode\(/); + }); + + it("paint tools offer Paint mode (not Link mode) to leave erasing", () => { + const menu = method("showPainterContextMenu"); + const terrain = menu.slice(menu.indexOf('mode === "terrain"'), menu.indexOf('mode === "tableLink"')); + expect(terrain).not.toContain("Link mode"); + expect(terrain.match(/"Paint mode"/g)?.length).toBe(2); + }); + + it("the brush only applies to terrain, so icons don't reset its size", () => { + expect(method("getBrushHexes")).toMatch(/this\.drawingMode !== "terrain"/); + expect(method("openIconPicker")).not.toMatch(/paintBrushSize\s*=/); + }); +}); From 33c9999205bff27db0b2c1f15ad2a341d76c9ef0 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Thu, 8 Oct 2026 08:59:16 -0400 Subject: [PATCH 020/558] feat(export): hexcrawl manual PDF, a printable gazetteer of a map MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New "Export hexcrawl manual (PDF)" in the Maps dialog's Export tab, next to the unchanged "PDF with reference table". Laid out like a printed hexcrawl: - Title page with the overview map; contents; how to use the book. - Map legend: terrain swatches with icons and hex counts, path types. - Random encounter tables the map's hexes link to (terrain and region tables), with die ranges; note links print as note names, untouched example tables are skipped. - Factions and regions summary (factions alone don't key a hex). - Hex key by map section: the section map, then only the keyed hexes in two columns, numbered XXYY from the map's top-left (0101, works with negative coordinates; note coordinates shown in grey). Entries are titled by their named location or a short landmark, with boxed read-aloud description, run-in Landmark/Towns/…/Weather/Hooks fields and GM-marked Hidden/Secret. - Index of towns, dungeons, features and quests with hex numbers. - Player edition option leaves out hidden and secret text. - Unedited template hint text and fill-in prompts like "(add seeds here)" are left out. Own print stylesheet (not the user's theme). The map renderer gains optional coordLabel/coordHalo (manual hex numbers); existing PNG/PDF exports draw exactly as before. Checked: desktop PDF export (the suspected activeDocument-in-webview bug) works; the webview page defines activeDocument. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/export/exporters/hexcrawlManual.ts | 343 +++++++++++++++++++++++++ src/export/exporters/mapWithTable.ts | 8 +- src/export/manual/hexNumber.ts | 26 ++ src/export/manual/manualHtml.ts | 311 ++++++++++++++++++++++ src/export/manual/manualModel.ts | 99 +++++++ src/export/manual/placeholders.ts | 57 ++++ src/export/mapPngRenderer.ts | 25 +- src/hex-map/MapModal.ts | 24 ++ tests/hexcrawlManual.test.ts | 118 +++++++++ 10 files changed, 1005 insertions(+), 10 deletions(-) create mode 100644 src/export/exporters/hexcrawlManual.ts create mode 100644 src/export/manual/hexNumber.ts create mode 100644 src/export/manual/manualHtml.ts create mode 100644 src/export/manual/manualModel.ts create mode 100644 src/export/manual/placeholders.ts create mode 100644 tests/hexcrawlManual.test.ts diff --git a/package.json b/package.json index 32099ef0..8026cf8e 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,8 @@ "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json versions.json", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/toolSwitch.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/toolSwitch.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/toolSwitch.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/toolSwitch.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/export/exporters/hexcrawlManual.ts b/src/export/exporters/hexcrawlManual.ts new file mode 100644 index 00000000..5f64c6ac --- /dev/null +++ b/src/export/exporters/hexcrawlManual.ts @@ -0,0 +1,343 @@ +/** + * Map → hexcrawl manual PDF: a printable gazetteer in the usual hexcrawl + * layout (see manual/manualHtml.ts). Sits next to the "PDF with reference + * table" export, which is unchanged. + * + * Reads the map's hex notes, keeps only hexes with something beyond terrain, + * drops unedited template hint text, renders each note's sections through + * Obsidian's markdown renderer, and prints with the manual's own stylesheet + * (not the user's theme) so the result looks the same in every vault. + */ + +import { Component, MarkdownRenderer, Notice, TFile } from "obsidian"; +import type HexmakerPlugin from "../../HexmakerPlugin"; +import { exportToPdfBytes } from "../pdfExporter"; +import { ensureExportFolder } from "../exportFolder"; +import { renderMapToPngBlob } from "../mapPngRenderer"; +import { getAllSectionData } from "../../sections"; +import { getFrontMatter, terrainFromFm } from "../../frontmatter"; +import { getIconUrl, normalizeFolder } from "../../utils"; +import { parseRandomTable, getDieRanges } from "../../random-tables/randomTable"; +import DEFAULT_HEX_TEMPLATE from "../../defaultHexTemplate.md"; +import { + blobToDataUri, + computeSubdivisions, + enumerateSections, + openInVault, + sanitiseFilename, + writeBinaryToVault, +} from "./mapWithTable"; +import { hexNumbering } from "../manual/hexNumber"; +import { PlaceholderFilter } from "../manual/placeholders"; +import { buildManualHtml, isKeyed, MANUAL_CSS, tableResultText } from "../manual/manualHtml"; +import type { ManualData, ManualHex, ManualLinks, ManualSection, ManualTable } from "../manual/manualModel"; + +export interface ManualExportOptions { + /** Filename stem (no extension). Defaults to " manual". */ + outputName?: string; + /** Leave out hidden and secret text. */ + player?: boolean; + pageSize?: "A4" | "Letter"; + /** Hex radius for the map images (print resolution). Default 60. */ + hexRadius?: number; + showIcons?: boolean; + showPaths?: boolean; + showFactionOverlay?: boolean; + showRegionOverlay?: boolean; +} + +/** Usable map area on a portrait page with the manual's margins, in CSS px. */ +const SECTION_MAP_PX = { width: 700, height: 410 }; +/** Smallest hex on a section map, in CSS px, before it's split further. */ +const MIN_HEX_PX = 34; + +export async function exportMapAsManual(plugin: HexmakerPlugin, mapName: string, opts: ManualExportOptions = {}): Promise { + const folder = await ensureExportFolder(plugin); + const stem = (opts.outputName ?? `${mapName} manual`).trim() || `${mapName} manual`; + const outPath = `${folder}/${sanitiseFilename(stem)}.pdf`; + const notice = new Notice(`Building ${stem}.pdf…`, 0); + try { + const data = await collectManualData(plugin, mapName, opts, (msg) => notice.setMessage(`${stem}.pdf: ${msg}`)); + notice.setMessage(`${stem}.pdf: printing…`); + const bytes = await exportToPdfBytes( + { bodyHtml: buildManualHtml(data), css: MANUAL_CSS, title: data.title }, + { + pageSize: opts.pageSize ?? "Letter", + landscape: false, + margins: { top: 0.6, bottom: 0.7, left: 0.65, right: 0.65 }, + displayHeaderFooter: true, + footerTemplate: `
${escapeHtml(data.title)}${data.player ? " · Player edition" : ""} /
`, + }, + ); + await writeBinaryToVault(plugin.app, outPath, bytes); + new Notice(`Exported to ${outPath}`); + void openInVault(plugin.app, outPath); + } catch (err) { + console.error(err); + new Notice(`Export failed: ${err instanceof Error ? err.message : String(err)}`); + } finally { + notice.hide(); + } +} + +/** Read everything the manual needs from the vault. */ +export async function collectManualData( + plugin: HexmakerPlugin, + mapName: string, + opts: ManualExportOptions, + progress: (msg: string) => void = () => {}, +): Promise { + const app = plugin.app; + const map = plugin.settings.maps.find((m) => m.name === mapName); + if (!map) throw new Error(`Map "${mapName}" not found`); + const player = !!opts.player; + const { x: ox, y: oy } = map.gridOffset; + const { cols, rows } = map.gridSize; + const numbering = hexNumbering(map.gridOffset, map.gridSize); + const palette = plugin.getPaletteByName(map.paletteName)?.terrains ?? plugin.settings.terrainPalettes[0]?.terrains ?? []; + const paletteByName = new Map(palette.map((t) => [t.name, t])); + + // Template hint text to ignore: the configured template plus the built-in one. + const templates = [DEFAULT_HEX_TEMPLATE]; + const templatePath = normalizeFolder(plugin.settings.templatePath ?? ""); + const templateFile = templatePath ? app.vault.getAbstractFileByPath(templatePath) : null; + if (templateFile instanceof TFile) templates.push(await app.vault.cachedRead(templateFile)); + const placeholders = new PlaceholderFilter(templates); + + const component = new Component(); + component.load(); + const renderHost = activeDocument.body.createDiv({ cls: "duckmage-export-render-host markdown-rendered" }); + const render = async (md: string, sourcePath: string): Promise => { + if (!md) return ""; + renderHost.empty(); + await MarkdownRenderer.render(app, md, renderHost, sourcePath, component); + return renderHost.innerHTML; + }; + + const terrainCounts = new Map(); + const regionCounts = new Map(); + const factions = new Map }>(); + const tableUse = new Map(); + const indexes: Record<"Towns" | "Dungeons" | "Features" | "Quests", Map> = { + Towns: new Map(), Dungeons: new Map(), Features: new Map(), Quests: new Map(), + }; + const keyedByKey = new Map(); + let hexCount = 0; + + try { + progress("reading hex notes…"); + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const x = col + ox, y = row + oy; + const path = plugin.hexPath(x, y, mapName); + const file = app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) continue; + hexCount++; + const fm = getFrontMatter(app, path); + const terrain = terrainFromFm(fm) ?? ""; + const region = typeof fm?.region === "string" ? fm.region : ""; + if (terrain) terrainCounts.set(terrain, (terrainCounts.get(terrain) ?? 0) + 1); + if (region) regionCounts.set(region, (regionCounts.get(region) ?? 0) + 1); + + const content = await app.vault.cachedRead(file); + const { text, links } = await getAllSectionData(app, path, content); + const names = (key: string) => (links.get(key) ?? []).map(basename); + const hexLinks: ManualLinks = { + towns: names("towns"), + dungeons: names("dungeons"), + features: names("features"), + quests: names("quests"), + factions: names("factions"), + }; + for (const f of hexLinks.factions) { + const e = factions.get(f) ?? { hexCount: 0, regions: new Set() }; + e.hexCount++; + if (region) e.regions.add(region); + factions.set(f, e); + } + for (const target of links.get("encounters table") ?? []) { + const dest = app.metadataCache.getFirstLinkpathDest(target, path); + if (dest) tableUse.set(dest.path, (tableUse.get(dest.path) ?? 0) + 1); + } + + const raw = { + landmark: placeholders.clean(text.get("landmark")), + description: placeholders.clean(text.get("description")), + hidden: placeholders.clean(text.get("hidden")), + secret: placeholders.clean(text.get("secret")), + weather: placeholders.clean(text.get("weather")), + hooks: placeholders.clean(text.get("hooks & rumors")), + }; + const candidate = { x, y, terrain, region, ...raw, links: hexLinks }; + if (!isKeyed(candidate, player)) continue; + + const number = numbering.number(x, y); + for (const [cat, key] of [["Towns", "towns"], ["Dungeons", "dungeons"], ["Features", "features"], ["Quests", "quests"]] as const) { + for (const name of hexLinks[key]) indexes[cat].set(name, [...(indexes[cat].get(name) ?? []), number]); + } + keyedByKey.set(`${x}_${y}`, { + number, + x, + y, + terrain, + terrainColor: paletteByName.get(terrain)?.color, + region: region || undefined, + landmark: await render(raw.landmark, path), + description: await render(raw.description, path), + hidden: player ? "" : await render(raw.hidden, path), + secret: player ? "" : await render(raw.secret, path), + weather: await render(raw.weather, path), + hooks: await render(raw.hooks, path), + links: hexLinks, + }); + } + } + } finally { + component.unload(); + renderHost.remove(); + } + + // Maps: an overview, then one per section of the key. + const mapOpts = { + hexRadius: opts.hexRadius ?? 60, + showIcons: opts.showIcons ?? true, + showPaths: opts.showPaths ?? true, + showFactionOverlay: opts.showFactionOverlay ?? false, + showRegionOverlay: opts.showRegionOverlay ?? false, + showCoords: true, + coordLabel: (x: number, y: number) => numbering.number(x, y), + coordColor: "#1f1c17", + coordHalo: "rgba(255,255,255,0.85)", + background: "#ffffff", + borderColor: "#3d372e", + }; + progress("drawing the overview map…"); + const overviewMapUri = await blobToDataUri(await renderMapToPngBlob(plugin, mapName, { ...mapOpts, showCoords: cols * rows <= 900 }), "image/png"); + const layout = computeSubdivisions({ + gridCols: cols, + gridRows: rows, + pageWidthPx: SECTION_MAP_PX.width, + pageHeightPx: SECTION_MAP_PX.height, + minHexPxOnPage: MIN_HEX_PX, + }); + const sections: ManualSection[] = []; + const parts = enumerateSections(layout, map.gridSize); + for (const [i, s] of parts.entries()) { + progress(`drawing section map ${i + 1} of ${parts.length}…`); + const png = await renderMapToPngBlob(plugin, mapName, { + ...mapOpts, + subgrid: { colStart: s.colStart, colEnd: s.colEnd, rowStart: s.rowStart, rowEnd: s.rowEnd }, + }); + const hexes: ManualHex[] = []; + for (let row = s.rowStart; row < s.rowEnd; row++) + for (let col = s.colStart; col < s.colEnd; col++) { + const h = keyedByKey.get(`${col + ox}_${row + oy}`); + if (h) hexes.push(h); + } + // Key order is by hex number (column, then row), as printed manuals do. + hexes.sort((a, b) => a.number.localeCompare(b.number)); + sections.push({ + label: s.label, + range: `${numbering.number(s.colStart + ox, s.rowStart + oy)}–${numbering.number(s.colEnd - 1 + ox, s.rowEnd - 1 + oy)}`, + mapUri: await blobToDataUri(png, "image/png"), + hexes, + }); + } + + progress("reading encounter tables…"); + const tables: ManualTable[] = []; + for (const [tablePath, usedBy] of [...tableUse].sort((a, b) => b[1] - a[1])) { + const file = app.vault.getAbstractFileByPath(tablePath); + if (!(file instanceof TFile)) continue; + const table = parseRandomTable(await app.vault.cachedRead(file)); + if (!table.entries.length || table.entries.every((e) => /^example result\b/i.test(e.result.trim()))) continue; + const total = table.entries.reduce((n, e) => n + e.weight, 0) || 1; + const ranges = table.dice > 0 ? getDieRanges(table) : table.entries.map((e) => `${Math.round((e.weight / total) * 100)}%`); + tables.push({ + name: file.basename, + die: table.dice > 0 ? `d${table.dice}` : "", + rows: table.entries.map((e, i) => ({ roll: ranges[i] ?? "", result: escapeHtml(tableResultText(e.result)) })), + usedBy, + }); + } + + progress("drawing the legend…"); + const legend = []; + for (const [name, count] of [...terrainCounts].sort((a, b) => b[1] - a[1])) { + const entry = paletteByName.get(name); + legend.push({ + name, + color: entry?.color ?? "#999999", + iconUri: entry?.icon ? await iconDataUri(getIconUrl(plugin, entry.icon)) : undefined, + hexCount: count, + }); + } + const pathTypes = new Map((plugin.settings.pathTypes ?? []).map((t) => [t.name, t])); + const pathCounts = new Map(); + for (const c of map.pathChains ?? []) pathCounts.set(c.typeName, (pathCounts.get(c.typeName) ?? 0) + c.hexes.length); + const paths = [...pathCounts].map(([name, count]) => { + const t = pathTypes.get(name); + return { + name, + color: t?.color ?? "#2b6cb0", + width: t?.width ?? 3, + dash: t?.lineStyle === "dashed" ? "6 4" : t?.lineStyle === "dotted" ? "1 4" : undefined, + count, + }; + }); + + const keyedCount = keyedByKey.size; + return { + title: mapName, + version: plugin.manifest?.version ?? "", + date: new Date().toISOString().slice(0, 10), + hexCount, + keyedCount, + player, + numberDigits: numbering.digits, + overviewMapUri, + legend, + paths, + tables, + factions: [...factions] + .map(([name, f]) => ({ name, hexCount: f.hexCount, regions: [...f.regions].sort() })) + .sort((a, b) => b.hexCount - a.hexCount), + regions: [...regionCounts].map(([name, hexCount]) => ({ name, hexCount })).sort((a, b) => b.hexCount - a.hexCount), + sections, + index: (Object.keys(indexes) as (keyof typeof indexes)[]).map((category) => ({ + category, + entries: [...indexes[category]] + .map(([name, hexes]) => ({ name, hexes: [...new Set(hexes)].sort() })) + .sort((a, b) => a.name.localeCompare(b.name)), + })), + }; +} + +// ── helpers ─────────────────────────────────────────────────────────────── + +function basename(target: string): string { + const stem = target.slice(target.lastIndexOf("/") + 1); + return stem.replace(/\.md$/i, "").split("#")[0]; +} + + +function escapeHtml(s: string): string { + return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} + +/** Terrain icons as data URIs so the print page needs no vault access. */ +async function iconDataUri(url: string): Promise { + if (url.startsWith("data:")) return url; + try { + const img = createEl("img"); + img.src = url; + await img.decode(); + const canvas = createEl("canvas"); + canvas.width = img.naturalWidth || 64; + canvas.height = img.naturalHeight || 64; + canvas.getContext("2d")?.drawImage(img, 0, 0, canvas.width, canvas.height); + return canvas.toDataURL("image/png"); + } catch { + return undefined; + } +} diff --git a/src/export/exporters/mapWithTable.ts b/src/export/exporters/mapWithTable.ts index 129e376b..e20c9297 100644 --- a/src/export/exporters/mapWithTable.ts +++ b/src/export/exporters/mapWithTable.ts @@ -415,11 +415,11 @@ function escapeHtmlAttr(s: string): string { return s.replace(/&/g, "&").replace(/"/g, """).replace(/|]/g, "_"); } -async function blobToDataUri(blob: Blob, type: string): Promise { +export async function blobToDataUri(blob: Blob, type: string): Promise { const bytes = new Uint8Array(await blob.arrayBuffer()); const CHUNK = 0x8000; const parts: string[] = []; @@ -429,7 +429,7 @@ async function blobToDataUri(blob: Blob, type: string): Promise { return `data:${type};base64,${btoa(parts.join(""))}`; } -async function writeBinaryToVault( +export async function writeBinaryToVault( app: App, path: string, data: Uint8Array, @@ -444,7 +444,7 @@ async function writeBinaryToVault( } } -async function openInVault(app: App, path: string): Promise { +export async function openInVault(app: App, path: string): Promise { const file = app.vault.getAbstractFileByPath(path); if (file instanceof TFile) { await app.workspace.getLeaf(false).openFile(file); diff --git a/src/export/manual/hexNumber.ts b/src/export/manual/hexNumber.ts new file mode 100644 index 00000000..1fff7f7b --- /dev/null +++ b/src/export/manual/hexNumber.ts @@ -0,0 +1,26 @@ +/** + * Hex numbers for printed hexcrawl material, the usual XXYY form: two digits + * of column then two of row, counted from the map's top-left hex as 01. So + * the top-left hex is 0101 and the hex 5 columns right, 11 rows down is 0612. + * Maps wider or taller than 99 hexes use three digits per axis (001001). + * + * Numbering is relative to the map grid, so maps with negative or offset + * coordinates still read naturally; the manual shows each hex's own note + * coordinates alongside for finding the note in Obsidian. + */ + +export interface HexNumbering { + /** "0712" for the hex at note coordinates (x, y). */ + number(x: number, y: number): string; + /** Digits per axis (2 or 3). */ + digits: number; +} + +export function hexNumbering(gridOffset: { x: number; y: number }, gridSize: { cols: number; rows: number }): HexNumbering { + const digits = Math.max(gridSize.cols, gridSize.rows) > 99 ? 3 : 2; + const pad = (n: number) => String(n).padStart(digits, "0"); + return { + digits, + number: (x, y) => pad(x - gridOffset.x + 1) + pad(y - gridOffset.y + 1), + }; +} diff --git a/src/export/manual/manualHtml.ts b/src/export/manual/manualHtml.ts new file mode 100644 index 00000000..4b8edf77 --- /dev/null +++ b/src/export/manual/manualHtml.ts @@ -0,0 +1,311 @@ +/** + * Build the printable HTML for a hexcrawl manual from {@link ManualData}. + * Pure (no Obsidian imports), so it can be unit-tested. + * + * Layout follows common hexcrawl/gazetteer practice: + * title page with the overview map → how to use → legend → random + * encounter tables → factions & regions → hex key by map section (section + * map, then the keyed hexes in two columns, numbered XXYY) → index. + * Hexes with nothing beyond their terrain aren't keyed: the map shows them. + */ + +import type { ManualData, ManualHex, ManualLinks, ManualSection } from "./manualModel"; + +const esc = (s: string) => + s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + +const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; + +const LINK_LABELS: [keyof ManualLinks, string][] = [ + ["towns", "Towns"], + ["dungeons", "Dungeons"], + ["features", "Features"], + ["quests", "Quests"], + ["factions", "Factions"], +]; + +/** True when a hex has something to print beyond its terrain (factions alone don't count). */ +export function isKeyed(h: Omit, player: boolean): boolean { + const text = h.landmark || h.description || h.weather || h.hooks || (!player && (h.hidden || h.secret)); + const links = h.links.towns.length || h.links.dungeons.length || h.links.features.length || h.links.quests.length; + return !!(text || links); +} + +function titlePage(d: ManualData): string { + return ` +
+
A hexcrawl gazetteer
+

${esc(d.title)}

+ ${esc(d.title)} overview map +
${plural(d.hexCount, "hex", "hexes")} · ${plural(d.keyedCount, "keyed location")} · ${esc(d.date)}${d.player ? " · Player edition" : ""}
+
Made with Hexmap World Creator ${esc(d.version)}
+
`; +} + +function contents(d: ManualData): string { + const items = [ + "How to use this book", + "Map legend", + d.tables.length ? "Random encounter tables" : "", + d.factions.length || d.regions.length ? "Factions and regions" : "", + `Hex key (${plural(d.sections.length, "section")})`, + d.index.some((c) => c.entries.length) ? "Index of locations" : "", + ].filter(Boolean); + return ` +
+

Contents

+
    ${items.map((i) => `
  1. ${esc(i)}
  2. `).join("")}
+

How to use this book

+

Hex numbers. Every hex has a ${d.numberDigits * 2}-digit number: the first ${d.numberDigits} digits count columns from the left edge of the map, the last ${d.numberDigits} count rows from the top, both starting at 01. The top-left hex is ${"0".repeat(d.numberDigits - 1)}1${"0".repeat(d.numberDigits - 1)}1. Numbers are printed in each hex on the maps.

+

Keyed hexes. The hex key lists only hexes with something to find. A hex that isn't listed is plain country of the terrain shown on the map; use its terrain's encounter table.

+ ${d.tables.length ? `

Encounters. When an encounter check calls for one, roll on the table for the hex's terrain (or the one named in its entry).

` : ""} + ${d.player ? `

Player edition. Hidden and secret details are left out of this edition.

` : `

Game master material. Entries marked GM are hidden or secret: not for players until found.

`} +

Each hex number is followed by the hex's map coordinates in grey, to find its note in Obsidian.

+
`; +} + +function legend(d: ManualData): string { + const terrains = d.legend + .map( + (t) => `
+ ${t.iconUri ? `` : ""} + ${esc(t.name)}${t.hexCount} +
`, + ) + .join(""); + const paths = d.paths + .map( + (p) => `
+ + ${esc(p.name)}${p.count} +
`, + ) + .join(""); + return ` +
+

Map legend

+

Terrain (hexes)

+
${terrains}
+ ${paths ? `

Roads and rivers (hexes)

${paths}
` : ""} +
`; +} + +function tables(d: ManualData): string { + if (!d.tables.length) return ""; + const blocks = d.tables + .map( + (t) => `
+

${esc(t.name)}${t.usedBy ? ` · ${plural(t.usedBy, "hex", "hexes")}` : ""}

+ + ${t.rows.map((r) => ``).join("")}
${esc(t.die || "%")}Result
${esc(r.roll)}${r.result}
+
`, + ) + .join(""); + return ` +
+

Random encounter tables

+
${blocks}
+
`; +} + +function factionsAndRegions(d: ManualData): string { + if (!d.factions.length && !d.regions.length) return ""; + const factions = d.factions.length + ? `

Factions

${d.factions + .map((f) => ``) + .join("")}
FactionHexesRegions
${esc(f.name)}${f.hexCount}${esc(f.regions.join(", "))}
` + : ""; + const regions = d.regions.length + ? `

Regions

${d.regions + .map((r) => ``) + .join("")}
RegionHexes
${esc(r.name)}${r.hexCount}
` + : ""; + return ` +
+

Factions and regions

+ ${factions} + ${regions} +
`; +} + +/** Entry title: the first named location, else a short landmark, else the terrain. */ +export function entryTitle(h: Pick): string { + const named = h.links.towns[0] ?? h.links.dungeons[0] ?? h.links.features[0]; + if (named) return esc(named); + const landmark = stripTags(h.landmark).split(/\n/)[0]?.trim() ?? ""; + if (landmark && landmark.length <= 48 && !/[.!?]\s/.test(landmark)) return esc(landmark.replace(/[.]$/, "")); + return esc(capitalise(h.terrain || "Hex")); +} + +function hexEntry(h: ManualHex, player: boolean): string { + const title = entryTitle(h); + const parts: string[] = []; + if (h.description) parts.push(`
${h.description}
`); + if (h.landmark && stripTags(h.landmark).replace(/[.]$/, "") !== stripTags(title)) parts.push(runIn("Landmark", h.landmark)); + for (const [key, label] of LINK_LABELS) { + if (h.links[key].length) parts.push(runIn(label, esc(h.links[key].join(", ")))); + } + if (h.weather) parts.push(runIn("Weather", h.weather)); + if (h.hooks) parts.push(runIn("Hooks and rumors", h.hooks)); + if (!player && h.hidden) parts.push(runIn("Hidden", h.hidden, true)); + if (!player && h.secret) parts.push(runIn("Secret", h.secret, true)); + const terrain = h.terrain + ? `${esc(h.terrain)}${h.region ? ` · ${esc(h.region)}` : ""}` + : ""; + return `
+
${h.number}${title}${h.x}, ${h.y}
+ ${terrain} + ${parts.join("\n ")} +
`; +} + +function section(s: ManualSection, player: boolean, single: boolean): string { + const heading = single ? "Hex key" : `Section ${esc(s.label)}`; + return ` +
+

${heading} hexes ${esc(s.range)}

+ ${heading} map + ${s.hexes.length + ? `
${s.hexes.map((h) => hexEntry(h, player)).join("\n")}
` + : `

No keyed hexes in this section.

`} +
`; +} + +function index(d: ManualData): string { + const cats = d.index.filter((c) => c.entries.length); + if (!cats.length) return ""; + return ` +
+

Index of locations

+
${cats + .map( + (c) => `

${esc(c.category)}

${c.entries + .map((e) => `
${esc(e.name)}${e.hexes.join(", ")}
`) + .join("")}
`, + ) + .join("")}
+
`; +} + +export function buildManualHtml(d: ManualData): string { + return `
+${titlePage(d)} +${contents(d)} +${legend(d)} +${tables(d)} +${factionsAndRegions(d)} +${d.sections.map((s) => section(s, d.player, d.sections.length === 1)).join("\n")} +${index(d)} +
`; +} + +// ── helpers ─────────────────────────────────────────────────────────────── + +const basename = (target: string) => target.slice(target.lastIndexOf("/") + 1).replace(/\.md$/i, "").split("#")[0]; + +/** Table results may be links or note paths; print the note's name. */ +export function tableResultText(result: string): string { + const linked = result.replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_m: string, target: string, alias?: string) => alias ?? basename(target)); + // A bare vault path (link-type table entries are stored without brackets). + return /^[^\s/][^\n]*\/[^\n/]+$/.test(linked.trim()) && !/\s\/\s/.test(linked) ? basename(linked.trim()) : linked; +} + + +function runIn(label: string, html: string, gm = false): string { + return `
${gm ? `GM ` : ""}${esc(label)}. ${unwrapParagraph(html)}
`; +} + +/** "

text

" → "text" so a run-in label can sit on the same line. */ +function unwrapParagraph(html: string): string { + const m = /^\s*

([\s\S]*?)<\/p>\s*$/.exec(html); + return m && !m[1].includes("

") ? m[1] : html; +} + +const stripTags = (html: string) => html.replace(/<[^>]+>/g, "").trim(); + +const capitalise = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); + +/** Print stylesheet for the manual. Self-contained: the user's theme isn't used. */ +export const MANUAL_CSS = ` +html, body { background: #fff; margin: 0; padding: 0; } +body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } +.hx-manual { + font-family: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif; + font-size: 9.6pt; line-height: 1.38; color: #1f1c17; +} +.hx-manual h1, .hx-manual h2, .hx-manual h3, .hx-manual h4, +.hx-num, .hx-kicker, .hx-meta, .hx-made, .hx-label, .hx-gm, .hx-table th, .hx-sub, .hx-coord, .hx-terrain { + font-family: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif; +} +.hx-page { break-before: page; } +.hx-legend-section { margin-top: 14pt; break-inside: avoid; } +.hx-manual h2 { + font-size: 15pt; font-weight: 700; letter-spacing: 0.02em; color: #5d1a1a; + border-bottom: 1.5pt solid #5d1a1a; padding-bottom: 3pt; margin: 0 0 9pt; +} +.hx-manual h3 { font-size: 10.5pt; margin: 12pt 0 5pt; color: #3a3328; text-transform: uppercase; letter-spacing: 0.06em; } +.hx-manual h4 { font-size: 9.5pt; margin: 0 0 4pt; color: #3a3328; } +.hx-manual p { margin: 0 0 6pt; } +.hx-sub { font-size: 0.72em; font-weight: 400; color: #8a8174; letter-spacing: 0; text-transform: none; } +.hx-small { font-size: 8.5pt; color: #6b6357; } + +/* Title page */ +.hx-title-page { text-align: center; padding-top: 0.25in; } +.hx-kicker { font-size: 9pt; letter-spacing: 0.3em; text-transform: uppercase; color: #8a8174; } +.hx-title { font-size: 30pt; margin: 6pt 0 14pt; color: #2a1c12; font-weight: 700; letter-spacing: 0.01em; } +.hx-overview { display: block; max-width: 100%; max-height: 6.6in; margin: 0 auto 14pt; border: 1pt solid #b8ad99; } +.hx-meta { font-size: 9pt; color: #4a4339; letter-spacing: 0.04em; } +.hx-made { margin-top: 4pt; font-size: 7.5pt; color: #9a9184; } + +/* Front matter */ +.hx-contents { margin: 0 0 14pt 1.2em; padding: 0; } +.hx-contents li { margin: 2pt 0; } + +/* Legend */ +.hx-legend { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4pt 12pt; } +.hx-swatch { display: flex; align-items: center; gap: 6pt; break-inside: avoid; } +.hx-chip { width: 18pt; height: 16pt; border-radius: 3pt; border: 0.6pt solid rgba(0,0,0,0.35); display: inline-flex; align-items: center; justify-content: center; flex: none; } +.hx-chip img { width: 12pt; height: 12pt; object-fit: contain; } +.hx-line { width: 30pt; height: 10pt; flex: none; } +.hx-swatch-name { flex: 1; } +.hx-swatch-count { color: #8a8174; font-variant-numeric: tabular-nums; } + +/* Tables */ +.hx-two-col { column-count: 2; column-gap: 0.3in; } +.hx-table-block { break-inside: avoid; margin-bottom: 10pt; } +.hx-table { width: 100%; border-collapse: collapse; font-size: 8.8pt; } +.hx-table th { text-align: left; font-size: 7.6pt; text-transform: uppercase; letter-spacing: 0.06em; color: #5d1a1a; border-bottom: 1pt solid #5d1a1a; padding: 2pt 4pt; } +.hx-table td { padding: 2pt 4pt; vertical-align: top; border-bottom: 0.4pt solid #e3dccd; } +.hx-table tr:nth-child(even) td { background: #f7f3ea; } +.hx-table p { margin: 0; } +.hx-roll { width: 1%; white-space: nowrap; font-variant-numeric: tabular-nums; font-weight: 600; color: #3a3328; } +.hx-wide { margin-bottom: 8pt; } + +/* Hex key */ +.hx-section-map { display: block; max-width: 100%; max-height: 4.3in; margin: 0 auto 10pt; border: 1pt solid #b8ad99; } +.hx-key { column-count: 2; column-gap: 0.28in; column-rule: 0.5pt solid #ddd5c6; } +.hx-entry { break-inside: avoid; margin: 0 0 9pt; } +.hx-entry header { display: flex; align-items: baseline; gap: 6pt; border-bottom: 0.6pt solid #cfc6b5; padding-bottom: 1.5pt; margin-bottom: 2pt; } +.hx-num { font-weight: 800; font-size: 11pt; color: #5d1a1a; font-variant-numeric: tabular-nums; letter-spacing: 0.02em; } +.hx-entry-title { flex: 1; font-weight: 700; font-variant: small-caps; letter-spacing: 0.03em; } +.hx-coord { font-size: 7pt; color: #a39a8c; } +.hx-terrain { display: block; font-size: 7.6pt; color: #6b6357; margin-bottom: 3pt; text-transform: capitalize; } +.hx-dot { display: inline-block; width: 7pt; height: 7pt; border-radius: 1.5pt; margin-right: 4pt; vertical-align: -0.5pt; border: 0.5pt solid rgba(0,0,0,0.3); } +.hx-read { background: #f4efe4; border-left: 2pt solid #b8ad99; padding: 3pt 6pt; margin: 2pt 0 4pt; font-style: italic; } +.hx-read p { margin: 0 0 3pt; } +.hx-read p:last-child { margin-bottom: 0; } +.hx-field { margin: 0 0 3pt; } +.hx-field p { display: inline; margin: 0; } +.hx-field ul { margin: 1pt 0 2pt 1.1em; padding: 0; } +.hx-label { font-size: 8pt; text-transform: uppercase; letter-spacing: 0.05em; color: #3a3328; } +.hx-gm { display: inline-block; font-size: 6.5pt; font-weight: 700; color: #fff; background: #5d1a1a; border-radius: 2pt; padding: 0 3pt; letter-spacing: 0.06em; vertical-align: 0.5pt; } +.hx-empty { color: #8a8174; font-style: italic; } +.hx-manual a, .hx-manual .internal-link { color: inherit; text-decoration: none; border-bottom: 0.4pt dotted #8a8174; } + +/* Index */ +.hx-index { column-count: 3; column-gap: 0.25in; } +.hx-index-cat { break-inside: avoid; margin-bottom: 10pt; } +.hx-index-row { display: flex; align-items: baseline; gap: 3pt; font-size: 8.8pt; } +.hx-leader { flex: 1; border-bottom: 0.6pt dotted #b8ad99; transform: translateY(-2pt); } +.hx-index-hexes { font-variant-numeric: tabular-nums; color: #5d1a1a; font-weight: 600; } +`; diff --git a/src/export/manual/manualModel.ts b/src/export/manual/manualModel.ts new file mode 100644 index 00000000..3d053a24 --- /dev/null +++ b/src/export/manual/manualModel.ts @@ -0,0 +1,99 @@ +/** + * Data for a printed hexcrawl manual (gazetteer): everything the HTML builder + * needs, already read from the vault. Text fields hold HTML rendered from the + * note's markdown (links, emphasis, lists), never raw user markdown. + */ + +export interface ManualLegendEntry { + name: string; + color: string; + /** Data URI of the terrain icon, if any. */ + iconUri?: string; + iconTint?: string; + hexCount: number; +} + +export interface ManualPathType { + name: string; + color: string; + width: number; + dash?: string; + count: number; +} + +export interface ManualLinks { + towns: string[]; + dungeons: string[]; + features: string[]; + quests: string[]; + factions: string[]; +} + +/** One keyed hex: a hex with something worth printing beyond its terrain. */ +export interface ManualHex { + /** "0712" */ + number: string; + /** The note's own coordinates, for finding it in Obsidian. */ + x: number; + y: number; + terrain: string; + terrainColor?: string; + region?: string; + /** Rendered HTML per text section ("" when empty). */ + landmark: string; + description: string; + hidden: string; + secret: string; + weather: string; + hooks: string; + links: ManualLinks; +} + +export interface ManualSection { + label: string; + /** "0101–1306" */ + range: string; + mapUri: string; + hexes: ManualHex[]; +} + +export interface ManualTable { + name: string; + /** "d8", "d100", or "" for weighted tables shown as percentages. */ + die: string; + rows: { roll: string; result: string }[]; + /** Hex count that link to this table. */ + usedBy: number; +} + +export interface ManualFaction { + name: string; + hexCount: number; + regions: string[]; +} + +export interface ManualIndexEntry { + name: string; + hexes: string[]; +} + +export interface ManualData { + title: string; + /** Plugin version, e.g. "1.5.6". */ + version: string; + /** ISO date. */ + date: string; + hexCount: number; + keyedCount: number; + /** Player version: hidden and secret text left out. */ + player: boolean; + numberDigits: number; + overviewMapUri: string; + legend: ManualLegendEntry[]; + paths: ManualPathType[]; + tables: ManualTable[]; + factions: ManualFaction[]; + regions: { name: string; hexCount: number }[]; + sections: ManualSection[]; + index: { category: string; entries: ManualIndexEntry[] }[]; +} diff --git a/src/export/manual/placeholders.ts b/src/export/manual/placeholders.ts new file mode 100644 index 00000000..998f98cf --- /dev/null +++ b/src/export/manual/placeholders.ts @@ -0,0 +1,57 @@ +/** + * Hex notes start from a template whose sections often contain hint text + * ("What the party sees and feels…"). Unedited hints must not end up in a + * printed manual, so section text is compared line by line against the hint + * lines of the templates in use, and lines that only repeat a hint are dropped. + */ + +/** Hint lines from the plugin's built-in templates, past and present. */ +const BUILT_IN_HINTS = [ + "What the party sees and feels. Terrain, atmosphere, any obvious features.", + "What the party sees and feels. Terrain, atmosphere, any obvious features. One or two sentences or a short paragraph.", + "The visible standout feature — spire, ruin, lighthouse, statue, village — that can be spotted or used for navigation.", + "Links to settlements or named locations in this hex.", + "Discoverable with exploration, tracking, or clues. Hidden lairs, ruins, tombs, camps, shortcuts.", + "Revealed only through specific actions, NPCs, or investigation.", + "Revealed only through specific actions, NPCs, or investigation. Havens, caches, true nature of a place.", + "Normal for region, or special (e.g. always pleasant, sandstorms, magic zone effect).", + "Who holds sway, patrols, or claims territory. Church, free states, beast territory, mages, bandits, nobody.", + "Seeds for adventures, things locals might mention, or what finding this hex could lead to.", + "- **Table:** *(terrain from world/encounters — e.g. Woods, Marsh, Beach, salt flats)*", + "- **Custom / notable:** Any fixed encounters, lairs, or \"no combat here\" notes for this hex.", + "- **Difficulty:** Normal / slow / treacherous / blocked", + "- **Notes:** Trail condition, shortcuts, routes to key adjacent hexes.", +]; + +const norm = (line: string) => line.replace(/\s+/g, " ").trim().toLowerCase(); + +/** + * A line that is only a fill-in prompt: a parenthesised note such as + * "(add seeds here)" or "(TBD)", or a bare "TODO …" / "TBD". Real text that + * merely ends in "here" ("The dragon sleeps here.") is kept. + */ +const PROMPT = /^\s*(?:[*_]*\((?:[^)]*\b(?:add|todo|tbd|fill in|placeholder|here)\b[^)]*)\)[*_]*|todo\b.*|tbd\.?)\s*$/i; + +/** Every non-heading, non-rule line of a template, as hint lines to ignore. */ +export function templateHintLines(template: string): string[] { + return template + .replace(/^---[\s\S]*?---/, "") + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => l && !/^#/.test(l) && !/^-{3,}$/.test(l) && !/\{\{/.test(l)); +} + +export class PlaceholderFilter { + private hints: Set; + + constructor(templates: string[] = []) { + this.hints = new Set([...BUILT_IN_HINTS, ...templates.flatMap(templateHintLines)].map(norm)); + } + + /** Section text with hint lines (and blank edges) removed; "" if only hints. */ + clean(text: string | undefined): string { + if (!text) return ""; + const kept = text.split(/\r?\n/).filter((l) => !this.hints.has(norm(l)) && !PROMPT.test(l.trim())); + return kept.join("\n").replace(/^\s+|\s+$/g, ""); + } +} diff --git a/src/export/mapPngRenderer.ts b/src/export/mapPngRenderer.ts index f57eedf5..6b8ba392 100644 --- a/src/export/mapPngRenderer.ts +++ b/src/export/mapPngRenderer.ts @@ -51,6 +51,14 @@ export interface MapPngRenderOptions { coordColor?: string; /** Draw coordinate labels in each hex. Default true. */ showCoords?: boolean; + /** + * Label text per hex instead of "x,y" (the hexcrawl manual prints XXYY hex + * numbers). When set, the label sits near the top edge, the usual place + * for hex numbers on printed maps. + */ + coordLabel?: (x: number, y: number) => string; + /** Outline drawn behind labels so they read on any terrain colour. */ + coordHalo?: string; /** Draw terrain icons. Default true. */ showIcons?: boolean; /** Include road/river/path chains. Default true. */ @@ -344,11 +352,20 @@ export async function renderMapToPngBlob( } if (showCoords) { const [hxStr, hyStr] = hex.key.split("_"); - ctx.fillStyle = coordColor; - ctx.font = `${Math.round(R * 0.22)}px sans-serif`; + const custom = opts.coordLabel; + const text = custom ? custom(Number(hxStr), Number(hyStr)) : `${hxStr},${hyStr}`; + const y = custom ? hex.cy - R * 0.52 : hex.cy + R * 0.75; + ctx.font = `${custom ? "600 " : ""}${Math.round(R * (custom ? 0.24 : 0.22))}px sans-serif`; ctx.textAlign = "center"; - ctx.textBaseline = "alphabetic"; - ctx.fillText(`${hxStr},${hyStr}`, hex.cx, hex.cy + R * 0.75); + ctx.textBaseline = custom ? "middle" : "alphabetic"; + if (opts.coordHalo) { + ctx.lineJoin = "round"; + ctx.lineWidth = Math.max(2, R * 0.08); + ctx.strokeStyle = opts.coordHalo; + ctx.strokeText(text, hex.cx, y); + } + ctx.fillStyle = coordColor; + ctx.fillText(text, hex.cx, y); } } diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index c917518e..46d7fcde 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -6,6 +6,7 @@ import { normalizeFolder, slugify, getIconUrl, createIconEl, importBinaryFileToV import { getSubmapFromFile, setSubmapInFile } from "../frontmatter"; import { exportMapAsPng } from "../export/mapPngRenderer"; import { exportMapAsPdf } from "../export/exporters/mapWithTable"; +import { exportMapAsManual } from "../export/exporters/hexcrawlManual"; import { FileLinkSuggestModal } from "./FileLinkSuggestModal"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; @@ -151,6 +152,11 @@ export class MapModal extends HexmakerModal { "Include region overlay", false, ); + const playerEdition = makeCheckbox( + optsForm, + "Manual: player edition (leave out hidden and secret)", + false, + ); // Output size: a dropdown of presets that map to a hex-radius value. // The actual PNG dimensions depend on grid size too, so we phrase the @@ -224,6 +230,24 @@ export class MapModal extends HexmakerModal { void exportMapAsPdf(this.plugin, mapName, collectOpts()); this.close(); }); + // A printable gazetteer: legend, encounter tables, keyed hexes by + // section, index. Uses its own print styling and hex numbering. + const exportManualBtn = actions.createEl("button", { + cls: "mod-cta", + text: "Export hexcrawl manual (PDF)", + }); + exportManualBtn.addEventListener("click", () => { + const o = collectOpts(); + void exportMapAsManual(this.plugin, mapName, { + outputName: `${nameInput.value.trim() || mapName} ${playerEdition.checked ? "player" : "manual"}`, + player: playerEdition.checked, + showIcons: o.showIcons, + showPaths: o.showPaths, + showFactionOverlay: o.showFactionOverlay, + showRegionOverlay: o.showRegionOverlay, + }); + this.close(); + }); } // ── Maps tab ────────────────────────────────────────────────────────────── diff --git a/tests/hexcrawlManual.test.ts b/tests/hexcrawlManual.test.ts new file mode 100644 index 00000000..8bbf574a --- /dev/null +++ b/tests/hexcrawlManual.test.ts @@ -0,0 +1,118 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { hexNumbering } from "../src/export/manual/hexNumber"; +import { PlaceholderFilter, templateHintLines } from "../src/export/manual/placeholders"; +import { buildManualHtml, entryTitle, isKeyed, tableResultText } from "../src/export/manual/manualHtml"; +import type { ManualData, ManualHex } from "../src/export/manual/manualModel"; + +/** Pure parts of the hexcrawl manual export (src/export/manual). */ + +const noLinks = { towns: [], dungeons: [], features: [], quests: [], factions: [] }; +const hex = (over: Partial = {}): ManualHex => ({ + number: "0101", x: 0, y: 0, terrain: "grass", + landmark: "", description: "", hidden: "", secret: "", weather: "", hooks: "", + links: { ...noLinks }, ...over, +}); + +describe("hex numbers", () => { + it("count from the map's top-left hex as 0101, whatever its coordinates", () => { + const n = hexNumbering({ x: -7, y: -9 }, { cols: 38, rows: 27 }); + expect(n.number(-7, -9)).toBe("0101"); + expect(n.number(-2, 4)).toBe("0614"); + expect(n.digits).toBe(2); + }); + + it("use three digits per axis past 99", () => { + const n = hexNumbering({ x: 0, y: 0 }, { cols: 120, rows: 40 }); + expect(n.number(0, 0)).toBe("001001"); + expect(n.number(104, 9)).toBe("105010"); + }); +}); + +describe("placeholder text", () => { + const filter = new PlaceholderFilter(["### description\nWhat the party sees and feels.\n### hooks\n(Write hooks here)"]); + + it("drops unedited template hints and fill-in prompts", () => { + expect(filter.clean("What the party sees and feels.")).toBe(""); + expect(filter.clean("(add seeds here)")).toBe(""); + expect(filter.clean("TODO")).toBe(""); + expect(filter.clean("Normal for region, or special (e.g. always pleasant, sandstorms, magic zone effect).")).toBe(""); + }); + + it("keeps real writing, including short lines ending in 'here'", () => { + expect(filter.clean("The dragon sleeps here.")).toBe("The dragon sleeps here."); + expect(filter.clean("What the party sees and feels.\nA ruined tower leans over the road.")).toBe("A ruined tower leans over the road."); + expect(filter.clean("Add salt to the well and it turns red.")).toBe("Add salt to the well and it turns red."); + }); + + it("reads hint lines from a template, skipping headings, rules and {{fields}}", () => { + expect(templateHintLines("---\nterrain:\n---\n# Hex {{x}}\n---\nHint one.\n### description\n")).toEqual(["Hint one."]); + }); +}); + +describe("what gets keyed", () => { + it("needs text or a location link; factions alone don't count", () => { + expect(isKeyed(hex({ links: { ...noLinks, factions: ["King Guzzard"] } }), false)).toBe(false); + expect(isKeyed(hex({ description: "

Fog.

" }), false)).toBe(true); + expect(isKeyed(hex({ links: { ...noLinks, dungeons: ["Dark Spire"] } }), false)).toBe(true); + }); + + it("player edition doesn't key a hex for hidden or secret text alone", () => { + expect(isKeyed(hex({ secret: "

A cache.

" }), false)).toBe(true); + expect(isKeyed(hex({ secret: "

A cache.

" }), true)).toBe(false); + }); +}); + +describe("entry titles", () => { + it("prefer a named location, then a short landmark, then the terrain", () => { + expect(entryTitle(hex({ links: { ...noLinks, towns: ["Farwharf"] }, landmark: "

A lighthouse

" }))).toBe("Farwharf"); + expect(entryTitle(hex({ landmark: "

Death Point

" }))).toBe("Death Point"); + expect(entryTitle(hex({ landmark: "

A crumbling towering pile of stone. It cuts through the forest.

" }))).toBe("Grass"); + }); +}); + +describe("table results", () => { + it("print note links and paths as the note's name", () => { + expect(tableResultText("[[RPG/world/creatures/Golem]]")).toBe("Golem"); + expect(tableResultText("[[RPG/world/creatures/Golem|the golem]]")).toBe("the golem"); + expect(tableResultText("RPG/duckmage/world/adventures 1/mailman/bandits")).toBe("bandits"); + expect(tableResultText("wolves / bears")).toBe("wolves / bears"); + expect(tableResultText("travellers")).toBe("travellers"); + }); +}); + +describe("manual document", () => { + const data = (player: boolean): ManualData => ({ + title: "the-coast", version: "1.5.6", date: "2026-10-08", hexCount: 3, keyedCount: 2, player, numberDigits: 2, + overviewMapUri: "data:image/png;base64,AA", legend: [{ name: "grass", color: "#6a6", hexCount: 3 }], paths: [], + tables: [{ name: "grass", die: "d6", rows: [{ roll: "1–3", result: "wolves" }], usedBy: 3 }], + factions: [{ name: "King Guzzard", hexCount: 2, regions: ["Guzzwood"] }], regions: [], + sections: [{ label: "A1", range: "0101–0302", mapUri: "data:image/png;base64,AA", hexes: [ + hex({ number: "0102", description: "

Fog.

", secret: player ? "" : "

A cache.

", links: { ...noLinks, dungeons: ["Dark Spire"] } }), + ] }], + index: [{ category: "Dungeons", entries: [{ name: "Dark Spire", hexes: ["0102"] }] }], + }); + + it("has the manual's parts in order", () => { + const html = buildManualHtml(data(false)); + const order = ["A hexcrawl gazetteer", "Contents", "How to use this book", "Map legend", "Random encounter tables", "Factions and regions", "Hex key", "Index of locations"]; + const at = order.map((s) => html.indexOf(s)); + expect(at.every((i) => i >= 0)).toBe(true); + expect([...at].sort((a, b) => a - b)).toEqual(at); + expect(html).toContain('id="hex-0102"'); + expect(html).toContain("Dark Spire"); + }); + + it("marks GM-only text, and the player edition leaves it out", () => { + expect(buildManualHtml(data(false))).toContain('GM Secret.'); + const player = buildManualHtml(data(true)); + expect(player).not.toContain("Secret."); + expect(player).toContain("Player edition"); + }); + + it("escapes names", () => { + const d = data(false); + d.title = "bad"; + expect(buildManualHtml(d)).not.toContain("bad"); + }); +}); From 2d7a534ce4e01ec8701becc27b94e52a90fb09e4 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Thu, 8 Oct 2026 09:10:50 -0400 Subject: [PATCH 021/558] fix(export): manual title page uses the build's version, not Obsidian's cached manifest Co-Authored-By: Claude Opus 5.5 --- src/export/exporters/hexcrawlManual.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/export/exporters/hexcrawlManual.ts b/src/export/exporters/hexcrawlManual.ts index 5f64c6ac..d54db44f 100644 --- a/src/export/exporters/hexcrawlManual.ts +++ b/src/export/exporters/hexcrawlManual.ts @@ -28,6 +28,7 @@ import { writeBinaryToVault, } from "./mapWithTable"; import { hexNumbering } from "../manual/hexNumber"; +import { pluginVersion } from "../../compat"; import { PlaceholderFilter } from "../manual/placeholders"; import { buildManualHtml, isKeyed, MANUAL_CSS, tableResultText } from "../manual/manualHtml"; import type { ManualData, ManualHex, ManualLinks, ManualSection, ManualTable } from "../manual/manualModel"; @@ -289,7 +290,7 @@ export async function collectManualData( const keyedCount = keyedByKey.size; return { title: mapName, - version: plugin.manifest?.version ?? "", + version: pluginVersion(plugin), date: new Date().toISOString().slice(0, 10), hexCount, keyedCount, From 46a470b84ef61bd8a7cdb52cda4c378f48289dfb Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 09:43:44 -0400 Subject: [PATCH 022/558] feat: space palette presets, palettes as notes, scalable icon pickers Palettes as notes - Each terrain palette is now a markdown note (Terrain | Color | Icon | Icon color | Category table) in a new "Palettes folder" setting (default {world}/palettes). Notes can be hand-edited and copied between vaults to share. - PaletteStore syncs both ways: saveSettings() writes/renames/trashes notes; vault modify/create/rename/delete re-parse hand edits into settings.terrainPalettes, which stays as the in-memory working copy and data.json cache (older versions still load). Own writes are recognised by content, so there is no echo loop. - One-time migration writes every existing palette, including user-made ones, to notes; names that can't be file names are cleaned and maps repointed. An existing note of the same name wins (synced from another device); unrelated notes are never overwritten. - Palette order is preserved (first palette = fallback/default). Presets - "Add palette" opens a chooser: built-in presets, copy an existing palette, or empty. New-map palette menus (map modal, submap picker, setup wizard) also list uninstalled presets; createNewMap installs on first use. - New Space - Sector (one hex per parsec, typed by mainworld) and Space - System (stars, planets, belts, stations, hazards) presets. Installing Space - Sector adds Jump route and Trade route path types. Space icon pack - 70 bundled space-* icons (terrain glyphs + ship/station tokens) from game-icons.net (CC BY 3.0), MDI (Apache 2.0), Tabler (MIT) and Kenney Simple Space (CC0). Credits/licences in icons/CREDITS.md; rebuilt by dev/build-space-icons.mjs. esbuild gains an .svg dataurl loader. Icon pickers scale to large libraries - HexmakerModal.addIconFilter() adds a search box + All/Terrain/Space/ Custom tabs to every icon grid (paint picker incl. manage mode, token modal, hex editor override + GM icons). Token modal icon area is taller and inline grids are drag-resizable. Terrain entry editor's icon dropdown is grouped by pack. Tests: tests/palettes.test.ts (note format, presets, icon packs, and PaletteStore against an in-memory vault). Follow-up: settlement / UWP generator tracked in #35. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE.md | 2 + CLAUDE.md | 2 + README.md | 5 +- dev/build-space-icons.mjs | 166 ++++++++++ esbuild.config.mjs | 2 +- icons/CREDITS.md | 102 ++++++ icons/LICENSE-APACHE-2.0.txt | 202 ++++++++++++ icons/space-anomaly.svg | 1 + icons/space-asteroid.png | Bin 0 -> 1147 bytes icons/space-atom-outline.svg | 1 + icons/space-beacon-outline.svg | 1 + icons/space-black-hole.svg | 1 + icons/space-comet.svg | 1 + icons/space-debris.svg | 1 + icons/space-defense-satellite.svg | 1 + icons/space-dots-hex.svg | 1 + icons/space-double-ring.svg | 1 + icons/space-dust-cloud.svg | 1 + icons/space-earth.svg | 1 + icons/space-frozen-orb.svg | 1 + icons/space-galaxy.svg | 1 + icons/space-meteor-outline.svg | 1 + icons/space-meteor.svg | 1 + icons/space-moon-outline.svg | 1 + icons/space-moon.svg | 1 + icons/space-orbit-outline.svg | 1 + icons/space-orbit.svg | 1 + icons/space-orbital.svg | 1 + icons/space-planet-core.svg | 1 + icons/space-planet-outline.svg | 1 + icons/space-planet.svg | 1 + icons/space-portal.svg | 1 + icons/space-radial-balance.svg | 1 + icons/space-radioactive.svg | 1 + icons/space-raider-a.png | Bin 0 -> 2041 bytes icons/space-raider-b.png | Bin 0 -> 2007 bytes icons/space-raider-c.png | Bin 0 -> 2172 bytes icons/space-raider-d.png | Bin 0 -> 2316 bytes icons/space-ring-dashed.svg | 1 + icons/space-ring-segments.svg | 1 + icons/space-ring.svg | 1 + icons/space-ringed-planet.svg | 1 + icons/space-rocket.svg | 1 + icons/space-satellite-a.png | Bin 0 -> 351 bytes icons/space-satellite-b.png | Bin 0 -> 1241 bytes icons/space-satellite-c.png | Bin 0 -> 936 bytes icons/space-satellite-d.png | Bin 0 -> 1148 bytes icons/space-shield-outline.svg | 1 + icons/space-ship-a.png | Bin 0 -> 855 bytes icons/space-ship-b.png | Bin 0 -> 1044 bytes icons/space-ship-c.png | Bin 0 -> 1068 bytes icons/space-ship-d.png | Bin 0 -> 1120 bytes icons/space-ship-f.png | Bin 0 -> 1710 bytes icons/space-ship-g.png | Bin 0 -> 1586 bytes icons/space-ship-i.png | Bin 0 -> 1639 bytes icons/space-ship-j.png | Bin 0 -> 1625 bytes icons/space-ship-k.png | Bin 0 -> 1339 bytes icons/space-ship-l.png | Bin 0 -> 1233 bytes icons/space-ship-sides-a.png | Bin 0 -> 2003 bytes icons/space-star-gate.svg | 1 + icons/space-star-large.png | Bin 0 -> 641 bytes icons/space-star-medium.png | Bin 0 -> 707 bytes icons/space-star-swirl.svg | 1 + icons/space-station-a.png | Bin 0 -> 2458 bytes icons/space-station-b.png | Bin 0 -> 2215 bytes icons/space-station-c.png | Bin 0 -> 2580 bytes icons/space-station.svg | 1 + icons/space-stone-sphere.svg | 1 + icons/space-sun-outline.svg | 1 + icons/space-sun-rays.svg | 1 + icons/space-sun.svg | 1 + icons/space-target-outline.svg | 1 + icons/space-twinkle.svg | 1 + icons/space-ufo.svg | 1 + icons/space-vortex.svg | 1 + icons/space-water-world.svg | 1 + icons/space-world.svg | 1 + package.json | 4 +- src/HexmakerModal.ts | 90 +++++ src/HexmakerPlugin.ts | 59 ++++ src/HexmakerSettingTab.ts | 69 ++-- src/SetupWizardView.ts | 7 +- src/bundledIcons.ts | 2 + src/bundledSpaceIcons.ts | 144 ++++++++ src/constants.ts | 2 + src/hex-map/HexEditorModal.ts | 7 +- src/hex-map/IconPickerModal.ts | 20 +- src/hex-map/MapModal.ts | 5 +- src/hex-map/SubmapPickerModal.ts | 7 +- src/hex-map/TerrainEntryEditorModal.ts | 14 +- src/hex-map/TokenModal.ts | 5 +- src/hex-map/help.md | 2 +- src/hex-map/newMapFields.ts | 5 +- src/md.d.ts | 5 + src/palettes/AddPaletteModal.ts | 98 ++++++ src/palettes/PaletteStore.ts | 394 ++++++++++++++++++++++ src/palettes/paletteNote.ts | 182 +++++++++++ src/palettes/paletteOptions.ts | 27 ++ src/palettes/presets.ts | 145 +++++++++ src/types.ts | 4 + src/utils.ts | 25 ++ styles.css | 86 ++++- tests/asset-hooks.mjs | 2 +- tests/palettes.test.ts | 435 +++++++++++++++++++++++++ tests/register.mjs | 1 + 105 files changed, 2313 insertions(+), 59 deletions(-) create mode 100644 dev/build-space-icons.mjs create mode 100644 icons/CREDITS.md create mode 100644 icons/LICENSE-APACHE-2.0.txt create mode 100644 icons/space-anomaly.svg create mode 100644 icons/space-asteroid.png create mode 100644 icons/space-atom-outline.svg create mode 100644 icons/space-beacon-outline.svg create mode 100644 icons/space-black-hole.svg create mode 100644 icons/space-comet.svg create mode 100644 icons/space-debris.svg create mode 100644 icons/space-defense-satellite.svg create mode 100644 icons/space-dots-hex.svg create mode 100644 icons/space-double-ring.svg create mode 100644 icons/space-dust-cloud.svg create mode 100644 icons/space-earth.svg create mode 100644 icons/space-frozen-orb.svg create mode 100644 icons/space-galaxy.svg create mode 100644 icons/space-meteor-outline.svg create mode 100644 icons/space-meteor.svg create mode 100644 icons/space-moon-outline.svg create mode 100644 icons/space-moon.svg create mode 100644 icons/space-orbit-outline.svg create mode 100644 icons/space-orbit.svg create mode 100644 icons/space-orbital.svg create mode 100644 icons/space-planet-core.svg create mode 100644 icons/space-planet-outline.svg create mode 100644 icons/space-planet.svg create mode 100644 icons/space-portal.svg create mode 100644 icons/space-radial-balance.svg create mode 100644 icons/space-radioactive.svg create mode 100644 icons/space-raider-a.png create mode 100644 icons/space-raider-b.png create mode 100644 icons/space-raider-c.png create mode 100644 icons/space-raider-d.png create mode 100644 icons/space-ring-dashed.svg create mode 100644 icons/space-ring-segments.svg create mode 100644 icons/space-ring.svg create mode 100644 icons/space-ringed-planet.svg create mode 100644 icons/space-rocket.svg create mode 100644 icons/space-satellite-a.png create mode 100644 icons/space-satellite-b.png create mode 100644 icons/space-satellite-c.png create mode 100644 icons/space-satellite-d.png create mode 100644 icons/space-shield-outline.svg create mode 100644 icons/space-ship-a.png create mode 100644 icons/space-ship-b.png create mode 100644 icons/space-ship-c.png create mode 100644 icons/space-ship-d.png create mode 100644 icons/space-ship-f.png create mode 100644 icons/space-ship-g.png create mode 100644 icons/space-ship-i.png create mode 100644 icons/space-ship-j.png create mode 100644 icons/space-ship-k.png create mode 100644 icons/space-ship-l.png create mode 100644 icons/space-ship-sides-a.png create mode 100644 icons/space-star-gate.svg create mode 100644 icons/space-star-large.png create mode 100644 icons/space-star-medium.png create mode 100644 icons/space-star-swirl.svg create mode 100644 icons/space-station-a.png create mode 100644 icons/space-station-b.png create mode 100644 icons/space-station-c.png create mode 100644 icons/space-station.svg create mode 100644 icons/space-stone-sphere.svg create mode 100644 icons/space-sun-outline.svg create mode 100644 icons/space-sun-rays.svg create mode 100644 icons/space-sun.svg create mode 100644 icons/space-target-outline.svg create mode 100644 icons/space-twinkle.svg create mode 100644 icons/space-ufo.svg create mode 100644 icons/space-vortex.svg create mode 100644 icons/space-water-world.svg create mode 100644 icons/space-world.svg create mode 100644 src/bundledSpaceIcons.ts create mode 100644 src/palettes/AddPaletteModal.ts create mode 100644 src/palettes/PaletteStore.ts create mode 100644 src/palettes/paletteNote.ts create mode 100644 src/palettes/paletteOptions.ts create mode 100644 src/palettes/presets.ts create mode 100644 tests/palettes.test.ts diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index d3f9ab73..aa4fe76a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -208,6 +208,8 @@ Parsed/serialized by `workflow.ts`. Template files live at `{workflowsFolder}/te | `hexGap` | CSS gap between cells | | `hexOrientation` | `"pointy"` or `"flat"` | | `terrainPalette` | `[{name, color, icon?, iconColor?}]` | +| `terrainPalettes` | In-memory working copy + data.json cache of the palette notes (source of truth: one note per palette in `palettesFolder`, synced both ways by `src/palettes/PaletteStore.ts`) | +| `palettesFolder` / `palettesMigrated` | Palette notes folder (blank = `{worldFolder}/palettes`) / one-time settings→notes migration flag | | `gridSize` | `{cols, rows}` | | `gridOffset` | `{x, y}` origin offset (adjusted by expand buttons) | | `zoomLevel` | Current zoom | diff --git a/CLAUDE.md b/CLAUDE.md index a9907ab9..2ad42432 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -156,6 +156,8 @@ Renders an interactive hex-grid map for tabletop RPG world-building inside Obsid - **Hex notes**: `{hexFolder}/{region}/{x}_{y}.md`. Created via `createHexNote(x, y, region)` using the configured template or `defaultHexTemplate.md`. - **Template placeholders**: `{{x}}`, `{{y}}`, `{{title}}`. Template must include `### Towns`, `### Dungeons`, `### Features`, `### Quests`, `### Factions`, `### Encounters Table` headings. +- **Terrain palettes**: one markdown note per palette in `palettesFolder` (default `{worldFolder}/palettes`; basename = palette name; a `| Terrain | Color | Icon | Icon color | Category |` table). `src/palettes/PaletteStore.ts` syncs both ways: `saveSettings()` → `sync()` writes/renames/trashes notes; vault events re-parse hand edits into `settings.terrainPalettes` (kept as the sync-readable working copy and data.json cache). Edit palettes in memory + `saveSettings()` as before — never write palette notes directly. Built-in presets (Limited, Expanded, Space - Sector, Space - System) live in `src/palettes/presets.ts`; `createNewMap` installs an uninstalled preset on first use. +- **Icon packs**: bundled `bw-*` (Terrain) and `space-*` (Space, third-party — credits in `icons/CREDITS.md`, rebuilt by `dev/build-space-icons.mjs`), plus the user's icons folder (Custom). Every icon grid gets search + pack tabs via `HexmakerModal.addIconFilter(grid, …)` — new icon grids must set `data-icon` on tiles and call it. - **Terrain**: YAML frontmatter `terrain: `. Read via `getTerrainFromFile` (metadata cache); written via `setTerrainInFile` (raw text patch). Both in `frontmatter.ts`. - **Icon override**: frontmatter `icon: `. Read via `getIconOverrideFromFile`; written via `setIconOverrideInFile`. - **Terrain icons**: plugin `icons/` folder + user custom icons folder → `plugin.availableIcons`. URLs via `getIconUrl(plugin, filename)`. Vault-sourced filenames tracked in `plugin.vaultIconsSet`. diff --git a/README.md b/README.md index 006a8901..62febf74 100644 --- a/README.md +++ b/README.md @@ -229,7 +229,8 @@ Open **Settings → Hexmap World Creator** to configure: | **Hex gap** | Gap between hexes in pixels. | | **Hex orientation** | `flat` (default) or `pointy` top hex style. | | **Path types** | Named path types used by the Path drawing tool. Each type has a name, colour, width, line style, and routing mode. Manage them from the Path button on the hex map toolbar. | -| **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map. | +| **Palettes folder** | Folder holding one note per terrain palette (default `{world folder}/palettes`). | +| **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Limited* and *Expanded* (fantasy overland), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | --- @@ -342,3 +343,5 @@ src/ ## Third-party libraries This plugin bundles [MiniSearch](https://github.com/lucaong/minisearch) (© Luca Ongaro, MIT License) for in-memory full-text search. + +The space icon pack (`icons/space-*`) uses icons from [game-icons.net](https://game-icons.net) by Lorc and Delapouite (CC BY 3.0), [Material Design Icons](https://pictogrammers.com/library/mdi/) (Apache 2.0), [Tabler Icons](https://tabler.io/icons) (MIT), and [Kenney Simple Space](https://kenney.nl/assets/simple-space) (CC0). Full per-icon credits and licence texts are in [`icons/CREDITS.md`](icons/CREDITS.md). diff --git a/dev/build-space-icons.mjs b/dev/build-space-icons.mjs new file mode 100644 index 00000000..cb76faa7 --- /dev/null +++ b/dev/build-space-icons.mjs @@ -0,0 +1,166 @@ +#!/usr/bin/env node +/** + * Rebuilds the bundled space icon set in icons/ (files named space-*.svg / .png). + * + * node dev/build-space-icons.mjs + * + * SVGs come from the Iconify API (one batched request per collection) and are + * written with explicit width/height so they rasterise correctly in and + * canvas (PNG export). Kenney sprites are white; they are recoloured to black + * silhouettes (alpha kept) so they read like the other glyphs in untinted + * picker previews. Tinted map rendering uses them as a mask, so colour there + * comes from the terrain's icon colour either way. + * + * Sources and licences: see icons/CREDITS.md. Zero dependencies (Node ≥ 22). + */ +import fs from "node:fs"; +import path from "node:path"; +import zlib from "node:zlib"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const outDir = path.join(root, "icons"); +const kenneyDir = process.argv[2]; + +// [collection, source name, bundled basename] +export const SVG_ICONS = [ + // game-icons.net — CC BY 3.0 (Lorc, Delapouite) + ["game-icons", "uncertainty", "space-anomaly"], + ["game-icons", "black-hole-bolas", "space-black-hole"], + ["game-icons", "comet-spark", "space-comet"], + ["game-icons", "fragmented-meteor", "space-debris"], + ["game-icons", "dust-cloud", "space-dust-cloud"], + ["game-icons", "star-swirl", "space-star-swirl"], + ["game-icons", "world", "space-world"], + ["game-icons", "ringed-planet", "space-ringed-planet"], + ["game-icons", "frozen-orb", "space-frozen-orb"], + ["game-icons", "radial-balance", "space-radial-balance"], + ["game-icons", "portal", "space-portal"], + ["game-icons", "star-gate", "space-star-gate"], + ["game-icons", "planet-core", "space-planet-core"], + ["game-icons", "galaxy", "space-galaxy"], + ["game-icons", "stone-sphere", "space-stone-sphere"], + ["game-icons", "vortex", "space-vortex"], + ["game-icons", "sun", "space-sun"], + ["game-icons", "orbital", "space-orbital"], + ["game-icons", "defense-satellite", "space-defense-satellite"], + // Tabler Icons — MIT + ["tabler", "atom-2", "space-atom-outline"], + ["tabler", "circle-dot", "space-target-outline"], + ["tabler", "shield", "space-shield-outline"], + ["tabler", "meteor", "space-meteor-outline"], + ["tabler", "circle-dashed", "space-ring-dashed"], + ["tabler", "planet", "space-planet-outline"], + ["tabler", "moon", "space-moon-outline"], + ["tabler", "sun", "space-sun-outline"], + ["tabler", "orbit", "space-orbit-outline"], + ["tabler", "building-broadcast-tower", "space-beacon-outline"], + // Material Design Icons (Pictogrammers) — Apache 2.0 + ["mdi", "circle-double", "space-double-ring"], + ["mdi", "meteor", "space-meteor"], + ["mdi", "dots-hexagon", "space-dots-hex"], + ["mdi", "circle-slice-8", "space-ring-segments"], + ["mdi", "star-four-points-outline", "space-twinkle"], + ["mdi", "rocket-launch", "space-rocket"], + ["mdi", "earth", "space-earth"], + ["mdi", "planet", "space-planet"], + ["mdi", "circle-outline", "space-ring"], + ["mdi", "moon-full", "space-moon"], + ["mdi", "water-circle", "space-water-world"], + ["mdi", "ufo-outline", "space-ufo"], + ["mdi", "white-balance-sunny", "space-sun-rays"], + ["mdi", "orbit", "space-orbit"], + ["mdi", "space-station", "space-station"], + ["mdi", "radioactive", "space-radioactive"], +]; + +// Kenney Simple Space — CC0. [sprite, bundled basename] +export const KENNEY_ICONS = [ + ["meteor_detailedLarge", "space-asteroid"], + ["star_large", "space-star-large"], + ["star_medium", "space-star-medium"], + ["ship_sidesA", "space-ship-sides-a"], + ...["A", "B", "C", "D", "F", "G", "I", "J", "K", "L"].map((l) => [`ship_${l}`, `space-ship-${l.toLowerCase()}`]), + ...["A", "B", "C", "D"].map((l) => [`enemy_${l}`, `space-raider-${l.toLowerCase()}`]), + ...["A", "B", "C"].map((l) => [`station_${l}`, `space-station-${l.toLowerCase()}`]), + ...["A", "B", "C", "D"].map((l) => [`satellite_${l}`, `space-satellite-${l.toLowerCase()}`]), +]; + +async function buildSvgs() { + const byCollection = new Map(); + for (const [col, name, out] of SVG_ICONS) { + if (!byCollection.has(col)) byCollection.set(col, []); + byCollection.get(col).push([name, out]); + } + for (const [col, list] of byCollection) { + const url = `https://api.iconify.design/${col}.json?icons=${list.map(([n]) => n).join(",")}`; + const res = await fetch(url); + if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`); + const data = await res.json(); + for (const [name, out] of list) { + const icon = data.icons?.[name] ?? data.icons?.[data.aliases?.[name]?.parent]; + if (!icon) throw new Error(`${col}:${name} not found`); + const w = icon.width ?? data.width ?? 24; + const h = icon.height ?? data.height ?? 24; + // Size up small-grid sets so /canvas rasterise them crisply. + const scale = Math.max(1, Math.round(128 / Math.max(w, h))); + const svg = + `` + + `${icon.body.replace(/currentColor/g, "#000")}\n`; + fs.writeFileSync(path.join(outDir, `${out}.svg`), svg); + } + console.log(`${col}: ${list.length} icons`); + } +} + +/** Blacken an indexed-colour PNG's palette; transparency (tRNS) is untouched. */ +function blackenIndexedPng(buf) { + if (buf[25] !== 3) throw new Error("expected an indexed-colour PNG"); + const out = Buffer.from(buf); + let off = 8; + while (off < out.length) { + const len = out.readUInt32BE(off); + const type = out.toString("latin1", off + 4, off + 8); + if (type === "PLTE") { + out.fill(0, off + 8, off + 8 + len); + const crc = zlib.crc32(out.subarray(off + 4, off + 8 + len)); + out.writeUInt32BE(crc >>> 0, off + 8 + len); + } + off += 12 + len; + } + return out; +} + +function buildKenney() { + if (!kenneyDir) { + console.log("kenney: skipped (pass the unzipped kenney_simple-space folder to rebuild)"); + return; + } + const src = path.join(kenneyDir, "PNG", "Retina"); + for (const [sprite, out] of KENNEY_ICONS) { + const png = fs.readFileSync(path.join(src, `${sprite}.png`)); + fs.writeFileSync(path.join(outDir, `${out}.png`), blackenIndexedPng(png)); + } + console.log(`kenney: ${KENNEY_ICONS.length} icons`); +} + +/** Regenerate src/bundledSpaceIcons.ts from whatever space-* files are in icons/. */ +function writeImports() { + const files = fs.readdirSync(outDir).filter((f) => /^space-.*\.(svg|png)$/.test(f)).sort(); + const ident = (f) => f.replace(/\.(svg|png)$/, "").replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase()); + const lines = [ + "// Generated by dev/build-space-icons.mjs — space icon pack (see icons/CREDITS.md).", + ...files.map((f) => `import ${ident(f)} from "../icons/${f}";`), + "", + "export const BUNDLED_SPACE_ICONS: [string, string][] = [", + ...files.map((f) => `\t["${f}", ${ident(f)}],`), + "];", + "", + ]; + fs.writeFileSync(path.join(root, "src", "bundledSpaceIcons.ts"), lines.join("\n")); + console.log(`src/bundledSpaceIcons.ts: ${files.length} imports`); +} + +await buildSvgs(); +buildKenney(); +writeImports(); diff --git a/esbuild.config.mjs b/esbuild.config.mjs index da33b777..11a7bed8 100644 --- a/esbuild.config.mjs +++ b/esbuild.config.mjs @@ -31,7 +31,7 @@ const context = await esbuild.context({ sourcemap: prod ? false : "inline", treeShaking: true, outfile: `${outDir}/${outFile}`, - loader: { ".md": "text", ".png": "dataurl" }, + loader: { ".md": "text", ".png": "dataurl", ".svg": "dataurl" }, }); if (prod) { diff --git a/icons/CREDITS.md b/icons/CREDITS.md new file mode 100644 index 00000000..b2d8a69b --- /dev/null +++ b/icons/CREDITS.md @@ -0,0 +1,102 @@ +# Icon credits + +The `bw-*` terrain icons ship with the plugin. The `space-*` icons are third-party, +used under the licences below. Files were renamed, and the Kenney sprites were +recoloured from white to black so they read in untinted previews. +Rebuild with `node dev/build-space-icons.mjs `. + +## game-icons.net — CC BY 3.0 + +Icons by **Lorc** and **Delapouite**, available on https://game-icons.net, licensed +under Creative Commons Attribution 3.0 (https://creativecommons.org/licenses/by/3.0/). + +- `space-anomaly.svg` ← `uncertainty` — by Lorc +- `space-black-hole.svg` ← `black-hole-bolas` — by Lorc +- `space-comet.svg` ← `comet-spark` — by Lorc +- `space-debris.svg` ← `fragmented-meteor` — by Lorc +- `space-dust-cloud.svg` ← `dust-cloud` — by Lorc +- `space-star-swirl.svg` ← `star-swirl` — by Lorc +- `space-world.svg` ← `world` — by Lorc +- `space-ringed-planet.svg` ← `ringed-planet` — by Lorc +- `space-frozen-orb.svg` ← `frozen-orb` — by Lorc +- `space-radial-balance.svg` ← `radial-balance` — by Lorc +- `space-portal.svg` ← `portal` — by Lorc +- `space-star-gate.svg` ← `star-gate` — by Delapouite +- `space-planet-core.svg` ← `planet-core` — by Delapouite +- `space-galaxy.svg` ← `galaxy` — by Delapouite +- `space-stone-sphere.svg` ← `stone-sphere` — by Lorc +- `space-vortex.svg` ← `vortex` — by Lorc +- `space-sun.svg` ← `sun` — by Lorc +- `space-orbital.svg` ← `orbital` — by Lorc +- `space-defense-satellite.svg` ← `defense-satellite` — by Delapouite + +## Material Design Icons (Pictogrammers) — Apache License 2.0 + +From https://pictogrammers.com/library/mdi/, licensed under the Apache License, +Version 2.0. A copy of the licence is in `LICENSE-APACHE-2.0.txt` in this folder. + +- `space-double-ring.svg` ← `circle-double` +- `space-meteor.svg` ← `meteor` +- `space-dots-hex.svg` ← `dots-hexagon` +- `space-ring-segments.svg` ← `circle-slice-8` +- `space-twinkle.svg` ← `star-four-points-outline` +- `space-rocket.svg` ← `rocket-launch` +- `space-earth.svg` ← `earth` +- `space-planet.svg` ← `planet` +- `space-ring.svg` ← `circle-outline` +- `space-moon.svg` ← `moon-full` +- `space-water-world.svg` ← `water-circle` +- `space-ufo.svg` ← `ufo-outline` +- `space-sun-rays.svg` ← `white-balance-sunny` +- `space-orbit.svg` ← `orbit` +- `space-station.svg` ← `space-station` +- `space-radioactive.svg` ← `radioactive` + +## Tabler Icons — MIT + +From https://tabler.io/icons. + +- `space-atom-outline.svg` ← `atom-2` +- `space-target-outline.svg` ← `circle-dot` +- `space-shield-outline.svg` ← `shield` +- `space-meteor-outline.svg` ← `meteor` +- `space-ring-dashed.svg` ← `circle-dashed` +- `space-planet-outline.svg` ← `planet` +- `space-moon-outline.svg` ← `moon` +- `space-sun-outline.svg` ← `sun` +- `space-orbit-outline.svg` ← `orbit` +- `space-beacon-outline.svg` ← `building-broadcast-tower` + +``` +MIT License + +Copyright (c) 2020-2026 Paweł Kuna + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +## Kenney Simple Space — CC0 1.0 + +Sprites from https://kenney.nl/assets/simple-space by Kenney (www.kenney.nl), dedicated +to the public domain (https://creativecommons.org/publicdomain/zero/1.0/). Credit is +not required, but given with thanks. + +- `space-asteroid.png`, `space-star-large.png`, `space-star-medium.png` +- `space-ship-*.png`, `space-ship-sides-a.png`, `space-raider-*.png` +- `space-station-a/b/c.png`, `space-satellite-a/b/c/d.png` diff --git a/icons/LICENSE-APACHE-2.0.txt b/icons/LICENSE-APACHE-2.0.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/icons/LICENSE-APACHE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/icons/space-anomaly.svg b/icons/space-anomaly.svg new file mode 100644 index 00000000..9b6e876e --- /dev/null +++ b/icons/space-anomaly.svg @@ -0,0 +1 @@ + diff --git a/icons/space-asteroid.png b/icons/space-asteroid.png new file mode 100644 index 0000000000000000000000000000000000000000..b174fa030ab72f3f346188c616e7ae40e62a2a63 GIT binary patch literal 1147 zcmcJP`BPJO6ve+uUhE5tgvH_jl3=k#x?o#mDFX>MtPO}MODHr6pi&0}r(g*kLS7zI ziHw*8#)4K1Na;Y4O|76cjZjiSsG-O<1q?+3HW+A0NG4>VIMeCv5cF*~w z#280A4?6&WV_Ynau|wqLz_^{%FGx%~fN~=fA_3?T*;}&kJ9}CZJvnNJ|A%(h)t=tD z>sZW4{8%aNQgx}MN>ad4HlR5lL;=9viK9g(bAQ*)Y8k6!B9b*RsU6p~rFafm*(-5R zf-vy|Yc+{0qhr!k9;xR@{FsIN*Uy1e+`oRn-#rr^uJwjzWM_FQnbsSck(rt(aG7I& z@{-b8+lX@XraZn|D9ObfI#2!E` z=Lhr9jH^ymd-7w;vzt~XH6C;?Q|h!a*fESSbo*XD#YJof=1i&+<|Ysb77b=wbKiRs zEO-%-a~cXo{I^KGSQi{s<-~UV^b}0b0?9n7vzQ1pHtFB?PHo^gU>E~r$}atDzF4Gj zdvotFFL1j z$OOaYHnRK!S65I~{uYzjAb5qGLUHr@`Xro-kdZzL#bm-sWA6uMy}H|}3ZzhlURM$1(ccg%Nb@Qn4T8)j-4Z~5t#+TEuLzfUf@ zAjht@VEYwU)N~p*K%g7CLg2DG95eQ6$`~Z1$W(j`(z6fF@`;o z%?$fr5}*;epQ0L{L&B#irV9N-3a>MVJzeJ*XV#jZH%K;T3Gd7@Qw_^*!LFHGeq|;3 z)@XD!=-Q=%q=g_fkE96mohtOH4`Otb)!GFU>Ad6@HRw{}LPBy#b;fqKqVJ$l1 zbEt@a0;C4F_rw$R$L?l$I|wp~`srO9>p8pzpGBH1p%3_o2?I6_a4Yzvi9y`#S?o*? zgvuf(*d%1U`lAVWF(P$7w7L>`LumdAdWvQdSrPD4iwEv1u^$M*g626d^rY3lv{1H1$l??#DlUw79?npb{=^W4Pr za{I+EoS>4mRo$h^Sz}klgUO|Kk#U{PGMrU4Su3Oddpau4f?M-G#Tx8t6~3&DxTr*0 I=MfJ254 diff --git a/icons/space-beacon-outline.svg b/icons/space-beacon-outline.svg new file mode 100644 index 00000000..3aded925 --- /dev/null +++ b/icons/space-beacon-outline.svg @@ -0,0 +1 @@ + diff --git a/icons/space-black-hole.svg b/icons/space-black-hole.svg new file mode 100644 index 00000000..58d4f864 --- /dev/null +++ b/icons/space-black-hole.svg @@ -0,0 +1 @@ + diff --git a/icons/space-comet.svg b/icons/space-comet.svg new file mode 100644 index 00000000..73339534 --- /dev/null +++ b/icons/space-comet.svg @@ -0,0 +1 @@ + diff --git a/icons/space-debris.svg b/icons/space-debris.svg new file mode 100644 index 00000000..eddb4991 --- /dev/null +++ b/icons/space-debris.svg @@ -0,0 +1 @@ + diff --git a/icons/space-defense-satellite.svg b/icons/space-defense-satellite.svg new file mode 100644 index 00000000..94d6f663 --- /dev/null +++ b/icons/space-defense-satellite.svg @@ -0,0 +1 @@ + diff --git a/icons/space-dots-hex.svg b/icons/space-dots-hex.svg new file mode 100644 index 00000000..45b2ae99 --- /dev/null +++ b/icons/space-dots-hex.svg @@ -0,0 +1 @@ + diff --git a/icons/space-double-ring.svg b/icons/space-double-ring.svg new file mode 100644 index 00000000..eb1ff054 --- /dev/null +++ b/icons/space-double-ring.svg @@ -0,0 +1 @@ + diff --git a/icons/space-dust-cloud.svg b/icons/space-dust-cloud.svg new file mode 100644 index 00000000..62d0bf22 --- /dev/null +++ b/icons/space-dust-cloud.svg @@ -0,0 +1 @@ + diff --git a/icons/space-earth.svg b/icons/space-earth.svg new file mode 100644 index 00000000..936e34c2 --- /dev/null +++ b/icons/space-earth.svg @@ -0,0 +1 @@ + diff --git a/icons/space-frozen-orb.svg b/icons/space-frozen-orb.svg new file mode 100644 index 00000000..c5481664 --- /dev/null +++ b/icons/space-frozen-orb.svg @@ -0,0 +1 @@ + diff --git a/icons/space-galaxy.svg b/icons/space-galaxy.svg new file mode 100644 index 00000000..46ca9f43 --- /dev/null +++ b/icons/space-galaxy.svg @@ -0,0 +1 @@ + diff --git a/icons/space-meteor-outline.svg b/icons/space-meteor-outline.svg new file mode 100644 index 00000000..41f6036a --- /dev/null +++ b/icons/space-meteor-outline.svg @@ -0,0 +1 @@ + diff --git a/icons/space-meteor.svg b/icons/space-meteor.svg new file mode 100644 index 00000000..b4f79ecb --- /dev/null +++ b/icons/space-meteor.svg @@ -0,0 +1 @@ + diff --git a/icons/space-moon-outline.svg b/icons/space-moon-outline.svg new file mode 100644 index 00000000..e7b48484 --- /dev/null +++ b/icons/space-moon-outline.svg @@ -0,0 +1 @@ + diff --git a/icons/space-moon.svg b/icons/space-moon.svg new file mode 100644 index 00000000..3b39799c --- /dev/null +++ b/icons/space-moon.svg @@ -0,0 +1 @@ + diff --git a/icons/space-orbit-outline.svg b/icons/space-orbit-outline.svg new file mode 100644 index 00000000..60235b4d --- /dev/null +++ b/icons/space-orbit-outline.svg @@ -0,0 +1 @@ + diff --git a/icons/space-orbit.svg b/icons/space-orbit.svg new file mode 100644 index 00000000..51617ab3 --- /dev/null +++ b/icons/space-orbit.svg @@ -0,0 +1 @@ + diff --git a/icons/space-orbital.svg b/icons/space-orbital.svg new file mode 100644 index 00000000..970fe0c7 --- /dev/null +++ b/icons/space-orbital.svg @@ -0,0 +1 @@ + diff --git a/icons/space-planet-core.svg b/icons/space-planet-core.svg new file mode 100644 index 00000000..5b67e141 --- /dev/null +++ b/icons/space-planet-core.svg @@ -0,0 +1 @@ + diff --git a/icons/space-planet-outline.svg b/icons/space-planet-outline.svg new file mode 100644 index 00000000..66ae6bc4 --- /dev/null +++ b/icons/space-planet-outline.svg @@ -0,0 +1 @@ + diff --git a/icons/space-planet.svg b/icons/space-planet.svg new file mode 100644 index 00000000..936e34c2 --- /dev/null +++ b/icons/space-planet.svg @@ -0,0 +1 @@ + diff --git a/icons/space-portal.svg b/icons/space-portal.svg new file mode 100644 index 00000000..9ebafdcc --- /dev/null +++ b/icons/space-portal.svg @@ -0,0 +1 @@ + diff --git a/icons/space-radial-balance.svg b/icons/space-radial-balance.svg new file mode 100644 index 00000000..ed57a920 --- /dev/null +++ b/icons/space-radial-balance.svg @@ -0,0 +1 @@ + diff --git a/icons/space-radioactive.svg b/icons/space-radioactive.svg new file mode 100644 index 00000000..0a7cedae --- /dev/null +++ b/icons/space-radioactive.svg @@ -0,0 +1 @@ + diff --git a/icons/space-raider-a.png b/icons/space-raider-a.png new file mode 100644 index 0000000000000000000000000000000000000000..fc93ba4e1f7d531041c8333dfa25f5e46bd410c4 GIT binary patch literal 2041 zcmeH{=~Giz6u|FGqU;0>7E~}{1cJ&EiZW2Zpu(^V0(Al9MX_R)vWQ}oKvJewk-Y97a^2VAxS9^V+=H@{S*4p-^{tcIp@wjAI{u4c~M(~ z%#2qU0|3lIf&-#;7U;u}tUG6<->G$?ByEb=1i($iy>>pdTR_pASenW1Wq8t2atb(2^fL(pgIVcKwtvnyD1bXMkn|$5x>d^~(wr!G=GBCC=JSX`<$R7?#|`#L(ehddHkTafqp zo1TH(r3>b)h<4E2X&QW~c6nz}rwQxws~%$(0}EZpSfuWagIuC~BbXA3( z*07!w4Qy?b4pVO36=cjn7mfTqD>pPkrj)y3D<$RNd}xhNqpm7ZDwVePfSkfB}UALJi9l;*^kQ$ImQm%Yv777hhs!z*|^?6-^jCTR> zNog%%(RLCGs5Zt>$po(wT>mweB@VU~RDj9Z;@HL2jvz?8`-W-ZQgWXYIf^DQVp|DG zowRC*77_?fl31Z*C-qJ%e7;$4rNM>#UQlKvS$`?c0j#!3Yg`IEAg|5iz7F63Ny)r) zVl9}YNWF>&#RmIJ>I8}59qnx!7~OFki0?koT~QwIf30^_BE&2UAE?j$W>W1v$Mbsj zq-2@BJ$@%B$zZ0{cxlo2&`XLm)pN`3s|>pn8`)6VK99sO;{#9`@^j8yITPhiT%^|PjCdJ5MTrCYSI2F}4f6|Xf#py9;Rtr(WN z@K!qF8Si9Kl{zl}T|@P30rL0`)p1qksG`aJRXBMrYFEkdnS_jL%SqAUv*riyvtQ8H z@JhFg$8T@2u4}6=U(sdon=G)3pJd|(1}F54N(n#QoSR~;Bpt~{6ng9f&`_D>5EwpHXiG;ZPre#ZoJPJzt&WdW5`)H zku-5Ui!P@x{5nEmdy5VIE7woRpR~=V9nH+_iyg8eRXx$T)R(?@5%NbC z<UvssWF=t@{c?pp%7K+YqKH2eZKe?SLr+?A8Svlienox`l<6PrSsu6 zRO@;z5bVYV2XcJm3-LybAu1St(vL$a0e2VnIS7*3fJ=rkG5VS+WXHlE?(J2G`90!m zjn-`ksb!8V=x@>f=>MR2=z2O^#nr#zdJOu@(IL+)%wGh@s55TwXB%>RF+Or$G+yI6 z{deoJCU`kxz>3G%HSmVOp3R!5u)JxZUB4Ar(RXSVJ2&%ab-z`%WAYC))sCxI{JsjA zJwo`%n0*ljWjg?-`KvV&ERU{gLKyC~038BLE@8|ml{^tfl zZT$AaRwgsZFIXaANmv4jghdd*%E?LK#A3lUSgr!TIte5!i39>62m%EHkWP$;L?VBY z2ml0dl8eYJA{~q;0wTE_f{6Y^Ihia0B>)7#tsq1OApnw-2?Qb>pag`+6A#ATYGa%y9_(LnUub#jD3ziqAk<^;M~vL^Y@yHt))fyYDWsr z#h+pOn@i$~J-^du$Iik|v;3nw0f;XLx)l9OZ-?Zs%zTgAoXE;v8;#7TnDbWAv=Y`- zZG#_I6rgeFE~Kw-0s6FU19Ba^bU%r}6I%ozeqsE`Kr*^5c$&|r4DQ>P4Y;^I;@-8g z3Hh(A=U%q5`Q5&(Z`Dv5bmxX|(^Nz~?GM2!s}2eMbJ_2oM%w3?a~$;Qg8A$xIy!yz z)K#iuCf$9J^LBkvlje>{hVjO;QOEQsGZE$d^`WRio#s0J`A66~L^J0^c1l5+XU^xBrba!s9P|-VifPsnZ?CM+=`rJtV_MSx`Xk}%A zg&)=*X_$Jz(~06d8B;`QytKT2LESS|!l#ST3A%pu^|t%S28S9slR!dj9Cn&i4d)?alK zMthz~ThNvO5k=9}>8U5F1@p zvT|{NkS-?_nJza4ZWmE37A)uGh?W+4I`|CPFw9A~2ENJOzI~-Agq_5CF^ktSO`gUX z?VK`R=8s$3nMg~K<6rSK>lL!m+lg<&tI_(b-TL7clwN`wZ4Ef3fI@JIPosE53q#ly zbZQPcN=>ZfHZ}nt(y!#=8~`yCSm~B0m)c=jiOyDoRuf^d*+eWtZMyRDHRpGOiRmr{XveMf! zZ94j+BvuMxhJNmai~|#u7rmsnZ!Q7zq}kG-4OfBF$9k8YsjQlVG=5#Zr|b0#zu zvbbASxIwehYmjzp(amPxv`kqb7rCmu<72fRZ*$N8tD0maP+@S7xz%8|EA$G27o9MWU&x_(1zgsaXFyR<)sn9IqjH%piN5|w*Qj{HWq4`gdUK5*zCt}vD zH7fu=)f6Az!i!BF`+CWo%sZ95xFOekE05XOTpY|_=jlL~O+1>yn}LE)*fcMc!9=;^ z^Jo)|>&nZ3B0r1Wo%Aj()Hk3=pkmbC+3WO`km*DE;W=st=U)`8XhK3q59{>ZH&(x5 MFRGtgrAtK0KfeIPd;kCd literal 0 HcmV?d00001 diff --git a/icons/space-raider-c.png b/icons/space-raider-c.png new file mode 100644 index 0000000000000000000000000000000000000000..29f0fa9f3fada1559c77d558e8e6a8224dc2b219 GIT binary patch literal 2172 zcmeHIYfw{X5dA_VfQSJfpy+tbK=FYZMNl3#0f|KgNeHOL0--zv1e#h!3MRQx&}gw- zZL5GHH$ZVBMuI4!2wtFqfZ_#F2`U7O@`@Uw1`yEA8J&K_q4 z`dLl4pAG=9+OnC!HlpxTniGxnL*FT#5vIlYZ1Vx&3Sz1M))WAfI95Q&CL{kjJ}dBl zD-b!CbIiCSb3Z#U7{gRJ7e`T4#l>-)%l)T9I2Sc`C>O;c)X1TT0;Y0hGO9{N=OR=( zOvMpYrl8X?97mX_Ooee2RG5QdFh|BgAVkK&I7}SHQH2UaF$_`3ATkG1z+?`Bs>pO0 zm60)&%7Hk>(GckEu=xc5)74uTJ|RCoeRFpFn>l_9o0inx{SXnLs@>UnP}P_#_m9f@ z$z*Hy&j}LBJi;dL(uEDj?HO-pz8w>KHSnh-uixHJ%Ii7bW06+DEQsrc41%%R@tfoF zyz_G}uCZ(ZF2Wg$iOv6pQJ5@Vy2eaWmhIu)woFZ8i6wXJ#rD^NqpeuPrwMyWEU@*9 zFPgw(@T>|oP|aAq>4i1CmS56jw`)iH@v0+k;O27=iei=mu@Flq%Ot0_I^5jIftl~T zo!(D8Ony!hvzC7EX+FNsRHBy_4-EvrN#2$P^}7N-pTEw=-j?=^MTIc2agF>-t4Yzv_B*QSMQam z;#p-cMsOD=mZjQuBh%#eO)6-ju8Pn+@14GcG44y_m4!%UU9Oi$m4WA=)-p{ZU>_~( z6VSTw8LVM#?VM|0l|KsF{54PM%+ zB_f6HP$#mbKLm?X9L?dV*A`r2`|c5wK}Iu^ES9G&sAr}%AXYqO0+@B-!9Ic8MnSqT zXT|OM9MRFhhE&B!f^gbqUJUb&{$y#U8a$nOpBW&HTp--=WT97HF2wE%ipcOb1ZeA@ z$w__drTZ=)5<~3a^iYspy&4`maGelOsqnP^;CuRmpisSPs9ygfI@QIhPQ@7PJSY@H z=_h+-!b`Jr=|9+Yg5Qs?awG=P_mgWm@2K(&UEZxclK9sVmkl-=-&ZlU?OHp>HT1Q* zoQt~?%X9XSn6sh;<{g^SW=x!^dr_>7eoeiRRXU%^Fj$9EDU3{dyrA`lK{dHjbJih< z&gfE>Tbk1wU4ieJqiv@oP|@U(Peh9=2=ylp9MhH*O;8#{5#CyQ9%&(=BBd$d5&8TP z-B>z}vsl0C0wKOK_M`XOD8Z8ABe`5>HMKcXpf|ffkjGtmmRr)O58TL%y1lFg6I;H& z>l~I!=|3}Y@=Cb1#utgAU0M6mFH1Mg{@S)8e zJD8#$x|&2B6$RT3NBhwE!PU7m>MNohw-xJ808U{pV<)1FH}#VamN>yQe_hAV1*FLK z694T%^#1x74}QeG0~1LxSsAuisKynD!m4-8)vPs%{`K7=YCec9m7pn`E6?CNJrFqG z{=l9?+cs&gBEt~}J#(k3TlwHsdyvT1{o*k}c1Eik(^P$~s@yN~`h}#n)Zh+%m|rEn z;q6_xvSZNt!IC;2*|rh!kP6hXXQp0SV$m$GddJ771z|VP@f#mIE2zt+c#Q{r2HSTW z-dm*1Xtu^+eZyfV_w1B@c&aJWQ64+;)IFlRZ(8Tk<$tEd#W)Q;cFV%i9)D*CpYZUW z`RZD?&e1d?^2AS%3Rj-3rb6*vj&dp0=2MpZ>*`O@WNE Ijgg1{0(YkX1^@s6 literal 0 HcmV?d00001 diff --git a/icons/space-raider-d.png b/icons/space-raider-d.png new file mode 100644 index 0000000000000000000000000000000000000000..03fbee4d799547a1c504e63a191434688617f3b2 GIT binary patch literal 2316 zcmeH|`&Uy}7RS#`A|yP#LxI797=)ryA2_u-4uat+@_tKE7ZIius!M|i)ruq+QpK8< z6qScmxF{$BBB)^$P%ia>Jj5Wu@EmRwG!Ve35JH}J!mKs_!Ti|0&OV>L_V=89*4jVp z^K*EpzqyI62>`%6V7G6ifyk0m$%cJilCLs=lI#`Y1;A~-sWxF50Hm1k;AlTX{!ja} z1OML+{88e((NHlfJu);3$N4DAJ5eXs1P>Ds2qh|QCB`4 zX5y$^2)n{S{+#X$z_OtLU$5vB!?PtSrltRic9Eu4u4&zuIV2Xxi^XHgtXRK^-%Kc^ z-{-^kjkJp+zu#&ECq9YU?L~d!El^;A`I#hb;fzNkqI)~{Cs{F9B2h8(pTQse6 zMy)$KO%}mU1eTEhiw_K=&1G>PN6*{DpPG7GK(~8i^Lc^lDVRM}Hdfl%UUlrk7R%f* zrskR?$=-fW-IK<)KrDuDi|R0dKaW&mP@68}bo8n;ueOr=Ts16BWP#P}x^H&F24l)$x zHreiNan9^0F$}o}wG#I8cI6NMMRZ8_Q^Gg=b<1|lW!e}jd!`b8#TN7|&@*{FPe>9f zW(8`zz$eW}XRBBH0$Tjm5lL$rwf_absN{kPC4YMYk+6xBl9u-A2Q}+@4xQpK0PD>g zIC(rUe6i??G#Bbn)D|g}i3GNv(i1cLz+U))!`+9jmC=n(7&EaZ z;fLfAhWLpe2${&ZYe+7h8)XC!vl0o(h~e^;95Z_iNIcSrzzA$&YsV~Nchpo$FH&b(tlkq_ ztUM%;qFIa8vm8ZZPN~!6x6q4mS&@1@J$y6e3sMTT_H;dyOQVIPy27cq90I z1THr#PAaUEeK%!`GPGw3`fKamDjg{_Y3N9p)vKC%cjw2H?~NtLuh#8Vyn2?t&8zG1 zk7ut7WQU&9c$6dKO{XU_>(p-CF86FZNFa=eu4)xmemz=n2E0p`P5*lEF?=5c_}j?( z2QFJ5Zw8$0Zg@*VqnF1=`BCe6vvMwJ`=soo5DXtclFFcP3(tyMn-nHU9x&f*J5Mz* zFsfPX1l&j|#eD^10O=V!SL4N7>%oJ=R zrJRe%nuQ#L;t;1_UgY)LI`ow$Li+Cn4|hcFLrxLa$xzWO&8+Jw?LmB4u9!LEbPORq#HaoRkH zZ#Y_Yj#`pSB~3& zb(aYn8oO(Hj|ao7JWbDZn4F%j6)CtNP)humlOhPkVdzFFk=v^lefg0L&Pjn)gF%+q|d9G;2(&_vCs%tCkdv(Nm&j>bJT+4Y}rVl}rw=tCeZUjrso@vrE%< ct-XZNa&O>=M=O`tEd5^rexbg%ybt932Pzs|f&c&j literal 0 HcmV?d00001 diff --git a/icons/space-ring-dashed.svg b/icons/space-ring-dashed.svg new file mode 100644 index 00000000..c3880a11 --- /dev/null +++ b/icons/space-ring-dashed.svg @@ -0,0 +1 @@ + diff --git a/icons/space-ring-segments.svg b/icons/space-ring-segments.svg new file mode 100644 index 00000000..86f9ddb5 --- /dev/null +++ b/icons/space-ring-segments.svg @@ -0,0 +1 @@ + diff --git a/icons/space-ring.svg b/icons/space-ring.svg new file mode 100644 index 00000000..94f59802 --- /dev/null +++ b/icons/space-ring.svg @@ -0,0 +1 @@ + diff --git a/icons/space-ringed-planet.svg b/icons/space-ringed-planet.svg new file mode 100644 index 00000000..f3c64a98 --- /dev/null +++ b/icons/space-ringed-planet.svg @@ -0,0 +1 @@ + diff --git a/icons/space-rocket.svg b/icons/space-rocket.svg new file mode 100644 index 00000000..a1219af5 --- /dev/null +++ b/icons/space-rocket.svg @@ -0,0 +1 @@ + diff --git a/icons/space-satellite-a.png b/icons/space-satellite-a.png new file mode 100644 index 0000000000000000000000000000000000000000..58de6c43e6c7b19e564520a13d7eac89a2b40293 GIT binary patch literal 351 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?I3?vN&YJLDImUKs7M+SzC{oH>NS%G}50G|+7 zAWbCT5jCuEBWActNjtGUtVPj1QGn9jd{K7#O-6cCgpHXYOva@?aCcpk=VD z!9W-&rG8<*5&M$o47b^4urf5*GxhGP-_hXLxSQKz{-y8R4|ln4-oEBu2qS|TlZD-` zSt;*|FV16(HTu3Y<9vg~|I2rtFS7l&mYKn)k}1XVVHR`A-t8dkJYD@<);T3K0RSH7 BaESl_ literal 0 HcmV?d00001 diff --git a/icons/space-satellite-b.png b/icons/space-satellite-b.png new file mode 100644 index 0000000000000000000000000000000000000000..9f78a3a522e6b58327d5609147cf7872e08176d7 GIT binary patch literal 1241 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H3?#oinD`S&v7|ftIx;Y9?C1WI$jZRL7$4vh z;tCWW1+)tRk7a%4K+_#cg8YK})+nGEOIgVnm~>gRnlIk4noU4|&@6G?yO0}UcT`aD<%R9`&f zJa?W1=}yLTRY?u|r-?l{=-V%H;K4Pipay1httAZd>((!3sbIK#Sx&Km^MHZk0l@~| z76!ZDZ@-#dW~^YfSnzxzkXms0CC_9KegFM@Mdlwu1+%ymv=kWrS_wLYFwFZbqt0X@ z_&`KZA%eO3K=C9tfe?nct}C7lI*c(Yj4YxJt`j$_FxWHBS-^0D%i}=OTm}Vg24lx# z91NS7K3JRxWOCRc^iShNT#Z8nV}<@@7j^?#gEl@6Z3h3;vPH~`&Q4G_ir&Z=$ojx} zhMG~sQpVpCK%B@KcTY4_*ym`T5sPt%X_VM-#f9~VXoGlQ-$JHGTnCnGJYK=@-~WK6 zk3$gS57FhF90_U%DqR|qnR=9&ro?`{X(4`!dCjs-3u1oHSu%UydXocdBn{fxW(2NV ztFp73ZAUuWnPkQ*Tq_!;>IpflW!Mw8sfQ&%n_>NwJB~~%L>nqqx1VO>`J?>c=c;90 zpHxzs8LI;r`pVvR&yv+(s5eNEW^-82P;)uRm0^R5 zIY_iYzG~G{<_NO~2`?K$SRX8($GnvJPtJjfml*S2-72@;`l+5ZPi#TkM~!Q&`B$zK zJY$`e;CC`{O=qW8gr8BDxp9$iL*SX0l}bM(mNxEod$Np?_f6|5j|~c!55()1hdMMT zop$4r>ylY?)0~Ipd!^e7v-PbD?&kGhn7iOXQ(n37Q$soNu=b4elXf~EX}@Xo`Fex* zv)_LgHP}4PY|#A7zD^93qU^iMZhnY5GxgB@`PnwVmrZ4jXaJ!yrVhZA7T`1}$ykQH|Jy8+Xou^$H9T_eE{)<0iwm0Sb%qb^b zKCdyh{eS(X<^GxHo*d0H;_f@G;lRih(7+_JfPodt{HK55P0CKbsoupWmmi;z&Y1S> zb>LaGyYlJtST$Vj;`P;8kIYPGd}Zs!)nWWTpK;%Nu?MGv@2egVkBrjV#ccA;du^EZ zE+&)jr)Rslnl~iWGrUms5WjFsf3;(z-GaUG^R}Pb#5niwr%iV?#4p^{UvJ%O#Q3nT z@_KF$yTP~9zc(0)9k`>P?WQc#ur=OphNuKX_5Pd)(M#+H>VBq#d&n~Ue#-XB{(zhd z`x}Rn1EyE%8+<$XZZy4UI4>akfprn{HbtuhaWB?_^p=L&6E)MAEE-=lycduy;JnDV zJ>Wm1o`Tf__9DmvOQ$mgT*&lp3gWZv_{%@1D}@f!Sfpm?**U~c8B%<2sg_;=yhR2xA*F42|FXto!uI%P;pJ;`Kw2pG*^VJ zZhp5ePrAt~^}y4oTh+Vy@5J4&mOOr+|IclH2|0Ir`}raQz_6du{qNx9B@Gsz-|R22 qdbD}^$|Jv%&tBGFi4=2CW<5iU)1MjFzoo~4QkSQzpUXO@geCwb+8Zzc literal 0 HcmV?d00001 diff --git a/icons/space-satellite-d.png b/icons/space-satellite-d.png new file mode 100644 index 0000000000000000000000000000000000000000..cba52d780c247dbfdd99898e01a15eb951cee863 GIT binary patch literal 1148 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H3?#oinD`S&v7|ftIx;Y9?C1WI$jZRL*c{*! z;tCWW1p^xbjBn!40A1i!666=`AOF6;e*gUa`}e=!ufKnPzWjW7d;WNP`Tq0s*XQ@w zufKm@f4+SG{r&pq<^B8LpYMM^A1E;YeE)fU{`dap-^=sc=db7I2g)-{@K*TBz`*3^ z>EaktaqI1^%HYcm3~e8k7R*_6Lb0n$Ty8~x!xmTFsV&DgN8~wXa!>Ql=L1h;D>_f;q>4>Q-*)?vg{+r7XM5CZZMyDf!~Zh z3xB??o_U^8;<;S@u|G_E&OB$Bk=hpDFddWxq2M3W0+v(pPa1QVD7yC|IU|ulIALZyO;i*zpj4Cf1gvb zffY+){{NgYr`joZ%KdtoNu|;2zJB<%SFw^`?bTWP`u|DtXRo*~U$@`zB>(d5c^m$& zb{4I$*PHy85}Sb4q9e07B1Yf&c&j literal 0 HcmV?d00001 diff --git a/icons/space-shield-outline.svg b/icons/space-shield-outline.svg new file mode 100644 index 00000000..e36d3c8c --- /dev/null +++ b/icons/space-shield-outline.svg @@ -0,0 +1 @@ + diff --git a/icons/space-ship-a.png b/icons/space-ship-a.png new file mode 100644 index 0000000000000000000000000000000000000000..8423a7c5ffcfbb5fe40db9c40d431a93492ca56b GIT binary patch literal 855 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H3?#oinD`S&v7|ftIx;Y9?C1WI$O`0N4e$wZ z1=7P0@TCR`0(~V}666;gKYxBa5P-<}KnMXq7DKJyri}~?OdOsrjv*Dd-rlGVzU3ft z>|w>qC{{*AnVhTJx)$Yb-IkRf=kR*o`~MSp7R;FZLeJZ8(#tcy|D8VbZ=R%r3d`I{ z;M}9qfQpxSg_^9@??zS*P zhKuIkKW^<}II-`i-nCQm6JE@YFIu~Y@#Me1XXSUg?P~~`|MPMDPPcgt;=j&p4=?Kd z!=V37`JnyI-aQQKzij4YYPBo=AC;%f->~$&&5kLnUofxv>+vCa-6GzCFEjn?Pwl

wtTzXw6-}TdzQW1!mabg_Pqc4thBz*8K~mMyvzF( z6|?XEt@;*iR5Zum_-k#R*U3V=vzNZ_(p5kH)5Q7y`-3eq&nMU4|9r6rNSELL{%{JA s&cFZr;~b6KuTTA-rp<#RwlrivFchf0a!h{au>_>V)78&qol`;+01NjWi2wiq literal 0 HcmV?d00001 diff --git a/icons/space-ship-b.png b/icons/space-ship-b.png new file mode 100644 index 0000000000000000000000000000000000000000..d53c81607d7c1216657f8cdff517d58a1e46326b GIT binary patch literal 1044 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H3?#oinD`S&v7|ftIx;Y9?C1WI$jZRL=n~)) z;tCWW1r&w=@16>Ipb=&zL4Lvc=g-dv0w8rh9|(ZF^B@Aq0*c9l#O4EK&gajU2SE^V zK3|@};nEUz1_mZePZ!6Kid%1QW(Hpl5IOd-iKB~Kp}R|Zk+PUde zAJ?f*HUGaqQ!_ugSG4w`-#N+jbN{*T+&^?ItD}o6{SaPF37H#aYleQ*yfC1BT*a*`5X?1N-_;egU0^tgWv$ zF*dOVtiIZIgW(|4huZ&k;tskC82;I+HAFG2Z+>UMc!jA#v}8KFfL;UdRTl08o{Z*^ z3=f$qR=;}0;KKdD`34KKLKMUM!|RL~7O{TNTQga1f%t*rD{L$s^c#+@c>RQ7FN2-y z-34q%xF2lR^XKUhKOlaWImuxULs-f7OvaN;KSa$vxeETVe3`^FiFJe2b$3n=@dH(t zR1_6r8IF7Mb22{t%+UXW;TY48Sz#*765I*KZ#5+kL@-2W_OE1k#$;itCB!&qKVzOC z;~CZsxmSFdH;5hB7deq7LASwnv$hIDHshOFvC9~4a6gzG+Q^Wg-|#-{ItRlyrXPt{ z=i4sGW0biiYQ%m;w?TQg`b_3mVh8+pPdvl8)at;@yCL7?4_(^N5G)e!vhBfvoH@^q zpAdQ@VOmg^%&)TSfl6-AyM)+1QNKQr4}|yiK>#Q;|Ghs0!=^n+ z3=B-go-U3d6}R5r$_&5kAad;EuJ_XKejiHX-r>0V%F>Wk3#Kx4E$TS>>#u#wbw8m? zDMrQb&-fPEJpXrJ{rvl9rCR-7>y#K6IUE?61R5Av6yVH%9};epqe zbu+!0&%d{?bgzKJpPCoGdwyU3$?SHneVW_uiN*?rc3;dcHqWkPn)KZHebC*Lyc6u? ztLDG^7GlS6_U8rm*zh8TjPvbwS=RPPc`wZ8uRZlbM_b`_O@{93VBwmEGoKgUeZyzW z$n)H})|p++f??Tb-G;jVE6fkn*lo#t_h5(ofg-yvH?IluH+-#m(Y^K54($VVc3(s< z8mcoqt9c>4%vt>f!oEU6bL>&kJ(9E@v?Os}V|ge@2DR!9xC* z>q{9X2P^qszON3cYBy}zw`untgZ(~A222Tm&u=Kpf39w&=deXiYFl~1Mh2nRtHR2& zr6<}u?3R-Vd%iuVl8NW_!o=FcGx!heS{L=^%eBqLYzo&ydt3ALmCYG4Z4I`}FDzf)`g literal 0 HcmV?d00001 diff --git a/icons/space-ship-d.png b/icons/space-ship-d.png new file mode 100644 index 0000000000000000000000000000000000000000..b5516a26039c29ed7861c25bef640ded6dda1fde GIT binary patch literal 1120 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H3?#oinD`S&v7|ftIx;Y9?C1WI$jZRLs2SiB z;tCWW1;m6vi2CH!Ky|7mL4LvaG~r7=~%`>!-%_L@!ATU=9TSl;(P zUvV$}*tRWF*4Me_IWsT`G%&CzFfejBz?uKb8(xcX7d%`Rt#W`hBF-*Y=D=&`-FNlG zSzmmAxNUopVS}UmyD#B-Oa^Zb?>(6InZ4&%LH&-Kdl(zsSon=#abC~;LUpk|}_lHXh(l4`n{QBUv zr|K3%q|jakAU|&x`Yac>Q8nyHEW`*ZL*g7v2=ty*A!ANzP&S`Jd<1YmS#NumQCS z-rr(%V8!{LUt?=7uVOfC_q;v+Lu?4M#CO|+a{Ict4lH`l`R!xqB*w7XbKChpgbFeG ztiGSKb=Jf1u)YhizW+F8RPDd{YQLgW#Kl+L`&xW9+MhYjIotZu*_D5JW_s06>K8P- z=V7+IN-?SPZ-JfH3puWG*S|q$KGfOBE0#?Cy=k_f^RGuWGdAp#y=}Sow&CQjPk#z5 z+$?#s@-8!{@VAdO6E583csuFe#Ga$SPyS?h=w`lwTdh4v?B(jG>MdJK>x0vd7m2-D z{k-;2Q2G|l%k09>zJL9ceCX2MgMPE@XKhT3x3^bXv#!!Q^>e{1&Z@MZhKXNW?mo6G s?)mI|=;fJzmcE&2DGHpp78D$?SI*A(b>gg-G$>biy85}Sb4q9e0EyUlMgRZ+ literal 0 HcmV?d00001 diff --git a/icons/space-ship-f.png b/icons/space-ship-f.png new file mode 100644 index 0000000000000000000000000000000000000000..155cf2c5969853dda5a96322f118572f9b09e8a9 GIT binary patch literal 1710 zcmeHH{Wp|(6u-~&cxEzYhB7kj#%w1x#0Vve=@GL@Od^xF+Hq3plveMf7T>gGgb+3) zCX15Fq&KZ%T5`fRqpgFqMNTrd@=~*;+GeLcXMfq#AFw~{J?GxfJ)ir_=iYPgO%E0= zWic!n0Ki)2?-!y+^wFmg`l#*CozjEBMxP)bfD741?_)>+tRgsYl~B+BZ~yTL%&!iQ z(@XT<86pZzsr{7kYx)18|7Q4newkVyzR~-)*(+-Ki8f;u za~@NR)=~{!8@1Rmz^e^NoRD-Gyn_4;__6R3g8ONRCt^;QO-nGE*|IDdfhkH zyPjl13-q1A#~3})+2KC6k=W*}-be0%6E#=@BRrn_^-I!$8;VPe!t1wQD%WYPPk7ry z30{1tpj{W(%7GsI_d|JRG)0gAIreAWRSh)lY^@*)@rA5;?xQP*3s~p{Y@^P7NNq2S zg??s^$#*NTy@NP!50YxLqGI1x;*f%*XVka16d0ltG}*@V8QSFr=m^pBx_Qm)rB5-r z8phq+WtqzfD8mMdl7w)i1E>11qp97}RvQfI^yRK?%01gb@etCxeL5K~n9=Fa)`V2A zv&g{^PPAOCJF-3+2N}~u?M36t*k}ncr)uoE1ApUe0`-95&2su8OEVDC{WHg_q@=~T zzPm4+;)ZJCfGa^Qeb1VDJxmSZC#J&9BVr&~ab5E)mIE(bluzoa3ev7wJ9;PVu*cyI zJE20dIE?$GksYmU8v~8I^4E$<-Xy!bSR^_~)2m-w*jiT7s1%GpOrk5i=fQ5P{=ogo z_0G*+JBJ(dqWwYRrVPoQl;&PLFao>N2&IUa^Ki1kch_T)69>lVx37%uNNZo<;MolN z`Msa;?2Adf72sq5W3-;?KUI6`5O z%X1~JB}r-n3cXjHP<1NdW?fM<1#;TlE`g5CGVL^HLN#{yin^&eyXoqyT|D5?xD`nw zv$O$~+ZRoP0fN~p7-jFh9C?QZumugZM{4rbF{$eYK*LI~uN4M7zSey9{PTzyNT7#* zRU=eIyc>+Z_eZuL);UX(KT+g)-!khg4|<5qUO`e?A7`cOipf7`MiBbu07# gIej}GIfpH!Pda4W;QB_FeEhM?gd)H5OC+g(0qPSRLI3~& literal 0 HcmV?d00001 diff --git a/icons/space-ship-g.png b/icons/space-ship-g.png new file mode 100644 index 0000000000000000000000000000000000000000..fef7cc1d9c0b693eb28005f6891007a1fe6275de GIT binary patch literal 1586 zcmeHH`&W{882`S!a+zFYX<`y7sX1FFO^+d7fN3c$9Wynn87#Zt@;37}F9_HXb(N;3 zp0s3|Wz7oLQd%mnlg*BqqPCOMGS&F4n|VohcEv0f$GD+f09s1$rZ3O{KsNl{5j)KN|M<@ZLe?zpGFNL; z!^8Fr==B42X0TVOjy<4HvZ@0lr&}cRJ)3wz+=$H4x$3VohNH;AR~qq8;%$oNsoFAT zW1L$Y&ylld4N9eBO1F4EeVZNeee0FBXwN^GEdOBj+h-%Y${(r(D=7Ug_T@2QTf^stp-fhQdwUxg)|Qo z_OzK(^@$+rMk6L%f=x|mw3bwd!>ZQS*3hpg0PZCm27*BpZ5k@5ScfbxFZTp>-^Uh; zjyl58YThdnSD@smuRvdk;mXo?R?^^z??fEPI?D2`5&0(jM1C$eZ&cH6;6;V z+?5Q;aQvsY>Kg9D_bj&%CcrRlC>=M7!o!(KttZU37xf8@M&8VR+vNfsMpt4CVV!-_ zYk_>*XnRDkkQ>}f;_ek50c{Jp{@MIN`jllep#mK6#1{YCJJ^gl#mE(#mEL@4{bY$% z6|s~OO+|X1r(mCvxRJsH1%~MuDOb2@84~rm*O!fv?YkxQoNh3FJ&H+A$DKzJVPnSa zpQOq_zKzJ90p_dJrz_EXTai6-W!alINdLgni&zbME=`dq(B1@{xWnO^E1?p_w;f>! zQL|MfXPT@XDS%AfBh<1C+%r@S#-JVPo^~^lxStD$Ij~Ndg6PQ_v^UWU`Vu=!;_g=* z0fOr62=?*J7LX>blx{-48HL&cOKnB#kk_X>T;k-8TeRL14{COT-?mOBXyA-V(1xL8 zWQKeaJ&G~hoV-}B3@lwcWrwh9d_C)^F$BpzMJ#xG+k4|ax#Nf0Z8}g*V$x(yoJSzw zhxCV;uXHHThl+uXy%%3d2I+;CsYDfUb)F_Wqq7J)r|eMdb(-uFrv%EGi_bSNv}&yo zHy+D^D-D1%C*yCfod10zc!0{q_<>`gSa+IC!Ks5BB+rFnIpU!`4(e3C%7eDYp=MME z#&FN`e%E7?RG@eyp$MytG}K*=8uI&lHu&|qvlwKnHVMHeC;CZGYw7%Rn>7Ypls*}MR|(>v!VQ`)R-VY8n(j*p1cT&+0&&^3Ry zi>hOUSiG()C{J9LqZ-X>AdMzkpP?}G{-S8`<4rm2eWI7L?VGFA8x+_nC`YwB72n)LLu~7C8xp^~W literal 0 HcmV?d00001 diff --git a/icons/space-ship-i.png b/icons/space-ship-i.png new file mode 100644 index 0000000000000000000000000000000000000000..3662211e576d28682f9167f6cd0896751d39ed75 GIT binary patch literal 1639 zcmeH`k55xq6vxkdEu}>YmKFrc>=O_{h^td-W^ip;abge^2+L4-1u7sSYG<%PuurpL ziOd!%3GdlvA740)g2o zz#Rp++U$s19o1&7Nnpj{q4HuN0PSw5Od6$n^nAePbH0>kBY!se7Bqw(P*-Ab*uVEu z-OgvVyhp)bqr>&;NBzwHj$U_d8eDZDu%@&4XT zp4VfKg=8Ww=lMowdBUjh9KlRTOq6+%lC)I!?>Le)l9vrjIJ;tE98zh;hsYJNuu%p$8*l|M1OeKe|7`A+x1i={f-qPzzM4z30lT^TlVN^#TArZ_;} zu$AnhbHt7Y*$UEvxcJj`Jj>9I&6jBv)Cqxw-?V{`Kp5#vu9Y?&IL-4%T}$8;57BTB zn)45(!ULA)C(5L1C*mm@bU5j@9kK6(MjPuF4Z=afY7B@3tRE7`XoFl?-tFrl8_9Nu zVt>9)ByC!?x8KiAUO_unvFDNkrqHl6OSVwWch062+6n8CbqchY<@qKd!jB`LL#hgx zSb)V%-#QHw^lSTHtknPgkaBA?pE~QkYM_jju>CJvQDFh)ZX$>8Bq@WPh;={vO8PMU zs1jVRAVj*0P!(oJj)|bF8Fjc1FMM2YAhFi|sIB1onvr7rLE6hu(Al%0R-9b3If!iQ z0m*hj>GQitQYE$QL89F-MCY<$_grITn2>B41c})8YOs({q=RLeFVZ)mRcUM}JCJ<+ z3tzIm7bH)1iDqP|iW?RPT?^mpKROOxM`^Rlb|iqu#QOQ*I=*LJvcFX!5vbTTNE+Fa6g$g8$oiTob83#B8j;u zYj`YWxKq-C(_Z@Lca*H=^c~kxh4x>Hhpc#`PWyJdfx^hgo@Q>&9e(+C>4WAc)2$j+ zpajpYZaq``2y|Bi%i}oIKZjawe#u zd|*B`hdF%qwZKqb8Z-J;@aYfddMD2wjBmDGjOPF1s)ipCS zg&f+oZ6>KTvoQoIOMHaIl&Fk^mSE#Xg_~)(F6}?DzwDj4_sl)N+%xyix#yTs411(I z5&!`E$Q==}76iX00%oc6uWA=90MDlFp#i|{YFl%L6#ziWnY-iZ7XJVE&o^MoOIfjq z2xG@a#kF&cVOnjwAetjJDp^E=K%k74N(mgJg94crS(J=G8(H z68gcHiJ8>Cm`s^&T^E>I5?h6A3c1TP{5KLp&doGT-tZp2xt_&ueO3mmg&=!N^Lw3o2 z)|&!sue?~cVtX~J>Vnt2AKQ6pudX<4-sX^pRZ0h>D)AU{G-z&(Y}~9NAvPwqxcGj& z>$?Oznxg-<-dG8d^xd4gy$rCutCVwWbdTEY+kFjlJ~*Lc!}mD8_Siv9Vy-uoG+mH= zowNh;-QI@EPI}+UjDDQ9PcU}*7wVLa8+Ch8dN+}p{X>!auRJj$D~&B0w9NMlh2t^- zvOK(s80X9iqfA=5yr~1h9|)(JGB*09L3CZ;UC*qW^%#1VQr}`+x<{=ucnm#P>{J$O zZ9a2H?OqX^^Jf?FX6{yKFwV9QbPFulwvj^&C zO0OMmaq%>MG?1I+<0>!BpxJJY!t)mf*6XYhL16~+I)*s+%}-s0!q@D|pUaM^tSwL$=({z$n1of+au>iy;Ve;VUydR(3i~V@q z+m_VaDg50(b+YoXVt0s`Z=;#tnxjM-d}d)|gGiXH_R!w#m3~)2FCHBWob9{O`?D;O zNC&laW*^sI=Z$5 zKj7W%?KU#P>}E3fQU>ty@~Y1v%Z0|;NIVpRSWdYN%TN|s*@H=VrbStU3W_kRi0??oeDMU0MFFnCu||w$>sd7c7KaK$IZSs zyHn9N;&MFGkZKh4q9xqyPj| zG{+ILv31FTTR4>fLEP;rnAi)cL!O>tDS1kC>D^!95Vr2}NS}=iP-NFJ?T0dzXgcL? zV=|Op!+bUNR9*A{YwKb~9U1Zcd2SJ>=eoT=7c92)*<^#SJ!$=R>~iJaXljbzca=9R z(9O1=`MN0>B-=`3(EXWLm{@6z)U1|-w+=apKcHF=v2*zLxIMHB&D>q&_yeP(20L5Q znYn^5d}QLcp@@Nk`iWn5@iBd#iwE(BZLBv#93DAv@bt?EC+n~*UY1}6y|-TDfWd~m z3s+#B0n1FazEK?BA#pm!L2Xpzz?Tx|c_kmHf;TUkva8>kXEUMH%{}h8uj_Pq5$dB7 zgYh`2bJGzx^-$@a_iAdtj(7rt(CrJXxpa0T6_?a z1%g|nZoIidLR(H&bHBMD91m<3z(VLb?xQrRN-v<|V#w7lsY>puPbuy$xj*vS1RIUS z4*pc*I>v5%AMFWOsoKs4EPo!aN%865Z_^k6YkB=F%z!EBS$B?Hh?drLg5nI^c$>b+ z(Q~L5`H2c~0T}360i&6Oqd`e7$PSwR=#z_gfZ^e)OK}EJQ?vPaI#j)&g$$pa$ZAbj zOO-K=h)!eJJ9zsnuX2**&$K;H|IUX4wHX%Uc9ZDR=*xv6MOw&a;KLLu`Q;Ez$zSzC Bq;3EJ literal 0 HcmV?d00001 diff --git a/icons/space-ship-l.png b/icons/space-ship-l.png new file mode 100644 index 0000000000000000000000000000000000000000..66026b3efdab3d71f89ea80d4f69d28d57f1cb9e GIT binary patch literal 1233 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H3?#oinD`S&v7|ftIx;Y9?C1WI$jZRLXd2)X z;tCWW1*C?+hHB6MKs{O|L4LvK&*$f#M}T}dI4_@n9th=u07%Y{XDD2#&CbBUEa>Ut z7*cWT?alPy+W`Wt4}IV7Ezi+eJ6R&g)1Twz-tQA8Z2SGc-sz6+TizSTr@fnd=FWHP zH^#*WJecS5$hbPNxIoZ>|9l>o4>YK7@~l|P#qIGlL`r1BiI-O$8BH?-JRGzxWh`N2 z>^$-2&8&uoDDDkrG7EM#oH=u5$w7v*tSNbU?_3NV)-qejab1XVSZ6kyi^Zd=A-R!Z zE$b7X&5IKm-m*TaS-n!B;Tu!Yx~mhx^tP)D1scvV6>Yp*!r+k3xbwn02M`^ZvHh<7 zg53_{8w}pcUWj$jE4O+9rb}-zLF z8$`#*Z@DP0u)E<*y44%b39$}&skdH&>9kvq*e66g z++(V#q3~fJb46NEfWw1Y_769fEND3Jo9{s{RJ%1)`+czXc80}Z?Qydp+HGLk6QSCV zgSA^Ebbt+64mRXC;~Iz^sZd3Cpmt1z+My4&qn|gz5A1|nQ0cu;X?Lg-{J~BrXPEEH z#Rc+%$Z9*01J3&nZ(#3Hj6Zi+{ecmq%_)Ax>Ff_K*75GtVd($mc;qQV#h3mhJ>~-^ z4uHEclnk$TS?U)_J~&!RB2zr#SP2kMU=Ba4`6P xDmpcpxnk4x;&~zmRR28RazROf35F~l==+}4J!Uh{a3&}ldb;|#taD0e0svRYj4c2F literal 0 HcmV?d00001 diff --git a/icons/space-ship-sides-a.png b/icons/space-ship-sides-a.png new file mode 100644 index 0000000000000000000000000000000000000000..201a6a47440cb0de432ae720f58349135760b746 GIT binary patch literal 2003 zcmeH|`8U*i7{@=~uNfIbhGxc+VJNyXj3rBMGL>zzj8K+~?`T70D1}Jh>XxNth%A$6 zp<;@ZGL`aGjnKVjj-_O2Cfp7!xJ8T59rw?;=f2N*KdZt+% z)Y+b{{tBWCR#8&aDS6&^1#nU8eAWR_$0yE4;sJo(`gsSsDf0jIpTB_fjP@hNlH4SJ z-vEh3BIC>W5`-^XkVIkrzmiB0gwK&Fa)cw}@eu@34D!omh+>$}XCg9=q=~~(q#6jv zh0`QM4wV~fOlZ_HU3iC@COGAWe2EOv0KJ?yVgT?Aw(GjUl)jJWqLTaV$;W#ho*Q@W zeE8MiRrdKvu^w4W*tfiHuzquFvT01d)8?Sgzf5T{f=}~ZdzR24s3HmN+WReoY>8zS zF)dlrcr~(clTtUZW2yTs0Q*S;Mq)5-Dh4maIZ!FF8>aVW7QmvLynKH^{DNE~V~6Lo zt8gr^Xfgd5u*8OjDper{dUO#pKt+xNMM9-X3*hDD<*AGEpx}^@RCisJ0VLpZ7maQD9oUBRqlJNJ zH#`}0>DLOlf{Mzt1{oC03=XqcLca}4eR~R2DAj}Ed83T&(a-p{aTM1);XEx#HM9=_ck5!owupQ8VB|*`pA02aN0})=XcIEvD zAW`X{V^yVssA0m5^0naIF2T-Q7GOnUIA{O3C{)`=MM|{1)KEf2Z;NW0hx;NgoHB*8 zx^~-Iu;5a$57z@~aRqII0tOLt`Tg#WL{svQLS^Zhbzz10J;1?_mDU4!JL^8>hJcLa zNjz#)h0$C)c%`%WIegQ-nhou%hLdi-uh*rbUYLygVJ!XIpJgR9>Y`BQPh@^m%Iq z(dU1Du4%m{Ea>oUbK-7laUA2%4W-xk9xRJCjZ-lf3q<&hf$M)Ri45G{sz%G%7dt@e zZhtaF<<{a0tmP)E^1NW%n67~j#+6J#l6CupWj=Y9JZ69T=*LcBWRXpdTdKP?rWUpM zw@Rq5u|F$d^58X#6t5HcYno|!9jUno_2u(6&Ui?z?CfQ7Iw{(#YJdQX8r$?Mxpvb1 zWoh-Qz_g+C6#?6(REDqqkW+8+ysaEFzIuWQC04B66PrX?3EI zRM*(pm^Z&sGD6L87~#c!0P^$b3cPFc{G=4_?< z@B809S-P}6wBacso8@z7DV*Qn{9RLh@8&U{PJ)Hs_pF`L7hczef50^jLc^{S_j~;p zO>Wq=t-gr7jBEaAH(dE*+&evV-06sidI80I!gp9?5VQVAY!04rxXDs$CV~|l85Xjv zaHwpxSc6(jnL6w@y?-WPe(RagW>N|6zWp4>zK$|gC!x3%A75R(mc>05Q7itNVspUa jM!;6-%%MMbp?Y!`fhIrT*6Xgyg-678^L4FR&pq-FNMnxE literal 0 HcmV?d00001 diff --git a/icons/space-star-gate.svg b/icons/space-star-gate.svg new file mode 100644 index 00000000..1d5da63d --- /dev/null +++ b/icons/space-star-gate.svg @@ -0,0 +1 @@ + diff --git a/icons/space-star-large.png b/icons/space-star-large.png new file mode 100644 index 0000000000000000000000000000000000000000..e47184a9d1e51ee753d6de032e047e4e3ad2e53b GIT binary patch literal 641 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?I3?vN&YJLDImUKs7M+SzC{oH>NS%G}T0G|+7 zAdMg7Ui3H!RKZyitj!_BB znT@d$D-RT~wrLq`*|u`aguV6*t9`;6zs{bS{!S<}dk^!ED5ca#n?D|6%Q?XINBqH_ zY!1~()%nmSE_QE__p4QYM9TW#T3FM%Ba=Y#W2;uwZTV0 z$w5s(P(iqZV*;lO%L^78rV=JOMk~gChPe&y4HFyOQ1Iji*9K%fwZWwU2}dyBd-bHM zpKOMj|A6!(aKoNZ6oJabz=1y&3*bBr*y&M`2dL8&zP~ykL_63MV z)ESxC)EWOizA4G6aY33>BcO*xM52e~55uC%oE8^ev&d*zF|xDGb&zo>HELw2n(4sc zswQwiL3jo8Nk7#9hxI}l3s$gjNrW&}8r;1r?Z54}yK+EZ?}36WmM2>or8h9vv;AOO X`Kd1;>9~y&DB*az`njxgN@xNARITpT literal 0 HcmV?d00001 diff --git a/icons/space-star-medium.png b/icons/space-star-medium.png new file mode 100644 index 0000000000000000000000000000000000000000..ed5212f2d5ad580a9c1b82f0e525782523f274eb GIT binary patch literal 707 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?I3?vN&YJLDImUKs7M+SzC{oH>NS%G|m0G|+7 zAWag8vX|ioYTzpg@(bqAmye(SzW@IGc>DVO3=NKT4h#%TDxNNmAsP4H-Z<^c6e!a0 z@N&aKCTG?*t{zbdErSq;6%7%LB@1{Zqz%d*INjqH{=PwR-`yE9o^Ep*EC1XnF0(4H z-xu>>zV+b~i;F!ur#Nu_5noXLfTiuYU&5slrpw!eSJ+rKP7YVU@T-97`Fy(t%c~wR zwXHg?m$2wo31jfpZQLtX*zIf(z8WrmA?R-b`;_traf}8$Vm?EB>4*#Ew! z^S9v1k5|s0IP$H+&Ex2icNJ-;e!5iIJWo2Mw&_^0{&SOwws8duO1AS)asAL~a+}TS zVSAQ2rw-5ZPdc0>I_A^zcyxTqmqqfF~JGL)WSXwXVyaNsp&Na&Gd zFgV1+@FJOwfyaQkit*wC9*z~kY%C#~%uHER7#WjKH8cpOIylTXQb=%+e87G3*zV80 zX@AdhhRmPq@b)NY&-pnAUR>e)!aw)GgA<$&v>Jsp8ts{Dm|G$rhCP_dwG))|JYD@< J);T3K0RW*b1dIRx literal 0 HcmV?d00001 diff --git a/icons/space-star-swirl.svg b/icons/space-star-swirl.svg new file mode 100644 index 00000000..5f10374c --- /dev/null +++ b/icons/space-star-swirl.svg @@ -0,0 +1 @@ + diff --git a/icons/space-station-a.png b/icons/space-station-a.png new file mode 100644 index 0000000000000000000000000000000000000000..78c80924d444d42b6a332ca2307c19663f1f4909 GIT binary patch literal 2458 zcmeH|`BM`K7RPg-T)I(%oDQ8?NAV&N5W@~fgMfq;34%HTfoOT4fP}+AAqgFj%i#zf z9E#Gcg|jjWjV#KDI33WzjU4Ta#pOYB44|Sm&|nhGu{eLk{xq-Zy-(Hm)qCHn_scsM z5*)DH%+`!Tp)3#N`Gqc0_9ac|i*;`Jyk-$bF+RI}D3m*LbM2ue6bdaRBxtYyqW)L> zb%Foq1>#ygD;NFpPK5@C5gZUh2?E3sK7b(@Ax8)t<=~KrfCwQ>ph8px^AVK5aSR7h zM2_QfLXIN{2%&%ogE5G}!N72FN*b1mg%n6b4Ws zhB62_2J$&D%;69W3?l#zgF$gmf7wQ%ECmDoeD!Q*INnhKHWLsGt7a<9{8wlqeNnD(@msWp2tV!(ZQN&b=ll zSNT?L8ou32iXYwJIN|yTPkaNPndp98Vo;V(Srh2l4(@-S8_mAa_S~}?T%;tu>hBG| z=R-eD?X%SXbFG&vVwJc_TYGSeEw$_cAjC9d+vp$(Uc9t!}QD z{MZ_-*sb=t+{Ef(%tHwaMytFcqa8{ZTFda>ok@Bv+a*&n>@x8^ZE9F0+9&k(IyXxP zu9)6Fi^EO`^MD*S`0b4LDxS4UtuVd)1Owxu9ViC$Q$wWEu_y~$?0(=$G$ z{YvOsukAO}Yn0_mzUM*_$qpnhDjx;B(e$$WPNa3m?bO=PRgL>?!Bs^)sJ--<+94vN zs6cuswE1a19K^139X)+o?eHwdwx{7WG)MR*tT02h*Q#zhx9!5Zul<9^(2)D#nxnaS&5bw?2-{Xi|49+ zefz^%4JK-*!3Ld7qvJ-hC}T)$%hZOScy|SP$&ck~XlP?}wb=rYOpo0>BG}`&#?D7e z(%o~+UoF=GntP>Bm1fBe<})0RO@iU2Zy;*vEw4)RfCnp~1=A7QuV=KGLdE$s+bTL| zln;I*pmcx-$kj)y*zI}Dd~l{bk!lT%M7z5_G+OgSn>0e(s;BeB_Qi+w6^Ya?U>j4R zMRUv#>Z{xM!?|M>(4L(fTndY9vA;Yg+%6c{sWY z7~*8O^|X;t?*!KP!yKJE=}m+tDVuGK&(K!)RLc?P$BbhG$G zip8^51D}x1Z%z>9VT7-fn zGy3KaTU$QWeP>6)9pV#X7Z*pi5wJY_clX5lmbgN7r{{6b2S0C~PWDlEnooa`c?*5# zY>P^k4DB-CZB`3Zw?YP+)Zur?L;p@(?>4y0ZgnW=Ej6GA?$Vp5?tG=d8$W0CMn}|^ zEKoOg&eKE7ri^R0^fP$j^*~9Z0AwA#pW*#9StmQv&ls4er|M);;MOM#)FBU{j`F+_ zs{4MPJ|48${ud9vP7&Mj-E~1)@j|9+7jh(R_WfdO&F0`@j})D^4R)n+EhYd%u))Xu rj709pJiTvQq{6acNj&vWG_t2T4$cDS?1UER%Qp@55B96yaWLzDtty^; literal 0 HcmV?d00001 diff --git a/icons/space-station-b.png b/icons/space-station-b.png new file mode 100644 index 0000000000000000000000000000000000000000..7293f4127b338e06e7fa1e7e12d25b87aba1eb08 GIT binary patch literal 2215 zcmeHI|2ve47JnILNOq{)8e}Z0Tha(!-+M=Brrmr^VpqLV*uD))V=-pNjEi;Ur7fgg zV-;QBddn8G$UAn0O`7gTB#cbAVFxp_(=s&Xz0>pD|Ki^BJm-AQInVi==bZD)`6fJ+ zX1>mP9RL94hv-3(dgOjo6P(_@pDtU`gHduoNB{ubht0GnjRC;m&+x-h!TS9F<$vu0 zmcn5({mzN$k)cNv6tMtA6rchHB`6t2#9;^-hQ$g6Dj`xN5)K80QaB0)1ropt7@{Bo z2t`u_U>Jgm6%vU;Uxy;FfJjCqVi;CP#0ZE=^es|QP^_R31rU*<5CiQ${W=B!#`A}Q z0;0YiU$~k4r47x3>-ngE?vdA{_c<(hh@S`IyB-P?T zxllriZSVA%V=^+*JH!46SXNa}W{HVw>qpP8&S(;b!l!ouz4r z-{hIyP)7A<_Aemf+oUr5xVrF!ZF8>9ua-ne=2p_urSa=s)rCyk9Ne&9Etxh7c*6EG zvm|?&-X1f|E=a3ao?<|NuD|lUrat*L%BD=o3k-tR|Zgl z@qW;%C*7Q-o!Z~%bIjuL{>AryI+#~!rn5@dv(0xZ*J#!cly8JRe=jtY0{pRW+cPd- zkg(jU(Lj?rF`X2Yo7RHA z;d#e-Nc*#9Y__fGEz66M>RT@oZs(_q3yZ<1-HXD&Ck0YG(P`5bnY-5*QI#AP_LRP& zXO|TlO7nWYGgDWT=gaE!L}mDAxoZ`qr}=75Rpqrm^rM~1>}qpKg7J>S=6^Y=709CN zSgv~VA7bH8%F$$P zqSUY$3O9AtfqlkXP(W+?o7P{7U5K0B27}cV922;8G_eo;mr!&92BQ;i=V^yKXH;0n zuR@WT9Vb1Y)navn-$px3e7w)NdPx(wqc^%#MSj^^A(BGu38Bc*n5nzF4yW2XV4^eB zr=Dq^NXm1OrKbnBvSlMM1nkR`P8C0Kp_HiGoY?P+pbx_g!;t54vQ z*){P5sy5_#5DGTPIdIfTvyiFSS5<}UZuL=_E9ts)!2l_`Zc!*LRK}xu8ZNo z?^r{!XuA!IseAVUg(;rE3|^j3#fXEV3$w~Ze0bbH8Dn1@-$)WAZe>3Q=A8}Y`9qF5 zqyYjWcZD37nJ7d|?%J%<{+3A1fCwt$9d6e}Iut>lytlV?A1?cs5jR}{t>!5+28xK8 zEQPO~<|?|Hu4Cib@kzc9kiR})%w92adyaHnDpW5oWZ4Zk7d#$musK08RR*fRVdH|K zvRX!E$gLF@d}Fu6(Mi`%;!uj4*D(1Zp_F$r;Ir1sF`Qb`w#8J7}UeZ?-+ z&P-RAE~7dq;X5|D#hz|1rOediQs^5dmoanZO#A!~=cm1%=d;#lz1I8lShW}&#OyK`B zf$pP(R86Nd$NYT*Fo^`?lQAk?!spWwCK(nZTp_}Z6Y|9p6k(DuJ|AYHLYN;XL{Kpm zMNmFQ#)Ozyf=S}UFkeVwQuzo8Wnx?^%I7n&IE_GpiNzR~k7}MU<472$DR9YD6h$#A zOr|4bVH{n8!eWd{Vq$!%m;}B~a)bcP6M4D0FiyT3yE4r*@>tp|k@qKIb<^grHNLRP zGO+1J!NF87>JrN=(+I|!NFxJ_-PT`E2}Bv)Z_K9_+lFmv55DJ$`Xxpo zSIHt?1ZM;8ad(L!FP>w8d)!m9khW0n1^LbA=;Dmr`84qCW%X*F#g|8ly<<8eZ*DB7 zSVU|oP8r`7Ke%mU($w8xWZNFaDF$lw^ldhXmM1;j6rLs{IY&;?VJfpy(KD5rdVUj! zW4jfrnRr!^(tRG>l|Qm+Q09}~Rz@E*5)2ho#tWb9>8f4@oK!q%c6?9eShjYMdak)| z$XXEyvC726L1rBrA+mN%Kk7_PahNmp233kh5dD1>k0m%UaTHh^%BarQy$*zA;dh(qsGM9JE=~G}B02@=duBs;GJNlycRV zgoMHCz7cUbcgHR&tnkDa2h7!0#QNUbz)q4&%$%Zz2tkfqOOcr7P4qjLgUX<}|LB9j zb4{m7$F+geRy=2|%c<|CiLEoty-qa&_|cH-b6(m6o;-fI}G z1ULMAIKyD(DnvQ1;hrCvZ#QgKl zDy6!=6wEke{>upxN!f{bIM(IU7df(YF&Mj6-AWY}KWPfAtW<4i?V|C*JpHj zb+rgC5|n|5pA>Uiaot%|cI~~R`^ke~K#O43h?`eoGw_+x+%#XiaQAxAoEghrTq`oG zr`^rnELyEmJj2yQe-rikt=hRm|FCZZ2-aT_8{2MHoJVS~q}_=Jb}712wcd(ui`Ez2 zYtFc`!KTx7XV^~5&NdxTcBh)3Jud^C{r0qF+2VNEWRtnHt<=}2Mdd(gwD4)MTNakf zkRgKST3MlaYa1_RJUnqgsehPfq7Ob_|F_<~zV;7Z=yUg|IuI1~eo0PPL$iSL<>9s} zwMVQ^P5kYrf;WoeznyDye|cmB3^%=RY|Yw9Eb@UvFGX&(SA_>(fAU(IsnHY)EZ6ua6#noyaN$to?KV=QDs6p( zwRcgh9~EU-zjltBk{w2Alv3eJW1GG`1ueM}sWAk}^fN-rW9Ti<*i+@VLb?X*2OMX$ z(pax>v;J!Xg>NrUf9Kp-atGZTW*z|>N>%Wmsc((f^_*B|qN{81;p0)xl}{5ZRGz#k zHKhL{WnbguUw6xJ1mvLDimq_|?j3dvcdTKS9d`UTaPs4=f?vqb`}}I7 zZV1QqO0Sk_$sIVHFi?c^7N_!FA%qTRTp3xXFdiQQ z8?Ntxno`!V&J#;jL8AADxpNJ?Efm4@4P3leu7IpxxFgL{by748y_wW%t}(2DprBiS zyh3#Ba5xhYJ&-aPdX@S;|I(LjjzfCN&k3$bp?K9u#A$D&5HUsede^y%jajP4k!9Vs zqscf^q$j)1^)F-TIIZ2&naNs6`aMVUufsU4^=G;`?!>5L723K>`KE2en#Tnq_O;`* TyqhCG_qdn4uiJfBR@#37tlzM) literal 0 HcmV?d00001 diff --git a/icons/space-station.svg b/icons/space-station.svg new file mode 100644 index 00000000..dea47edd --- /dev/null +++ b/icons/space-station.svg @@ -0,0 +1 @@ + diff --git a/icons/space-stone-sphere.svg b/icons/space-stone-sphere.svg new file mode 100644 index 00000000..96957a34 --- /dev/null +++ b/icons/space-stone-sphere.svg @@ -0,0 +1 @@ + diff --git a/icons/space-sun-outline.svg b/icons/space-sun-outline.svg new file mode 100644 index 00000000..e2e0ecf2 --- /dev/null +++ b/icons/space-sun-outline.svg @@ -0,0 +1 @@ + diff --git a/icons/space-sun-rays.svg b/icons/space-sun-rays.svg new file mode 100644 index 00000000..a7010ed7 --- /dev/null +++ b/icons/space-sun-rays.svg @@ -0,0 +1 @@ + diff --git a/icons/space-sun.svg b/icons/space-sun.svg new file mode 100644 index 00000000..c210fa54 --- /dev/null +++ b/icons/space-sun.svg @@ -0,0 +1 @@ + diff --git a/icons/space-target-outline.svg b/icons/space-target-outline.svg new file mode 100644 index 00000000..63f5ce9e --- /dev/null +++ b/icons/space-target-outline.svg @@ -0,0 +1 @@ + diff --git a/icons/space-twinkle.svg b/icons/space-twinkle.svg new file mode 100644 index 00000000..ea92f6d5 --- /dev/null +++ b/icons/space-twinkle.svg @@ -0,0 +1 @@ + diff --git a/icons/space-ufo.svg b/icons/space-ufo.svg new file mode 100644 index 00000000..73776e7f --- /dev/null +++ b/icons/space-ufo.svg @@ -0,0 +1 @@ + diff --git a/icons/space-vortex.svg b/icons/space-vortex.svg new file mode 100644 index 00000000..1099b87a --- /dev/null +++ b/icons/space-vortex.svg @@ -0,0 +1 @@ + diff --git a/icons/space-water-world.svg b/icons/space-water-world.svg new file mode 100644 index 00000000..b09b5d8b --- /dev/null +++ b/icons/space-water-world.svg @@ -0,0 +1 @@ + diff --git a/icons/space-world.svg b/icons/space-world.svg new file mode 100644 index 00000000..388c2cfd --- /dev/null +++ b/icons/space-world.svg @@ -0,0 +1 @@ + diff --git a/package.json b/package.json index 032ae80a..847d916b 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,8 @@ "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json versions.json", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/palettes.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/palettes.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerModal.ts b/src/HexmakerModal.ts index 89698a01..cff168b2 100644 --- a/src/HexmakerModal.ts +++ b/src/HexmakerModal.ts @@ -1,4 +1,8 @@ import { App, Modal } from "obsidian"; +import { ICON_PACK_LABELS, iconLabel, iconPack, type IconPack } from "./utils"; + +/** Last pack tab picked in any icon filter — remembered for the session. */ +let lastIconPack: IconPack | "all" = "all"; /** Base class for all Hexmaker modals. Provides shared behaviour. */ export class HexmakerModal extends Modal { @@ -6,6 +10,92 @@ export class HexmakerModal extends Modal { super(app); } + /** + * Put a search box + pack tabs (All / Terrain / Space / Custom) above an + * icon grid so large icon libraries stay navigable. Works on any grid + * whose tiles are `.duckmage-icon-option` elements carrying + * `data-icon=""`; tiles with an empty `data-icon` ("no icon", + * "clear all") are always shown. Tiles are filtered in place, so each + * grid keeps its own click/selection behaviour. + * + * `vaultIcons` is the set of icon names that come from the user's icons + * folder (plugin.vaultIconsSet). Returns a function that re-applies the + * filter — call it if the grid is re-rendered. + */ + protected addIconFilter(grid: HTMLElement, vaultIcons: Set): () => void { + const bar = createDiv({ cls: "duckmage-icon-filter-bar" }); + grid.before(bar); + const search = bar.createEl("input", { + type: "search", + cls: "duckmage-icon-filter-search", + attr: { placeholder: "Filter icons…", "aria-label": "Filter icons" }, + }); + const tabs = bar.createDiv({ cls: "duckmage-icon-filter-tabs" }); + const empty = createDiv({ cls: "duckmage-icon-filter-empty", text: "No icons match." }); + grid.after(empty); + + const tiles = (): HTMLElement[] => + Array.from(grid.querySelectorAll(".duckmage-icon-option[data-icon]")); + + let pack: IconPack | "all" = lastIconPack; + const apply = () => { + const query = search.value.trim().toLowerCase(); + let shown = 0; + for (const tile of tiles()) { + const icon = tile.dataset["icon"] ?? ""; + if (!icon) continue; + const match = + (pack === "all" || iconPack(icon, vaultIcons) === pack) && + (!query || iconLabel(icon).includes(query) || icon.toLowerCase().includes(query)); + tile.toggle(match); + if (match) shown++; + } + empty.toggle(shown === 0); + }; + + const renderTabs = () => { + tabs.empty(); + const counts = new Map(); + for (const tile of tiles()) { + const icon = tile.dataset["icon"]; + if (icon) counts.set(iconPack(icon, vaultIcons), (counts.get(iconPack(icon, vaultIcons)) ?? 0) + 1); + } + // One pack (or none) → tabs add nothing; search alone is enough. + if (counts.size < 2) { + pack = "all"; + return; + } + if (pack !== "all" && !counts.has(pack)) pack = "all"; + const total = [...counts.values()].reduce((a, b) => a + b, 0); + const entries: [IconPack | "all", string, number][] = [ + ["all", "All", total], + ...(Object.keys(ICON_PACK_LABELS) as IconPack[]) + .filter((p) => counts.has(p)) + .map((p): [IconPack, string, number] => [p, ICON_PACK_LABELS[p], counts.get(p) ?? 0]), + ]; + for (const [key, label, n] of entries) { + const tab = tabs.createEl("button", { + cls: `duckmage-icon-filter-tab${pack === key ? " is-active" : ""}`, + text: `${label} ${n}`, + }); + tab.addEventListener("click", () => { + pack = key; + lastIconPack = key; + renderTabs(); + apply(); + }); + } + }; + + search.addEventListener("input", apply); + renderTabs(); + apply(); + return () => { + renderTabs(); + apply(); + }; + } + /** Make this modal draggable by its title-bar area. Safe to call multiple times. */ protected makeDraggable(): void { const modalEl = this.modalEl; diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index d6f98c96..305c704f 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -21,6 +21,13 @@ import { VIEW_TYPE_SETUP_WIZARD, } from "./constants"; import { SetupWizardView } from "./SetupWizardView"; +import { PaletteStore } from "./palettes/PaletteStore"; +import { + getPreset, + mergePathTypes, + presetToPalette, + uniquePaletteName, +} from "./palettes/presets"; import { normalizeFolder, makeTableTemplate, slugify } from "./utils"; import { BUNDLED_ICONS } from "./bundledIcons"; import { parseWorkflow, buildWorkflowContent } from "./random-tables/workflow"; @@ -41,6 +48,7 @@ export default class HexmakerPlugin extends Plugin { settings: HexmakerPluginSettings; availableIcons: string[] = []; vaultIconsSet: Set = new Set(); + paletteStore = new PaletteStore(this); async onload() { await this.loadSettings(); @@ -48,6 +56,7 @@ export default class HexmakerPlugin extends Plugin { // returns null for all vault paths so custom icons are silently dropped. this.app.workspace.onLayoutReady(() => { this.loadAvailableIcons(); + void this.paletteStore.init(); void this.autoRegisterMapsFromVault(); if (!this.settings.setupComplete && !this.settings.setupDismissed) { this.openSetupWizard(); @@ -68,18 +77,25 @@ export default class HexmakerPlugin extends Plugin { this.registerEvent( this.app.vault.on("create", (f) => { if (isIconFile(f.path)) this.loadAvailableIcons(); + this.paletteStore.onModify(f); }), ); this.registerEvent( this.app.vault.on("delete", (f) => { if (isIconFile(f.path)) this.loadAvailableIcons(); + this.paletteStore.onDelete(f); }), ); this.registerEvent( this.app.vault.on("rename", (f, oldPath) => { if (isIconFile(f.path) || isIconFile(oldPath)) this.loadAvailableIcons(); + this.paletteStore.onRename(f, oldPath); }), ); + // Palette notes edited by hand (or by sync) flow back into the palettes. + this.registerEvent( + this.app.vault.on("modify", (f) => this.paletteStore.onModify(f)), + ); await this.migrateHexFilesToDefaultRegion(); @@ -438,6 +454,8 @@ export default class HexmakerPlugin extends Plugin { async saveSettings() { await this.saveData(this.settings); + // Mirror palette edits (from any editor) into the palette notes. + void this.paletteStore.sync(); // Settings hold map-level state (paths, palette, grid size, overlays). // A save made from one view/window leaves sibling map views stale — // flag them so they re-render on next activation (issue #32). The @@ -453,6 +471,8 @@ export default class HexmakerPlugin extends Plugin { // the synced state without a manual Obsidian restart. async onExternalSettingsChange(): Promise { await this.loadSettings(); + // data.json carries a cached copy of the palettes; the notes win. + await this.paletteStore.reload(); this.loadAvailableIcons(); this.refreshHexMap(); this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_TABLE).forEach((leaf) => { @@ -1149,6 +1169,8 @@ export default class HexmakerPlugin extends Plugin { if (this.settings.maps.some((r) => r.name === name)) return { error: `Map "${name}" already exists.` }; + await this.ensurePaletteInstalled(paletteName); + const hexFolder = normalizeFolder(this.settings.hexFolder); const folderPath = hexFolder ? `${hexFolder}/${name}` : name; if (!this.app.vault.getAbstractFileByPath(folderPath)) { @@ -1220,6 +1242,43 @@ export default class HexmakerPlugin extends Plugin { return this.settings.terrainPalettes.find((p) => p.name === name); } + /** + * Terrains for an installed palette, or for a built-in preset that isn't + * installed yet (lets new-map dropdowns preview presets before install). + */ + getPaletteOrPresetTerrains(name: string): TerrainColor[] { + return this.getPaletteByName(name)?.terrains ?? getPreset(name)?.terrains ?? []; + } + + /** + * Add a copy of a built-in preset as a new palette (a unique name is chosen + * if the preset's name is taken) and merge the preset's path types. Saves; + * the palette note is written by the sync that follows. Returns the new + * palette's name. + */ + async installPalettePreset(presetName: string, asName?: string): Promise { + const preset = getPreset(presetName); + if (!preset) return undefined; + const name = uniquePaletteName( + asName ?? preset.name, + this.settings.terrainPalettes.map((p) => p.name), + ); + this.settings.terrainPalettes.push(presetToPalette(preset, name)); + const added = mergePathTypes(this.settings.pathTypes, preset.pathTypes); + await this.saveSettings(); + new Notice( + `Hexmaker: added palette "${name}"` + + (added.length ? ` and path types ${added.join(", ")}.` : "."), + ); + return name; + } + + /** Install `name` from the presets if no palette by that name exists yet. */ + async ensurePaletteInstalled(name: string): Promise { + if (this.getPaletteByName(name) || !getPreset(name)) return; + await this.installPalettePreset(name); + } + getMapPalette(mapName: string): TerrainColor[] { const map = this.getMap(mapName); return ( diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index f5f7fa34..8e3e024d 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -1,6 +1,10 @@ import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import type HexmakerPlugin from "./HexmakerPlugin"; import { normalizeFolder } from "./utils"; +import { AddPaletteModal } from "./palettes/AddPaletteModal"; + +const PALETTES_FOLDER_DESC = + "Vault-relative folder for terrain palette notes (one note per palette — edit as text, copy between vaults to share). Defaults to a palettes folder inside the world folder."; // --------------------------------------------------------------------------- // Obsidian 1.13 declarative settings API — local structural types. @@ -100,6 +104,7 @@ const FOLDER_PATH_KEYS = new Set([ "regionsFolder", "tablesFolder", "workflowsFolder", + "palettesFolder", ]); /** Settings keys whose change should re-render open hex map views. */ @@ -200,6 +205,7 @@ export class HexmakerSettingTab extends PluginSettingTab { this.requestDeclarativeRerender(); })(); }); + this.addOpenNoteButton(setting.controlEl, pal.name); }, }; }); @@ -595,6 +601,12 @@ export class HexmakerSettingTab extends PluginSettingTab { "World/workflows", "Vault-relative folder for workflow notes. Browsable from the random tables view via the workflows tab.", ), + folderText( + "Palettes folder", + "palettesFolder", + "World/palettes", + PALETTES_FOLDER_DESC, + ), // Terrain palettes LAST, deliberately: on update() the declarative // renderer reuses unchanged rows but re-creates a changed list and // appends it at the END of the page — a mid-page list visibly "drops @@ -606,7 +618,7 @@ export class HexmakerSettingTab extends PluginSettingTab { items: [ { name: "", - desc: "Each region uses one palette. Assign a palette when creating a region — it cannot be changed after. Edit palette contents from the terrain tool on the hex map.", + desc: "Each region uses one palette. Assign a palette when creating a region — it cannot be changed after. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note.", searchable: false, }, ], @@ -637,16 +649,9 @@ export class HexmakerSettingTab extends PluginSettingTab { addItem: { name: "Add palette", action: () => { - palettes.push({ - name: "New palette", - terrains: - this.plugin.settings.terrainPalettes[0]?.terrains.map((t) => ({ - ...t, - })) ?? [], - }); - void this.plugin - .saveSettings() - .then(() => this.requestDeclarativeRerender()); + new AddPaletteModal(this.app, this.plugin, () => + this.requestDeclarativeRerender(), + ).open(); }, }, }, @@ -712,6 +717,19 @@ export class HexmakerSettingTab extends PluginSettingTab { * generated). Typed dynamically because the installed 1.12 typings predate * the method; declaring it on this class would shadow the real one. */ + /** "Open note" button for a palette row — opens the palette's note in a new tab. */ + private addOpenNoteButton(parent: HTMLElement, paletteName: string): void { + const btn = parent.createEl("button", { text: "Open note" }); + btn.addEventListener("click", () => { + const file = this.plugin.paletteStore.noteFor(paletteName); + if (!file) { + new Notice(`No note found for palette "${paletteName}" yet.`); + return; + } + void this.app.workspace.getLeaf("tab").openFile(file); + }); + } + private requestDeclarativeRerender(): void { const tab = this as unknown as { update?: () => void }; if (typeof tab.update !== "function") return; @@ -1321,12 +1339,25 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); + new Setting(containerEl) + .setName("Palettes folder") + .setDesc(PALETTES_FOLDER_DESC) + .addText((text) => + text + .setPlaceholder("World/palettes") + .setValue(this.plugin.settings.palettesFolder) + .onChange(async (value) => { + this.plugin.settings.palettesFolder = normalizeFolder(value ?? ""); + await this.plugin.saveSettings(); + }), + ); + // Terrain palettes last — mirrors getSettingDefinitions() ordering // (see comment there: the declarative renderer re-appends a changed // list at the page end, so the list lives at the end in both paths). new Setting(containerEl).setName("Terrain palettes").setHeading(); containerEl.createEl("p", { - text: "Each region uses one palette. Assign a palette when creating a region — it cannot be changed after. Edit palette contents from the terrain tool on the hex map.", + text: "Each region uses one palette. Assign a palette when creating a region — it cannot be changed after. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note.", cls: "setting-item-description", }); @@ -1384,6 +1415,8 @@ export class HexmakerSettingTab extends PluginSettingTab { text: `(${usedBy} region${usedBy !== 1 ? "s" : ""})`, }); + this.addOpenNoteButton(rowEl, pal.name); + const deleteBtn = rowEl.createEl("button", { text: "Delete" }); deleteBtn.disabled = usedBy > 0 || palettes.length <= 1; deleteBtn.title = @@ -1402,16 +1435,8 @@ export class HexmakerSettingTab extends PluginSettingTab { } new Setting(listEl).addButton((btn) => - btn.setButtonText("Add palette").onClick(async () => { - palettes.push({ - name: "New palette", - terrains: - this.plugin.settings.terrainPalettes[0]?.terrains.map((t) => ({ - ...t, - })) ?? [], - }); - await this.plugin.saveSettings(); - renderPaletteList(); + btn.setButtonText("Add palette").onClick(() => { + new AddPaletteModal(this.app, this.plugin, renderPaletteList).open(); }), ); }; diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index 3b80fc4d..b2080508 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -3,6 +3,7 @@ import type HexmakerPlugin from "./HexmakerPlugin"; import type { HexMapView } from "./hex-map/HexMapView"; import { normalizeFolder, slugify } from "./utils"; import { VIEW_TYPE_SETUP_WIZARD, VIEW_TYPE_HEX_MAP } from "./constants"; +import { fillPaletteSelect } from "./palettes/paletteOptions"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -321,10 +322,7 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { const paletteRow = container.createDiv({ cls: "duckmage-wizard-field" }); paletteRow.createEl("label", { text: "Terrain palette", cls: "duckmage-wizard-label" }); const paletteSelect = paletteRow.createEl("select", { cls: "duckmage-wizard-select" }); - for (const pal of plugin.settings.terrainPalettes) { - const opt = paletteSelect.createEl("option", { value: pal.name, text: pal.name }); - if (pal.name === ctx.paletteName) opt.selected = true; - } + fillPaletteSelect(plugin, paletteSelect, ctx.paletteName); paletteSelect.addEventListener("change", () => { ctx.paletteName = paletteSelect.value; }); @@ -357,6 +355,7 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { const folderPath = hexBase ? `${hexBase}/${name}` : name; await ensureFolder(plugin.app, folderPath); + await plugin.ensurePaletteInstalled(ctx.paletteName); if (!plugin.settings.maps.find(m => m.name === name)) { plugin.settings.maps.push({ name, diff --git a/src/bundledIcons.ts b/src/bundledIcons.ts index af586fa3..d8c36999 100644 --- a/src/bundledIcons.ts +++ b/src/bundledIcons.ts @@ -1,3 +1,4 @@ +import { BUNDLED_SPACE_ICONS } from "./bundledSpaceIcons"; import bwBadlands from "../icons/bw-badlands.png"; import bwBrokenlands from "../icons/bw-brokenlands.png"; import bwCactus from "../icons/bw-cactus.png"; @@ -74,4 +75,5 @@ export const BUNDLED_ICONS: Map = new Map([ ["bw-swamp.png", bwSwamp], ["bw-volcano.png", bwVolcano], ["bw-volcano-dormant.png", bwVolcanoDormant], + ...BUNDLED_SPACE_ICONS, ]); diff --git a/src/bundledSpaceIcons.ts b/src/bundledSpaceIcons.ts new file mode 100644 index 00000000..21a350cd --- /dev/null +++ b/src/bundledSpaceIcons.ts @@ -0,0 +1,144 @@ +// Generated by dev/build-space-icons.mjs — space icon pack (see icons/CREDITS.md). +import spaceAnomaly from "../icons/space-anomaly.svg"; +import spaceAsteroid from "../icons/space-asteroid.png"; +import spaceAtomOutline from "../icons/space-atom-outline.svg"; +import spaceBeaconOutline from "../icons/space-beacon-outline.svg"; +import spaceBlackHole from "../icons/space-black-hole.svg"; +import spaceComet from "../icons/space-comet.svg"; +import spaceDebris from "../icons/space-debris.svg"; +import spaceDefenseSatellite from "../icons/space-defense-satellite.svg"; +import spaceDotsHex from "../icons/space-dots-hex.svg"; +import spaceDoubleRing from "../icons/space-double-ring.svg"; +import spaceDustCloud from "../icons/space-dust-cloud.svg"; +import spaceEarth from "../icons/space-earth.svg"; +import spaceFrozenOrb from "../icons/space-frozen-orb.svg"; +import spaceGalaxy from "../icons/space-galaxy.svg"; +import spaceMeteorOutline from "../icons/space-meteor-outline.svg"; +import spaceMeteor from "../icons/space-meteor.svg"; +import spaceMoonOutline from "../icons/space-moon-outline.svg"; +import spaceMoon from "../icons/space-moon.svg"; +import spaceOrbitOutline from "../icons/space-orbit-outline.svg"; +import spaceOrbit from "../icons/space-orbit.svg"; +import spaceOrbital from "../icons/space-orbital.svg"; +import spacePlanetCore from "../icons/space-planet-core.svg"; +import spacePlanetOutline from "../icons/space-planet-outline.svg"; +import spacePlanet from "../icons/space-planet.svg"; +import spacePortal from "../icons/space-portal.svg"; +import spaceRadialBalance from "../icons/space-radial-balance.svg"; +import spaceRadioactive from "../icons/space-radioactive.svg"; +import spaceRaiderA from "../icons/space-raider-a.png"; +import spaceRaiderB from "../icons/space-raider-b.png"; +import spaceRaiderC from "../icons/space-raider-c.png"; +import spaceRaiderD from "../icons/space-raider-d.png"; +import spaceRingDashed from "../icons/space-ring-dashed.svg"; +import spaceRingSegments from "../icons/space-ring-segments.svg"; +import spaceRing from "../icons/space-ring.svg"; +import spaceRingedPlanet from "../icons/space-ringed-planet.svg"; +import spaceRocket from "../icons/space-rocket.svg"; +import spaceSatelliteA from "../icons/space-satellite-a.png"; +import spaceSatelliteB from "../icons/space-satellite-b.png"; +import spaceSatelliteC from "../icons/space-satellite-c.png"; +import spaceSatelliteD from "../icons/space-satellite-d.png"; +import spaceShieldOutline from "../icons/space-shield-outline.svg"; +import spaceShipA from "../icons/space-ship-a.png"; +import spaceShipB from "../icons/space-ship-b.png"; +import spaceShipC from "../icons/space-ship-c.png"; +import spaceShipD from "../icons/space-ship-d.png"; +import spaceShipF from "../icons/space-ship-f.png"; +import spaceShipG from "../icons/space-ship-g.png"; +import spaceShipI from "../icons/space-ship-i.png"; +import spaceShipJ from "../icons/space-ship-j.png"; +import spaceShipK from "../icons/space-ship-k.png"; +import spaceShipL from "../icons/space-ship-l.png"; +import spaceShipSidesA from "../icons/space-ship-sides-a.png"; +import spaceStarGate from "../icons/space-star-gate.svg"; +import spaceStarLarge from "../icons/space-star-large.png"; +import spaceStarMedium from "../icons/space-star-medium.png"; +import spaceStarSwirl from "../icons/space-star-swirl.svg"; +import spaceStationA from "../icons/space-station-a.png"; +import spaceStationB from "../icons/space-station-b.png"; +import spaceStationC from "../icons/space-station-c.png"; +import spaceStation from "../icons/space-station.svg"; +import spaceStoneSphere from "../icons/space-stone-sphere.svg"; +import spaceSunOutline from "../icons/space-sun-outline.svg"; +import spaceSunRays from "../icons/space-sun-rays.svg"; +import spaceSun from "../icons/space-sun.svg"; +import spaceTargetOutline from "../icons/space-target-outline.svg"; +import spaceTwinkle from "../icons/space-twinkle.svg"; +import spaceUfo from "../icons/space-ufo.svg"; +import spaceVortex from "../icons/space-vortex.svg"; +import spaceWaterWorld from "../icons/space-water-world.svg"; +import spaceWorld from "../icons/space-world.svg"; + +export const BUNDLED_SPACE_ICONS: [string, string][] = [ + ["space-anomaly.svg", spaceAnomaly], + ["space-asteroid.png", spaceAsteroid], + ["space-atom-outline.svg", spaceAtomOutline], + ["space-beacon-outline.svg", spaceBeaconOutline], + ["space-black-hole.svg", spaceBlackHole], + ["space-comet.svg", spaceComet], + ["space-debris.svg", spaceDebris], + ["space-defense-satellite.svg", spaceDefenseSatellite], + ["space-dots-hex.svg", spaceDotsHex], + ["space-double-ring.svg", spaceDoubleRing], + ["space-dust-cloud.svg", spaceDustCloud], + ["space-earth.svg", spaceEarth], + ["space-frozen-orb.svg", spaceFrozenOrb], + ["space-galaxy.svg", spaceGalaxy], + ["space-meteor-outline.svg", spaceMeteorOutline], + ["space-meteor.svg", spaceMeteor], + ["space-moon-outline.svg", spaceMoonOutline], + ["space-moon.svg", spaceMoon], + ["space-orbit-outline.svg", spaceOrbitOutline], + ["space-orbit.svg", spaceOrbit], + ["space-orbital.svg", spaceOrbital], + ["space-planet-core.svg", spacePlanetCore], + ["space-planet-outline.svg", spacePlanetOutline], + ["space-planet.svg", spacePlanet], + ["space-portal.svg", spacePortal], + ["space-radial-balance.svg", spaceRadialBalance], + ["space-radioactive.svg", spaceRadioactive], + ["space-raider-a.png", spaceRaiderA], + ["space-raider-b.png", spaceRaiderB], + ["space-raider-c.png", spaceRaiderC], + ["space-raider-d.png", spaceRaiderD], + ["space-ring-dashed.svg", spaceRingDashed], + ["space-ring-segments.svg", spaceRingSegments], + ["space-ring.svg", spaceRing], + ["space-ringed-planet.svg", spaceRingedPlanet], + ["space-rocket.svg", spaceRocket], + ["space-satellite-a.png", spaceSatelliteA], + ["space-satellite-b.png", spaceSatelliteB], + ["space-satellite-c.png", spaceSatelliteC], + ["space-satellite-d.png", spaceSatelliteD], + ["space-shield-outline.svg", spaceShieldOutline], + ["space-ship-a.png", spaceShipA], + ["space-ship-b.png", spaceShipB], + ["space-ship-c.png", spaceShipC], + ["space-ship-d.png", spaceShipD], + ["space-ship-f.png", spaceShipF], + ["space-ship-g.png", spaceShipG], + ["space-ship-i.png", spaceShipI], + ["space-ship-j.png", spaceShipJ], + ["space-ship-k.png", spaceShipK], + ["space-ship-l.png", spaceShipL], + ["space-ship-sides-a.png", spaceShipSidesA], + ["space-star-gate.svg", spaceStarGate], + ["space-star-large.png", spaceStarLarge], + ["space-star-medium.png", spaceStarMedium], + ["space-star-swirl.svg", spaceStarSwirl], + ["space-station-a.png", spaceStationA], + ["space-station-b.png", spaceStationB], + ["space-station-c.png", spaceStationC], + ["space-station.svg", spaceStation], + ["space-stone-sphere.svg", spaceStoneSphere], + ["space-sun-outline.svg", spaceSunOutline], + ["space-sun-rays.svg", spaceSunRays], + ["space-sun.svg", spaceSun], + ["space-target-outline.svg", spaceTargetOutline], + ["space-twinkle.svg", spaceTwinkle], + ["space-ufo.svg", spaceUfo], + ["space-vortex.svg", spaceVortex], + ["space-water-world.svg", spaceWaterWorld], + ["space-world.svg", spaceWorld], +]; diff --git a/src/constants.ts b/src/constants.ts index 7a0ae96e..1bcf0287 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -340,4 +340,6 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { iconOrder: [], setupComplete: false, setupDismissed: false, + palettesFolder: "", + palettesMigrated: false, }; diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index daee38aa..88823850 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -6,6 +6,7 @@ import { normalizeFolder, makeTableTemplate, createIconEl, + iconLabel, } from "../utils"; import { getTerrainFromFile, @@ -546,7 +547,7 @@ export class HexEditorModal extends HexmakerModal { const makeTile = (icon: string | null): HTMLElement => { const label = icon - ? icon.replace(/^bw-/, "").replace(/\.(png|jpg|jpeg|gif|svg|webp)$/i, "").replace(/-/g, " ") + ? iconLabel(icon) : "— clear all —"; const tile = grid.createDiv({ cls: "duckmage-icon-option" }); tile.dataset["icon"] = icon ?? ""; @@ -619,6 +620,7 @@ export class HexEditorModal extends HexmakerModal { makeTile(null); for (const icon of icons) makeTile(icon); + this.addIconFilter(grid, this.plugin.vaultIconsSet); } private renderIconGrid( @@ -633,7 +635,7 @@ export class HexEditorModal extends HexmakerModal { const makeTile = (icon: string | null) => { const label = icon - ? icon.replace(/^bw-/, "").replace(/\.(png|jpg|jpeg|gif|svg|webp)$/i, "").replace(/-/g, " ") + ? iconLabel(icon) : noneLabel; const tile = grid.createDiv({ cls: `duckmage-icon-option${selected === icon ? " is-selected" : ""}`, @@ -662,6 +664,7 @@ export class HexEditorModal extends HexmakerModal { makeTile(null); for (const icon of icons) makeTile(icon); + this.addIconFilter(grid, this.plugin.vaultIconsSet); } private getFilesForDropdown( diff --git a/src/hex-map/IconPickerModal.ts b/src/hex-map/IconPickerModal.ts index 34054df5..a533cdfa 100644 --- a/src/hex-map/IconPickerModal.ts +++ b/src/hex-map/IconPickerModal.ts @@ -1,7 +1,7 @@ import { App, TFile, setIcon } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; -import { getIconUrl, normalizeFolder } from "../utils"; +import { getIconUrl, iconLabel, normalizeFolder } from "../utils"; export class IconPickerModal extends HexmakerModal { private manageMode = false; @@ -88,11 +88,9 @@ export class IconPickerModal extends HexmakerModal { const icons = this.plugin.availableIcons.filter((i) => !hidden.has(i)); for (const icon of icons) { - const label = icon - .replace(/^bw-/, "") - .replace(/\.(png|jpg|jpeg|gif|svg|webp)$/i, "") - .replace(/-/g, " "); + const label = iconLabel(icon); const btn = grid.createDiv({ cls: "duckmage-icon-option" }); + btn.dataset["icon"] = icon; const preview = btn.createDiv({ cls: "duckmage-icon-preview" }); const img = preview.createEl("img", { cls: "duckmage-icon-preview-img" }); img.src = getIconUrl(this.plugin, icon); @@ -106,8 +104,12 @@ export class IconPickerModal extends HexmakerModal { } else { this.renderManageGrid(grid, hidden); } + this.reapplyIconFilter = this.addIconFilter(grid, this.plugin.vaultIconsSet); } + /** Re-applies the search/pack filter after the manage grid re-renders. */ + private reapplyIconFilter: () => void = () => {}; + private renderManageGrid(grid: HTMLElement, hidden: Set): void { grid.empty(); const icons = this.plugin.availableIcons; @@ -116,14 +118,12 @@ export class IconPickerModal extends HexmakerModal { for (let i = 0; i < icons.length; i++) { const icon = icons[i]; const isHidden = hidden.has(icon); - const label = icon - .replace(/^bw-/, "") - .replace(/\.(png|jpg|jpeg|gif|svg|webp)$/i, "") - .replace(/-/g, " "); + const label = iconLabel(icon); const btn = grid.createDiv({ cls: `duckmage-icon-option${isHidden ? " duckmage-icon-hidden" : ""}`, }); + btn.dataset["icon"] = icon; btn.draggable = true; // Grip handle @@ -149,6 +149,7 @@ export class IconPickerModal extends HexmakerModal { void this.plugin.saveSettings().then(() => { this.plugin.loadAvailableIcons(); this.renderManageGrid(grid, new Set(this.plugin.settings.hiddenIcons ?? [])); + this.reapplyIconFilter(); }); }); @@ -182,6 +183,7 @@ export class IconPickerModal extends HexmakerModal { void this.plugin.saveSettings().then(() => { this.plugin.loadAvailableIcons(); this.renderManageGrid(grid, new Set(this.plugin.settings.hiddenIcons ?? [])); + this.reapplyIconFilter(); }); }); } diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index c917518e..b4e55651 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -7,6 +7,7 @@ import { getSubmapFromFile, setSubmapInFile } from "../frontmatter"; import { exportMapAsPng } from "../export/mapPngRenderer"; import { exportMapAsPdf } from "../export/exporters/mapWithTable"; import { FileLinkSuggestModal } from "./FileLinkSuggestModal"; +import { fillPaletteSelect } from "../palettes/paletteOptions"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; @@ -548,9 +549,7 @@ export class MapModal extends HexmakerModal { el.createEl("label", { text: "Palette", cls: "duckmage-map-field-label" }); const paletteRow = el.createDiv({ cls: "duckmage-region-row" }); const paletteSelect = paletteRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); - for (const pal of this.plugin.settings.terrainPalettes) { - paletteSelect.createEl("option", { value: pal.name, text: pal.name }); - } + fillPaletteSelect(this.plugin, paletteSelect); // Stagger offset el.createEl("label", { text: "Stagger offset", cls: "duckmage-map-field-label" }); diff --git a/src/hex-map/SubmapPickerModal.ts b/src/hex-map/SubmapPickerModal.ts index 1d63048b..abacb159 100644 --- a/src/hex-map/SubmapPickerModal.ts +++ b/src/hex-map/SubmapPickerModal.ts @@ -2,6 +2,7 @@ import { App, Notice } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { getIconUrl, createIconEl } from "../utils"; +import { fillPaletteSelect } from "../palettes/paletteOptions"; export class SubmapPickerModal extends HexmakerModal { constructor( @@ -126,9 +127,7 @@ export class SubmapPickerModal extends HexmakerModal { const paletteRow = createBody.createDiv({ cls: "duckmage-submap-create-row" }); paletteRow.createSpan({ text: "Palette", cls: "duckmage-submap-create-label" }); const paletteSelect = paletteRow.createEl("select", { cls: "duckmage-submap-create-palette" }); - for (const pal of this.plugin.settings.terrainPalettes) { - paletteSelect.createEl("option", { value: pal.name, text: pal.name }); - } + fillPaletteSelect(this.plugin, paletteSelect); // Starting coordinates const originRow = createBody.createDiv({ cls: "duckmage-submap-create-row" }); @@ -160,7 +159,7 @@ export class SubmapPickerModal extends HexmakerModal { const renderTerrainGrid = () => { terrainGrid.empty(); selectedTerrainType = undefined; - const palette = this.plugin.getPaletteByName(paletteSelect.value)?.terrains ?? []; + const palette = this.plugin.getPaletteOrPresetTerrains(paletteSelect.value); const noneTile = terrainGrid.createDiv({ cls: "duckmage-terrain-option duckmage-terrain-option-clear is-selected", diff --git a/src/hex-map/TerrainEntryEditorModal.ts b/src/hex-map/TerrainEntryEditorModal.ts index 8d3d9553..f20c5d63 100644 --- a/src/hex-map/TerrainEntryEditorModal.ts +++ b/src/hex-map/TerrainEntryEditorModal.ts @@ -2,7 +2,7 @@ import { App, Notice, Setting, TFile } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { TerrainColor } from "../types"; -import { normalizeFolder } from "../utils"; +import { ICON_PACK_LABELS, iconLabel, iconPack, normalizeFolder, type IconPack } from "../utils"; export class TerrainEntryEditorModal extends HexmakerModal { // Pending values — only written to the entry on Save @@ -62,9 +62,17 @@ export class TerrainEntryEditorModal extends HexmakerModal { .setName("Icon") .addDropdown(dropdown => { dropdown.addOption("", "— no icon —"); + // Grouped by pack so a long icon list stays scannable. + const groups = new Map(); + for (const pack of Object.keys(ICON_PACK_LABELS) as IconPack[]) { + groups.set(pack, dropdown.selectEl.createEl("optgroup", { attr: { label: ICON_PACK_LABELS[pack] } })); + } for (const icon of this.plugin.availableIcons) { - const label = icon.replace(/^bw-/, "").replace(/\.png$/, "").replace(/-/g, " "); - dropdown.addOption(icon, label); + groups.get(iconPack(icon, this.plugin.vaultIconsSet)) + ?.createEl("option", { value: icon, text: iconLabel(icon) }); + } + for (const group of groups.values()) { + if (group.childElementCount === 0) group.remove(); } dropdown.setValue(this.pendingIcon ?? ""); dropdown.onChange(value => { this.pendingIcon = value || undefined; }); diff --git a/src/hex-map/TokenModal.ts b/src/hex-map/TokenModal.ts index 18531ab5..8ed8110b 100644 --- a/src/hex-map/TokenModal.ts +++ b/src/hex-map/TokenModal.ts @@ -2,7 +2,7 @@ import { App, Notice, Setting, TFile } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { TokenShape, TokenSize } from "../types"; -import { normalizeFolder, getIconUrl } from "../utils"; +import { normalizeFolder, getIconUrl, iconLabel } from "../utils"; export interface TokenModalResult { icon: string | undefined; @@ -136,7 +136,7 @@ export class TokenModal extends HexmakerModal { const makeIconTile = (icon: string | null) => { const label = icon - ? icon.replace(/^bw-/, "").replace(/\.(png|jpg|jpeg|gif|svg|webp)$/i, "").replace(/-/g, " ") + ? iconLabel(icon) : "no icon"; const tile = iconGrid.createDiv({ cls: `duckmage-icon-option${this.pendingIcon === icon ? " is-selected" : ""}`, @@ -161,6 +161,7 @@ export class TokenModal extends HexmakerModal { }; makeIconTile(null); for (const icon of visibleIcons) makeIconTile(icon); + this.addIconFilter(iconGrid, this.plugin.vaultIconsSet); // ── Shape ───────────────────────────────────────────────────────────── new Setting(contentEl) diff --git a/src/hex-map/help.md b/src/hex-map/help.md index a112bd41..c391b16f 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -25,7 +25,7 @@ Paint a connected chain of road or river hexes. Left-click hexes to extend the c Opens the terrain palette. Select a color/icon to enter paint mode, then left-click hexes to apply that terrain. Use **Pick** (⌖) to sample terrain from an existing hex. Use **Clear** to erase terrain from hexes. Right-click the terrain button to open the palette editor where you can reorder, rename, recolor, and add terrain types. ### Icon -Opens the icon palette. Select an icon to enter paint mode, then left-click hexes to apply a custom icon override (independent of the terrain icon). Useful for marking notable locations. +Opens the icon palette. Select an icon to enter paint mode, then left-click hexes to apply a custom icon override (independent of the terrain icon). Useful for marking notable locations. Every icon list (here, in the token editor, and in the hex editor) has a filter box and **All / Terrain / Space / Custom** tabs; drag the bottom edge of an inline icon list to make it taller. ### Link table Opens a folder-tree picker scoped to your Tables folder. Select a random-encounter table, then left-click hexes to link that table into each hex's **Encounters Table** section. diff --git a/src/hex-map/newMapFields.ts b/src/hex-map/newMapFields.ts index f4c1a2b1..81f9f525 100644 --- a/src/hex-map/newMapFields.ts +++ b/src/hex-map/newMapFields.ts @@ -1,4 +1,5 @@ import type HexmakerPlugin from "../HexmakerPlugin"; +import { fillPaletteSelect } from "../palettes/paletteOptions"; export interface NewMapFieldRefs { nameInput: HTMLInputElement; @@ -37,9 +38,7 @@ export function renderNewMapFields( rowsInput.setCssProps({ width: "55px" }); const paletteSelect = row.createEl("select"); - for (const pal of plugin.settings.terrainPalettes) { - paletteSelect.createEl("option", { value: pal.name, text: pal.name }); - } + fillPaletteSelect(plugin, paletteSelect); return { nameInput, colsInput, rowsInput, paletteSelect }; } diff --git a/src/md.d.ts b/src/md.d.ts index 672e485e..86983d48 100644 --- a/src/md.d.ts +++ b/src/md.d.ts @@ -7,3 +7,8 @@ declare module "*.png" { const dataUrl: string; export default dataUrl; } + +declare module "*.svg" { + const dataUrl: string; + export default dataUrl; +} diff --git a/src/palettes/AddPaletteModal.ts b/src/palettes/AddPaletteModal.ts new file mode 100644 index 00000000..2da2db9f --- /dev/null +++ b/src/palettes/AddPaletteModal.ts @@ -0,0 +1,98 @@ +import { App } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { PALETTE_PRESETS, uniquePaletteName } from "./presets"; + +/** + * "Add palette" chooser: install a built-in preset, copy an existing + * palette, or start empty. The palette note is written by the settings sync. + */ +export class AddPaletteModal extends HexmakerModal { + constructor( + app: App, + private plugin: HexmakerPlugin, + private onAdded: () => void, + ) { + super(app); + } + + onOpen(): void { + this.titleEl.setText("Add palette"); + this.makeDraggable(); + const { contentEl } = this; + contentEl.addClass("duckmage-add-palette-modal"); + + contentEl.createEl("h4", { text: "Presets" }); + const presetList = contentEl.createDiv({ cls: "duckmage-add-palette-list" }); + for (const preset of PALETTE_PRESETS) { + const installed = this.plugin.getPaletteByName(preset.name) !== undefined; + this.option( + presetList, + installed ? `${preset.name} (another copy)` : preset.name, + `${preset.terrains.length} terrains · ${preset.description}`, + preset.terrains.map((t) => t.color), + async () => { + await this.plugin.installPalettePreset(preset.name); + }, + ); + } + + const palettes = this.plugin.settings.terrainPalettes; + if (palettes.length > 0) { + contentEl.createEl("h4", { text: "Copy an existing palette" }); + const copyList = contentEl.createDiv({ cls: "duckmage-add-palette-list" }); + for (const pal of palettes) { + this.option( + copyList, + `Copy of ${pal.name}`, + `${pal.terrains.length} terrains`, + pal.terrains.map((t) => t.color), + async () => { + palettes.push({ + name: uniquePaletteName(`${pal.name} copy`, palettes.map((p) => p.name)), + terrains: pal.terrains.map((t) => ({ ...t })), + }); + await this.plugin.saveSettings(); + }, + ); + } + } + + contentEl.createEl("h4", { text: "Start from scratch" }); + const emptyList = contentEl.createDiv({ cls: "duckmage-add-palette-list" }); + this.option(emptyList, "Empty palette", "No terrains — add them from the terrain tool or the palette note.", [], async () => { + palettes.push({ name: uniquePaletteName("New palette", palettes.map((p) => p.name)), terrains: [] }); + await this.plugin.saveSettings(); + }); + } + + private option( + parent: HTMLElement, + title: string, + desc: string, + swatches: string[], + action: () => Promise, + ): void { + const btn = parent.createEl("button", { cls: "duckmage-add-palette-option" }); + const text = btn.createDiv({ cls: "duckmage-add-palette-text" }); + text.createDiv({ text: title, cls: "duckmage-add-palette-title" }); + text.createDiv({ text: desc, cls: "duckmage-add-palette-desc" }); + if (swatches.length > 0) { + const strip = btn.createDiv({ cls: "duckmage-add-palette-swatches" }); + for (const color of swatches.slice(0, 16)) { + strip.createSpan({ cls: "duckmage-add-palette-swatch" }).setCssProps({ "--duckmage-bg": color }); + } + } + btn.addEventListener("click", () => { + btn.disabled = true; + void action().then(() => { + this.close(); + this.onAdded(); + }); + }); + } + + onClose(): void { + this.contentEl.empty(); + } +} diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts new file mode 100644 index 00000000..2ecc6e4b --- /dev/null +++ b/src/palettes/PaletteStore.ts @@ -0,0 +1,394 @@ +import { Notice, TAbstractFile, TFile, TFolder } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { TerrainPalette } from "../types"; +import { normalizeFolder } from "../utils"; +import { + buildPaletteNote, + paletteFileName, + parsePaletteNote, + terrainsEqual, + updatePaletteNote, +} from "./paletteNote"; +import { uniquePaletteName } from "./presets"; + +/** + * Keeps `settings.terrainPalettes` and the palette notes in sync. + * + * Notes are the source of truth once migrated; `settings.terrainPalettes` + * stays as the in-memory working copy (every reader is synchronous) and as a + * cache in data.json so older plugin versions still load. + * + * - memory → notes: `sync()` runs after every saveSettings(). It renames + * notes whose palette was renamed, creates notes for new palettes, + * rewrites the table of changed ones, and trashes notes whose palette was + * deleted. Callers that edit palettes need no palette-specific code. + * - notes → memory: vault events on the palettes folder re-parse the note + * and update the palette in place (terrains array identity preserved). + * + * Our own writes are recognised by comparing against `lastContent`, so a + * sync never loops back through the vault event handlers. + */ +export class PaletteStore { + /** Note path each palette object was last bound to (rename detection). */ + private boundPath = new WeakMap(); + /** Paths of every palette note we have bound, for delete detection. */ + private knownPaths = new Set(); + /** Content we last wrote or read per path. */ + private lastContent = new Map(); + private ready = false; + private attachedFolder = ""; + private reattachTimer: number | undefined; + private queue: Promise = Promise.resolve(); + + constructor(private plugin: HexmakerPlugin) {} + + folder(): string { + const configured = normalizeFolder(this.plugin.settings.palettesFolder ?? ""); + if (configured) return configured; + const world = normalizeFolder(this.plugin.settings.worldFolder ?? ""); + return world ? `${world}/palettes` : "palettes"; + } + + private pathFor(name: string): string { + return `${this.folder()}/${paletteFileName(name)}.md`; + } + + /** Where a palette's note should live: beside its current note, else top level. */ + private targetPath(name: string, prev: string | undefined): string { + if (!prev) return this.pathFor(name); + const dir = prev.slice(0, prev.lastIndexOf("/")); + return `${dir}/${paletteFileName(name)}.md`; + } + + private inFolder(path: string): boolean { + return path.startsWith(this.folder() + "/") && path.endsWith(".md"); + } + + private isPaletteFile(f: TAbstractFile): f is TFile { + return f instanceof TFile && f.extension === "md" && !f.basename.startsWith("_") && this.inFolder(f.path); + } + + private paletteFiles(): TFile[] { + const root = this.plugin.app.vault.getAbstractFileByPath(this.folder()); + if (!(root instanceof TFolder)) return []; + const out: TFile[] = []; + const walk = (folder: TFolder) => { + for (const child of folder.children) { + if (child instanceof TFolder) walk(child); + else if (this.isPaletteFile(child)) out.push(child); + } + }; + walk(root); + return out.sort((a, b) => a.path.localeCompare(b.path)); + } + + private enqueue(task: () => Promise): Promise { + this.queue = this.queue.then(task).catch((e) => { + console.error("Hexmaker: palette sync failed", e); + }); + return this.queue; + } + + private bind(pal: TerrainPalette, path: string, content: string): void { + this.boundPath.set(pal, path); + this.knownPaths.add(path); + this.lastContent.set(path, content); + } + + private async ensureFolder(): Promise { + const folder = this.folder(); + if (this.plugin.app.vault.getAbstractFileByPath(folder)) return; + try { + await this.plugin.app.vault.createFolder(folder); + } catch { + /* created concurrently */ + } + } + + /** Rename a palette in memory and repoint every map that uses it. */ + private renamePalette(pal: TerrainPalette, newName: string): void { + for (const m of this.plugin.settings.maps) { + if (m.paletteName === pal.name) m.paletteName = newName; + } + pal.name = newName; + } + + /** + * Call once the vault is indexed (onLayoutReady). Converts legacy + * settings-only palettes to notes the first time, then loads every note. + */ + init(): Promise { + return this.enqueue(() => this.attach()); + } + + /** Bind to the current folder: migrate if needed, then load from notes. */ + private async attach(): Promise { + this.boundPath = new WeakMap(); + this.knownPaths.clear(); + this.lastContent.clear(); + this.attachedFolder = this.folder(); + await this.ensureFolder(); + const settings = this.plugin.settings; + let dirty = false; + + // Migration (and safety net): when the folder holds no palette notes — + // first run after upgrading, or the folder setting was pointed somewhere + // new — write every in-memory palette, built-in or user-made, as a note. + const existing: TFile[] = []; + for (const f of this.paletteFiles()) { + if (parsePaletteNote(await this.plugin.app.vault.cachedRead(f))) existing.push(f); + } + if (!settings.palettesMigrated || existing.length === 0) { + const paletteNames = new Set(existing.map((f) => f.basename.toLowerCase())); + for (const pal of settings.terrainPalettes) { + const safe = paletteFileName(pal.name); + if (paletteNames.has(safe.toLowerCase())) { + // A palette note of that name already exists (e.g. synced from a + // device that migrated first) — the note wins on load below. + if (safe !== pal.name) this.renamePalette(pal, safe); + continue; + } + let name = safe; + if (this.plugin.app.vault.getAbstractFileByPath(this.pathFor(name))) { + // Some unrelated note already has this name. + const folder = this.plugin.app.vault.getAbstractFileByPath(this.folder()); + const siblings = folder instanceof TFolder + ? folder.children.map((c) => c.name.replace(/.md$/, "")) + : []; + name = uniquePaletteName(safe, siblings); + } + if (name !== pal.name) this.renamePalette(pal, name); + const content = buildPaletteNote(pal.terrains); + const path = this.pathFor(pal.name); + this.bind(pal, path, content); + await this.plugin.app.vault.create(path, content); + paletteNames.add(name.toLowerCase()); + } + if (!settings.palettesMigrated) { + settings.palettesMigrated = true; + new Notice(`Hexmaker: terrain palettes are now notes in "${this.folder()}".`); + } + dirty = true; + } + + if (await this.loadAll()) dirty = true; + this.ready = true; + if (dirty) await this.persist(); + } + + /** + * Replace the in-memory palette list with the notes on disk, reusing the + * existing palette objects (matched by name) so open views and modals keep + * valid references. Returns true when anything changed. + */ + private async loadAll(): Promise { + const settings = this.plugin.settings; + const byName = new Map(settings.terrainPalettes.map((p) => [p.name.toLowerCase(), p])); + const next: TerrainPalette[] = []; + let changed = false; + for (const file of this.paletteFiles()) { + const content = await this.plugin.app.vault.cachedRead(file); + const terrains = parsePaletteNote(content); + if (!terrains) continue; + let pal = byName.get(file.basename.toLowerCase()); + if (pal && next.includes(pal)) pal = undefined; // same basename in two subfolders + if (pal) { + if (pal.name !== file.basename) { + this.renamePalette(pal, file.basename); + changed = true; + } + if (!terrainsEqual(pal.terrains, terrains)) { + pal.terrains.splice(0, pal.terrains.length, ...terrains); + changed = true; + } + } else { + pal = { name: file.basename, terrains }; + changed = true; + } + this.bind(pal, file.path, content); + next.push(pal); + } + if (next.length === 0) return changed; // never empty the list; the cache stays usable + // Keep the existing palette order (the first palette is the fallback for + // maps and the default for new ones); notes new to us go after, by path. + const rank = new Map(settings.terrainPalettes.map((p, i) => [p, i])); + next.sort((a, b) => (rank.get(a) ?? Infinity) - (rank.get(b) ?? Infinity)); + if (next.length !== settings.terrainPalettes.length || next.some((p, i) => p !== settings.terrainPalettes[i])) { + changed = true; + } + settings.terrainPalettes = next; + return changed; + } + + /** Reload after data.json was replaced from outside (Obsidian Sync). */ + reload(): Promise { + if (!this.ready) return this.queue; + return this.enqueue(async () => { + if (await this.loadAll()) await this.persist(); + }); + } + + private async persist(): Promise { + await this.plugin.saveData(this.plugin.settings); + this.plugin.refreshHexMap(); + } + + /** memory → notes. Safe to call often; only touches notes that differ. */ + sync(): Promise { + if (!this.ready) return this.queue; + return this.enqueue(async () => { + if (this.folder() !== this.attachedFolder) { + // Folder setting changed: start over against the new folder once the + // user stops typing (settings save per keystroke — attaching at once + // would seed "w", "wo", "wor"… with palette notes). Notes in the old + // folder are left alone. + window.clearTimeout(this.reattachTimer); + this.reattachTimer = window.setTimeout(() => { + void this.enqueue(async () => { + if (this.folder() !== this.attachedFolder) await this.attach(); + }); + }, 1500); + return; + } + const { vault, fileManager } = this.plugin.app; + await this.ensureFolder(); + const claimed = new Set(); + let renamedInMemory = false; + + for (const pal of this.plugin.settings.terrainPalettes) { + // Two palettes can't share a file — the later one gets a suffix. + const prev = this.boundPath.get(pal); + let target = this.targetPath(pal.name, prev); + if (claimed.has(target.toLowerCase())) { + this.renamePalette(pal, uniquePaletteName(pal.name, this.plugin.settings.terrainPalettes.map((p) => p.name))); + target = this.targetPath(pal.name, prev); + renamedInMemory = true; + } + claimed.add(target.toLowerCase()); + + let file = vault.getAbstractFileByPath(target); + if (prev && prev !== target && !file) { + const prevFile = vault.getAbstractFileByPath(prev); + if (prevFile instanceof TFile) { + this.knownPaths.delete(prev); + this.lastContent.delete(prev); + this.boundPath.set(pal, target); + this.knownPaths.add(target); + await fileManager.renameFile(prevFile, target); + file = vault.getAbstractFileByPath(target); + } + } + + if (file instanceof TFile) { + const current = await vault.read(file); + const parsed = parsePaletteNote(current); + const next = parsed && terrainsEqual(parsed, pal.terrains) + ? current + : updatePaletteNote(current, pal.terrains); + if (next !== current) { + this.lastContent.set(target, next); + await vault.modify(file, next); + } + this.bind(pal, target, next); + } else { + const content = buildPaletteNote(pal.terrains); + this.bind(pal, target, content); + await vault.create(target, content); + } + } + + // Palettes deleted in memory → trash their notes (only notes we own). + for (const path of [...this.knownPaths]) { + if (claimed.has(path.toLowerCase())) continue; + this.knownPaths.delete(path); + this.lastContent.delete(path); + const file = vault.getAbstractFileByPath(path); + if (file instanceof TFile) await fileManager.trashFile(file); + } + + if (renamedInMemory) await this.persist(); + }); + } + + /** The note backing a palette, if it has been written. */ + noteFor(name: string): TFile | undefined { + const pal = this.plugin.getPaletteByName(name); + const path = (pal && this.boundPath.get(pal)) ?? this.pathFor(name); + const file = this.plugin.app.vault.getAbstractFileByPath(path); + return file instanceof TFile ? file : undefined; + } + + // ── notes → memory (vault events) ────────────────────────────────────────── + + private paletteBoundTo(path: string): TerrainPalette | undefined { + return this.plugin.settings.terrainPalettes.find((p) => this.boundPath.get(p) === path); + } + + onModify(file: TAbstractFile): void { + if (!this.ready || !this.isPaletteFile(file)) return; + void this.enqueue(async () => { + const content = await this.plugin.app.vault.read(file); + if (this.lastContent.get(file.path) === content) return; // our own write + const terrains = parsePaletteNote(content); + if (!terrains) return; // mid-edit / table removed: keep the last good copy + this.lastContent.set(file.path, content); + let pal = this.paletteBoundTo(file.path) + ?? this.plugin.settings.terrainPalettes.find((p) => p.name.toLowerCase() === file.basename.toLowerCase()); + if (pal) { + if (terrainsEqual(pal.terrains, terrains)) return; + pal.terrains.splice(0, pal.terrains.length, ...terrains); + } else { + pal = { name: file.basename, terrains }; + this.plugin.settings.terrainPalettes.push(pal); + } + this.bind(pal, file.path, content); + await this.persist(); + }); + } + + onDelete(file: TAbstractFile): void { + if (!this.ready || !(file instanceof TFile) || !this.knownPaths.has(file.path)) return; + void this.enqueue(async () => { + this.knownPaths.delete(file.path); + this.lastContent.delete(file.path); + const pal = this.paletteBoundTo(file.path); + const list = this.plugin.settings.terrainPalettes; + if (!pal || list.length <= 1) return; // keep at least one palette + // Maps keep their paletteName so they reattach if the note comes back + // (e.g. restored from trash, or delivered late by sync). + list.splice(list.indexOf(pal), 1); + await this.persist(); + }); + } + + onRename(file: TAbstractFile, oldPath: string): void { + if (!this.ready || !(file instanceof TFile)) return; + const wasOurs = this.knownPaths.has(oldPath); + const isPalette = this.isPaletteFile(file); + if (!wasOurs) { + if (isPalette) this.onModify(file); // moved into the folder + return; + } + void this.enqueue(async () => { + const pal = this.paletteBoundTo(oldPath); + this.knownPaths.delete(oldPath); + const content = this.lastContent.get(oldPath); + this.lastContent.delete(oldPath); + if (!pal) return; + if (!isPalette) { + // Moved out of the palettes folder: same as a delete. + const list = this.plugin.settings.terrainPalettes; + if (list.length > 1) list.splice(list.indexOf(pal), 1); + await this.persist(); + return; + } + if (content !== undefined) this.bind(pal, file.path, content); + else this.boundPath.set(pal, file.path); + this.knownPaths.add(file.path); + if (pal.name !== file.basename) { + this.renamePalette(pal, file.basename); + await this.persist(); + } + }); + } +} diff --git a/src/palettes/paletteNote.ts b/src/palettes/paletteNote.ts new file mode 100644 index 00000000..efc0ff54 --- /dev/null +++ b/src/palettes/paletteNote.ts @@ -0,0 +1,182 @@ +import type { TerrainColor } from "../types"; + +// Plain-text palette notes. +// +// A palette is a markdown note whose basename is the palette name and whose +// body holds one terrain per table row: +// +// | Terrain | Color | Icon | Icon color | Category | +// | --- | --- | --- | --- | --- | +// | ocean | #29507f | | | sea | +// +// Columns are matched by header name (case-insensitive, any order), so a +// hand-edited or shared note only needs the Terrain and Color columns. Text +// outside the table is the user's and is preserved when the plugin rewrites +// the table after an in-app edit. + +/** Frontmatter key written into every palette note (informational only). */ +export const PALETTE_NOTE_MARKER = "hexmaker-palette"; + +const HEADERS = ["Terrain", "Color", "Icon", "Icon color", "Category"] as const; + +type Column = "name" | "color" | "icon" | "iconColor" | "category"; + +function columnFor(header: string): Column | null { + const h = header.trim().toLowerCase().replace(/\s+/g, " "); + if (h === "terrain" || h === "name") return "name"; + if (h === "color" || h === "colour") return "color"; + if (h === "icon") return "icon"; + if (h === "icon color" || h === "icon colour" || h === "tint") return "iconColor"; + if (h === "category") return "category"; + return null; +} + +/** Characters Obsidian/Windows/macOS reject (or treat specially) in a note name. */ +const UNSAFE_NAME_CHARS = /[\\/:*?"<>|#^[\]]/g; + +/** Palette name → a basename that is legal on every platform Obsidian runs on. */ +export function paletteFileName(name: string): string { + const cleaned = name + .replace(UNSAFE_NAME_CHARS, "-") + .replace(/\s+/g, " ") + .trim() + .replace(/^\.+/, ""); + return cleaned || "Palette"; +} + +/** Split a markdown table row into cells, honouring `\|` escapes. */ +function splitRow(line: string): string[] { + let s = line.trim(); + if (s.startsWith("|")) s = s.slice(1); + if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1); + const cells: string[] = []; + let cur = ""; + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (ch === "\\" && s[i + 1] === "|") { + cur += "|"; + i++; + } else if (ch === "|") { + cells.push(cur.trim()); + cur = ""; + } else { + cur += ch; + } + } + cells.push(cur.trim()); + return cells; +} + +const SEPARATOR_ROW = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/; + +interface TableSpan { + start: number; // index of the header line + end: number; // index one past the last body row + columns: (Column | null)[]; +} + +/** Locate the first table with a Terrain (or Name) and a Color column. */ +function findPaletteTable(lines: string[]): TableSpan | null { + for (let i = 0; i < lines.length - 1; i++) { + if (!lines[i].trim().startsWith("|")) continue; + if (!SEPARATOR_ROW.test(lines[i + 1])) continue; + const columns = splitRow(lines[i]).map(columnFor); + if (!columns.includes("name") || !columns.includes("color")) continue; + let end = i + 2; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { start: i, end, columns }; + } + return null; +} + +/** + * Parse the terrain table out of a palette note. Returns null when the note + * has no recognisable palette table (so callers can tell "not a palette" + * apart from "a palette with zero terrains"). + */ +export function parsePaletteNote(content: string): TerrainColor[] | null { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const span = findPaletteTable(lines); + if (!span) return null; + const terrains: TerrainColor[] = []; + for (let i = span.start + 2; i < span.end; i++) { + const cells = splitRow(lines[i]); + const row: Partial> = {}; + span.columns.forEach((col, idx) => { + if (col && cells[idx]) row[col] = cells[idx]; + }); + if (!row.name) continue; + const entry: TerrainColor = { name: row.name, color: row.color || "#888888" }; + if (row.icon) entry.icon = row.icon; + if (row.iconColor) entry.iconColor = row.iconColor; + if (row.category) entry.category = row.category; + terrains.push(entry); + } + return terrains; +} + +function escapeCell(value: string | undefined): string { + return (value ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " ").trim(); +} + +/** Serialize terrains as the canonical five-column markdown table. */ +export function serializePaletteTable(terrains: TerrainColor[]): string { + const lines = [ + `| ${HEADERS.join(" | ")} |`, + `| ${HEADERS.map(() => "---").join(" | ")} |`, + ]; + for (const t of terrains) { + const cells = [t.name, t.color, t.icon, t.iconColor, t.category].map(escapeCell); + lines.push(`| ${cells.join(" | ")} |`); + } + return lines.join("\n"); +} + +/** A complete new palette note. */ +export function buildPaletteNote(terrains: TerrainColor[]): string { + return [ + "---", + `${PALETTE_NOTE_MARKER}: 1`, + "---", + "", + "Hexmaker terrain palette. The note name is the palette name. Each table row is one terrain:", + "colors are any CSS color, icons are file names from the icon picker, and categories group", + "terrains in the picker. Edit here or from the terrain tool on the hex map. Copy this note", + "into another vault's palettes folder to share it.", + "", + serializePaletteTable(terrains), + "", + ].join("\n"); +} + +/** + * Rewrite only the terrain table inside an existing note, keeping any + * frontmatter and prose the user added. Falls back to a fresh note when the + * existing content has no palette table. + */ +export function updatePaletteNote(content: string, terrains: TerrainColor[]): string { + const normalized = content.replace(/\r\n?/g, "\n"); + const lines = normalized.split("\n"); + const span = findPaletteTable(lines); + if (!span) return buildPaletteNote(terrains); + return [ + ...lines.slice(0, span.start), + serializePaletteTable(terrains), + ...lines.slice(span.end), + ].join("\n"); +} + +/** Structural equality used to skip no-op rewrites. */ +export function terrainsEqual(a: TerrainColor[], b: TerrainColor[]): boolean { + if (a.length !== b.length) return false; + return a.every((t, i) => { + const u = b[i]; + return ( + t.name === u.name && + t.color === u.color && + (t.icon ?? "") === (u.icon ?? "") && + (t.iconColor ?? "") === (u.iconColor ?? "") && + (t.category ?? "") === (u.category ?? "") + ); + }); +} diff --git a/src/palettes/paletteOptions.ts b/src/palettes/paletteOptions.ts new file mode 100644 index 00000000..332e8cc7 --- /dev/null +++ b/src/palettes/paletteOptions.ts @@ -0,0 +1,27 @@ +import type HexmakerPlugin from "../HexmakerPlugin"; +import { PALETTE_PRESETS } from "./presets"; + +/** + * Fill a palette × + + + +

+
+
+ diff --git a/dev/space-gen-preview.ts b/dev/space-gen-preview.ts new file mode 100644 index 00000000..b3d9f5c7 --- /dev/null +++ b/dev/space-gen-preview.ts @@ -0,0 +1,98 @@ +/** + * Sandbox for the procedural space generators (Star scatter, Orbits), + * rendered with the same drawPreview the new-map setup modal uses. + * Build: npx esbuild dev/space-gen-preview.ts --bundle --format=iife --outfile=dev/space-gen-preview.js + * Serve: npm run sandbox → /dev/space-gen-preview.html + */ +import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS, SPACE_PATH_TYPES, SYSTEM_PATH_TYPES } from "../src/palettes/presets"; +import { starScatter, STAR_SCATTER_OPTIONS } from "../src/worldgen/procedural/starScatter"; +import { orbits, ORBITS_OPTIONS } from "../src/worldgen/procedural/orbits"; +import type { ProcGrid, ProcOption } from "../src/worldgen/procedural/common"; +import { drawPreview } from "../src/worldgen/preview"; + +type Gen = "sector" | "system"; +const state = { + gen: "sector" as Gen, + orientation: "flat" as "flat" | "pointy", + cols: 8, + rows: 10, + seed: 1, + options: {} as Record, +}; + +const colors = (gen: Gen) => + new Map((gen === "sector" ? SPACE_SECTOR_TERRAINS : SPACE_SYSTEM_TERRAINS).map((t) => [t.name, t.color])); +const pathColors = new Map([...SPACE_PATH_TYPES, ...SYSTEM_PATH_TYPES].map((p) => [p.name, p.color])); + +function controls(): void { + const box = document.getElementById("controls")!; + box.replaceChildren(); + const opts: ProcOption[] = state.gen === "sector" ? STAR_SCATTER_OPTIONS : ORBITS_OPTIONS; + for (const o of opts) { + const label = document.createElement("label"); + label.textContent = o.label + " "; + const sel = document.createElement("select"); + for (const c of o.choices) sel.add(new Option(c.label, c.value)); + sel.value = state.options[o.key] ?? o.default; + sel.onchange = () => { state.options[o.key] = sel.value; render(); }; + label.append(sel); + box.append(label); + } +} + +function render(): void { + const grid: ProcGrid = { + cols: state.cols, rows: state.rows, offset: { x: 0, y: 0 }, stagger: "odd", orientation: state.orientation, + }; + const wall = document.getElementById("wall")!; + wall.replaceChildren(); + // Six seeds side by side so the variety is visible at a glance. + for (let i = 0; i < 6; i++) { + const seed = state.seed + i; + const r = state.gen === "sector" + ? starScatter(SPACE_SECTOR_TERRAINS, grid, seed, state.options, "Jump route") + : orbits(SPACE_SYSTEM_TERRAINS, grid, seed, state.options, "Orbit"); + const fig = document.createElement("figure"); + const canvas = document.createElement("canvas"); + drawPreview(canvas, r.cells, grid, state.orientation, colors(state.gen), undefined, r.paths, pathColors, 300, 18); + const cap = document.createElement("figcaption"); + cap.textContent = `seed ${seed}` + (r.warnings.length ? ` — ${r.warnings.join(" ")}` : ""); + fig.append(canvas, cap); + wall.append(fig); + } + const legend = document.getElementById("legend")!; + legend.replaceChildren(...[...colors(state.gen)].map(([name, color]) => { + const s = document.createElement("span"); + s.innerHTML = `${name}`; + return s; + })); +} + +function setGen(gen: Gen): void { + state.gen = gen; + state.options = {}; + [state.cols, state.rows] = gen === "sector" ? [8, 10] : [13, 13]; + (document.getElementById("cols") as HTMLInputElement).value = String(state.cols); + (document.getElementById("rows") as HTMLInputElement).value = String(state.rows); + document.querySelectorAll("[data-gen]").forEach((b) => b.classList.toggle("on", b.dataset.gen === gen)); + controls(); + render(); +} + +document.querySelectorAll("[data-gen]").forEach((b) => (b.onclick = () => setGen(b.dataset.gen as Gen))); +(document.getElementById("reroll") as HTMLButtonElement).onclick = () => { state.seed += 6; render(); }; +(document.getElementById("orient") as HTMLSelectElement).onchange = (e) => { + state.orientation = (e.target as HTMLSelectElement).value as "flat" | "pointy"; + render(); +}; +for (const id of ["cols", "rows"] as const) { + (document.getElementById(id) as HTMLInputElement).onchange = (e) => { + state[id] = Math.max(3, Math.min(60, Number((e.target as HTMLInputElement).value) || 3)); + render(); + }; +} +(window as unknown as { __render: typeof render; __state: typeof state; __setGen: typeof setGen }).__render = render; +(window as unknown as { __state: typeof state }).__state = state; +(window as unknown as { __setGen: typeof setGen }).__setGen = setGen; +setGen("sector"); +document.title = "ready"; diff --git a/package.json b/package.json index 2063b4b2..2c81bf60 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 5603ae09..59525115 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -1256,6 +1256,15 @@ export default class HexmakerPlugin extends Plugin { onProgress?: (done: number, total: number) => void, /** Optional generated terrain per hex, keyed "x_y". */ terrainAt?: Map, + extra: { + /** Terrain shown on unpainted hexes. When set, hex notes are created + * on use: only hexes that get a terrain other than the base get a + * note now; the rest appear when clicked, painted, or linked. */ + baseTerrain?: string; + parent?: { map: string; hex: string }; + /** Silence the "generated N notes" notice (caller reports instead). */ + quiet?: boolean; + } = {}, ): Promise<{ name: string } | { error: string }> { const name = slugify(rawName); if (!name) return { error: "Enter a map name." }; @@ -1280,20 +1289,30 @@ export default class HexmakerPlugin extends Plugin { pathChains: [], staggerOffset, createdWith: pluginVersion(this), + ...(extra.baseTerrain ? { baseTerrain: extra.baseTerrain } : {}), + ...(extra.parent ? { parent: extra.parent } : {}), }); await this.saveSettings(); - const xs = Array.from({ length: cols }, (_, i) => i + initialX); - const ys = Array.from({ length: rows }, (_, i) => i + initialY); - const total = cols * rows; - const created = await this.generateHexNotes( - name, - xs, - ys, - (done) => onProgress?.(done, total), - terrainAt, - ); - if (created > 0) + let created: number; + if (extra.baseTerrain) { + // Notes on use: write only hexes that differ from the base terrain. + const painted = [...(terrainAt ?? new Map())] + .filter(([, t]) => t && t !== extra.baseTerrain); + created = await this.generateHexNotesAt(name, painted, (done) => onProgress?.(done, painted.length)); + } else { + const xs = Array.from({ length: cols }, (_, i) => i + initialX); + const ys = Array.from({ length: rows }, (_, i) => i + initialY); + const total = cols * rows; + created = await this.generateHexNotes( + name, + xs, + ys, + (done) => onProgress?.(done, total), + terrainAt, + ); + } + if (created > 0 && !extra.quiet) new Notice( `Hexmaker: generated ${created} hex note${created !== 1 ? "s" : ""} for "${name}".`, ); @@ -1301,6 +1320,32 @@ export default class HexmakerPlugin extends Plugin { return { name }; } + /** Create notes for specific hexes ("x_y" → terrain), skipping ones that exist. */ + async generateHexNotesAt( + mapName: string, + cells: [string, string][], + onProgress?: (done: number) => void, + ): Promise { + const template = await this.loadHexTemplate(); + if (template === null) return 0; + let created = 0; + let done = 0; + const CHUNK = 20; + for (let i = 0; i < cells.length; i += CHUNK) { + await Promise.all( + cells.slice(i, i + CHUNK).map(async ([key, terrain]) => { + const [x, y] = key.split("_").map(Number); + if (!this.app.vault.getAbstractFileByPath(this.hexPath(x, y, mapName))) { + if (await this.createHexNote(x, y, mapName, template, terrain)) created++; + } + done++; + }), + ); + onProgress?.(done); + } + return created; + } + async generateHexNotes( mapName: string, xs: number[], diff --git a/src/export/mapPngRenderer.ts b/src/export/mapPngRenderer.ts index 6b8ba392..e6d9755d 100644 --- a/src/export/mapPngRenderer.ts +++ b/src/export/mapPngRenderer.ts @@ -213,6 +213,11 @@ export async function renderMapToPngBlob( if (file instanceof TFile) { const terrainName = getTerrainFromFile(plugin.app, file.path); if (terrainName) terrain = terrainByName.get(terrainName); + } + // Unpainted hexes (often noteless) draw as the map's base terrain, + // matching the on-screen map. + if (!terrain && map?.baseTerrain) terrain = terrainByName.get(map.baseTerrain); + if (file instanceof TFile) { iconOverride = getIconOverrideFromFile(plugin.app, file.path) ?? undefined; if (showFactionOverlay) { for (const fName of getHexFactionLinks(plugin.app, file)) { diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 958cd032..f0c97cb2 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -47,6 +47,7 @@ import { GeoRegionPickerModal } from "./GeoRegionPickerModal"; import { DrawingToolPanel, OverlayPanel } from "./HexSidePanel"; import { TokenModal } from "./TokenModal"; import { SubmapPickerModal } from "./SubmapPickerModal"; +import { NewMapSetupModal } from "../worldgen/NewMapSetupModal"; import { TokenInfoModal } from "./TokenInfoModal"; import { getTokenDataFromCache, @@ -453,6 +454,27 @@ export class HexMapView extends ItemView { return true; } + /** + * "New submap…" for hex (x, y): the setup modal (size, palette, generator, + * base terrain, preview). On create, links the hex and enters the new map; + * "Open in generator" also opens the Generator view on it. + */ + openNewSubmapSetup(x: number, y: number): void { + const parentMap = this.activeMapName; + new NewMapSetupModal( + this.app, + this.plugin, + ({ name }) => { + void (async () => { + await this.plugin.linkSubmap(parentMap, x, y, name); + if (this.activeMapName === parentMap) this.navigateToMap(name); + else this.renderGrid(); + })(); + }, + { map: parentMap, x, y }, + ).open(); + } + canNavigateBack(): boolean { return this.mapHistory.some((m) => m !== this.activeMapName && this.plugin.getMap(m)); } @@ -3370,7 +3392,11 @@ export class HexMapView extends ItemView { const terrainKey = terrainOverrides?.has(path) ? terrainOverrides.get(path)! : fm ? terrainFromFm(fm) : pendingTerrainOf(path); - const terrainEntry = terrainKey != null ? paletteByName.get(terrainKey) : undefined; + // Hexes with no terrain (often no note at all — notes are created on + // use) show the map's base terrain, e.g. "void" on a system map. + const ownTerrain = terrainKey != null ? paletteByName.get(terrainKey) : undefined; + const baseEntry = !ownTerrain && region.baseTerrain ? paletteByName.get(region.baseTerrain) : undefined; + const terrainEntry = ownTerrain ?? baseEntry; const hexEl = parent.createDiv({ cls: `duckmage-hex${exists ? " duckmage-hex-exists" : ""}`, @@ -3605,9 +3631,18 @@ export class HexMapView extends ItemView { ); } + if (!submap) { + menu.addItem((item) => + item + .setTitle("New submap…") + .setIcon("map-plus") + .onClick(() => this.openNewSubmapSetup(x, y)), + ); + } + menu.addItem((item) => item - .setTitle(submap ? "Change submap…" : "Create / link submap…") + .setTitle(submap ? "Change submap…" : "Link existing map…") .setIcon("map-pin") .onClick(() => { const parentMap = this.activeMapName; @@ -3628,6 +3663,7 @@ export class HexMapView extends ItemView { void this.plugin.unlinkSubmap(parentMap, x, y).then(() => this.renderGrid()); }, { map: parentMap, x, y }, + () => this.openNewSubmapSetup(x, y), ).open(); }), ); diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 8b608a3e..de8a5ffc 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -21,6 +21,7 @@ import { import { drawPreview, PREVIEW_AUTO_LIMIT } from "../worldgen/preview"; import { randomSeed } from "../../packages/hex-wfc/src"; import { fillPaletteSelect } from "../palettes/paletteOptions"; +import { NewMapSetupModal } from "../worldgen/NewMapSetupModal"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; @@ -551,6 +552,21 @@ export class MapModal extends HexmakerModal { // ── New map tab ─────────────────────────────────────────────────────────── private renderNewMapTab(el: HTMLElement): void { + // Guided setup: the same modal used for new submaps — palette, size, + // any generator (incl. Star scatter / Orbits), base terrain, preview. + const guided = el.createDiv({ cls: "duckmage-region-row duckmage-map-guided-row" }); + guided.createEl("button", { text: "Guided setup…" }).addEventListener("click", () => { + new NewMapSetupModal(this.app, this.plugin, ({ name }) => { + this.view.switchMapFromModal(name); + this.onChanged(); + }).open(); + this.close(); + }); + guided.createSpan({ + cls: "setting-item-description", + text: "Pick a size and a generator with a live preview, or fill in the form below.", + }); + // Name el.createEl("label", { text: "Name", cls: "duckmage-map-field-label" }); const nameRow = el.createDiv({ cls: "duckmage-region-row" }); @@ -612,7 +628,7 @@ export class MapModal extends HexmakerModal { const current = generatorSelect.value; generatorSelect.empty(); generatorSelect.createEl("option", { value: "", text: "Blank" }); - const names = this.plugin.getPaletteByName(paletteSelect.value)?.terrains.map((t) => t.name) ?? []; + const names = this.plugin.getPaletteOrPresetTerrains(paletteSelect.value).map((t) => t.name); for (const g of generators) { if (generatorFitsPalette(g.model, names)) generatorSelect.createEl("option", { value: g.file.path, text: g.model.name }); @@ -715,7 +731,7 @@ export class MapModal extends HexmakerModal { offset: { x: Number(originXInput.value) || 0, y: Number(originYInput.value) || 0 }, stagger: staggerVal, }; - const palette = this.plugin.getPaletteByName(paletteSelect.value)?.terrains.map((t) => t.name) ?? []; + const palette = this.plugin.getPaletteOrPresetTerrains(paletteSelect.value).map((t) => t.name); const r = generateTerrain(this.plugin, g.model, palette, grid, Number(seedInput.value) >>> 0); if (!r.ok) { previewStatus.setText(`This generator couldn't fill the map: ${r.message}`); @@ -915,7 +931,7 @@ export class MapModal extends HexmakerModal { let terrainAt: Map | undefined; let generatedPaths: { type: string; route?: string; hexes: string[] }[] = []; if (generator) { - const palette = this.plugin.getPaletteByName(paletteName)?.terrains.map((t) => t.name) ?? []; + const palette = this.plugin.getPaletteOrPresetTerrains(paletteName).map((t) => t.name); const solved = generateTerrain( this.plugin, generator.model, palette, { cols, rows, offset: { x: initialX, y: initialY }, stagger: staggerOffset }, seed, diff --git a/src/hex-map/SubmapPickerModal.ts b/src/hex-map/SubmapPickerModal.ts index 4c1bd44e..df5dd26a 100644 --- a/src/hex-map/SubmapPickerModal.ts +++ b/src/hex-map/SubmapPickerModal.ts @@ -16,6 +16,9 @@ export class SubmapPickerModal extends HexmakerModal { /** The hex being linked. Enables the create-first layout: section open, * auto-named `-x-y`, child palette pre-selected. */ private origin?: { map: string; x: number; y: number }, + /** When set (single-hex use), "create" hands off to the new-submap setup + * modal (size, generator, preview) instead of the inline form. */ + private onNewSubmap?: () => void, ) { super(app); } @@ -95,6 +98,15 @@ export class SubmapPickerModal extends HexmakerModal { filterInput.addEventListener("input", () => renderMapList(filterInput.value)); } + if (this.onNewSubmap) { + const newRow = contentEl.createDiv({ cls: "duckmage-submap-new-row" }); + const newBtn = newRow.createEl("button", { text: "New submap…", cls: maps.length ? "" : "mod-cta" }); + newRow.createSpan({ cls: "setting-item-description", text: "Choose size, palette and a generator, then go straight in." }); + newBtn.addEventListener("click", () => { this.close(); this.onNewSubmap?.(); }); + this.renderButtons(contentEl, maps.length > 0, () => selectedMap); + return; + } + // ── Create & link new map (collapsible) ────────────────────────────── const createSection = contentEl.createDiv({ cls: "duckmage-editor-collapsible" }); const createHeader = createSection.createDiv({ cls: "duckmage-editor-collapsible-header" }); @@ -244,9 +256,13 @@ export class SubmapPickerModal extends HexmakerModal { ), ); - // ── Bottom button row (Link existing + Cancel) ──────────────────────── + this.renderButtons(contentEl, maps.length > 0, () => selectedMap); + } + + /** Bottom button row: Remove link / Link existing / Cancel. */ + private renderButtons(contentEl: HTMLElement, hasMaps: boolean, selected: () => string): void { const bottomRow = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); - if (maps.length > 0) { + if (hasMaps) { if (this.current) { bottomRow.createEl("button", { text: "Remove link", cls: "mod-warning" }) .addEventListener("click", () => { this.close(); this.onUnlink(); }); @@ -254,7 +270,7 @@ export class SubmapPickerModal extends HexmakerModal { bottomRow.createEl("button", { text: "Link", cls: "mod-cta" }) .addEventListener("click", () => { this.close(); - this.onLink(selectedMap, false); + this.onLink(selected(), false); }); } bottomRow.createEl("button", { text: "Cancel" }) diff --git a/src/palettes/presets.ts b/src/palettes/presets.ts index 6e6be2ac..c81d5e7e 100644 --- a/src/palettes/presets.ts +++ b/src/palettes/presets.ts @@ -87,6 +87,11 @@ export const SPACE_PATH_TYPES: PathType[] = [ { name: "Trade route", color: "#f59e0b", width: 3, lineStyle: "solid", routing: "through" }, ]; +// System-scale: faint dotted rings the Orbits generator draws around the star. +export const SYSTEM_PATH_TYPES: PathType[] = [ + { name: "Orbit", color: "#3b4a6b", width: 1, lineStyle: "dotted", routing: "through" }, +]; + export const PALETTE_PRESETS: PalettePreset[] = [ { name: LIMITED_PALETTE_NAME, @@ -107,8 +112,9 @@ export const PALETTE_PRESETS: PalettePreset[] = [ }, { name: SPACE_SYSTEM_PALETTE_NAME, - description: "A single star system: stars, planets, belts, stations, and hazards.", + description: "A single star system: stars, planets, belts, stations, and hazards. Adds an Orbit path type.", terrains: SPACE_SYSTEM_TERRAINS, + pathTypes: SYSTEM_PATH_TYPES, }, ]; diff --git a/src/types.ts b/src/types.ts index 9a5f4356..937f6151 100644 --- a/src/types.ts +++ b/src/types.ts @@ -58,6 +58,10 @@ export interface MapData { * the breadcrumb and "Up". Set by plugin.linkSubmap; recovered by scanning * hex notes when missing (maps linked before this existed). */ parent?: { map: string; hex: string }; + /** Terrain shown on hexes with no terrain of their own (e.g. "void"). + * Maps created with a base terrain create hex notes on use only — an + * absent note renders as this terrain. */ + baseTerrain?: string; gridSize: { cols: number; rows: number }; gridOffset: { x: number; y: number }; pathChains: PathChain[]; diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts new file mode 100644 index 00000000..dafb7557 --- /dev/null +++ b/src/worldgen/NewMapSetupModal.ts @@ -0,0 +1,376 @@ +import { App, Notice } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { TerrainColor } from "../types"; +import { fillPaletteSelect } from "../palettes/paletteOptions"; +import { defaultSubmapName } from "../hex-map/submapNav"; +import { randomSeed } from "../../packages/hex-wfc/src"; +import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; +import { pathColors } from "./generators"; +import { SIZE_PRESETS, type SizePreset } from "./sizePresets"; +import { + BLANK_ID, + kindsForPalette, + listGeneratorKinds, + suggestBaseTerrain, + type GenerateOutcome, + type TerrainGeneratorKind, +} from "./registry"; + +/** Submaps are local (a system, a dungeon): smaller, odd sizes so there's a true centre hex. */ +export const SUBMAP_SIZE_PRESETS: SizePreset[] = [ + { label: "Small", cols: 9, rows: 9 }, + { label: "Medium", cols: 13, rows: 13 }, + { label: "Large", cols: 19, rows: 19 }, +]; + +export interface NewMapSetupResult { + name: string; +} + +/** + * Set up a new map or submap before anything is written: name, palette, + * size, generator (Blank, Star scatter, Orbits, learned WFC generators) and + * its options, base terrain, with a live preview. Then either + * - "Generate & enter": create the map with the previewed terrain, or + * - "Open in generator": create it blank and open the Generator view on it + * for hands-on tuning. + * `onCreated` runs after creation (callers link the parent hex / switch maps). + */ +export class NewMapSetupModal extends HexmakerModal { + private kinds: TerrainGeneratorKind[] = []; + private kindId = BLANK_ID; + private options: Record = {}; + private seed = randomSeed(); + private cols: number; + private rows: number; + private baseTerrain: string | undefined; + private lastOutcome: GenerateOutcome | undefined; + + constructor( + app: App, + private plugin: HexmakerPlugin, + private onCreated: (result: NewMapSetupResult, opts: { openGenerator: boolean }) => void, + /** Hex this map is a submap of. Drives naming, palette and size defaults. */ + private origin?: { map: string; x: number; y: number }, + ) { + super(app); + const preset = origin ? SUBMAP_SIZE_PRESETS[1] : SIZE_PRESETS[0]; + this.cols = preset.cols; + this.rows = preset.rows; + } + + onOpen(): void { + this.makeDraggable(); + this.modalEl.addClass("duckmage-setup-modal"); + this.titleEl.setText( + this.origin + ? `New submap — ${this.origin.map}, hex ${this.origin.x}, ${this.origin.y}` + : "New map", + ); + void listGeneratorKinds(this.plugin).then((kinds) => { + this.kinds = kinds; + this.render(); + }); + this.contentEl.createDiv({ cls: "duckmage-setup-loading", text: "Loading generators…" }); + } + + onClose(): void { + this.contentEl.empty(); + } + + private terrains(paletteName: string): TerrainColor[] { + return this.plugin.getPaletteOrPresetTerrains(paletteName); + } + + private render(): void { + const { contentEl } = this; + contentEl.empty(); + const form = contentEl.createDiv({ cls: "duckmage-setup-form" }); + const side = contentEl.createDiv({ cls: "duckmage-setup-preview" }); + contentEl.addClass("duckmage-setup-layout"); + + // ── Name ── + const nameRow = this.row(form, "Name"); + const nameInput = nameRow.createEl("input", { type: "text", cls: "duckmage-setup-name" }); + nameInput.value = this.origin + ? defaultSubmapName(this.origin.map, this.origin.x, this.origin.y, this.plugin.settings.maps.map((m) => m.name)) + : ""; + nameInput.placeholder = "Map name"; + + // ── Palette ── + const palRow = this.row(form, "Palette"); + const paletteSelect = palRow.createEl("select"); + fillPaletteSelect( + this.plugin, + paletteSelect, + this.origin ? this.plugin.childPaletteFor(this.origin.map) : this.plugin.settings.terrainPalettes[0]?.name, + ); + + // ── Size ── + const sizeRow = this.row(form, "Size"); + const presetBox = sizeRow.createDiv({ cls: "duckmage-setup-size-presets" }); + const custom = sizeRow.createDiv({ cls: "duckmage-setup-size-custom" }); + const colsInput = custom.createEl("input", { type: "number", value: String(this.cols), attr: { min: "1", max: "200", "aria-label": "Columns" } }); + custom.createSpan({ text: "×" }); + const rowsInput = custom.createEl("input", { type: "number", value: String(this.rows), attr: { min: "1", max: "200", "aria-label": "Rows" } }); + const presets = this.origin ? SUBMAP_SIZE_PRESETS : SIZE_PRESETS; + const presetBtns: HTMLButtonElement[] = []; + const syncPresetBtns = () => presets.forEach((p, i) => + presetBtns[i].toggleClass("is-active", p.cols === this.cols && p.rows === this.rows)); + for (const p of presets) { + const b = presetBox.createEl("button", { text: p.label, attr: { title: `${p.cols} × ${p.rows}` } }); + b.addEventListener("click", () => { + this.cols = p.cols; this.rows = p.rows; + colsInput.value = String(p.cols); rowsInput.value = String(p.rows); + syncPresetBtns(); + refresh(); + }); + presetBtns.push(b); + } + syncPresetBtns(); + const onSize = () => { + this.cols = Math.max(1, Math.min(200, Number(colsInput.value) || 1)); + this.rows = Math.max(1, Math.min(200, Number(rowsInput.value) || 1)); + syncPresetBtns(); + refresh(); + }; + colsInput.addEventListener("change", onSize); + rowsInput.addEventListener("change", onSize); + + // ── Generator ── + const genRow = this.row(form, "Generator"); + const genList = genRow.createDiv({ cls: "duckmage-setup-generators" }); + const optsBox = form.createDiv({ cls: "duckmage-setup-options" }); + + // ── Base terrain ── + const baseRow = this.row(form, "Base terrain"); + const baseSelect = baseRow.createEl("select"); + baseRow.createDiv({ + cls: "setting-item-description", + text: "Shown on unpainted hexes. With a base terrain, hex notes are created as you use hexes instead of all up front.", + }); + + // ── Preview ── + const canvas = side.createEl("canvas", { cls: "duckmage-setup-canvas" }); + const seedRow = side.createDiv({ cls: "duckmage-setup-seed-row" }); + const rerollBtn = seedRow.createEl("button", { text: "🎲 Re-roll", attr: { title: "New random seed" } }); + const seedLabel = seedRow.createSpan({ cls: "duckmage-setup-seed" }); + const status = side.createDiv({ cls: "duckmage-setup-status" }); + rerollBtn.addEventListener("click", () => { this.seed = randomSeed(); refresh(); }); + + // ── Actions ── + const actions = contentEl.createDiv({ cls: "duckmage-setup-actions" }); + const goBtn = actions.createEl("button", { cls: "mod-cta" }); + const genBtn = actions.createEl("button", { text: "Open in generator", attr: { title: "Create the map blank and open the generator view on it to tune generation by hand" } }); + actions.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); + + const renderGenerators = () => { + const terrains = this.terrains(paletteSelect.value); + const fitting = kindsForPalette(this.kinds, terrains); + if (!fitting.some((k) => k.id === this.kindId)) { + // Default to the first built-in generator that fits, else Blank. + this.kindId = fitting.find((k) => k.source === "built-in")?.id ?? BLANK_ID; + this.options = {}; + } + genList.empty(); + for (const k of fitting) { + const card = genList.createEl("button", { cls: `duckmage-setup-gen${k.id === this.kindId ? " is-active" : ""}` }); + card.createDiv({ cls: "duckmage-setup-gen-title", text: k.label + (k.source === "learned" ? " (learned)" : "") }); + card.createDiv({ cls: "duckmage-setup-gen-desc", text: k.description }); + card.addEventListener("click", () => { + this.kindId = k.id; + this.options = {}; + renderGenerators(); + refresh(); + }); + } + const hidden = this.kinds.length - fitting.length; + if (hidden > 0) { + genList.createDiv({ + cls: "setting-item-description", + text: `${hidden} other generator${hidden === 1 ? "" : "s"} don't fit this palette.`, + }); + } + // Options for the chosen generator. + optsBox.empty(); + const kind = this.kind(); + for (const opt of kind?.options ?? []) { + const r = this.row(optsBox, opt.label); + const sel = r.createEl("select"); + for (const c of opt.choices) sel.createEl("option", { value: c.value, text: c.label }); + sel.value = this.options[opt.key] ?? opt.default; + sel.addEventListener("change", () => { this.options[opt.key] = sel.value; refresh(); }); + } + goBtn.setText(this.kindId === BLANK_ID ? (this.origin ? "Create & enter" : "Create") : (this.origin ? "Generate & enter" : "Generate")); + }; + + const renderBase = () => { + const terrains = this.terrains(paletteSelect.value); + baseSelect.empty(); + baseSelect.createEl("option", { value: "", text: "None (create every hex note)" }); + for (const t of terrains) baseSelect.createEl("option", { value: t.name, text: t.name }); + this.baseTerrain = suggestBaseTerrain(terrains); + baseSelect.value = this.baseTerrain ?? ""; + }; + baseSelect.addEventListener("change", () => { this.baseTerrain = baseSelect.value || undefined; refresh(); }); + + const refresh = () => { + seedLabel.setText(`seed ${this.seed}`); + const terrains = this.terrains(paletteSelect.value); + const kind = this.kind(); + const grid = this.grid(); + status.empty(); + this.lastOutcome = undefined; + let cells = new Map(); + let paths: { type: string; route?: string; hexes: string[] }[] = []; + let featureCells: Set | undefined; + if (kind && kind.id !== BLANK_ID) { + if (this.cols * this.rows > PREVIEW_AUTO_LIMIT) { + status.setText("Large map — the preview is skipped; terrain is generated on create."); + } else { + const outcome = kind.generate({ terrains, grid, seed: this.seed, options: this.resolvedOptions(kind) }); + this.lastOutcome = outcome; + if (!outcome.ok) { + status.setText(outcome.message); + status.addClass("mod-warning"); + } else { + status.removeClass("mod-warning"); + cells = outcome.cells; + paths = outcome.paths; + featureCells = outcome.featureCells; + if (outcome.warnings.length) status.setText(outcome.warnings.join(" ")); + } + } + } + // Unpainted hexes preview as the base terrain, like the map will show them. + if (this.baseTerrain) { + for (let i = 0; i < this.cols; i++) + for (let j = 0; j < this.rows; j++) { + const k = `${i}_${j}`; + if (!cells.has(k)) cells.set(k, this.baseTerrain); + } + } + rerollBtn.toggle(!!kind && kind.id !== BLANK_ID); + drawPreview( + canvas, + cells, + grid, + this.plugin.settings.hexOrientation, + new Map(terrains.map((t) => [t.name, t.color])), + featureCells, + paths, + pathColors(this.plugin), + 320, + 18, + ); + }; + + paletteSelect.addEventListener("change", () => { renderGenerators(); renderBase(); refresh(); }); + + goBtn.addEventListener("click", () => void this.create(nameInput.value, paletteSelect.value, false, goBtn, genBtn)); + genBtn.addEventListener("click", () => void this.create(nameInput.value, paletteSelect.value, true, goBtn, genBtn)); + nameInput.addEventListener("keydown", (e) => { + if (e.key === "Enter") goBtn.click(); + }); + + renderGenerators(); + renderBase(); + refresh(); + nameInput.focus(); + nameInput.select(); + } + + private row(parent: HTMLElement, label: string): HTMLElement { + const r = parent.createDiv({ cls: "duckmage-setup-row" }); + r.createDiv({ cls: "duckmage-setup-label", text: label }); + return r.createDiv({ cls: "duckmage-setup-control" }); + } + + private kind(): TerrainGeneratorKind | undefined { + return this.kinds.find((k) => k.id === this.kindId); + } + + private resolvedOptions(kind: TerrainGeneratorKind): Record { + const out: Record = {}; + for (const o of kind.options) out[o.key] = this.options[o.key] ?? o.default; + return out; + } + + private grid() { + const parent = this.origin ? this.plugin.getMap(this.origin.map) : undefined; + return { + cols: this.cols, + rows: this.rows, + offset: { x: 0, y: 0 }, + stagger: parent?.staggerOffset ?? this.plugin.settings.staggerOffset ?? "odd", + }; + } + + private async create( + rawName: string, + paletteName: string, + openGenerator: boolean, + ...buttons: HTMLButtonElement[] + ): Promise { + const kind = this.kind(); + const terrains = this.terrains(paletteName); + let outcome: GenerateOutcome | undefined; + if (!openGenerator && kind && kind.id !== BLANK_ID) { + outcome = this.lastOutcome + ?? kind.generate({ terrains, grid: this.grid(), seed: this.seed, options: this.resolvedOptions(kind) }); + if (!outcome.ok) { + new Notice(outcome.message); + return; + } + } + + for (const b of buttons) b.disabled = true; + const goBtn = buttons[0]; + const label = goBtn.getText(); + goBtn.setText("Creating…"); + const result = await this.plugin.createNewMap( + rawName.trim(), + this.cols, + this.rows, + paletteName, + 0, + 0, + this.grid().stagger, + (done, total) => goBtn.setText(`Creating ${done} / ${total}…`), + outcome?.ok ? outcome.cells : undefined, + { + baseTerrain: this.baseTerrain, + parent: this.origin ? { map: this.origin.map, hex: `${this.origin.x}_${this.origin.y}` } : undefined, + quiet: true, + }, + ); + if ("error" in result) { + new Notice(result.error); + for (const b of buttons) b.disabled = false; + goBtn.setText(label); + return; + } + + // Generated paths (jump routes, rivers…) become map path chains. + if (outcome?.ok && outcome.paths.length && kind) { + const { chains, missing } = kind.toChains(outcome.paths); + const map = this.plugin.getMap(result.name); + if (map && chains.length) { + map.pathChains.push(...chains); + await this.plugin.saveSettings(); + } + if (missing.length) new Notice(`Skipped paths with no matching path type: ${missing.join(", ")}`); + } + + this.close(); + this.onCreated(result, { openGenerator }); + if (openGenerator) { + await this.plugin.openTerrainGenerator({ + mapName: result.name, + paletteName, + generatorPath: kind?.generatorPath, + }); + } + } +} diff --git a/src/worldgen/procedural/common.ts b/src/worldgen/procedural/common.ts new file mode 100644 index 00000000..cb4f865e --- /dev/null +++ b/src/worldgen/procedural/common.ts @@ -0,0 +1,101 @@ +import { cellKey, hexDistance, type Orientation, type Stagger } from "../../../packages/hex-wfc/src"; +import type { TerrainColor } from "../../types"; + +/** + * Shared types and helpers for the procedural (non-learned) generators. + * Pure: no Obsidian imports, deterministic for a given seed. + */ + +export interface ProcGrid { + cols: number; + rows: number; + offset: { x: number; y: number }; + stagger: Stagger; + orientation: Orientation; +} + +export interface ProcPath { + /** Path type name (must exist in settings.pathTypes to be drawn). */ + type: string; + hexes: string[]; +} + +export interface ProcResult { + /** Terrain per hex ("x_y"); every hex of the grid is set. */ + cells: Map; + paths: ProcPath[]; + warnings: string[]; +} + +export interface ProcOption { + key: string; + label: string; + choices: { value: string; label: string }[]; + default: string; +} + +/** Every "x_y" key of the grid, column-major like map creation. */ +export function gridKeys(grid: ProcGrid): [number, number][] { + const out: [number, number][] = []; + for (let i = 0; i < grid.cols; i++) + for (let j = 0; j < grid.rows; j++) out.push([grid.offset.x + i, grid.offset.y + j]); + return out; +} + +export function distance(a: [number, number], b: [number, number], grid: ProcGrid): number { + return hexDistance(a, b, grid.orientation, grid.stagger); +} + +/** The hex nearest the middle of the grid. */ +export function centerHex(grid: ProcGrid): [number, number] { + return [grid.offset.x + Math.floor((grid.cols - 1) / 2), grid.offset.y + Math.floor((grid.rows - 1) / 2)]; +} + +export { cellKey }; + +/** + * Find a palette terrain for a role: the first name match (case-insensitive), + * else — when `category` is given — the first terrain in that category. + * Lets the generators run on renamed or user-made palettes, not just the + * shipped presets. + */ +export function findTerrain( + terrains: TerrainColor[], + names: string[], + category?: string, +): string | undefined { + const byName = new Map(terrains.map((t) => [t.name.toLowerCase(), t.name])); + for (const n of names) { + const hit = byName.get(n.toLowerCase()); + if (hit) return hit; + } + if (category) return terrains.find((t) => t.category?.toLowerCase() === category)?.name; + return undefined; +} + +/** All terrains in a category (case-insensitive), in palette order. */ +export function inCategory(terrains: TerrainColor[], category: string): string[] { + return terrains.filter((t) => t.category?.toLowerCase() === category).map((t) => t.name); +} + +/** + * Weighted pick. `weights` maps lower-case terrain names to weights; names + * not listed get `fallback`. Returns undefined for an empty list. + */ +export function weightedPick( + rand: () => number, + names: string[], + weights: Record, + fallback = 1, +): string | undefined { + if (names.length === 0) return undefined; + const w = names.map((n) => Math.max(0, weights[n.toLowerCase()] ?? fallback)); + const total = w.reduce((a, b) => a + b, 0); + if (total <= 0) return names[Math.floor(rand() * names.length)]; + let r = rand() * total; + for (let i = 0; i < names.length; i++) { + r -= w[i]; + if (r < 0) return names[i]; + } + return names[names.length - 1]; +} diff --git a/src/worldgen/procedural/orbits.ts b/src/worldgen/procedural/orbits.ts new file mode 100644 index 00000000..8bbf3b1e --- /dev/null +++ b/src/worldgen/procedural/orbits.ts @@ -0,0 +1,232 @@ +import { hexCenter, mulberry32 } from "../../../packages/hex-wfc/src"; +import type { TerrainColor } from "../../types"; +import { + cellKey, + centerHex, + distance, + findTerrain, + gridKeys, + inCategory, + weightedPick, + type ProcGrid, + type ProcOption, + type ProcPath, + type ProcResult, +} from "./common"; + +/** + * Star-system "orbits": a star at the centre, then one body per orbit ring + * (hex distance from the star), typed by zone — hot inner rocks, a + * habitable middle, cold giants outside. Belts fill part of a ring; giants + * may get a moon; the mainworld may get a station or starport alongside; + * a comet and a jump point sit out past the last orbit. + * + * Works on any palette with a background ("void" / "empty space" / first + * `space` terrain) and at least one star and one body — by name, or the + * `stars` / `bodies` categories. + */ + +export const ORBITS_ID = "procedural:orbits"; + +export const ORBITS_OPTIONS: ProcOption[] = [ + { + key: "star", + label: "Star", + choices: [ + { value: "random", label: "Random" }, + { value: "yellow star", label: "Yellow star" }, + { value: "red dwarf", label: "Red dwarf" }, + { value: "blue giant", label: "Blue giant" }, + { value: "white dwarf", label: "White dwarf" }, + { value: "brown dwarf", label: "Brown dwarf" }, + ], + default: "random", + }, + { + key: "bodies", + label: "Planets", + choices: [ + { value: "few", label: "Few" }, + { value: "normal", label: "Normal" }, + { value: "crowded", label: "Crowded" }, + ], + default: "normal", + }, +]; + +/** Galactic mix: red dwarfs dominate. */ +const STAR_WEIGHTS: Record = { + "red dwarf": 6, + "yellow star": 3, + "brown dwarf": 1.5, + "white dwarf": 1, + "blue giant": 0.5, +}; + +const ZONE_WEIGHTS: Record<"inner" | "habitable" | "outer", Record> = { + inner: { "molten planet": 4, "rocky planet": 4, "desert planet": 2, "asteroid belt": 0.5 }, + habitable: { "terrestrial planet": 4, "ocean planet": 3, "desert planet": 3, "rocky planet": 2, "asteroid belt": 1 }, + outer: { "gas giant": 4, "ice giant": 3, "ice planet": 3, "asteroid belt": 1.5, "rocky planet": 1 }, +}; + +const BODY_NAMES = [ + "terrestrial planet", "ocean planet", "desert planet", "ice planet", "rocky planet", + "molten planet", "gas giant", "ice giant", "asteroid belt", +]; + +export interface OrbitRoles { + background: string; + stars: string[]; + bodies: string[]; + moon?: string; + comet?: string; + station?: string; + starport?: string; + jumpPoint?: string; + jumpLimit?: string; + belt?: string; +} + +export function orbitRoles(terrains: TerrainColor[]): OrbitRoles | undefined { + const background = findTerrain(terrains, ["void", "empty space", "deep space", "space"], "space"); + let stars = inCategory(terrains, "stars"); + if (stars.length === 0) { + const s = findTerrain(terrains, ["yellow star", "star", "sun"]); + stars = s ? [s] : []; + } + const names = new Set(terrains.map((t) => t.name.toLowerCase())); + let bodies = inCategory(terrains, "bodies").filter((b) => !/^(moon|comet)$/i.test(b)); + if (bodies.length === 0) bodies = terrains.map((t) => t.name).filter((n) => BODY_NAMES.includes(n.toLowerCase())); + if (!background || stars.length === 0 || bodies.length === 0) return undefined; + const pick = (n: string) => (names.has(n) ? terrains.find((t) => t.name.toLowerCase() === n)!.name : undefined); + return { + background, + stars, + bodies, + moon: pick("moon"), + comet: pick("comet"), + station: pick("space station"), + starport: pick("starport"), + jumpPoint: pick("jump point"), + jumpLimit: pick("jump limit"), + belt: bodies.find((b) => /belt/i.test(b)), + }; +} + +export function orbitsFits(terrains: TerrainColor[]): boolean { + return orbitRoles(terrains) !== undefined; +} + +export function orbits( + terrains: TerrainColor[], + grid: ProcGrid, + seed: number, + options: Record = {}, + /** Path type to draw occupied orbits with (e.g. "Orbit"); none = no rings. */ + orbitPathType?: string, +): ProcResult { + const roles = orbitRoles(terrains); + if (!roles) { + return { cells: new Map(), paths: [], warnings: ["This palette has no void, star, or planet terrains."] }; + } + const rand = mulberry32(seed); + const hexes = gridKeys(grid); + const center = centerHex(grid); + const cells = new Map(); + const dist = new Map(); + let maxD = 0; + for (const h of hexes) { + const k = cellKey(h[0], h[1]); + cells.set(k, roles.background); + const d = distance(center, h, grid); + dist.set(k, d); + maxD = Math.max(maxD, d); + } + // The largest ring that is complete on this grid — orbits beyond it would + // be clipped by the map edge. + const fullRing = Math.min( + ...hexes.filter((h) => h[0] === grid.offset.x || h[1] === grid.offset.y + || h[0] === grid.offset.x + grid.cols - 1 || h[1] === grid.offset.y + grid.rows - 1) + .map((h) => distance(center, h, grid)), + ); + const ring = (d: number) => hexes.filter((h) => dist.get(cellKey(h[0], h[1])) === d); + const set = (h: [number, number], t: string | undefined) => { if (t) cells.set(cellKey(h[0], h[1]), t); }; + + // Star. + const wanted = options.star && options.star !== "random" + ? roles.stars.find((s) => s.toLowerCase() === options.star) + : undefined; + const star = wanted ?? weightedPick(rand, roles.stars, STAR_WEIGHTS)!; + set(center, star); + // The 100-diameter limit hugs the star: mark the first ring. + if (roles.jumpLimit && fullRing >= 3) for (const h of ring(1)) set(h, roles.jumpLimit); + + // Orbits from ring 2 out to the last full ring. + const first = 2; + const last = Math.max(first, fullRing); + const skip = options.bodies === "few" ? 0.45 : options.bodies === "crowded" ? 0.05 : 0.2; + const warnings: string[] = []; + if (fullRing < 2) warnings.push("Map is too small for orbits — try Medium or Large."); + let mainworld: [number, number] | undefined; + const paths: ProcPath[] = []; + for (let d = first; d <= last; d++) { + if (rand() < skip) continue; + // Draw the orbit itself: the ring, in order around the star, closed. + if (orbitPathType) { + const around = sortAround(ring(d), center, grid).map((h) => cellKey(h[0], h[1])); + if (around.length > 2) paths.push({ type: orbitPathType, hexes: [...around, around[0]] }); + } + const t = (d - first) / Math.max(1, last - first); + const zone = t < 0.3 ? "inner" : t < 0.6 ? "habitable" : "outer"; + const body = weightedPick(rand, roles.bodies, ZONE_WEIGHTS[zone], 0.5)!; + const hexesOnRing = ring(d); + if (hexesOnRing.length === 0) continue; + if (roles.belt && body === roles.belt) { + // Belts sweep an arc of the ring rather than sitting on one hex. + const start = Math.floor(rand() * hexesOnRing.length); + const span = Math.max(2, Math.floor(hexesOnRing.length * (0.3 + rand() * 0.4))); + const sorted = sortAround(hexesOnRing, center, grid); + for (let i = 0; i < span; i++) set(sorted[(start + i) % sorted.length], body); + continue; + } + const pos = hexesOnRing[Math.floor(rand() * hexesOnRing.length)]; + set(pos, body); + if (zone === "habitable" && !mainworld) mainworld = pos; + // Giants get a moon on a free neighbouring hex. + if (roles.moon && /giant/i.test(body) && rand() < 0.7) { + const free = hexes.filter((h) => distance(h, pos, grid) === 1 + && cells.get(cellKey(h[0], h[1])) === roles.background); + if (free.length) set(free[Math.floor(rand() * free.length)], roles.moon); + } + } + + // Installations beside the mainworld (or the first body if none was habitable). + const anchor = mainworld ?? hexes.find((h) => roles.bodies.includes(cells.get(cellKey(h[0], h[1]))!)); + if (anchor) { + const free = hexes.filter((h) => distance(h, anchor, grid) === 1 + && cells.get(cellKey(h[0], h[1])) === roles.background); + const pickFree = () => free.splice(Math.floor(rand() * free.length), 1)[0]; + if (roles.starport && free.length) set(pickFree(), roles.starport); + if (roles.station && free.length && rand() < 0.5) set(pickFree(), roles.station); + } + + // Out past the last orbit: a jump point and maybe a comet. + const outer = hexes.filter((h) => (dist.get(cellKey(h[0], h[1])) ?? 0) > last + && cells.get(cellKey(h[0], h[1])) === roles.background); + const takeOuter = () => outer.splice(Math.floor(rand() * outer.length), 1)[0]; + if (roles.jumpPoint && outer.length) set(takeOuter(), roles.jumpPoint); + if (roles.comet && outer.length && rand() < 0.6) set(takeOuter(), roles.comet); + if (maxD > last + 1 && outer.length === 0) warnings.push("No room outside the orbits for a jump point."); + + return { cells, paths, warnings }; +} + +/** Order hexes on a ring by angle around the centre, so arcs are contiguous. */ +function sortAround(hexes: [number, number][], center: [number, number], grid: ProcGrid): [number, number][] { + const [cx, cy] = hexCenter(center[0], center[1], grid.orientation, grid.stagger); + const angle = (h: [number, number]) => { + const [px, py] = hexCenter(h[0], h[1], grid.orientation, grid.stagger); + return Math.atan2(py - cy, px - cx); + }; + return [...hexes].sort((a, b) => angle(a) - angle(b)); +} diff --git a/src/worldgen/procedural/starScatter.ts b/src/worldgen/procedural/starScatter.ts new file mode 100644 index 00000000..c72bddb0 --- /dev/null +++ b/src/worldgen/procedural/starScatter.ts @@ -0,0 +1,190 @@ +import { mulberry32 } from "../../../packages/hex-wfc/src"; +import type { TerrainColor } from "../../types"; +import { + cellKey, + distance, + findTerrain, + gridKeys, + inCategory, + weightedPick, + type ProcGrid, + type ProcOption, + type ProcPath, + type ProcResult, +} from "./common"; + +/** + * Sector "star scatter": the classic subsector roll. Each hex holds a star + * system with some probability (standard = 50%, the 4+ on 1d6 rule), typed + * by its mainworld. A few nebula / dust patches thin out the systems inside + * them, rare features (black hole, anomaly, deep-space station) are + * sprinkled in, and nearby systems can be joined by jump routes. + * + * Works on any palette with a background terrain ("empty space" / "void" / + * first `space` terrain) and at least one terrain in the `worlds` category + * (or a "star system" terrain). + */ + +export const STAR_SCATTER_ID = "procedural:star-scatter"; + +export const STAR_SCATTER_OPTIONS: ProcOption[] = [ + { + key: "density", + label: "System density", + choices: [ + { value: "sparse", label: "Sparse (1 in 3)" }, + { value: "standard", label: "Standard (1 in 2)" }, + { value: "dense", label: "Dense (2 in 3)" }, + { value: "cluster", label: "Cluster (5 in 6)" }, + ], + default: "standard", + }, + { + key: "clouds", + label: "Nebulae", + choices: [ + { value: "none", label: "None" }, + { value: "few", label: "A few" }, + { value: "many", label: "Many" }, + ], + default: "few", + }, + { + key: "routes", + label: "Jump routes", + choices: [ + { value: "none", label: "None" }, + { value: "1", label: "Jump-1 (neighbours)" }, + { value: "2", label: "Jump-2" }, + ], + default: "2", + }, +]; + +const DENSITY: Record = { sparse: 1 / 3, standard: 1 / 2, dense: 2 / 3, cluster: 5 / 6 }; + +/** Rough mainworld mix for a habitable-ish sector. Unlisted world terrains weigh 1. */ +const WORLD_WEIGHTS: Record = { + "garden world": 3, + "desert world": 3, + "barren world": 3.5, + "ocean world": 2, + "ice world": 2, + "asteroid belt": 1.5, + "molten world": 1, + "gas giant": 1, +}; + +const FEATURE_WEIGHTS: Record = { + "deep-space station": 3, + anomaly: 2, + "black hole": 1, +}; + +export interface StarScatterRoles { + background: string; + worlds: string[]; + clouds: string[]; + features: string[]; +} + +export function starScatterRoles(terrains: TerrainColor[]): StarScatterRoles | undefined { + const background = findTerrain(terrains, ["empty space", "void", "deep space", "space"], "space"); + let worlds = inCategory(terrains, "worlds"); + if (worlds.length === 0) { + const system = findTerrain(terrains, ["star system", "system", "star"]); + worlds = system ? [system] : []; + } + if (!background || worlds.length === 0) return undefined; + const clouds = inCategory(terrains, "space").filter( + (t) => t !== background && !/rift/i.test(t), + ); + const cloudNames = clouds.length ? clouds : [findTerrain(terrains, ["nebula", "dust cloud"])].filter((t): t is string => !!t); + const features = inCategory(terrains, "features").filter((t) => !/^star system$/i.test(t)); + return { background, worlds, clouds: cloudNames, features }; +} + +export function starScatterFits(terrains: TerrainColor[]): boolean { + return starScatterRoles(terrains) !== undefined; +} + +export function starScatter( + terrains: TerrainColor[], + grid: ProcGrid, + seed: number, + options: Record = {}, + jumpRouteType?: string, +): ProcResult { + const roles = starScatterRoles(terrains); + if (!roles) { + return { cells: new Map(), paths: [], warnings: ["This palette has no space background or world terrains."] }; + } + const rand = mulberry32(seed); + const density = DENSITY[options.density ?? "standard"] ?? 0.5; + const hexes = gridKeys(grid); + const cells = new Map(); + for (const [x, y] of hexes) cells.set(cellKey(x, y), roles.background); + + // Nebula / dust patches: a few blobs grown from random seeds. + const cloudCount = roles.clouds.length === 0 ? 0 + : options.clouds === "none" ? 0 + : Math.max(1, Math.round((hexes.length / 80) * (options.clouds === "many" ? 2.5 : 1))); + const inCloud = new Set(); + for (let c = 0; c < cloudCount; c++) { + const center = hexes[Math.floor(rand() * hexes.length)]; + const radius = 1 + Math.floor(rand() * 2) + (rand() < 0.3 ? 1 : 0); + const terrain = roles.clouds[Math.floor(rand() * roles.clouds.length)]; + for (const h of hexes) { + const d = distance(center, h, grid); + // Ragged edge: the outer ring is only partly filled. + if (d < radius || (d === radius && rand() < 0.45)) { + const k = cellKey(h[0], h[1]); + cells.set(k, terrain); + inCloud.add(k); + } + } + } + + // Systems: one roll per hex; nebulae halve the odds. + const systems: [number, number][] = []; + for (const [x, y] of hexes) { + const k = cellKey(x, y); + const odds = inCloud.has(k) ? density / 2 : density; + if (rand() >= odds) continue; + const roll = rand(); + const feature = roles.features.length > 0 && roll < 0.04 + ? weightedPick(rand, roles.features, FEATURE_WEIGHTS) + : undefined; + cells.set(k, feature ?? weightedPick(rand, roles.worlds, WORLD_WEIGHTS)!); + if (!feature || /station/i.test(feature)) systems.push([x, y]); + } + + // Jump routes: each system links to its nearest neighbour within range. + const paths: ProcPath[] = []; + const range = options.routes === "none" ? 0 : Number(options.routes ?? 2) || 0; + const warnings: string[] = []; + if (range > 0 && systems.length > 1) { + if (!jumpRouteType) { + warnings.push('No "Jump route" path type — routes skipped. Install the Space - Sector preset to add it.'); + } else { + const seen = new Set(); + for (const a of systems) { + let best: [number, number] | undefined; + let bestD = Infinity; + for (const b of systems) { + if (a === b) continue; + const d = distance(a, b, grid); + if (d <= range && d < bestD) { best = b; bestD = d; } + } + if (!best) continue; + const ka = cellKey(a[0], a[1]), kb = cellKey(best[0], best[1]); + const id = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`; + if (seen.has(id)) continue; + seen.add(id); + paths.push({ type: jumpRouteType, hexes: [ka, kb] }); + } + } + } + if (systems.length === 0) warnings.push("No systems rolled — try a higher density or another seed."); + return { cells, paths, warnings }; +} diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts new file mode 100644 index 00000000..006a8535 --- /dev/null +++ b/src/worldgen/registry.ts @@ -0,0 +1,157 @@ +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { TerrainColor } from "../types"; +import { + generateTerrain, + generatorFitsPalette, + listGenerators, + toPathChains, + type GridSpec, +} from "./generators"; +import { findTerrain, type ProcGrid, type ProcOption } from "./procedural/common"; +import { STAR_SCATTER_ID, STAR_SCATTER_OPTIONS, starScatter, starScatterFits } from "./procedural/starScatter"; +import { ORBITS_ID, ORBITS_OPTIONS, orbits, orbitsFits } from "./procedural/orbits"; + +/** + * One list of terrain generators for map creation: Blank, the built-in + * procedural generators (Star scatter, Orbits), and every learned WFC + * generator file. Callers (setup modal, New map tab) only see this + * interface; WFC specifics stay in generators.ts. + */ + +export interface GeneratedPath { + type: string; + route?: string; + hexes: string[]; +} + +export type GenerateOutcome = + | { + ok: true; + cells: Map; + paths: GeneratedPath[]; + featureCells?: Set; + warnings: string[]; + } + | { ok: false; message: string }; + +export interface GenerateRequest { + terrains: TerrainColor[]; + grid: GridSpec; + seed: number; + options: Record; +} + +export interface TerrainGeneratorKind { + id: string; + label: string; + description: string; + source: "blank" | "built-in" | "learned"; + options: ProcOption[]; + /** Can this generator produce terrain for a palette with these terrains? */ + fits(terrains: TerrainColor[]): boolean; + generate(req: GenerateRequest): GenerateOutcome; + /** For learned generators: the generator note (for "Open generator"). */ + generatorPath?: string; + /** Turn generated paths into map path chains (drops unknown path types). */ + toChains(paths: GeneratedPath[]): { chains: { typeName: string; hexes: string[] }[]; missing: string[] }; +} + +export const BLANK_ID = "blank"; + +/** + * The terrain a fresh map shows where nothing has been painted: the space + * background on space palettes ("void" / "empty space"), otherwise none. + */ +export function suggestBaseTerrain(terrains: TerrainColor[]): string | undefined { + return findTerrain(terrains, ["void", "empty space", "deep space"]); +} + +function procGrid(plugin: HexmakerPlugin, grid: GridSpec): ProcGrid { + return { ...grid, orientation: plugin.settings.hexOrientation }; +} + +export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise { + const toChains = (paths: GeneratedPath[]) => toPathChains(plugin, paths); + // Path types for generated routes/orbits. Fall back to the preset names: + // the Space presets add these path types when they are installed, which + // happens during map creation — before the paths are turned into chains. + const pathTypeNamed = (re: RegExp, fallback: string) => + (plugin.settings.pathTypes ?? []).find((t) => re.test(t.name))?.name ?? fallback; + const jumpRoute = pathTypeNamed(/jump route/i, "Jump route"); + const orbitPath = pathTypeNamed(/^orbit$/i, "Orbit"); + + const kinds: TerrainGeneratorKind[] = [ + { + id: BLANK_ID, + label: "Blank", + description: "An empty map to paint by hand.", + source: "blank", + options: [], + fits: () => true, + generate: () => ({ ok: true, cells: new Map(), paths: [], warnings: [] }), + toChains, + }, + { + id: STAR_SCATTER_ID, + label: "Star scatter", + description: "Sector chart: each hex rolls for a star system, typed by its main world; nebulae and jump routes.", + source: "built-in", + options: STAR_SCATTER_OPTIONS, + fits: starScatterFits, + generate: (req) => { + const r = starScatter(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, jumpRoute); + return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; + }, + toChains, + }, + { + id: ORBITS_ID, + label: "Orbits", + description: "Star system: a star at the centre, planets on rings by zone, belts, moons, starport and jump point.", + source: "built-in", + options: ORBITS_OPTIONS, + fits: orbitsFits, + generate: (req) => { + const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitPath); + return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; + }, + toChains, + }, + ]; + + for (const g of await listGenerators(plugin)) { + kinds.push({ + id: `wfc:${g.file.path}`, + label: g.file.basename, + description: "Learned from a painted map.", + source: "learned", + options: [], + generatorPath: g.file.path, + fits: (terrains) => generatorFitsPalette(g.model, terrains.map((t) => t.name)), + generate: (req) => { + const res = generateTerrain(plugin, g.model, req.terrains.map((t) => t.name), req.grid, req.seed); + if (!res.ok) return { ok: false, message: res.message }; + return { ok: true, cells: res.cells, paths: res.paths, featureCells: res.featureCells, warnings: res.warnings }; + }, + toChains: (paths) => toPathChains(plugin, paths, g.model), + }); + } + return kinds; +} + +/** Generators usable with a palette, Blank first. */ +export function kindsForPalette(kinds: TerrainGeneratorKind[], terrains: TerrainColor[]): TerrainGeneratorKind[] { + return kinds.filter((k) => k.fits(terrains)); +} + +/** + * Notes-on-use: should a generated or painted terrain create/update the hex + * note? Not when it's the map's base terrain and the hex has no note yet — + * an absent note already renders as the base terrain. + */ +export function shouldWriteCell(plugin: HexmakerPlugin, mapName: string, key: string, terrain: string): boolean { + const base = plugin.getMap(mapName)?.baseTerrain; + if (!base || terrain !== base) return true; + const [x, y] = key.split("_").map(Number); + return plugin.app.vault.getAbstractFileByPath(plugin.hexPath(x, y, mapName)) !== null; +} diff --git a/styles.css b/styles.css index eec33ba5..96a3dc8d 100644 --- a/styles.css +++ b/styles.css @@ -1805,6 +1805,169 @@ input.duckmage-input-error { background: var(--duckmage-bg, transparent); } +/* ── New map / submap setup modal ───────────────────────────────────── */ +.duckmage-setup-modal { + width: min(860px, 94vw); +} + +.duckmage-setup-layout { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 1em 1.25em; +} + +.duckmage-setup-form { + display: flex; + flex-direction: column; + gap: 0.55em; + min-width: 0; +} + +.duckmage-setup-row { + display: grid; + grid-template-columns: 7.5em minmax(0, 1fr); + align-items: start; + gap: 0.5em; +} + +.duckmage-setup-label { + padding-top: 0.35em; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.duckmage-setup-control { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.4em; + min-width: 0; +} + +.duckmage-setup-name { + flex: 1 1 12em; +} + +.duckmage-setup-size-presets { + display: flex; + gap: 0.25em; +} + +.duckmage-setup-size-presets button.is-active { + background: var(--interactive-accent); + color: var(--text-on-accent); +} + +.duckmage-setup-size-custom { + display: flex; + align-items: center; + gap: 0.25em; +} + +.duckmage-setup-size-custom input { + width: 4.5em; +} + +.duckmage-setup-generators { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(12em, 1fr)); + gap: 0.4em; + width: 100%; + max-height: 15em; + overflow-y: auto; +} + +.duckmage-setup-gen { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.2em; + height: auto; + padding: 0.45em 0.6em; + text-align: left; + white-space: normal; +} + +.duckmage-setup-gen.is-active { + outline: 2px solid var(--interactive-accent); + outline-offset: -2px; +} + +.duckmage-setup-gen-title { + font-weight: var(--font-semibold); +} + +.duckmage-setup-gen-desc { + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +.duckmage-setup-options { + display: flex; + flex-direction: column; + gap: 0.4em; +} + +.duckmage-setup-preview { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.4em; + width: 320px; +} + +.duckmage-setup-canvas { + max-width: 100%; + border-radius: 6px; + background: var(--background-secondary); +} + +.duckmage-setup-seed-row { + display: flex; + align-items: center; + gap: 0.5em; +} + +.duckmage-setup-seed { + color: var(--text-faint); + font-size: var(--font-ui-smaller); + font-family: var(--font-monospace); +} + +.duckmage-setup-status { + color: var(--text-muted); + font-size: var(--font-ui-smaller); + text-align: center; +} + +.duckmage-setup-status.mod-warning { + color: var(--text-warning); +} + +.duckmage-setup-actions { + grid-column: 1 / -1; + display: flex; + justify-content: flex-end; + gap: 0.5em; +} + +.duckmage-submap-new-row, +.duckmage-map-guided-row { + display: flex; + align-items: center; + gap: 0.6em; + margin: 0.4em 0 0.8em; +} + +@media (max-width: 700px) { + .duckmage-setup-layout { + grid-template-columns: 1fr; + } + .duckmage-setup-preview { + width: 100%; + } +} + /* Token modal title row with inline preview */ .duckmage-token-modal-title-row { display: flex; diff --git a/tests/proceduralGenerators.test.ts b/tests/proceduralGenerators.test.ts new file mode 100644 index 00000000..46935012 --- /dev/null +++ b/tests/proceduralGenerators.test.ts @@ -0,0 +1,194 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + SPACE_SECTOR_TERRAINS, + SPACE_SYSTEM_TERRAINS, +} from "../src/palettes/presets"; +import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { starScatter, starScatterFits, starScatterRoles } from "../src/worldgen/procedural/starScatter"; +import { orbits, orbitsFits, orbitRoles } from "../src/worldgen/procedural/orbits"; +import { centerHex, distance, findTerrain, weightedPick, type ProcGrid } from "../src/worldgen/procedural/common"; +import { mulberry32 } from "../packages/hex-wfc/src"; +import { suggestBaseTerrain } from "../src/worldgen/registry"; + +const grid = (cols: number, rows: number, orientation: "flat" | "pointy" = "flat"): ProcGrid => ({ + cols, rows, offset: { x: 0, y: 0 }, stagger: "odd", orientation, +}); + +const count = (cells: Map, pred: (t: string) => boolean) => + [...cells.values()].filter(pred).length; + +describe("procedural helpers", () => { + it("findTerrain matches names case-insensitively, then falls back to a category", () => { + const t = [{ name: "Void", color: "#000", category: "space" }, { name: "x", color: "#111", category: "space" }]; + expect(findTerrain(t, ["void"])).toBe("Void"); + expect(findTerrain(t, ["nothing"], "space")).toBe("Void"); + expect(findTerrain(t, ["nothing"])).toBeUndefined(); + }); + + it("weightedPick honours weights and is deterministic per seed", () => { + const r = mulberry32(1); + const picks = Array.from({ length: 2000 }, () => weightedPick(r, ["a", "b"], { a: 9, b: 1 })); + const a = picks.filter((p) => p === "a").length; + expect(a).toBeGreaterThan(1600); + expect(weightedPick(mulberry32(5), [], {})).toBeUndefined(); + }); + + it("suggests void / empty space as the base terrain", () => { + expect(suggestBaseTerrain(SPACE_SYSTEM_TERRAINS)).toBe("void"); + expect(suggestBaseTerrain(SPACE_SECTOR_TERRAINS)).toBe("empty space"); + expect(suggestBaseTerrain(DEFAULT_TERRAIN_PALETTE)).toBeUndefined(); + }); +}); + +describe("star scatter", () => { + it("fits the sector palette but not fantasy palettes", () => { + expect(starScatterFits(SPACE_SECTOR_TERRAINS)).toBe(true); + expect(starScatterFits(LIMITED_TERRAIN_PALETTE)).toBe(false); + expect(starScatterFits(DEFAULT_TERRAIN_PALETTE)).toBe(false); + }); + + it("resolves roles from the sector preset", () => { + const roles = starScatterRoles(SPACE_SECTOR_TERRAINS)!; + expect(roles.background).toBe("empty space"); + expect(roles.worlds).toContain("garden world"); + expect(roles.clouds).toEqual(expect.arrayContaining(["nebula", "dust cloud"])); + expect(roles.clouds).not.toContain("rift"); + expect(roles.features).not.toContain("star system"); + }); + + it("fills every hex, deterministically for a seed", () => { + const g = grid(8, 10); + const a = starScatter(SPACE_SECTOR_TERRAINS, g, 42); + const b = starScatter(SPACE_SECTOR_TERRAINS, g, 42); + expect(a.cells.size).toBe(80); + expect([...a.cells]).toEqual([...b.cells]); + const c = starScatter(SPACE_SECTOR_TERRAINS, g, 43); + expect([...c.cells]).not.toEqual([...a.cells]); + }); + + it("density changes how many systems roll", () => { + const g = grid(32, 40); + const names = new Set(SPACE_SECTOR_TERRAINS.filter((t) => t.category !== "space").map((t) => t.name)); + const systems = (density: string) => + count(starScatter(SPACE_SECTOR_TERRAINS, g, 7, { density, clouds: "none" }).cells, (t) => names.has(t)); + const sparse = systems("sparse"), standard = systems("standard"), dense = systems("dense"); + expect(sparse).toBeLessThan(standard); + expect(standard).toBeLessThan(dense); + // Standard ≈ half of 1280 hexes. + expect(standard).toBeGreaterThan(1280 * 0.42); + expect(standard).toBeLessThan(1280 * 0.58); + }); + + it("only uses palette terrains", () => { + const names = new Set(SPACE_SECTOR_TERRAINS.map((t) => t.name)); + const r = starScatter(SPACE_SECTOR_TERRAINS, grid(16, 16), 3, { clouds: "many" }); + for (const t of r.cells.values()) expect(names.has(t)).toBe(true); + }); + + it("draws jump routes between systems within range, only when a path type is given", () => { + const g = grid(16, 16); + const without = starScatter(SPACE_SECTOR_TERRAINS, g, 9, { routes: "2" }); + expect(without.paths).toEqual([]); + expect(without.warnings.join(" ")).toMatch(/Jump route/); + + const r = starScatter(SPACE_SECTOR_TERRAINS, g, 9, { routes: "2" }, "Jump route"); + expect(r.paths.length).toBeGreaterThan(0); + for (const p of r.paths) { + expect(p.type).toBe("Jump route"); + const [a, b] = p.hexes.map((k) => k.split("_").map(Number) as [number, number]); + expect(distance(a, b, g)).toBeLessThanOrEqual(2); + } + const none = starScatter(SPACE_SECTOR_TERRAINS, g, 9, { routes: "none" }, "Jump route"); + expect(none.paths).toEqual([]); + }); + + it("works on a minimal custom palette (renamed terrains, categories only)", () => { + const custom = [ + { name: "Black", color: "#000", category: "space" }, + { name: "Haven", color: "#0f0", category: "worlds" }, + ]; + expect(starScatterFits(custom)).toBe(true); + const r = starScatter(custom, grid(6, 6), 1, { density: "dense" }); + expect(new Set(r.cells.values())).toEqual(new Set(["Black", "Haven"])); + }); +}); + +describe("orbits", () => { + it("fits the system palette but not the sector or fantasy palettes", () => { + expect(orbitsFits(SPACE_SYSTEM_TERRAINS)).toBe(true); + expect(orbitsFits(SPACE_SECTOR_TERRAINS)).toBe(false); + expect(orbitsFits(LIMITED_TERRAIN_PALETTE)).toBe(false); + }); + + it("resolves roles from the system preset", () => { + const roles = orbitRoles(SPACE_SYSTEM_TERRAINS)!; + expect(roles.background).toBe("void"); + expect(roles.stars).toHaveLength(5); + expect(roles.bodies).not.toContain("moon"); + expect(roles.belt).toBe("asteroid belt"); + expect(roles.jumpPoint).toBe("jump point"); + }); + + for (const orientation of ["flat", "pointy"] as const) { + it(`puts a star at the centre and bodies on rings (${orientation})`, () => { + const g = grid(13, 13, orientation); + const r = orbits(SPACE_SYSTEM_TERRAINS, g, 11, { bodies: "crowded" }); + expect(r.cells.size).toBe(169); + const [cx, cy] = centerHex(g); + const stars = new Set(orbitRoles(SPACE_SYSTEM_TERRAINS)!.stars); + expect(stars.has(r.cells.get(`${cx}_${cy}`)!)).toBe(true); + // Exactly one star. + expect(count(r.cells, (t) => stars.has(t))).toBe(1); + // Non-belt planets: at most one per ring. + const planets = new Set(["terrestrial planet", "ocean planet", "desert planet", "ice planet", "rocky planet", "molten planet", "gas giant", "ice giant"]); + const ringsUsed = new Map(); + for (const [k, t] of r.cells) { + if (!planets.has(t)) continue; + const d = distance([cx, cy], k.split("_").map(Number) as [number, number], g); + ringsUsed.set(d, (ringsUsed.get(d) ?? 0) + 1); + } + expect(ringsUsed.size).toBeGreaterThan(1); + for (const n of ringsUsed.values()) expect(n).toBe(1); + }); + } + + it("honours a chosen star", () => { + const g = grid(9, 9); + const r = orbits(SPACE_SYSTEM_TERRAINS, g, 5, { star: "blue giant" }); + const [cx, cy] = centerHex(g); + expect(r.cells.get(`${cx}_${cy}`)).toBe("blue giant"); + }); + + it("is deterministic and only uses palette terrains", () => { + const g = grid(13, 13); + const a = orbits(SPACE_SYSTEM_TERRAINS, g, 77); + expect([...a.cells]).toEqual([...orbits(SPACE_SYSTEM_TERRAINS, g, 77).cells]); + const names = new Set(SPACE_SYSTEM_TERRAINS.map((t) => t.name)); + for (const t of a.cells.values()) expect(names.has(t)).toBe(true); + }); + + it("draws each occupied orbit as a closed ring of adjacent hexes when given a path type", () => { + const g = grid(13, 13); + expect(orbits(SPACE_SYSTEM_TERRAINS, g, 21).paths).toEqual([]); + const r = orbits(SPACE_SYSTEM_TERRAINS, g, 21, { bodies: "crowded" }, "Orbit"); + expect(r.paths.length).toBeGreaterThan(1); + const [cx, cy] = centerHex(g); + for (const p of r.paths) { + expect(p.type).toBe("Orbit"); + expect(p.hexes[0]).toBe(p.hexes[p.hexes.length - 1]); + const pts = p.hexes.map((k) => k.split("_").map(Number) as [number, number]); + const d = distance([cx, cy], pts[0], g); + expect(pts.length - 1).toBe(6 * d); // a full ring has 6d hexes + for (let i = 1; i < pts.length; i++) { + expect(distance(pts[i - 1], pts[i], g)).toBe(1); + expect(distance([cx, cy], pts[i], g)).toBe(d); + } + } + }); + + it("warns on maps too small for orbits", () => { + const r = orbits(SPACE_SYSTEM_TERRAINS, grid(3, 3), 1); + expect(r.warnings.join(" ")).toMatch(/too small/); + }); +}); From 86ba9717720efb3ef40cff5496a0f7686f86be8d Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 12:01:15 -0400 Subject: [PATCH 033/558] feat(generator): paths grouped by type, with settings per type The Paths section listed every learned route as its own card, which got long fast (24 routes on a combined generator). Routes are now grouped by path type, most common type first, each group folded by default: - The group header has a checkbox for the whole type (partly ticked when some routes are off; ticking it turns them all back on), how many routes are on, and how many paths were placed. - Amount keeps that share of the type's routes, turning off the ones the example had least of (among those still on); a route turned off this way says so. - Wiggle, Length and Follow terrain on the header multiply every route's own setting. - Open a group to set single routes as before. hex-wfc: new `pathTypes` setting (frontmatter `path-types: Road = keep 0.5, wiggle 1.25; River = off`), resolved into per-route tweaks by effectivePathTweaks() before routing. Co-Authored-By: Claude Opus 5.5 --- packages/hex-wfc/src/format.ts | 32 +++- packages/hex-wfc/src/index.ts | 2 + packages/hex-wfc/src/model.ts | 60 ++++++++ packages/hex-wfc/src/solve.ts | 3 +- src/worldgen/GeneratorPanel.ts | 264 ++++++++++++++++++++++++--------- styles.css | 59 ++++++++ tests/hexWfcPathTweaks.test.ts | 37 +++++ 7 files changed, 385 insertions(+), 72 deletions(-) diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index c703d07f..fe25de9d 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -26,6 +26,7 @@ import { type Symmetry, type CountRange, type PathTweak, + type PathTypeTweak, type TerrainEntry, } from "./model"; @@ -33,7 +34,7 @@ export const FORMAT_VERSION = 1; const MARKER = "hex-wfc"; const EXAMPLE_KEY = "example-hexes"; -type SettingKind = "number" | "string" | "symmetry" | "boolean" | "list" | "mix" | "counts" | "paths"; +type SettingKind = "number" | "string" | "symmetry" | "boolean" | "list" | "mix" | "counts" | "paths" | "pathTypes"; /** Frontmatter key for each saved solver setting. */ export const SETTING_KEYS: Record = { @@ -59,6 +60,7 @@ export const SETTING_KEYS: Record = { features: "features", drawPaths: "draw-paths", paths: "paths", + pathTypes: "path-types", }; const SETTING_KINDS: Record = { @@ -84,6 +86,7 @@ const SETTING_KINDS: Record = { features: "boolean", drawPaths: "boolean", paths: "paths", + pathTypes: "pathTypes", }; const num = (n: number) => String(Math.round(n * 1000) / 1000); @@ -125,6 +128,16 @@ export function encodeSetting(field: keyof GeneratorSettings, value: unknown): s }) .filter((e) => !e.endsWith("= ")) .join("; "); + case "pathTypes": + return Object.entries(value as Record) + .map(([type, t]) => { + const opts: string[] = []; + if (t.off) opts.push("off"); + for (const k of ["keep", "wiggle", "length", "follow"] as const) if (t[k] !== undefined) opts.push(`${k} ${num(t[k])}`); + return `${type} = ${opts.join(", ")}`; + }) + .filter((e) => !e.endsWith("= ")) + .join("; "); default: return String(value); } @@ -201,6 +214,23 @@ export function decodeSetting(field: keyof GeneratorSettings, raw: string): { va } return { value: out }; } + case "pathTypes": { + const out: Record = {}; + for (const item of items()) { + const eq = item.indexOf(" = "); + if (eq < 0) return { error: `has "${item}"; write it like "Road = keep 0.5, wiggle 1.5"` }; + const type = item.slice(0, eq).trim(); + const tweak: PathTypeTweak = {}; + for (const part of item.slice(eq + 3).split(",").map((x) => x.trim()).filter(Boolean)) { + const m = /^(keep|wiggle|length|follow) (\S+)$/.exec(part); + if (part === "off") tweak.off = true; + else if (m && Number.isFinite(Number(m[2])) && Number(m[2]) >= 0) tweak[m[1] as "keep"] = Number(m[2]); + else return { error: `has "${part}" for ${type}; use off, keep N, wiggle N, length N or follow N` }; + } + out[type] = tweak; + } + return { value: out }; + } } } diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index 223137b3..d7a2fa99 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -28,6 +28,8 @@ export { type Symmetry, type CountRange, type PathTweak, + type PathTypeTweak, + effectivePathTweaks, pathRouteKey, } from "./model"; export { mergeModels } from "./merge"; diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index a481ad34..d8810456 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -110,6 +110,63 @@ export interface PathTweak { as?: string; } +/** + * Adjustments to every learned route of one path type (all Roads, say). + * Applied on top of each route's own PathTweak; see effectivePathTweaks(). + */ +export interface PathTypeTweak { + /** Place none of this type. */ + off?: boolean; + /** + * Share of the type's routes to keep (0–1). The routes the example had most + * of are kept; the rest are turned off. Unset = all. + */ + keep?: number; + /** Multipliers on every route's wiggle, length and terrain following. */ + wiggle?: number; + length?: number; + follow?: number; +} + +/** + * Each route's tweak with its path type's settings applied: a type that's off + * turns its routes off, `keep` turns off the least common of the type's + * routes that are still on, and the type's multipliers multiply the route's. + * Routes are grouped by their learned type. + */ +export function effectivePathTweaks( + routes: PathFeature[], + tweaks: Record = {}, + types: Record = {}, +): Record { + const out: Record = {}; + for (const r of routes) { + const key = pathRouteKey(r); + out[key] = { ...(tweaks[key] ?? {}) }; + } + const byType = new Map(); + for (const r of routes) byType.set(r.type, [...(byType.get(r.type) ?? []), r]); + for (const [type, list] of byType) { + const t = types[type]; + if (!t) continue; + for (const r of list) { + const tw = out[pathRouteKey(r)]; + if (t.off) tw.off = true; + for (const k of ["wiggle", "length", "follow"] as const) { + if (t[k] !== undefined) tw[k] = (tw[k] ?? 1) * t[k]; + } + } + if (!t.off && t.keep !== undefined && t.keep < 1) { + const on = list + .filter((r) => !out[pathRouteKey(r)].off) + .sort((a, b) => b.count - a.count || pathRouteKey(a).localeCompare(pathRouteKey(b))); + const kept = t.keep <= 0 ? 0 : Math.max(1, Math.round(t.keep * on.length)); + for (const r of on.slice(kept)) out[pathRouteKey(r)].off = true; + } + } + return out; +} + /** Key that identifies a learned path route, e.g. "Road: edge > peak". */ export function pathRouteKey(p: { type: string; from: string; to: string }): string { return `${p.type}: ${p.from} > ${p.to}`; @@ -178,6 +235,8 @@ export interface GeneratorSettings { drawPaths?: boolean; /** Per-route adjustments, keyed by pathRouteKey(). */ paths?: Record; + /** Per path type adjustments (all Roads, all Rivers), on top of `paths`. */ + pathTypes?: Record; } export const DEFAULT_SETTINGS: Required = { @@ -203,6 +262,7 @@ export const DEFAULT_SETTINGS: Required = { features: true, drawPaths: true, paths: {}, + pathTypes: {}, }; export interface AdjacencyEntry { diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 06c53329..bacbfde1 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -24,6 +24,7 @@ import { hexNeighbors, directionRing, cellKey, parseCellKey, toCellMap, type Orientation, type Stagger } from "./grid"; import { adjacencyLookup, + effectivePathTweaks, resolveSettings, type HexWfcModel, type GeneratorSettings, @@ -251,7 +252,7 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { if (pathsEnabled(model, opts) && model.paths?.length) { const N = grid.cols * grid.rows; const scale = model.exampleHexes ? Math.sqrt(N / model.exampleHexes) : 1; - const routed = routePaths(model.paths, best.cells, grid, mulberry32(opts.seed ^ 0x7f4a7c15), scale, s.paths); + const routed = routePaths(model.paths, best.cells, grid, mulberry32(opts.seed ^ 0x7f4a7c15), scale, effectivePathTweaks(model.paths, s.paths, s.pathTypes)); paths = routed.paths; pathRoutes = routed.routes; best.warnings.push(...routed.warnings); diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 273dbbd1..d9b4a7de 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -40,6 +40,9 @@ import { pathsEnabled, pathRouteKey, type PathTweak, + type PathTypeTweak, + type PathFeature, + effectivePathTweaks, type RouteStat, randomSeed, SYMMETRIES, @@ -68,6 +71,8 @@ export class GeneratorPanel { static seedLocked = false; /** Titles of the setting sections folded away. */ static collapsed = new Set(); + /** Path types whose routes are shown (groups start folded). */ + static openPathTypes = new Set(); /** * The save last loaded. While the page still shows its generator, seed and * size (and no setting has changed), the preview and Create map use the @@ -500,6 +505,8 @@ export class GeneratorPanel { // Path rows (filled in further down) and the last drawn preview, so // hovering a row can redraw it with that route highlighted. const pathRows = new Map(); + /** Each path type's "placed of wanted" total in its group header. */ + const pathGroupPlaced = new Map(); let lastDraw: ((highlight?: string) => void) | null = null; let hoveredRoute: string | undefined; const updatePathRows = (stats: RouteStat[]) => { @@ -516,6 +523,17 @@ export class GeneratorPanel { row.placed.setText(`${st.placed} of ${st.wanted}`); row.placed.toggleClass("is-short", st.placed < st.wanted); } + for (const { el: placedEl, routes } of pathGroupPlaced.values()) { + let placed = 0, wanted = 0; + for (const r of routes) { + const st = byRoute.get(r); + if (!st || !pathsEnabled(model)) continue; + placed += st.placed; + wanted += st.wanted; + } + placedEl.setText(wanted ? `${placed} of ${wanted}` : "Off"); + placedEl.toggleClass("is-short", placed < wanted); + } }; /** The loaded save, while the page shows exactly its generator, seed and size. */ const showingSave = (): GeneratorSave | null => { @@ -823,7 +841,7 @@ export class GeneratorPanel { if (model.paths?.length) { el = this.section(main, "Paths"); el.createEl("p", { - text: "Roads and rivers drawn over the terrain. Count is how many of each route to draw; leave it blank for the learned amount for this map size (drag or scroll on it). Hover a row to highlight its paths on the preview.", + text: "Roads and rivers drawn over the terrain, grouped by type. Each type's checkbox and sliders apply to all its routes; Amount turns off the routes the example had least of. Open a type to set single routes: Count is how many to draw (blank = learned amount for this map size; drag or scroll on it). Hover a route to highlight it on the preview.", cls: "duckmage-map-origin-desc", }); const tweaks: Record = Object.fromEntries(Object.entries(s().paths).map(([k, t]) => [k, { ...t }])); @@ -834,6 +852,16 @@ export class GeneratorPanel { else delete tweaks[route]; save({ paths: Object.keys(tweaks).length ? { ...tweaks } : undefined }); }; + const types: Record = Object.fromEntries(Object.entries(s().pathTypes).map(([k, t]) => [k, { ...t }])); + const effective = () => effectivePathTweaks(model.paths ?? [], tweaks, types); + const saveType = (type: string, patch: Partial) => { + const t: PathTypeTweak = { ...(types[type] ?? {}), ...patch }; + for (const k of Object.keys(t) as (keyof PathTypeTweak)[]) if (t[k] === undefined || t[k] === false) delete t[k]; + if (Object.keys(t).length) types[type] = t; + else delete types[type]; + save({ pathTypes: Object.keys(types).length ? { ...types } : undefined }); + refreshGroups(); + }; const table = el.createDiv({ cls: "duckmage-wfc-paths" }); this.toggle(table, "Draw paths", "", pathsEnabled(model), (v) => { save({ drawPaths: v }); @@ -842,84 +870,180 @@ export class GeneratorPanel { table.toggleClass("is-off", !pathsEnabled(model)); const mapTypes = (this.plugin.settings.pathTypes ?? []).map((t) => t.name); const typeColors = pathColors(this.plugin); - for (const f of model.paths) { - const route = pathRouteKey(f); - const end = (e: string) => (e === "edge" ? "map edge" : e === "path" ? `a ${f.type}` : e === "none" ? "anywhere" : e); - const tw = tweaks[route] ?? {}; - const row = table.createDiv({ cls: "duckmage-wfc-path-row" + (tw.off ? " is-off" : "") }); - row.addEventListener("mouseenter", () => { - hoveredRoute = route; - lastDraw?.(route); - }); - row.addEventListener("mouseleave", () => { - hoveredRoute = undefined; - lastDraw?.(); - }); - - // Line 1: on, name, route, count, becomes, placed - const top = row.createDiv({ cls: "duckmage-wfc-path-top" }); - const on = top.createEl("input", { type: "checkbox", attr: { "aria-label": `Draw ${f.type} (${end(f.from)} to ${end(f.to)})` } }); - on.checked = !tw.off; - on.addEventListener("change", () => { - row.toggleClass("is-off", !on.checked); - saveTweak(route, { off: !on.checked || undefined }); - }); - const name = top.createSpan({ cls: "duckmage-wfc-terrain-name" }); - name.createSpan({ cls: "duckmage-wfc-swatch" }).setCssProps({ - "--duckmage-wfc-swatch": typeColors.get(tw.as ?? f.type) ?? "var(--background-modifier-border)", - }); - name.createSpan({ text: f.type }); - top.createSpan({ text: `${end(f.from)} → ${end(f.to)}`, cls: "duckmage-map-origin-desc duckmage-wfc-path-route" }); - const countWrap = top.createSpan({ cls: "duckmage-wfc-path-count" }); - countWrap.createSpan({ text: "Count", cls: "duckmage-map-origin-label" }); - const count = countWrap.createEl("input", { type: "number", cls: "duckmage-wfc-num", attr: { min: "0", placeholder: "Auto" } }); - count.value = tw.count === undefined ? "" : String(tw.count); - const rowState = { placed: top.createSpan({ cls: "duckmage-wfc-path-placed", text: "–" }), count, auto: 1 }; - makeScrubbable(count, { min: 0, max: 99, pxPerStep: 8, initial: () => rowState.auto }); - count.addEventListener("input", () => { - if (count.hasClass("is-scrubbing")) { - tweaks[route] = { ...(tweaks[route] ?? {}), count: Number(count.value) }; - model.settings = { ...(model.settings ?? {}), paths: { ...tweaks } }; - schedulePreview(); - } - }); - count.addEventListener("change", () => { - saveTweak(route, { count: count.value === "" ? undefined : Math.max(0, Math.floor(Number(count.value) || 0)) }); + // One collapsible group per path type, most common type first. + const byType = new Map(); + for (const f of model.paths) byType.set(f.type, [...(byType.get(f.type) ?? []), f]); + const groupOrder = [...byType].sort((a, b) => + b[1].reduce((n, f) => n + f.count, 0) - a[1].reduce((n, f) => n + f.count, 0) || a[0].localeCompare(b[0])); + const groupRefreshers: (() => void)[] = []; + const refreshGroups = () => groupRefreshers.forEach((r) => r()); + for (const [type, routes] of groupOrder) { + const group = table.createDiv({ cls: "duckmage-wfc-path-group" }); + const open = () => GeneratorPanel.openPathTypes.has(type); + group.toggleClass("is-collapsed", !open()); + const head = group.createDiv({ cls: "duckmage-wfc-path-group-head" }); + const title = head.createDiv({ cls: "duckmage-wfc-path-group-title" }); + const fold = title.createEl("button", { cls: "clickable-icon duckmage-wfc-fold", attr: { "aria-label": `Show ${type} routes` } }); + setIcon(fold, "chevron-down"); + const all = title.createEl("input", { type: "checkbox", attr: { "aria-label": `Draw ${type} paths` } }); + const name = title.createSpan({ cls: "duckmage-wfc-terrain-name" }); + name.createSpan({ cls: "duckmage-wfc-swatch" }).setCssProps({ "--duckmage-wfc-swatch": typeColors.get(type) ?? "var(--background-modifier-border)" }); + name.createSpan({ text: type }); + const summary = title.createSpan({ cls: "duckmage-map-origin-desc duckmage-wfc-path-group-summary" }); + const placedEl = title.createSpan({ cls: "duckmage-wfc-path-placed", text: "–" }); + const toggleOpen = () => { + if (!GeneratorPanel.openPathTypes.delete(type)) GeneratorPanel.openPathTypes.add(type); + group.toggleClass("is-collapsed", !open()); + fold.setAttr("aria-expanded", String(open())); + }; + fold.addEventListener("click", toggleOpen); + name.addEventListener("click", toggleOpen); + all.addEventListener("change", () => { + if (all.checked) { + // Turning a type on also turns its routes back on. + for (const f of routes) { + const key = pathRouteKey(f); + if (tweaks[key]?.off) { + const { off: _off, ...rest } = tweaks[key]; + if (Object.keys(rest).length) tweaks[key] = rest; + else delete tweaks[key]; + } + } + save({ paths: Object.keys(tweaks).length ? { ...tweaks } : undefined }); + saveType(type, { off: undefined }); + } else saveType(type, { off: true }); }); - const asWrap = top.createSpan({ cls: "duckmage-wfc-path-as" }); - asWrap.createSpan({ text: "As", cls: "duckmage-map-origin-label" }); - const asSel = asWrap.createEl("select", { attr: { title: "Path type it is drawn as on the map" } }); - const learnedKnown = mapTypes.includes(f.type); - asSel.createEl("option", { value: "", text: learnedKnown ? f.type : `${f.type} (no such type: skipped)` }); - for (const t of mapTypes) if (t !== f.type) asSel.createEl("option", { value: t, text: t }); - asSel.value = tw.as && mapTypes.includes(tw.as) ? tw.as : ""; - asSel.addEventListener("change", () => saveTweak(route, { as: asSel.value || undefined })); - top.appendChild(rowState.placed); - pathRows.set(route, rowState); - - // Line 2: shape of the route - const knobs = row.createDiv({ cls: "duckmage-wfc-path-knobs" }); - const knob = (label: string, title: string, key: "wiggle" | "length" | "follow", max: number) => { + // Settings for the whole type: how many of its routes, and multipliers + // on every route's own wiggle, length and terrain following. + const knobs = head.createDiv({ cls: "duckmage-wfc-path-knobs duckmage-wfc-path-group-knobs" }); + const amountCell = knobs.createSpan({ cls: "duckmage-wfc-mix", attr: { title: `How many of the ${type} routes to draw. Lower turns off the ones the example had least of.` } }); + amountCell.createSpan({ text: "Amount", cls: "duckmage-map-origin-label" }); + const amount = amountCell.createEl("input", { type: "range", attr: { min: "0", max: "100", step: "5" } }); + amount.value = String(Math.round((types[type]?.keep ?? 1) * 100)); + const amountLabel = amountCell.createSpan(); + const showAmount = () => amountLabel.setText(amount.value === "100" ? "All" : `${amount.value}%`); + showAmount(); + amount.addEventListener("input", showAmount); + amount.addEventListener("change", () => saveType(type, { keep: amount.value === "100" ? undefined : Number(amount.value) / 100 })); + const typeKnob = (label: string, key: "wiggle" | "length" | "follow", title: string) => { const cell = knobs.createSpan({ cls: "duckmage-wfc-mix", attr: { title } }); cell.createSpan({ text: label, cls: "duckmage-map-origin-label" }); - const slider = cell.createEl("input", { type: "range" }); - slider.min = "0"; - slider.max = String(max); - slider.step = "0.25"; - slider.value = String(tw[key] ?? 1); + const slider = cell.createEl("input", { type: "range", attr: { min: "0", max: "3", step: "0.25" } }); + slider.value = String(types[type]?.[key] ?? 1); const valueLabel = cell.createSpan({ text: `×${slider.value}` }); slider.addEventListener("input", () => valueLabel.setText(`×${slider.value}`)); - slider.addEventListener("change", () => { - const v = Number(slider.value); - saveTweak(route, { [key]: v === 1 ? undefined : v }); - }); + slider.addEventListener("change", () => saveType(type, { [key]: Number(slider.value) === 1 ? undefined : Number(slider.value) })); }; - knob("Wiggle", "How much it meanders. 0 = as straight as the terrain allows.", "wiggle", 3); - if (f.to === "none" || f.to === "edge") knob("Length", "How long it runs, relative to the example.", "length", 3); - knob("Follow terrain", "How strongly it keeps to the terrains it ran through in the example. 0 = ignores terrain.", "follow", 3); + typeKnob("Wiggle", "wiggle", `Multiplies every ${type} route's wiggle.`); + if (routes.some((f) => f.to === "none" || f.to === "edge")) typeKnob("Length", "length", `Multiplies every ${type} route's length.`); + typeKnob("Follow terrain", "follow", `Multiplies how strongly every ${type} route keeps to its terrains.`); + + const body = group.createDiv({ cls: "duckmage-wfc-path-group-body" }); + const rowEls: { route: string; row: HTMLElement; on: HTMLInputElement; why: HTMLElement }[] = []; + for (const f of [...routes].sort((a, b) => b.count - a.count || pathRouteKey(a).localeCompare(pathRouteKey(b)))) { + const route = pathRouteKey(f); + const end = (e: string) => (e === "edge" ? "map edge" : e === "path" ? `a ${f.type}` : e === "none" ? "anywhere" : e); + const tw = tweaks[route] ?? {}; + const row = body.createDiv({ cls: "duckmage-wfc-path-row" }); + row.addEventListener("mouseenter", () => { + hoveredRoute = route; + lastDraw?.(route); + }); + row.addEventListener("mouseleave", () => { + hoveredRoute = undefined; + lastDraw?.(); + }); + + // Line 1: on, route, count, becomes, placed + const top = row.createDiv({ cls: "duckmage-wfc-path-top" }); + const on = top.createEl("input", { type: "checkbox", attr: { "aria-label": `Draw ${f.type} (${end(f.from)} to ${end(f.to)})` } }); + on.checked = !tw.off; + on.addEventListener("change", () => { + saveTweak(route, { off: !on.checked || undefined }); + refreshGroups(); + }); + const routeName = top.createSpan({ cls: "duckmage-wfc-terrain-name" }); + routeName.createSpan({ cls: "duckmage-wfc-swatch" }).setCssProps({ + "--duckmage-wfc-swatch": typeColors.get(tw.as ?? f.type) ?? "var(--background-modifier-border)", + }); + routeName.createSpan({ text: `${end(f.from)} → ${end(f.to)}` }); + const why = top.createSpan({ cls: "duckmage-map-origin-desc duckmage-wfc-path-route" }); + + const countWrap = top.createSpan({ cls: "duckmage-wfc-path-count" }); + countWrap.createSpan({ text: "Count", cls: "duckmage-map-origin-label" }); + const count = countWrap.createEl("input", { type: "number", cls: "duckmage-wfc-num", attr: { min: "0", placeholder: "Auto" } }); + count.value = tw.count === undefined ? "" : String(tw.count); + const rowState = { placed: top.createSpan({ cls: "duckmage-wfc-path-placed", text: "–" }), count, auto: 1 }; + makeScrubbable(count, { min: 0, max: 99, pxPerStep: 8, initial: () => rowState.auto }); + count.addEventListener("input", () => { + if (count.hasClass("is-scrubbing")) { + tweaks[route] = { ...(tweaks[route] ?? {}), count: Number(count.value) }; + model.settings = { ...(model.settings ?? {}), paths: { ...tweaks } }; + schedulePreview(); + } + }); + count.addEventListener("change", () => { + saveTweak(route, { count: count.value === "" ? undefined : Math.max(0, Math.floor(Number(count.value) || 0)) }); + }); + + const asWrap = top.createSpan({ cls: "duckmage-wfc-path-as" }); + asWrap.createSpan({ text: "As", cls: "duckmage-map-origin-label" }); + const asSel = asWrap.createEl("select", { attr: { title: "Path type it is drawn as on the map" } }); + const learnedKnown = mapTypes.includes(f.type); + asSel.createEl("option", { value: "", text: learnedKnown ? f.type : `${f.type} (no such type: skipped)` }); + for (const t of mapTypes) if (t !== f.type) asSel.createEl("option", { value: t, text: t }); + asSel.value = tw.as && mapTypes.includes(tw.as) ? tw.as : ""; + asSel.addEventListener("change", () => saveTweak(route, { as: asSel.value || undefined })); + top.appendChild(rowState.placed); + pathRows.set(route, rowState); + + // Line 2: shape of the route + const routeKnobs = row.createDiv({ cls: "duckmage-wfc-path-knobs" }); + const knob = (label: string, title: string, key: "wiggle" | "length" | "follow", max: number) => { + const cell = routeKnobs.createSpan({ cls: "duckmage-wfc-mix", attr: { title } }); + cell.createSpan({ text: label, cls: "duckmage-map-origin-label" }); + const slider = cell.createEl("input", { type: "range" }); + slider.min = "0"; + slider.max = String(max); + slider.step = "0.25"; + slider.value = String(tw[key] ?? 1); + const valueLabel = cell.createSpan({ text: `×${slider.value}` }); + slider.addEventListener("input", () => valueLabel.setText(`×${slider.value}`)); + slider.addEventListener("change", () => { + const v = Number(slider.value); + saveTweak(route, { [key]: v === 1 ? undefined : v }); + }); + }; + knob("Wiggle", "How much it meanders, on top of the type's. 0 = as straight as the terrain allows.", "wiggle", 3); + if (f.to === "none" || f.to === "edge") knob("Length", "How long it runs, relative to the example.", "length", 3); + knob("Follow terrain", "How strongly it keeps to the terrains it ran through in the example. 0 = ignores terrain.", "follow", 3); + rowEls.push({ route, row, on, why }); + } + + // Header checkbox, summary and each row's on/off state, from the + // route settings with the type's applied. + groupRefreshers.push(() => { + const eff = effective(); + const own = rowEls.filter((r) => !tweaks[r.route]?.off).length; + const drawn = rowEls.filter((r) => !eff[r.route]?.off).length; + const typeOff = !!types[type]?.off; + all.checked = !typeOff && own > 0; + all.indeterminate = !typeOff && own > 0 && own < rowEls.length; + group.toggleClass("is-off", drawn === 0); + summary.setText(`${drawn} of ${rowEls.length} route${rowEls.length === 1 ? "" : "s"} on`); + for (const r of rowEls) { + const ownOff = !!tweaks[r.route]?.off; + const byType = !ownOff && !!eff[r.route]?.off; + r.on.checked = !ownOff; + r.row.toggleClass("is-off", ownOff || byType); + r.why.setText(byType ? (typeOff ? `off: all ${type} off` : `off: ${type} amount`) : ""); + } + }); + pathGroupPlaced.set(type, { el: placedEl, routes: rowEls.map((r) => r.route) }); } + refreshGroups(); } diff --git a/styles.css b/styles.css index 4a39a65d..4a12982a 100644 --- a/styles.css +++ b/styles.css @@ -5608,3 +5608,62 @@ button.duckmage-wfc-library-tab.is-active { gap: 0.25em 1em; margin-top: 0.35em; } + +/* One group per path type: a header with the type's checkbox, summary and + sliders for all its routes, and the routes themselves (folded by default). */ +.duckmage-wfc-path-group { + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + overflow: hidden; +} + +.duckmage-wfc-path-group-head { + padding: 0.4em 0.6em; + background: var(--background-secondary); +} + +.duckmage-wfc-path-group-title { + display: flex; + align-items: center; + gap: 0.5em; +} + +.duckmage-wfc-path-group-title .duckmage-wfc-terrain-name { + font-weight: 600; + cursor: pointer; +} + +.duckmage-wfc-path-group-summary { + flex: 1; + margin: 0; +} + +.duckmage-wfc-path-group-title .duckmage-wfc-fold { + padding: 0.15em; + height: auto; +} + +.duckmage-wfc-path-group.is-collapsed .duckmage-wfc-path-group-title .duckmage-wfc-fold { + transform: rotate(-90deg); +} + +.duckmage-wfc-path-group.is-collapsed .duckmage-wfc-path-group-body { + display: none; +} + +.duckmage-wfc-path-group.is-off .duckmage-wfc-path-group-knobs, +.duckmage-wfc-path-group.is-off .duckmage-wfc-path-group-title .duckmage-wfc-terrain-name { + opacity: 0.45; +} + +/* In a group the route name is its own span; the note (why it's off) takes + only the space left over, so it never pushes the placed count down. */ +.duckmage-wfc-path-group-body .duckmage-wfc-path-route { + min-width: 0; +} + +.duckmage-wfc-path-group-body { + display: grid; + gap: 0.4em; + padding: 0.4em 0.6em 0.6em 1.6em; +} diff --git a/tests/hexWfcPathTweaks.test.ts b/tests/hexWfcPathTweaks.test.ts index da7e00c7..c48f3237 100644 --- a/tests/hexWfcPathTweaks.test.ts +++ b/tests/hexWfcPathTweaks.test.ts @@ -3,6 +3,7 @@ import expect from "expect"; import { cellKey, decodeSetting, + effectivePathTweaks, encodeSetting, hexNeighbors, learnModel, @@ -135,3 +136,39 @@ describe("wheelValue", () => { expect(wheelValue(9, -100, { min: 0, max: 9 })).toBe(9); }); }); + +describe("path type settings", () => { + const route = (type: string, to: string, count: number) => ({ type, from: "edge", to, count, turn: 0.2, length: 0.5, through: {} }); + const routes = [route("Road", "town", 3), route("Road", "peak", 1), route("Road", "lake", 2), route("River", "sea", 1)]; + const key = (type: string, to: string) => pathRouteKey({ type, from: "edge", to }); + + it("turning a type off turns off its routes only", () => { + const t = effectivePathTweaks(routes, {}, { Road: { off: true } }); + expect([t[key("Road", "town")].off, t[key("Road", "peak")].off, t[key("River", "sea")].off]).toEqual([true, true, undefined]); + }); + + it("keep turns off the type's least common routes, among those still on", () => { + const half = effectivePathTweaks(routes, {}, { Road: { keep: 0.5 } }); + // 3 roads: keep round(1.5) = 2, the two most common (town 3, lake 2). + expect([half[key("Road", "town")].off, half[key("Road", "lake")].off, half[key("Road", "peak")].off]).toEqual([undefined, undefined, true]); + // With town turned off by hand, keep 0.5 of the remaining two = lake. + const manual = effectivePathTweaks(routes, { [key("Road", "town")]: { off: true } }, { Road: { keep: 0.5 } }); + expect([manual[key("Road", "lake")].off, manual[key("Road", "peak")].off]).toEqual([undefined, true]); + // Keeping something always keeps at least one route. + expect(Object.values(effectivePathTweaks(routes, {}, { Road: { keep: 0.01 } })).filter((t) => !t.off)).toHaveLength(2); + }); + + it("type multipliers multiply each route's own", () => { + const t = effectivePathTweaks(routes, { [key("Road", "town")]: { wiggle: 2, count: 4 } }, { Road: { wiggle: 0.5, length: 1.5 } }); + expect(t[key("Road", "town")]).toEqual({ wiggle: 1, count: 4, length: 1.5 }); + expect(t[key("Road", "peak")]).toEqual({ wiggle: 0.5, length: 1.5 }); + expect(t[key("River", "sea")]).toEqual({}); + }); + + it("round-trip through the file", () => { + const types = { Road: { keep: 0.5, wiggle: 1.25 }, "Old river": { off: true, follow: 0 } }; + const back = decodeSetting("pathTypes", String(encodeSetting("pathTypes", types))); + expect(back).toEqual({ value: types }); + expect(decodeSetting("pathTypes", "Road = sometimes")).toHaveProperty("error"); + }); +}); From bd0bee828189863fe5f4e19425ba50965144fad8 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 12:07:19 -0400 Subject: [PATCH 034/558] fix(paths): rivers hugged and crossed the coast; add "avoid impassable" per path type Two causes, measured on bay-area-and-the-coast over 20 seeds (dev/wfc-river-shore.mts): 22.7% of river hexes ran next to water and 28.8% ran on it. - Routes are costed per hex by how much more often the example's path ran through that terrain than it covers the map. Uncapped, a terrain that is rare on the map but common under the example's rivers (grass, often a strip along the coast) became nearly free, so routes took long detours along it. The preference is now capped (at most ~5x cheaper or dearer at Follow terrain x1). - Routes ignored impassable terrain, so rivers ran over the sea and started on sea-covered map edges. Each path type now has "Avoid impassable terrain", on by default: its paths never start, run or end on terrain marked impassable (Guarantees), except where an end is that terrain (a river into the shallows). Turning it off is stored as `path-types: River = cross-impassable`. After: 18.0% next to water (land overall: 24.8%) and 2.1% on water (river mouths). Fewer routes fit where land is cut up by water; those report as not placed. Co-Authored-By: Claude Opus 5.5 --- dev/wfc-river-shore.mts | 41 +++++++++++++++++++++++++++++++++ packages/hex-wfc/src/format.ts | 4 +++- packages/hex-wfc/src/model.ts | 8 +++++++ packages/hex-wfc/src/paths.ts | 40 +++++++++++++++++++++++++------- packages/hex-wfc/src/solve.ts | 2 +- src/worldgen/GeneratorPanel.ts | 15 ++++++++++++ tests/hexWfcPathTweaks.test.ts | 42 ++++++++++++++++++++++++++++++++++ 7 files changed, 142 insertions(+), 10 deletions(-) create mode 100644 dev/wfc-river-shore.mts diff --git a/dev/wfc-river-shore.mts b/dev/wfc-river-shore.mts new file mode 100644 index 00000000..3912e7cb --- /dev/null +++ b/dev/wfc-river-shore.mts @@ -0,0 +1,41 @@ +// How much generated paths hug water: share of path hexes next to a water +// hex, and share on water, over many seeds of a vault generator. Read-only. +// Usage (from WSL, plugin root): +// VAULT=/mnt/c/.../journal npx tsx dev/wfc-river-shore.mts [type] [seeds] +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { parseModelMarkdown, solve, hexNeighbors, cellKey, parseCellKey } from "../packages/hex-wfc/src"; + +const vault = process.env.VAULT ?? join(process.cwd(), "../../../.."); +const data = JSON.parse(readFileSync(join(vault, ".obsidian/plugins/duckmage-plugin/data.json"), "utf8")); +const world = String(data.worldFolder ?? "").replace(/^\/+|\/+$/g, ""); +const name = process.argv[2] ?? "bay-area-and-the-coast"; +const type = process.argv[3] ?? "River"; +const seeds = Number(process.argv[4] ?? 20); +const parsed = parseModelMarkdown(readFileSync(join(vault, world, "generators", `${name}.md`), "utf8")); +const model = "model" in parsed ? parsed.model : (parsed as never); +const water = new Set(["shallows", "ocean", "trench", "water"]); +const orientation = data.hexOrientation ?? "flat", stagger = data.staggerOffset ?? "odd"; +let hexes = 0, nearWater = 0, onWater = 0, paths = 0, land = 0, landNearWater = 0; +// IMPASSABLE=none routes without blocking water (to compare). +const impassable = process.env.IMPASSABLE === "none" ? [] : [...water]; +for (let seed = 1; seed <= seeds; seed++) { + const r = solve(model, { cols: 38, rows: 25, orientation, stagger, seed, impassable }); + if (!r.ok) continue; + for (const [h, t] of r.cells) { + if (water.has(t)) continue; + land++; + const [x, y] = parseCellKey(h)!; + if (hexNeighbors(x, y, orientation, stagger).some(([nx, ny]) => water.has(r.cells.get(cellKey(nx, ny)) ?? ""))) landNearWater++; + } + for (const p of r.paths.filter((p) => p.type === type)) { + paths++; + for (const h of p.hexes) { + const [x, y] = parseCellKey(h)!; + hexes++; + if (water.has(r.cells.get(h) ?? "")) onWater++; + else if (hexNeighbors(x, y, orientation, stagger).some(([nx, ny]) => water.has(r.cells.get(cellKey(nx, ny)) ?? ""))) nearWater++; + } + } +} +console.log(`${name} ${type}: ${paths} paths, ${hexes} hexes; next to water ${(100 * nearWater / hexes).toFixed(1)}%, on water ${(100 * onWater / hexes).toFixed(1)}%, avg length ${(hexes / paths).toFixed(1)}; land next to water overall ${(100 * landNearWater / land).toFixed(1)}%`); diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index fe25de9d..390fa40d 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -133,6 +133,7 @@ export function encodeSetting(field: keyof GeneratorSettings, value: unknown): s .map(([type, t]) => { const opts: string[] = []; if (t.off) opts.push("off"); + if (t.crossImpassable) opts.push("cross-impassable"); for (const k of ["keep", "wiggle", "length", "follow"] as const) if (t[k] !== undefined) opts.push(`${k} ${num(t[k])}`); return `${type} = ${opts.join(", ")}`; }) @@ -224,8 +225,9 @@ export function decodeSetting(field: keyof GeneratorSettings, raw: string): { va for (const part of item.slice(eq + 3).split(",").map((x) => x.trim()).filter(Boolean)) { const m = /^(keep|wiggle|length|follow) (\S+)$/.exec(part); if (part === "off") tweak.off = true; + else if (part === "cross-impassable") tweak.crossImpassable = true; else if (m && Number.isFinite(Number(m[2])) && Number(m[2]) >= 0) tweak[m[1] as "keep"] = Number(m[2]); - else return { error: `has "${part}" for ${type}; use off, keep N, wiggle N, length N or follow N` }; + else return { error: `has "${part}" for ${type}; use off, cross-impassable, keep N, wiggle N, length N or follow N` }; } out[type] = tweak; } diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index d8810456..9c42257a 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -108,6 +108,8 @@ export interface PathTweak { follow?: number; /** Path type to draw it as on the map, instead of its learned type. */ as?: string; + /** May cross impassable terrain. Set from its path type (PathTypeTweak). */ + crossImpassable?: boolean; } /** @@ -122,6 +124,11 @@ export interface PathTypeTweak { * of are kept; the rest are turned off. Unset = all. */ keep?: number; + /** + * Let this type's paths cross impassable terrain. By default they never + * start, run or end on it, except where an end is that terrain itself. + */ + crossImpassable?: boolean; /** Multipliers on every route's wiggle, length and terrain following. */ wiggle?: number; length?: number; @@ -152,6 +159,7 @@ export function effectivePathTweaks( for (const r of list) { const tw = out[pathRouteKey(r)]; if (t.off) tw.off = true; + if (t.crossImpassable) tw.crossImpassable = true; for (const k of ["wiggle", "length", "follow"] as const) { if (t[k] !== undefined) tw[k] = (tw[k] ?? 1) * t[k]; } diff --git a/packages/hex-wfc/src/paths.ts b/packages/hex-wfc/src/paths.ts index 35431320..16535f6c 100644 --- a/packages/hex-wfc/src/paths.ts +++ b/packages/hex-wfc/src/paths.ts @@ -39,6 +39,14 @@ export interface RouteStat { } const MIN_PATH_HEXES = 3; +/** + * Cap on how much a path prefers or avoids a terrain (log of how much more + * often the example's path ran through it than it covers the map). Uncapped, + * a terrain that's rare on the map but common under the example's paths + * became nearly free to cross, so rivers ran long detours along a thin strip + * of it (a coast). At 1.2 a favoured terrain is at most ~5x cheaper. + */ +const PREF_CAP = 1.2; /** Remove consecutive duplicates (repeat clicks). */ function clean(hexes: string[]): string[] { @@ -145,6 +153,8 @@ export function routePaths( rng: () => number, sizeScale: number, tweaks: Record = {}, + /** Terrains paths may not cross unless their tweak says crossImpassable. */ + impassable: string[] = [], ): { paths: PathOutput[]; warnings: string[]; routes: RouteStat[] } { const { cols, rows, ox, oy, orientation, stagger } = grid; const N = cols * rows; @@ -157,6 +167,7 @@ export function routePaths( nbr.push(hexNeighbors(x, y, orientation, stagger).filter(([nx, ny]) => inGrid(nx, ny)).map(([nx, ny]) => idx(nx, ny))); } const terrainOf = (c: number) => cells.get(keyOf(c)) ?? ""; + const impassableSet = new Set(impassable); const share = new Map(); for (const t of cells.values()) share.set(t, (share.get(t) ?? 0) + 1 / N); const border = (c: number) => { @@ -182,8 +193,8 @@ export function routePaths( return all; }; - /** Cheapest route from `start` to the nearest target, avoiding `taken` (no braids). */ - const dijkstra = (cost: Float64Array, start: number, targets: Set, taken: Set): number[] | null => { + /** Cheapest route from `start` to the nearest target, avoiding `taken` (no braids) and `blocked` hexes. */ + const dijkstra = (cost: Float64Array, start: number, targets: Set, taken: Set, blocked: Uint8Array | null): number[] | null => { const dist = new Float64Array(N).fill(Infinity); const prev = new Int32Array(N).fill(-1); const heap = new MinHeap(); @@ -199,6 +210,7 @@ export function routePaths( } for (const n of nbr[c]) { if (taken.has(n) && !targets.has(n)) continue; + if (blocked?.[n] && !targets.has(n)) continue; const nd = d + cost[n]; if (nd < dist[n]) { dist[n] = nd; @@ -210,8 +222,11 @@ export function routePaths( return null; }; - const routeOne = (f: PathFeature, cost: Float64Array, taken: Set): number[] | null => { - const starts = candidates(f.from, taken, null).filter((c) => f.from === "path" || !taken.has(c)); + const routeOne = (f: PathFeature, cost: Float64Array, taken: Set, blocked: Uint8Array | null): number[] | null => { + // An end on impassable terrain is only allowed when that terrain is the + // anchor itself (a river that ends in the shallows). + const endOk = (anchor: string) => (c: number) => !blocked?.[c] || terrainOf(c) === anchor; + const starts = candidates(f.from, taken, null).filter((c) => (f.from === "path" || !taken.has(c)) && endOk(f.from)(c)); if (!starts.length) return null; // A few random starts; keep the cheapest. let start = starts[Math.floor(rng() * starts.length)]; @@ -226,12 +241,13 @@ export function routePaths( const sx = ox + (start % cols), sy = oy + Math.floor(start / cols); const atLength: number[] = []; for (let c = 0; c < N; c++) { + if (blocked?.[c]) continue; const d = hexDistance([sx, sy], [ox + (c % cols), oy + Math.floor(c / cols)], orientation, stagger); if (Math.abs(d - want) <= 1) atLength.push(c); } targets = new Set(atLength.length ? [atLength[Math.floor(rng() * atLength.length)]] : []); } else { - targets = new Set(candidates(f.to, taken, f.to === "edge" ? startSide : null)); + targets = new Set(candidates(f.to, taken, f.to === "edge" ? startSide : null).filter(endOk(f.to))); // Edge-to-edge: don't let it cut a corner; it should run at least most // of the learned length. if (f.to === "edge") { @@ -246,7 +262,7 @@ export function routePaths( if (f.to !== "path") for (const c of taken) targets.delete(c); targets.delete(start); if (!targets.size) return null; - const route = dijkstra(cost, start, targets, taken); + const route = dijkstra(cost, start, targets, taken, blocked); return route && route.length >= MIN_PATH_HEXES ? route : null; }; @@ -264,7 +280,8 @@ export function routePaths( const follow = tw.follow ?? 1; // Cheap on terrains the example's path ran through (relative to how // common they are), plus smooth noise so routes wiggle like the example. - const pref = (t: string) => follow * Math.log(((f.through[t] ?? 0) + 0.01) / ((share.get(t) ?? 0) + 0.01)); + const pref = (t: string) => + follow * Math.max(-PREF_CAP, Math.min(PREF_CAP, Math.log(((f.through[t] ?? 0) + 0.01) / ((share.get(t) ?? 0) + 0.01)))); const noiseAmp = (0.5 + 3 * f.turn) * (tw.wiggle ?? 1); const phase = [rng(), rng(), rng()].map((v) => v * Math.PI * 2); const freq = 0.6 + rng() * 0.6; @@ -275,6 +292,13 @@ export function routePaths( cost[c] = Math.max(0.05, 1.5 - pref(terrainOf(c)) + noiseAmp * (0.5 + 0.5 * noise)); } + // Impassable hexes this route may not cross (unless it's allowed to). + let blocked: Uint8Array | null = null; + if (impassableSet.size && !tw.crossImpassable) { + blocked = new Uint8Array(N); + for (let c = 0; c < N; c++) if (impassableSet.has(terrainOf(c))) blocked[c] = 1; + } + const auto = Math.max(1, Math.round(f.count * sizeScale)); const count = tw.off ? 0 : Math.max(0, Math.round(tw.count ?? auto)); const stat: RouteStat = { route, auto, wanted: count, placed: 0 }; @@ -284,7 +308,7 @@ export function routePaths( takenByType.set(f.type, taken); let made = 0; for (let k = 0; k < count; k++) { - const path = routeOne(f, cost, taken); + const path = routeOne(f, cost, taken, blocked); if (!path) continue; out.push({ type: f.type, route: stat.route, hexes: path.map(keyOf) }); for (const c of path) taken.add(c); diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index bacbfde1..24b012cd 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -252,7 +252,7 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { if (pathsEnabled(model, opts) && model.paths?.length) { const N = grid.cols * grid.rows; const scale = model.exampleHexes ? Math.sqrt(N / model.exampleHexes) : 1; - const routed = routePaths(model.paths, best.cells, grid, mulberry32(opts.seed ^ 0x7f4a7c15), scale, effectivePathTweaks(model.paths, s.paths, s.pathTypes)); + const routed = routePaths(model.paths, best.cells, grid, mulberry32(opts.seed ^ 0x7f4a7c15), scale, effectivePathTweaks(model.paths, s.paths, s.pathTypes), s.impassable); paths = routed.paths; pathRoutes = routed.routes; best.warnings.push(...routed.warnings); diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index d9b4a7de..95c4a446 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -939,6 +939,21 @@ export class GeneratorPanel { typeKnob("Wiggle", "wiggle", `Multiplies every ${type} route's wiggle.`); if (routes.some((f) => f.to === "none" || f.to === "edge")) typeKnob("Length", "length", `Multiplies every ${type} route's length.`); typeKnob("Follow terrain", "follow", `Multiplies how strongly every ${type} route keeps to its terrains.`); + // Guarantee: never over impassable terrain (on unless turned off). + const impassableList = s().impassable; + const avoid = knobs.createEl("label", { + cls: "duckmage-wfc-toggle duckmage-wfc-path-avoid", + attr: { + title: impassableList.length + ? `${type} paths never start, run or end on ${impassableList.join(", ")}, except where an end is that terrain (a river into the shallows). Set the list under Guarantees.` + : "No terrain is marked impassable yet (Guarantees, Impassable terrain).", + }, + }); + const avoidBox = avoid.createEl("input", { type: "checkbox" }); + avoidBox.checked = !types[type]?.crossImpassable; + avoidBox.disabled = !impassableList.length; + avoid.createSpan({ text: "Avoid impassable terrain" }); + avoidBox.addEventListener("change", () => saveType(type, { crossImpassable: avoidBox.checked ? undefined : true })); const body = group.createDiv({ cls: "duckmage-wfc-path-group-body" }); const rowEls: { route: string; row: HTMLElement; on: HTMLInputElement; why: HTMLElement }[] = []; diff --git a/tests/hexWfcPathTweaks.test.ts b/tests/hexWfcPathTweaks.test.ts index c48f3237..6131bda8 100644 --- a/tests/hexWfcPathTweaks.test.ts +++ b/tests/hexWfcPathTweaks.test.ts @@ -10,6 +10,8 @@ import { modelToMarkdown, parseModelMarkdown, pathRouteKey, + routePaths, + mulberry32, pathsEnabled, solve, type HexWfcModel, @@ -172,3 +174,43 @@ describe("path type settings", () => { expect(decodeSetting("pathTypes", "Road = sometimes")).toHaveProperty("error"); }); }); + +describe("paths and impassable terrain", () => { + // 20x12: land, with a 2-wide lake running top to bottom down the middle + // except a land bridge on rows 0-1. + const cols = 20, rows = 12; + const cells = new Map(); + for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) cells.set(cellKey(x, y), (x === 9 || x === 10) && y > 1 ? "water" : "grass"); + const grid = { cols, rows, ox: 0, oy: 0, orientation: "flat" as const, stagger: "odd" as const }; + const road = { type: "Road", from: "edge", to: "edge", count: 4, turn: 0.2, length: 1, through: { grass: 1 } }; + const onWater = (paths: { hexes: string[] }[]) => paths.flatMap((p) => p.hexes).filter((h) => cells.get(h) === "water").length; + + it("never cross it by default, going round instead", () => { + const r = routePaths([road], cells, grid, mulberry32(3), 1, {}, ["water"]); + expect(r.paths.length).toBeGreaterThan(0); + expect(onWater(r.paths)).toBe(0); + }); + + it("may cross it when the type allows", () => { + // A route that likes water: only the guarantee keeps it off. + const wet = { ...road, through: { water: 1 } }; + expect(onWater(routePaths([wet], cells, grid, mulberry32(3), 1, {}, ["water"]).paths)).toBe(0); + const tweaks = effectivePathTweaks([wet], {}, { Road: { crossImpassable: true } }); + expect(onWater(routePaths([wet], cells, grid, mulberry32(3), 1, tweaks, ["water"]).paths)).toBeGreaterThan(0); + }); + + it("can still end in it when that terrain is the end (a river into a lake)", () => { + const river = { type: "River", from: "edge", to: "water", count: 2, turn: 0.2, length: 0.5, through: { grass: 1 } }; + const r = routePaths([river], cells, grid, mulberry32(5), 1, {}, ["water"]); + expect(r.paths.length).toBeGreaterThan(0); + for (const p of r.paths) { + expect(cells.get(p.hexes[p.hexes.length - 1])).toBe("water"); + expect(p.hexes.slice(0, -1).every((h) => cells.get(h) !== "water")).toBe(true); + } + }); + + it("round-trips the type setting", () => { + const back = decodeSetting("pathTypes", String(encodeSetting("pathTypes", { River: { crossImpassable: true, keep: 0.5 } }))); + expect(back).toEqual({ value: { River: { crossImpassable: true, keep: 0.5 } } }); + }); +}); From 2fef9b62213da3fd52dcc050984234019c0a02cd Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 12:11:21 -0400 Subject: [PATCH 035/558] feat(map list): right-click opens a region's existing generator Right-clicking a region in the map list offered only "Create generator", which learned another copy every time (the-coast had 7). If the region already has a generator, the menu now leads with "Open generator ", which jumps to it on the generator page; "Learn a new generator" stays below it. The match prefers a generator learned from that region alone, newest first, before combined ones (generatorsForRegion). Co-Authored-By: Claude Opus 5.5 --- src/hex-map/MapModal.ts | 41 +++++++++++++++++++++++++------- src/worldgen/generators.ts | 15 ++++++++++++ tests/worldgenGenerators.test.ts | 17 +++++++++++++ 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index f532d26a..c112cbca 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -12,6 +12,7 @@ import { listGenerators, generatorFitsPalette, saveGeneratorFromMap, + generatorsForRegion, generateTerrain, paletteColors, pathColors, @@ -277,14 +278,28 @@ export class MapModal extends HexmakerModal { }); li.addEventListener("contextmenu", (e: MouseEvent) => { e.preventDefault(); - const menu = new Menu(); - menu.addItem((item) => - item - .setTitle(`Create generator from ${map.name}`) - .setIcon("wand-sparkles") - .onClick(() => void this.createGeneratorFrom(map.name)), - ); - menu.showAtMouseEvent(e); + const at = { x: e.clientX, y: e.clientY }; + // A region that already has a generator opens it; learning another + // stays available below. + void listGenerators(this.plugin).then((all) => { + const existing = generatorsForRegion(all, map.name)[0]; + const menu = new Menu(); + if (existing) { + menu.addItem((item) => + item + .setTitle(`Open generator "${existing.model.name}"`) + .setIcon("wand-sparkles") + .onClick(() => void this.openGenerator(map.name, existing)), + ); + } + menu.addItem((item) => + item + .setTitle(existing ? `Learn a new generator from ${map.name}` : `Create generator from ${map.name}`) + .setIcon(existing ? "plus" : "wand-sparkles") + .onClick(() => void this.createGeneratorFrom(map.name)), + ); + menu.showAtPosition(at); + }); }); if (isConfirming) { @@ -796,6 +811,16 @@ export class MapModal extends HexmakerModal { }); } + /** Open a region's existing generator in the terrain generator. */ + private async openGenerator(mapName: string, g: GeneratorFile): Promise { + this.close(); + await this.plugin.openTerrainGenerator({ + mapName, + generatorPath: g.file.path, + paletteName: g.model.meta.palette, + }); + } + // ── Delete ──────────────────────────────────────────────────────────────── private async deleteMap(name: string): Promise { diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index e5292d31..37fa2ffc 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -170,6 +170,21 @@ export function sourceInfluenceOf(model: HexWfcModel): number[] | undefined { return list.reduce((n, v) => n + v, 0) > 0 ? list : undefined; } +/** + * Generators learned from a region, best match first: ones learned from it + * alone before combined ones, then newest, then by name. + */ +export function generatorsForRegion(generators: GeneratorFile[], mapName: string): GeneratorFile[] { + return generators + .filter((g) => sourceMapsOf(g.model).includes(mapName)) + .sort( + (a, b) => + sourceMapsOf(a.model).length - sourceMapsOf(b.model).length || + (b.model.meta.created ?? "").localeCompare(a.model.meta.created ?? "") || + a.model.name.localeCompare(b.model.name), + ); +} + /** How many painted hexes each region has (what influence defaults to). */ export function regionSizes(plugin: HexmakerPlugin, mapNames: string[]): number[] { return mapNames.map((m) => readMapTerrain(plugin, m).size); diff --git a/tests/worldgenGenerators.test.ts b/tests/worldgenGenerators.test.ts index 961ac2f2..a45fe351 100644 --- a/tests/worldgenGenerators.test.ts +++ b/tests/worldgenGenerators.test.ts @@ -9,6 +9,7 @@ import { readLockedHexes, saveGeneratorFromMap, sourceMapsOf, + generatorsForRegion, saveGeneratorSettings, generateTerrain, fillMap, @@ -271,3 +272,19 @@ describe("generator source regions", () => { expect(sourceMapsOf(model({}))).toEqual([]); }); }); + +describe("a region's generators", () => { + const gen = (name: string, meta: Record) => + ({ file: { path: `g/${name}.md` }, model: { name, terrains: [], adjacency: [], meta }, warnings: [] }) as unknown as Parameters[0][number]; + const all = [ + gen("combo", { "source-maps": "the-coast + the-north", created: "2026-10-09" }), + gen("the-coast", { "source-map": "the-coast", created: "2026-10-01" }), + gen("the-coast-2", { "source-map": "the-coast", created: "2026-10-05" }), + gen("north", { "source-map": "the-north" }), + ]; + it("prefers one learned from the region alone, newest first, then combined ones", () => { + expect(generatorsForRegion(all, "the-coast").map((g) => g.model.name)).toEqual(["the-coast-2", "the-coast", "combo"]); + expect(generatorsForRegion(all, "the-north").map((g) => g.model.name)).toEqual(["north", "combo"]); + expect(generatorsForRegion(all, "island")).toEqual([]); + }); +}); From af74f558ce5b45a4d34cd0c331c8680d937267ad Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 12:12:58 -0400 Subject: [PATCH 036/558] fix(map list): open the newest of same-day generators Generators record only the date they were made, so same-day ones fell back to name order (the-coast-4 over the-coast-7). Ties now go by the file's creation time. Co-Authored-By: Claude Opus 5.5 --- src/worldgen/generators.ts | 2 ++ tests/worldgenGenerators.test.ts | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index 37fa2ffc..d7212c54 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -181,6 +181,8 @@ export function generatorsForRegion(generators: GeneratorFile[], mapName: string (a, b) => sourceMapsOf(a.model).length - sourceMapsOf(b.model).length || (b.model.meta.created ?? "").localeCompare(a.model.meta.created ?? "") || + // `created` is a date only; same-day ones go by when the file was made. + (b.file.stat?.ctime ?? 0) - (a.file.stat?.ctime ?? 0) || a.model.name.localeCompare(b.model.name), ); } diff --git a/tests/worldgenGenerators.test.ts b/tests/worldgenGenerators.test.ts index a45fe351..9c271989 100644 --- a/tests/worldgenGenerators.test.ts +++ b/tests/worldgenGenerators.test.ts @@ -287,4 +287,13 @@ describe("a region's generators", () => { expect(generatorsForRegion(all, "the-north").map((g) => g.model.name)).toEqual(["north", "combo"]); expect(generatorsForRegion(all, "island")).toEqual([]); }); + + it("breaks same-day ties by when the file was made", () => { + const made = (name: string, ctime: number) => { + const g = gen(name, { "source-map": "r", created: "2026-10-08" }); + (g.file as unknown as { stat: { ctime: number } }).stat = { ctime }; + return g; + }; + expect(generatorsForRegion([made("r-4", 100), made("r-7", 400), made("r-5", 200)], "r").map((g) => g.model.name)).toEqual(["r-7", "r-5", "r-4"]); + }); }); From 0af13a8796aad370c9d3d41597168e5a099e7287 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 13:02:27 -0400 Subject: [PATCH 037/558] feat(generator): suggest impassable terrain from what the learned paths avoid Under Guarantees > Impassable terrain, a "Suggested" line offers terrain to add (never added for you), with the reason on hover and below: - With paths: terrain covering at least 3% of the region that every path type ran through at under a quarter of its share (ends don't count, so a river into the sea doesn't make the sea crossable), and only when missing it that completely would be very unlikely by chance. On the vault's generators this finds ocean and shallows on the coast maps and nothing false (bay-area's roads never touch grass, but its rivers do). - Without paths: only big terrain that looks like water by name or colour. Also fixes two save-then-reload races on the page: adding a suggestion now redraws the chips in place, and Reset settings waits for the write before re-rendering (it could re-read the old settings). Co-Authored-By: Claude Opus 5.5 --- dev/wfc-impassable-guess.mts | 43 +++++++++++ package.json | 4 +- src/worldgen/GeneratorPanel.ts | 41 +++++++++- src/worldgen/impassableHint.ts | 107 +++++++++++++++++++++++++++ styles.css | 18 +++++ tests/worldgenImpassableHint.test.ts | 60 +++++++++++++++ 6 files changed, 268 insertions(+), 5 deletions(-) create mode 100644 dev/wfc-impassable-guess.mts create mode 100644 src/worldgen/impassableHint.ts create mode 100644 tests/worldgenImpassableHint.test.ts diff --git a/dev/wfc-impassable-guess.mts b/dev/wfc-impassable-guess.mts new file mode 100644 index 00000000..61d7a87f --- /dev/null +++ b/dev/wfc-impassable-guess.mts @@ -0,0 +1,43 @@ +// For each terrain in a vault generator: its share of the example, its share +// under the example's paths (by type), and how often paths end on it. Terrain +// that is common but that paths avoid looks impassable. Read-only. +// VAULT=/mnt/c/.../journal npx tsx dev/wfc-impassable-guess.mts +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { parseModelMarkdown } from "../packages/hex-wfc/src"; + +const vault = process.env.VAULT ?? join(process.cwd(), "../../../.."); +const data = JSON.parse(readFileSync(join(vault, ".obsidian/plugins/duckmage-plugin/data.json"), "utf8")); +const world = String(data.worldFolder ?? "").replace(/^\/+|\/+$/g, ""); +const name = process.argv[2] ?? "the-coast"; +const parsed = parseModelMarkdown(readFileSync(join(vault, world, "generators", `${name}.md`), "utf8")); +const model = "model" in parsed ? parsed.model : (parsed as never); +const total = model.terrains.reduce((n, t) => n + t.weight, 0); +const paths = model.paths ?? []; +const types = [...new Set(paths.map((p) => p.type))]; +// Path-weighted share of each terrain under each type: sum(count * length * through). +const under = new Map>(); +for (const ty of types) { + const m = new Map(); + let w = 0; + for (const p of paths.filter((p) => p.type === ty)) { + const pw = p.count * Math.max(p.length, 0.05); + w += pw; + for (const [t, s] of Object.entries(p.through)) m.set(t, (m.get(t) ?? 0) + s * pw); + } + for (const [t, v] of m) m.set(t, v / (w || 1)); + under.set(ty, m); +} +const ends = new Map(); +for (const p of paths) for (const e of [p.from, p.to]) if (!["edge", "none", "path"].includes(e)) ends.set(e, (ends.get(e) ?? 0) + p.count); +const rows = model.terrains.map((t) => ({ + terrain: t.name, + map: t.weight / total, + ...Object.fromEntries(types.map((ty) => [ty, under.get(ty)!.get(t.name) ?? 0])), + ends: ends.get(t.name) ?? 0, +})); +const pct = (v: number) => (v * 100).toFixed(1).padStart(5) + "%"; +console.log(`${name}: ${paths.length} routes (${types.join(", ")})`); +console.log("terrain".padEnd(20) + " map " + types.map((t) => t.slice(0, 6).padStart(7)).join("") + " ends"); +for (const r of rows.sort((a, b) => b.map - a.map)) + console.log(r.terrain.padEnd(20) + pct(r.map) + types.map((t) => pct((r as Record)[t]).padStart(7)).join("") + String(r.ends).padStart(6)); diff --git a/package.json b/package.json index ef0a76f8..9c696725 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenSizePresets.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenSizePresets.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenSizePresets.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenSizePresets.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 95c4a446..9b7aaa8a 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -28,6 +28,7 @@ import { import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; import { makeScrubbable, wheelValue } from "./scrub"; import { rebalance, toPercents } from "./regionWeights"; +import { suggestImpassable } from "./impassableHint"; import { GeneratorLibrary } from "./GeneratorLibrary"; import { sizePresets } from "./sizePresets"; import { listSaves, writeSave, readSave, applySave, renameGenerator } from "./saves"; @@ -202,6 +203,8 @@ export class GeneratorPanel { // A just-loaded save's settings win over a possibly stale read of the file. const isThisGenerator = (sv: GeneratorSave) => sv.generatorPath === g.file.path || sv.generatorName === model.name; if (GeneratorPanel.loadedSave && isThisGenerator(GeneratorPanel.loadedSave)) model.settings = { ...GeneratorPanel.loadedSave.settings }; + /** The last settings write, for anything that must re-read the file after it. */ + let lastWrite: Promise = Promise.resolve(); const save = (patch: Partial>) => { GeneratorPanel.loadedSave = null; const next: Record = { ...(model.settings ?? {}) }; @@ -210,7 +213,7 @@ export class GeneratorPanel { else next[k] = v; } model.settings = next; - saveGeneratorSettings(this.plugin, g.file, patch).catch((e: unknown) => { + lastWrite = saveGeneratorSettings(this.plugin, g.file, patch).catch((e: unknown) => { new Notice(`Couldn't save generator settings: ${e instanceof Error ? e.message : String(e)}`); }); schedulePreview(); @@ -357,8 +360,9 @@ export class GeneratorPanel { new ConfirmModal(this.app, "Reset settings", `Reset all of "${model.name}"'s settings to their defaults?`, "Reset", () => { const cleared: Partial> = {}; for (const k of Object.keys(model.settings ?? {})) cleared[k as keyof GeneratorSettings] = undefined; + // Re-render once written, or the page re-reads the old settings. save(cleared); - this.host.rerender(); + void lastWrite.then(() => this.host.rerender()); }).open(); }); @@ -766,7 +770,38 @@ export class GeneratorPanel { this.toggle(el, "Guaranteed features", "Always place the example's anchored terrain lines (such as a river painted as terrain). Drawn paths have their own section below.", s().features, (v) => save({ features: v })); } this.toggle(el, "Connected land", "Fill cut-off pockets so every passable hex connects.", s().connected, (v) => save({ connected: v })); - this.terrainFilter(el, "Impassable terrain", model.terrains.map((t) => t.name), colors, s().impassable, (list) => save({ impassable: list })); + const impassableBox = el.createDiv(); + const hintBox = el.createDiv({ cls: "duckmage-wfc-hint" }); + // Terrain the learned paths go around, offered to add (never added for you). + const drawHints = () => { + hintBox.empty(); + const hints = suggestImpassable(model, colors, s().impassable); + if (!hints.length) return; + const row = hintBox.createDiv({ cls: "duckmage-region-row" }); + row.createSpan({ text: "Suggested", cls: "duckmage-map-origin-label" }); + for (const h of hints) { + const chip = row.createSpan({ cls: "duckmage-wfc-chip duckmage-wfc-hint-chip", attr: { title: h.reason } }); + chip.createSpan({ cls: "duckmage-wfc-swatch" }).setCssProps({ "--duckmage-wfc-swatch": colors.get(h.terrain) ?? "var(--background-modifier-border)" }); + chip.createSpan({ text: h.terrain }); + } + const add = row.createEl("button", { text: hints.length > 1 ? "Add all" : "Add" }); + add.addEventListener("click", () => { + // Redraw here rather than re-rendering the page: the page would + // re-read the file before this save has landed. + save({ impassable: [...s().impassable, ...hints.map((h) => h.terrain).filter((t) => !s().impassable.includes(t))] }); + drawImpassable(); + }); + hintBox.createEl("p", { text: hints.map((h) => `${h.terrain}: ${h.reason}.`).join(" "), cls: "duckmage-map-origin-desc" }); + }; + const drawImpassable = () => { + impassableBox.empty(); + this.terrainFilter(impassableBox, "Impassable terrain", model.terrains.map((t) => t.name), colors, s().impassable, (list) => { + save({ impassable: list }); + drawHints(); + }); + drawHints(); + }; + drawImpassable(); // Terrain mix: per-terrain controls and what they do to the preview el = this.section(main, "Terrain mix"); diff --git a/src/worldgen/impassableHint.ts b/src/worldgen/impassableHint.ts new file mode 100644 index 00000000..4db93bd3 --- /dev/null +++ b/src/worldgen/impassableHint.ts @@ -0,0 +1,107 @@ +/** + * Suggest which terrains a generator should treat as impassable, without + * knowing what any terrain is. + * + * Main signal: the example's paths. A terrain that covers a good part of the + * region but that no path type ever ran through (ends don't count: a river + * may end in the sea) is something the paths went around. It's only + * suggested when a miss that complete would be very unlikely by chance, so + * small terrains the paths simply weren't drawn near aren't suggested. + * + * Fallback, only for generators without paths: a big terrain that looks like + * water (blue, or named like it). + */ + +import type { HexWfcModel, PathFeature } from "../../packages/hex-wfc/src"; + +export interface ImpassableHint { + terrain: string; + reason: string; +} + +/** Below this share of the region a terrain isn't suggested. */ +const MIN_SHARE = 0.03; +/** A path type "avoids" a terrain if it ran through it at under this fraction of its share. */ +const AVOID_RATIO = 0.25; +/** Suggest only if missing it this completely by chance is under this probability. */ +const MAX_CHANCE = 0.001; + +const WATERY = /\b(ocean|sea|lake|water|shallows|deep|trench|abyss|chasm|lava|magma|void|reef|lagoon|bay)\b/i; + +/** Roughly how many hexes a route covered in the example. */ +function routeHexes(p: PathFeature, exampleHexes: number): number { + const side = Math.sqrt(Math.max(exampleHexes, 1)); + return Math.max(3, p.length * side) * Math.max(p.count, 0); +} + +/** Hue (0-360) and saturation (0-1) of a #rrggbb colour, or null. */ +function hueSat(color: string | undefined): { h: number; s: number } | null { + const m = /^#?([0-9a-f]{6})$/i.exec(color?.trim() ?? ""); + if (!m) return null; + const n = parseInt(m[1], 16); + const r = ((n >> 16) & 255) / 255, g = ((n >> 8) & 255) / 255, b = (n & 255) / 255; + const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min; + if (d === 0) return { h: 0, s: 0 }; + const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4; + return { h: (h * 60 + 360) % 360, s: max === 0 ? 0 : d / max }; +} + +const pct = (v: number) => `${Math.round(v * 100)}%`; + +export function suggestImpassable( + model: HexWfcModel, + colors: Map = new Map(), + already: string[] = [], +): ImpassableHint[] { + const total = model.terrains.reduce((n, t) => n + Math.max(0, t.weight), 0); + if (total <= 0) return []; + const taken = new Set(already); + const candidates = model.terrains + .map((t) => ({ name: t.name, share: Math.max(0, t.weight) / total })) + .filter((t) => t.share >= MIN_SHARE && !taken.has(t.name)); + const paths = model.paths ?? []; + const example = model.exampleHexes ?? total; + + if (paths.length) { + // Hexes each path type covered, and how many of them were on each terrain + // (leaving out the terrains a route starts or ends on). + const byType = new Map }>(); + for (const p of paths) { + const hexes = routeHexes(p, example); + const entry = byType.get(p.type) ?? { hexes: 0, on: new Map() }; + entry.hexes += hexes; + for (const [t, s] of Object.entries(p.through)) { + if (t === p.from || t === p.to) continue; + entry.on.set(t, (entry.on.get(t) ?? 0) + s * hexes); + } + byType.set(p.type, entry); + } + const allHexes = [...byType.values()].reduce((n, e) => n + e.hexes, 0); + const routes = paths.filter((p) => p.count > 0).length; + const out: ImpassableHint[] = []; + for (const c of candidates) { + const avoidedByAll = [...byType.values()].every((e) => (e.on.get(c.name) ?? 0) / Math.max(e.hexes, 1) < AVOID_RATIO * c.share); + if (!avoidedByAll) continue; + // Chance that hexes placed at random would all miss a terrain this big. + const chance = Math.pow(1 - c.share, allHexes); + if (chance >= MAX_CHANCE) continue; + out.push({ terrain: c.name, reason: `${routes} learned route${routes === 1 ? "" : "s"} never cross it, though it covers ${pct(c.share)} of the region` }); + } + return out.sort((a, b) => a.terrain.localeCompare(b.terrain)); + } + + // No paths to go on: only big terrain that looks like water. + const out: ImpassableHint[] = []; + for (const c of candidates) { + if (c.share < 0.05) continue; + const hs = hueSat(colors.get(c.name)); + const blue = !!hs && hs.h >= 185 && hs.h <= 250 && hs.s >= 0.25; + const named = WATERY.test(c.name); + if (!blue && !named) continue; + out.push({ + terrain: c.name, + reason: `looks like water (${[named ? "its name" : "", blue ? "its colour" : ""].filter(Boolean).join(" and ")}) and covers ${pct(c.share)}; there are no paths to tell for sure`, + }); + } + return out.sort((a, b) => a.terrain.localeCompare(b.terrain)); +} diff --git a/styles.css b/styles.css index 4a12982a..6e4ac02a 100644 --- a/styles.css +++ b/styles.css @@ -5233,6 +5233,24 @@ tr:hover .duckmage-rt-entry-copy-btn:hover { margin: 0.35em 0; } +/* Suggested impassable terrain under the Impassable chips: dashed, to read + as "not added yet". */ +.duckmage-wfc-hint:empty { + display: none; +} + +.duckmage-wfc-hint .duckmage-region-row { + margin: 0.3em 0 0; +} + +.duckmage-wfc-hint-chip { + padding: 0.05em 0.5em; + border: 1px dashed var(--background-modifier-border-hover); + border-radius: var(--radius-s); + color: var(--text-muted); + cursor: help; +} + .duckmage-wfc-matches:empty { display: none; } diff --git a/tests/worldgenImpassableHint.test.ts b/tests/worldgenImpassableHint.test.ts new file mode 100644 index 00000000..7d062fc6 --- /dev/null +++ b/tests/worldgenImpassableHint.test.ts @@ -0,0 +1,60 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { suggestImpassable } from "../src/worldgen/impassableHint"; +import type { HexWfcModel, PathFeature } from "../packages/hex-wfc/src"; + +/** Suggesting impassable terrain from a generator (src/worldgen/impassableHint.ts). */ + +const terrains = (shares: Record) => Object.entries(shares).map(([name, weight]) => ({ name, weight })); +const route = (type: string, to: string, through: Record, count = 1): PathFeature => + ({ type, from: "edge", to, count, turn: 0.2, length: 0.5, through }); +const model = (shares: Record, paths: PathFeature[] = []): HexWfcModel => + ({ name: "m", terrains: terrains(shares), adjacency: [], meta: {}, exampleHexes: 900, paths }); + +describe("impassable suggestions", () => { + const coast = { sea: 300, grass: 300, forest: 200, marsh: 30, hills: 70 }; + const paths = [ + route("Road", "edge", { grass: 0.6, forest: 0.3, hills: 0.1 }, 3), + route("Road", "town", { grass: 0.5, forest: 0.5 }, 2), + route("River", "sea", { grass: 0.7, hills: 0.2, sea: 0.1 }, 2), + ]; + + it("suggests big terrain that every path type goes around", () => { + expect(suggestImpassable(model(coast, paths)).map((h) => h.terrain)).toEqual(["sea"]); + }); + + it("doesn't count a path that ends in it (a river into the sea) as crossing", () => { + // The river's 10% "through" sea is its mouth, so sea is still suggested. + const hint = suggestImpassable(model(coast, paths))[0]; + expect(hint.reason).toContain("never cross it"); + }); + + it("doesn't suggest small terrain the paths just weren't drawn near", () => { + expect(suggestImpassable(model(coast, paths)).map((h) => h.terrain)).not.toContain("marsh"); + }); + + it("doesn't suggest terrain one path type uses, even if another avoids it", () => { + const withMountains = { ...coast, mountain: 150 }; + const roadsOverMountains = [...paths, route("Road", "peak", { mountain: 0.8, grass: 0.2 }, 3)]; + expect(suggestImpassable(model(withMountains, roadsOverMountains)).map((h) => h.terrain)).not.toContain("mountain"); + }); + + it("needs enough path to be sure", () => { + const one = [route("Road", "town", { grass: 1 }, 1)]; + // A single short road missing a third of the map proves little. + expect(suggestImpassable({ ...model(coast, one), exampleHexes: 40 })).toEqual([]); + }); + + it("skips terrain already marked impassable", () => { + expect(suggestImpassable(model(coast, paths), new Map(), ["sea"])).toEqual([]); + }); + + it("without paths, only suggests big terrain that looks like water", () => { + const colors = new Map([["deepblue", "#2a4d9b"], ["grass", "#5a9a3a"], ["Lake", "#999999"]]); + const m = model({ deepblue: 300, grass: 400, Lake: 100, forest: 200 }); + const hints = suggestImpassable(m, colors); + expect(hints.map((h) => h.terrain)).toEqual(["deepblue", "Lake"]); + expect(hints[0].reason).toContain("colour"); + expect(hints[1].reason).toContain("name"); + }); +}); From af54370d729c87a1b42368cbb410bf49938bee01 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 13:08:04 -0400 Subject: [PATCH 038/558] fix(paths): don't give up when a route's start is cut off by impassable terrain With shallows impassable, bay-area placed no paths at all on 11 of 40 maps (38x25): its maps are ~70% water with land left in corner pieces, and the router tried a single start; if that start couldn't reach a valid end, the route (and every branch off it) failed. Each route now: - only considers ends it can actually reach over passable land (an end can be stepped onto from that land, e.g. a river into the sea); - tries up to 12 starts, the usual cheapest one first; - for edge-to-edge and "just stops" routes, settles for the longest run the land allows when the learned length doesn't fit. bay-area: 0 of 40 maps without paths (was 11); routes that already worked take the same first start. dev/wfc-route-stats.mts reports per-route placement for a vault generator. Co-Authored-By: Claude Opus 5.5 --- dev/wfc-route-stats.mts | 29 ++++++++++ packages/hex-wfc/src/paths.ts | 96 +++++++++++++++++++++++----------- tests/hexWfcPathTweaks.test.ts | 30 +++++++++++ 3 files changed, 125 insertions(+), 30 deletions(-) create mode 100644 dev/wfc-route-stats.mts diff --git a/dev/wfc-route-stats.mts b/dev/wfc-route-stats.mts new file mode 100644 index 00000000..110f5433 --- /dev/null +++ b/dev/wfc-route-stats.mts @@ -0,0 +1,29 @@ +// Per-route placement over several seeds of a vault generator, with its saved +// settings, optionally overriding impassable. Read-only. Usage (WSL, plugin root): +// VAULT=/mnt/c/.../journal npx tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs \ +// dev/wfc-route-stats.ts [cols] [rows] [seeds] [impassable,list|-] +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { parseModelMarkdown, solve } from "../packages/hex-wfc/src"; + +const vault = process.env.VAULT ?? join(process.cwd(), "../../../.."); +const data = JSON.parse(readFileSync(join(vault, ".obsidian/plugins/duckmage-plugin/data.json"), "utf8")) as Record; +const world = String(data.worldFolder ?? "").replace(/^\/+|\/+$/g, ""); +const [name = "bay-area", c = "25", r = "16", n = "10", imp] = process.argv.slice(2); +const parsed = parseModelMarkdown(readFileSync(join(vault, world, "generators", `${name}.md`), "utf8")); +if (!("model" in parsed)) throw new Error("not a generator"); +const model = parsed.model; +const override = imp === undefined ? {} : { impassable: imp === "-" ? [] : imp.split(",") }; +const stats = new Map(); +for (let seed = 1; seed <= Number(n); seed++) { + const res = solve(model, { cols: Number(c), rows: Number(r), orientation: (data.hexOrientation as "flat") ?? "flat", seed, ...override }); + if (!res.ok) continue; + for (const st of res.pathRoutes) { + const e = stats.get(st.route) ?? { wanted: 0, placed: 0 }; + e.wanted += st.wanted; + e.placed += st.placed; + stats.set(st.route, e); + } +} +console.log(`${name} ${c}x${r}, ${n} seeds, impassable ${JSON.stringify(override.impassable ?? model.settings?.impassable ?? "(saved/default)")}`); +for (const [route, e] of stats) console.log(` ${route.padEnd(40)} placed ${e.placed} of ${e.wanted}`); diff --git a/packages/hex-wfc/src/paths.ts b/packages/hex-wfc/src/paths.ts index 16535f6c..b9cdf85f 100644 --- a/packages/hex-wfc/src/paths.ts +++ b/packages/hex-wfc/src/paths.ts @@ -228,42 +228,78 @@ export function routePaths( const endOk = (anchor: string) => (c: number) => !blocked?.[c] || terrainOf(c) === anchor; const starts = candidates(f.from, taken, null).filter((c) => (f.from === "path" || !taken.has(c)) && endOk(f.from)(c)); if (!starts.length) return null; - // A few random starts; keep the cheapest. + const dist = (a: number, b: number) => + hexDistance([ox + (a % cols), oy + Math.floor(a / cols)], [ox + (b % cols), oy + Math.floor(b / cols)], orientation, stagger); + + /** + * Route from one start, to ends it can actually reach (land cut off by + * impassable terrain or other paths doesn't count). If none of those is + * as far as the learned length asks, the farthest one will do. + */ + const attempt = (start: number): number[] | null => { + const reach = new Uint8Array(N); + reach[start] = 1; + const stack = [start]; + while (stack.length) { + const c = stack.pop()!; + for (const n of nbr[c]) { + if (reach[n] || blocked?.[n] || taken.has(n)) continue; + reach[n] = 1; + stack.push(n); + } + } + // An end can be stepped onto from reachable land (a river into the sea). + const reachable = (c: number) => reach[c] === 1 || nbr[c].some((n) => reach[n] === 1); + const startSide = border(start) ? sideOf(start) : null; + let targets: Set; + if (f.to === "none") { + const want = Math.max(3, Math.round(f.length * Math.max(cols, rows))); + const land: { c: number; d: number }[] = []; + for (let c = 0; c < N; c++) if (reach[c] && c !== start) land.push({ c, d: dist(start, c) }); + let atLength = land.filter((x) => Math.abs(x.d - want) <= 1); + if (!atLength.length && land.length) { + const best = Math.max(...land.filter((x) => x.d <= want).map((x) => x.d), 0); + atLength = best >= MIN_PATH_HEXES - 1 ? land.filter((x) => x.d === best) : []; + } + targets = new Set(atLength.length ? [atLength[Math.floor(rng() * atLength.length)].c] : []); + } else { + targets = new Set(candidates(f.to, taken, f.to === "edge" ? startSide : null).filter((c) => endOk(f.to)(c) && reachable(c))); + // Edge-to-edge: don't let it cut a corner; it should run at least most + // of the learned length (or as far as the land allows). + if (f.to === "edge") { + const minLen = Math.round(0.6 * f.length * Math.max(cols, rows)); + const far = [...targets].filter((c) => dist(start, c) >= minLen); + if (far.length) targets = new Set(far); + else if (targets.size) { + const longest = Math.max(...[...targets].map((c) => dist(start, c))); + targets = new Set([...targets].filter((c) => dist(start, c) === longest)); + } + } + } + if (f.to !== "path") for (const c of taken) targets.delete(c); + targets.delete(start); + if (!targets.size) return null; + const route = dijkstra(cost, start, targets, taken, blocked); + return route && route.length >= MIN_PATH_HEXES ? route : null; + }; + + // A few random starts; try the cheapest first, then others if it fails + // (it may sit on a scrap of land the route can't leave). + const tried = new Set(); let start = starts[Math.floor(rng() * starts.length)]; for (let t = 0; t < 6; t++) { const c = starts[Math.floor(rng() * starts.length)]; if (cost[c] < cost[start]) start = c; } - const startSide = border(start) ? sideOf(start) : null; - let targets: Set; - if (f.to === "none") { - const want = Math.max(3, Math.round(f.length * Math.max(cols, rows))); - const sx = ox + (start % cols), sy = oy + Math.floor(start / cols); - const atLength: number[] = []; - for (let c = 0; c < N; c++) { - if (blocked?.[c]) continue; - const d = hexDistance([sx, sy], [ox + (c % cols), oy + Math.floor(c / cols)], orientation, stagger); - if (Math.abs(d - want) <= 1) atLength.push(c); - } - targets = new Set(atLength.length ? [atLength[Math.floor(rng() * atLength.length)]] : []); - } else { - targets = new Set(candidates(f.to, taken, f.to === "edge" ? startSide : null).filter(endOk(f.to))); - // Edge-to-edge: don't let it cut a corner; it should run at least most - // of the learned length. - if (f.to === "edge") { - const minLen = Math.round(0.6 * f.length * Math.max(cols, rows)); - const sx = ox + (start % cols), sy = oy + Math.floor(start / cols); - const far = [...targets].filter( - (c) => hexDistance([sx, sy], [ox + (c % cols), oy + Math.floor(c / cols)], orientation, stagger) >= minLen, - ); - if (far.length) targets = new Set(far); - } + for (let k = 0; k < 12 && tried.size < starts.length; k++) { + tried.add(start); + const route = attempt(start); + if (route) return route; + const left = starts.filter((c) => !tried.has(c)); + if (!left.length) break; + start = left[Math.floor(rng() * left.length)]; } - if (f.to !== "path") for (const c of taken) targets.delete(c); - targets.delete(start); - if (!targets.size) return null; - const route = dijkstra(cost, start, targets, taken, blocked); - return route && route.length >= MIN_PATH_HEXES ? route : null; + return null; }; const out: PathOutput[] = []; diff --git a/tests/hexWfcPathTweaks.test.ts b/tests/hexWfcPathTweaks.test.ts index 6131bda8..d95c2f68 100644 --- a/tests/hexWfcPathTweaks.test.ts +++ b/tests/hexWfcPathTweaks.test.ts @@ -214,3 +214,33 @@ describe("paths and impassable terrain", () => { expect(back).toEqual({ value: { River: { crossImpassable: true, keep: 0.5 } } }); }); }); + +describe("paths on land cut up by impassable terrain", () => { + // 30x14 sea with a 3-row strip of land along the bottom and single land + // hexes dotted along the other edges (starts a route can't leave). + const cols = 30, rows = 14; + const cells = new Map(); + for (let y = 0; y < rows; y++) + for (let x = 0; x < cols; x++) { + const speck = (y === 0 && x % 3 === 0) || ((x === 0 || x === cols - 1) && y % 3 === 0 && y < rows - 3); + cells.set(cellKey(x, y), y >= rows - 3 || speck ? "grass" : "sea"); + } + const grid = { cols, rows, ox: 0, oy: 0, orientation: "flat" as const, stagger: "odd" as const }; + + it("tries other starts, and settles for the longest run the land allows", () => { + // Learned as running the whole map; only the strip can take one. + const river = { type: "River", from: "edge", to: "edge", count: 1, turn: 0.2, length: 1.4, through: { grass: 1 } }; + for (let seed = 1; seed <= 6; seed++) { + const r = routePaths([river], cells, grid, mulberry32(seed), 1, {}, ["sea"]); + expect(r.paths).toHaveLength(1); + expect(r.paths[0].hexes.every((h) => cells.get(h) === "grass")).toBe(true); + } + }); + + it("finds a stopping point on reachable land for routes that just stop", () => { + const road = { type: "Road", from: "edge", to: "none", count: 2, turn: 0.2, length: 0.8, through: { grass: 1 } }; + const r = routePaths([road], cells, grid, mulberry32(9), 1, {}, ["sea"]); + expect(r.paths.length).toBeGreaterThan(0); + expect(r.paths.flatMap((p) => p.hexes).every((h) => cells.get(h) === "grass")).toBe(true); + }); +}); From ccbf0dda980790dcd9462f5980941194a202f8f0 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 13:39:58 -0400 Subject: [PATCH 039/558] feat: map types, per-terrain submap defaults, Planet surface generator - Map types (Settings > Map types, and a "What will you map?" step in onboarding): World / fantasy overland and Space. Turning one off hides its palette presets, built-in generators and icon pack from menus; it never touches palettes, maps or icons already in use. Space-only onboarding starts the first map on Space - Sector. - Per-terrain submap defaults: the setup modal reads the origin hex's terrain and pre-fills palette, size, generator + options and base terrain from that terrain's saved defaults. Each row has a "Default for " checkbox; ticked choices are saved on create. Stored as a "Submap defaults" table in the parent palette's note (shareable, hand-editable), synced like child-palette. Presets ship defaults: sector worlds -> Space - System + Orbits; system planets -> Expanded + Planet surface tuned per type (ocean 85% water, desert arid, ice frozen, molten volcanic...). - Planet surface generator (World): seeded fractal elevation + moisture and a latitude temperature gradient -> sea/shelf/deep, beaches, plains, forest, jungle, swamp, hills, mountains, peaks, snow, desert, badlands, volcanoes. Exact water fraction by quantile; options: water %, climate, relief. Role lookup by name then category, so Limited, Expanded and similar user palettes work. Tests: tests/submapDefaults.test.ts (table round-trip/no-churn/removal, hand-written rows, preset defaults reference real terrains, map kinds, planet surface water %, climate, determinism). Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 52 ++++- src/HexmakerSettingTab.ts | 43 +++++ src/SetupWizardView.ts | 36 +++- src/constants.ts | 1 + src/mapKinds.ts | 48 +++++ src/palettes/AddPaletteModal.ts | 3 +- src/palettes/PaletteStore.ts | 53 +++-- src/palettes/paletteNote.ts | 141 +++++++++++++- src/palettes/paletteOptions.ts | 7 +- src/palettes/presets.ts | 55 +++++- src/types.ts | 17 ++ src/worldgen/NewMapSetupModal.ts | 79 +++++++- src/worldgen/procedural/planetSurface.ts | 236 +++++++++++++++++++++++ src/worldgen/registry.ts | 28 ++- styles.css | 45 +++++ tests/submapDefaults.test.ts | 171 ++++++++++++++++ 17 files changed, 990 insertions(+), 29 deletions(-) create mode 100644 src/mapKinds.ts create mode 100644 src/worldgen/procedural/planetSurface.ts create mode 100644 tests/submapDefaults.test.ts diff --git a/package.json b/package.json index 2c81bf60..eece6f15 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 59525115..34d33668 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -23,6 +23,7 @@ import { } from "./constants"; import { SetupWizardView } from "./SetupWizardView"; import { PaletteStore } from "./palettes/PaletteStore"; +import { ALL_MAP_KINDS, isIconHiddenByKind } from "./mapKinds"; import { getPreset, mergePathTypes, @@ -35,6 +36,7 @@ import { parseWorkflow, buildWorkflowContent } from "./random-tables/workflow"; import type { HexmakerPluginSettings, MapData, + SubmapDefault, TerrainColor, TerrainPalette, } from "./types"; @@ -509,6 +511,10 @@ export default class HexmakerPlugin extends Plugin { if (!this.settings.defaultMap) { this.settings.defaultMap = this.settings.maps[0]?.name ?? "default"; } + // Own copy (never alias DEFAULT_SETTINGS); unset in older data = all types. + this.settings.mapKinds = Array.isArray(this.settings.mapKinds) + ? [...this.settings.mapKinds] + : [...ALL_MAP_KINDS]; } async saveSettings() { @@ -572,7 +578,10 @@ export default class HexmakerPlugin extends Plugin { loadAvailableIcons() { this.vaultIconsSet = new Set(); - const pluginIcons: string[] = Array.from(BUNDLED_ICONS.keys()); + // Icon packs of disabled map types stay out of the pickers (palettes that + // already use them still render — getIconUrl reads BUNDLED_ICONS). + const pluginIcons: string[] = Array.from(BUNDLED_ICONS.keys()) + .filter((i) => !isIconHiddenByKind(this.settings, i)); const vaultIcons: string[] = []; const iconsFolder = normalizeFolder(this.settings.iconsFolder ?? ""); @@ -1494,6 +1503,47 @@ export default class HexmakerPlugin extends Plugin { /** Maps whose parent scan came up empty this session (cleared on any link change). */ private noParentMaps = new Set(); + /** + * Saved setup for a new submap made from a `terrain` hex on `parentMap`: + * the parent palette's Submap defaults row for that terrain (from its + * note), else the matching preset's row (palettes installed before the + * preset gained defaults still get them). + */ + submapDefaultFor(parentMap: string, terrain: string | null | undefined): SubmapDefault | undefined { + if (!terrain) return undefined; + const paletteName = this.getMap(parentMap)?.paletteName; + if (!paletteName) return undefined; + const own = this.getPaletteByName(paletteName)?.submapDefaults?.[terrain]; + if (own) return own; + return getPreset(paletteName)?.submapDefaults?.[terrain]; + } + + /** + * Remember (or forget) choices for new submaps of `terrain` on the parent + * map's palette. `set` fields are stored; `clear` fields are removed. + * Saved into the palette note's Submap defaults table by the sync. + */ + async saveSubmapDefault( + parentMap: string, + terrain: string, + set: SubmapDefault, + clear: (keyof SubmapDefault)[], + ): Promise { + const paletteName = this.getMap(parentMap)?.paletteName; + const pal = paletteName ? this.getPaletteByName(paletteName) : undefined; + if (!pal) return; + // Start from what the user currently sees (own row, else the preset row). + const current: SubmapDefault = { ...(this.submapDefaultFor(parentMap, terrain) ?? {}) }; + for (const k of clear) delete current[k]; + Object.assign(current, set); + const defaults = { ...(pal.submapDefaults ?? {}) }; + if (Object.keys(current).length) defaults[terrain] = current; + else delete defaults[terrain]; + if (Object.keys(defaults).length) pal.submapDefaults = defaults; + else delete pal.submapDefaults; + await this.saveSettings(); + } + /** Install `name` from the presets if no palette by that name exists yet. */ async ensurePaletteInstalled(name: string): Promise { if (this.getPaletteByName(name) || !getPreset(name)) return; diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index 8e3e024d..5f8442a6 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -2,6 +2,7 @@ import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import type HexmakerPlugin from "./HexmakerPlugin"; import { normalizeFolder } from "./utils"; import { AddPaletteModal } from "./palettes/AddPaletteModal"; +import { MAP_KINDS, enabledKinds, type MapKind } from "./mapKinds"; const PALETTES_FOLDER_DESC = "Vault-relative folder for terrain palette notes (one note per palette — edit as text, copy between vaults to share). Defaults to a palettes folder inside the world folder."; @@ -607,6 +608,20 @@ export class HexmakerSettingTab extends PluginSettingTab { "World/palettes", PALETTES_FOLDER_DESC, ), + { + type: "group", + heading: "Map types", + items: MAP_KINDS.map((k): LocalSettingDefinition => ({ + name: k.label, + desc: k.description, + render: (setting: Setting) => { + setting.addToggle((t) => + t.setValue(enabledKinds(this.plugin.settings).has(k.id)) + .onChange((v) => void this.setMapKind(k.id, v)), + ); + }, + })), + }, // Terrain palettes LAST, deliberately: on update() the declarative // renderer reuses unchanged rows but re-creates a changed list and // appends it at the END of the page — a mid-page list visibly "drops @@ -717,6 +732,23 @@ export class HexmakerSettingTab extends PluginSettingTab { * generated). Typed dynamically because the installed 1.12 typings predate * the method; declaring it on this class would shadow the real one. */ + /** + * Turn a map type on/off. Hides (never deletes) its presets, generators + * and icon pack. At least one type stays on. + */ + private async setMapKind(kind: MapKind, on: boolean): Promise { + const kinds = enabledKinds(this.plugin.settings); + if (on) kinds.add(kind); + else kinds.delete(kind); + if (kinds.size === 0) { + new Notice("Keep at least one map type enabled."); + kinds.add(kind); + } + this.plugin.settings.mapKinds = MAP_KINDS.map((k) => k.id).filter((id) => kinds.has(id)); + await this.plugin.saveSettings(); + this.plugin.loadAvailableIcons(); + } + /** "Open note" button for a palette row — opens the palette's note in a new tab. */ private addOpenNoteButton(parent: HTMLElement, paletteName: string): void { const btn = parent.createEl("button", { text: "Open note" }); @@ -1352,6 +1384,17 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); + new Setting(containerEl).setName("Map types").setHeading(); + for (const k of MAP_KINDS) { + new Setting(containerEl) + .setName(k.label) + .setDesc(k.description) + .addToggle((t) => + t.setValue(enabledKinds(this.plugin.settings).has(k.id)) + .onChange((v) => void this.setMapKind(k.id, v)), + ); + } + // Terrain palettes last — mirrors getSettingDefinitions() ordering // (see comment there: the declarative renderer re-appends a changed // list at the page end, so the list lives at the end in both paths). diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index b2080508..859934c9 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -4,6 +4,8 @@ import type { HexMapView } from "./hex-map/HexMapView"; import { normalizeFolder, slugify } from "./utils"; import { VIEW_TYPE_SETUP_WIZARD, VIEW_TYPE_HEX_MAP } from "./constants"; import { fillPaletteSelect } from "./palettes/paletteOptions"; +import { MAP_KINDS, enabledKinds, type MapKind } from "./mapKinds"; +import { SPACE_SECTOR_PALETTE_NAME } from "./palettes/presets"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -28,6 +30,8 @@ interface WizardContext { mapRows: number; paletteName: string; hexOrientation: "flat" | "pointy"; + /** Map types to enable (src/mapKinds.ts). */ + mapKinds: MapKind[]; } interface WizardCallbacks { @@ -80,7 +84,7 @@ function makeWelcomeStep(): WizardStep { return { id: "welcome", title: "Welcome to Hexmaker!", - render(container) { + render(container, ctx, cbs) { container.createEl("p", { text: "Hexmaker turns your Obsidian vault into a living, interactive hex map. Each hex on the map is a Markdown note — you can paint terrain, add icons, link towns, dungeons, factions, and encounter tables, and run random tables right from the map.", cls: "duckmage-wizard-text", @@ -93,8 +97,35 @@ function makeWelcomeStep(): WizardStep { text: "This panel doesn't block anything — feel free to click around Obsidian, browse the file tree, or create folders while it's open.", cls: "duckmage-wizard-text duckmage-wizard-tip", }); + + // What kinds of maps? Drives which palettes, generators and icon + // packs are offered. Changeable later in settings → Map types. + const kinds = container.createDiv({ cls: "duckmage-wizard-field duckmage-wizard-kinds" }); + kinds.createEl("label", { text: "What will you map?", cls: "duckmage-wizard-label" }); + for (const k of MAP_KINDS) { + const row = kinds.createEl("label", { cls: "duckmage-wizard-kind" }); + const cb = row.createEl("input", { type: "checkbox" }); + cb.checked = ctx.mapKinds.includes(k.id); + const text = row.createDiv(); + text.createDiv({ text: k.label, cls: "duckmage-wizard-kind-title" }); + text.createDiv({ text: k.description, cls: "duckmage-wizard-kind-desc" }); + cb.addEventListener("change", () => { + ctx.mapKinds = MAP_KINDS.map((m) => m.id).filter((id) => + id === k.id ? cb.checked : ctx.mapKinds.includes(id)); + cbs.onUpdate(); + }); + } + }, + canProceed: (ctx) => ctx.mapKinds.length > 0, + async onNext(ctx, plugin) { + plugin.settings.mapKinds = [...ctx.mapKinds]; + // Space only: start the first map as a sector chart. + if (!ctx.mapKinds.includes("world") && ctx.mapKinds.includes("space")) { + ctx.paletteName = SPACE_SECTOR_PALETTE_NAME; + } + await plugin.saveSettings(); + plugin.loadAvailableIcons(); }, - canProceed: () => true, }; } @@ -473,6 +504,7 @@ export class SetupWizardView extends ItemView { mapRows: 16, paletteName: plugin.settings.terrainPalettes[0]?.name ?? "Limited", hexOrientation: plugin.settings.hexOrientation ?? "flat", + mapKinds: [...enabledKinds(plugin.settings)], }; this.steps = [ makeWelcomeStep(), diff --git a/src/constants.ts b/src/constants.ts index fe31e673..0ccbdd0d 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -343,4 +343,5 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { setupDismissed: false, palettesFolder: "", palettesMigrated: false, + mapKinds: ["world", "space"], }; diff --git a/src/mapKinds.ts b/src/mapKinds.ts new file mode 100644 index 00000000..2b38f385 --- /dev/null +++ b/src/mapKinds.ts @@ -0,0 +1,48 @@ +/** + * Map types ("kinds"): the genres of map a user works with. Each kind owns + * palette presets, procedural generators and (optionally) an icon pack. + * Turning a kind off in settings hides those from menus — it never touches + * palettes, maps or icons already in use. + */ + +export type MapKind = "world" | "space"; + +export interface MapKindInfo { + id: MapKind; + label: string; + description: string; + /** Bundled icon prefix this kind owns (hidden from pickers when off). */ + iconPrefix?: string; +} + +export const MAP_KINDS: MapKindInfo[] = [ + { + id: "world", + label: "World / fantasy overland", + description: "Continents, regions and local areas: forests, mountains, coasts. Includes the Limited and Expanded palettes and the Planet surface generator.", + }, + { + id: "space", + label: "Space", + description: "Sector charts and star systems: Space - Sector / Space - System palettes, Star scatter and Orbits generators, the space icon pack.", + iconPrefix: "space-", + }, +]; + +export const ALL_MAP_KINDS: MapKind[] = MAP_KINDS.map((k) => k.id); + +/** Kinds enabled in settings; unset (older data.json) = all. */ +export function enabledKinds(settings: { mapKinds?: string[] }): Set { + const list = Array.isArray(settings.mapKinds) ? settings.mapKinds : ALL_MAP_KINDS; + return new Set(list.filter((k): k is MapKind => (ALL_MAP_KINDS as string[]).includes(k))); +} + +export function isKindEnabled(settings: { mapKinds?: string[] }, kind: MapKind | undefined): boolean { + return kind === undefined || enabledKinds(settings).has(kind); +} + +/** Icon names hidden from pickers because their kind is off. */ +export function isIconHiddenByKind(settings: { mapKinds?: string[] }, icon: string): boolean { + const on = enabledKinds(settings); + return MAP_KINDS.some((k) => k.iconPrefix && !on.has(k.id) && icon.startsWith(k.iconPrefix)); +} diff --git a/src/palettes/AddPaletteModal.ts b/src/palettes/AddPaletteModal.ts index 2da2db9f..f97ae44c 100644 --- a/src/palettes/AddPaletteModal.ts +++ b/src/palettes/AddPaletteModal.ts @@ -2,6 +2,7 @@ import { App } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { PALETTE_PRESETS, uniquePaletteName } from "./presets"; +import { isKindEnabled } from "../mapKinds"; /** * "Add palette" chooser: install a built-in preset, copy an existing @@ -24,7 +25,7 @@ export class AddPaletteModal extends HexmakerModal { contentEl.createEl("h4", { text: "Presets" }); const presetList = contentEl.createDiv({ cls: "duckmage-add-palette-list" }); - for (const preset of PALETTE_PRESETS) { + for (const preset of PALETTE_PRESETS.filter((p) => isKindEnabled(this.plugin.settings, p.kind))) { const installed = this.plugin.getPaletteByName(preset.name) !== undefined; this.option( presetList, diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index 4a4b51ed..f500b933 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -7,19 +7,39 @@ import { paletteFileName, parsePaletteNote, readChildPalette, + readSubmapDefaults, setChildPalette, + setSubmapDefaults, + submapDefaultsKey, terrainsEqual, updatePaletteNote, } from "./paletteNote"; import { uniquePaletteName } from "./presets"; -/** Copy a note's `child-palette` onto the palette. Returns true if it changed. */ -function applyChildPalette(pal: TerrainPalette, content: string): boolean { +/** + * Copy a note's metadata (`child-palette`, the Submap defaults table) onto + * the palette. Returns true if anything changed. + */ +function applyNoteMeta(pal: TerrainPalette, content: string): boolean { + let changed = false; const child = readChildPalette(content); - if (pal.childPalette === child) return false; - if (child) pal.childPalette = child; - else delete pal.childPalette; - return true; + if (pal.childPalette !== child) { + if (child) pal.childPalette = child; + else delete pal.childPalette; + changed = true; + } + const defaults = readSubmapDefaults(content); + if (submapDefaultsKey(pal.submapDefaults) !== submapDefaultsKey(defaults)) { + if (defaults) pal.submapDefaults = defaults; + else delete pal.submapDefaults; + changed = true; + } + return changed; +} + +/** A fresh note for a palette, metadata included. */ +function newNote(pal: TerrainPalette): string { + return setSubmapDefaults(buildPaletteNote(pal.terrains, pal.childPalette), pal.submapDefaults); } /** @@ -169,7 +189,7 @@ export class PaletteStore { name = uniquePaletteName(safe, siblings); } if (name !== pal.name) this.renamePalette(pal, name); - const content = buildPaletteNote(pal.terrains, pal.childPalette); + const content = newNote(pal); const path = this.pathFor(pal.name); this.bind(pal, path, content); await this.plugin.app.vault.create(path, content); @@ -216,7 +236,7 @@ export class PaletteStore { pal = { name: file.basename, terrains }; changed = true; } - if (applyChildPalette(pal, content)) changed = true; + if (applyNoteMeta(pal, content)) changed = true; this.bind(pal, file.path, content); next.push(pal); } @@ -294,11 +314,14 @@ export class PaletteStore { if (file instanceof TFile) { const current = await vault.read(file); const parsed = parsePaletteNote(current); - const next = setChildPalette( - parsed && terrainsEqual(parsed, pal.terrains) - ? current - : updatePaletteNote(current, pal.terrains), - pal.childPalette, + const next = setSubmapDefaults( + setChildPalette( + parsed && terrainsEqual(parsed, pal.terrains) + ? current + : updatePaletteNote(current, pal.terrains), + pal.childPalette, + ), + pal.submapDefaults, ); if (next !== current) { this.lastContent.set(target, next); @@ -306,7 +329,7 @@ export class PaletteStore { } this.bind(pal, target, next); } else { - const content = buildPaletteNote(pal.terrains, pal.childPalette); + const content = newNote(pal); this.bind(pal, target, content); await vault.create(target, content); } @@ -360,7 +383,7 @@ export class PaletteStore { this.plugin.settings.terrainPalettes.push(pal); changed = true; } - if (applyChildPalette(pal, content)) changed = true; + if (applyNoteMeta(pal, content)) changed = true; this.bind(pal, file.path, content); if (changed) await this.persist(); }); diff --git a/src/palettes/paletteNote.ts b/src/palettes/paletteNote.ts index 6affa17a..f421ba8f 100644 --- a/src/palettes/paletteNote.ts +++ b/src/palettes/paletteNote.ts @@ -1,4 +1,4 @@ -import type { TerrainColor } from "../types"; +import type { SubmapDefault, TerrainColor } from "../types"; // Plain-text palette notes. // @@ -162,6 +162,145 @@ export function setChildPalette(content: string, value: string | undefined): str return `---\n${body}---${fm[2]}${text.slice(fm[0].length)}`; } +// ── Submap defaults table ──────────────────────────────────────────────── +// +// ## Submap defaults +// | Terrain | Palette | Size | Generator | Options | Base terrain | +// | ocean world | Space - System | 13x13 | procedural:orbits | bodies=normal | void | +// +// Optional per-terrain setup for new submaps (see SubmapDefault). Any cell +// may be blank. Recognised by its Terrain + Generator header columns, so it +// never collides with the terrain table (Terrain + Color). + +const SUBMAP_HEADING = "## Submap defaults"; +const SUBMAP_HEADERS = ["Terrain", "Palette", "Size", "Generator", "Options", "Base terrain"] as const; + +type SubmapColumn = "terrain" | "palette" | "size" | "generator" | "options" | "base"; + +function submapColumnFor(header: string): SubmapColumn | null { + const h = header.trim().toLowerCase().replace(/\s+/g, " "); + if (h === "terrain") return "terrain"; + if (h === "palette") return "palette"; + if (h === "size") return "size"; + if (h === "generator") return "generator"; + if (h === "options") return "options"; + if (h === "base terrain" || h === "base") return "base"; + return null; +} + +function findSubmapTable(lines: string[]): { start: number; end: number; columns: (SubmapColumn | null)[] } | null { + for (let i = 0; i < lines.length - 1; i++) { + if (!lines[i].trim().startsWith("|")) continue; + if (!SEPARATOR_ROW.test(lines[i + 1])) continue; + const columns = splitRow(lines[i]).map(submapColumnFor); + if (!columns.includes("terrain") || !columns.includes("generator")) continue; + let end = i + 2; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { start: i, end, columns }; + } + return null; +} + +function parseOptions(raw: string): Record | undefined { + const out: Record = {}; + for (const part of raw.split(/[;,]/)) { + const m = /^\s*([^=]+?)\s*=\s*(.*?)\s*$/.exec(part); + if (m && m[1]) out[m[1]] = m[2]; + } + return Object.keys(out).length ? out : undefined; +} + +/** The "Submap defaults" table, or undefined when the note has none (or it's empty). */ +export function readSubmapDefaults(content: string): Record | undefined { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const span = findSubmapTable(lines); + if (!span) return undefined; + const out: Record = {}; + for (let i = span.start + 2; i < span.end; i++) { + const cells = splitRow(lines[i]); + const row: Partial> = {}; + span.columns.forEach((col, idx) => { + if (col && cells[idx]) row[col] = cells[idx]; + }); + if (!row.terrain) continue; + const d: SubmapDefault = {}; + if (row.palette) d.palette = row.palette; + const size = row.size ? /^(\d+)\s*[x×*]\s*(\d+)$/i.exec(row.size) : null; + if (size) { d.cols = Number(size[1]); d.rows = Number(size[2]); } + if (row.generator) d.generator = row.generator; + const opts = row.options ? parseOptions(row.options) : undefined; + if (opts) d.options = opts; + if (row.base) d.baseTerrain = row.base; + out[row.terrain] = d; + } + return Object.keys(out).length ? out : undefined; +} + +export function serializeSubmapDefaults(defaults: Record): string { + const lines = [ + `| ${SUBMAP_HEADERS.join(" | ")} |`, + `| ${SUBMAP_HEADERS.map(() => "---").join(" | ")} |`, + ]; + for (const [terrain, d] of Object.entries(defaults)) { + const size = d.cols && d.rows ? `${d.cols}x${d.rows}` : ""; + const opts = d.options ? Object.entries(d.options).map(([k, v]) => `${k}=${v}`).join("; ") : ""; + const cells = [terrain, d.palette, size, d.generator, opts, d.baseTerrain].map(escapeCell); + lines.push(`| ${cells.join(" | ")} |`); + } + return lines.join("\n"); +} + +/** Order-independent comparison key for defaults (undefined ≡ empty). */ +export function submapDefaultsKey(d: Record | undefined): string { + if (!d) return ""; + const norm = Object.keys(d).sort().map((t) => { + const v = d[t]; + const opts = v.options ? Object.keys(v.options).sort().map((k) => [k, v.options![k]]) : []; + return [t, v.palette ?? "", v.cols ?? 0, v.rows ?? 0, v.generator ?? "", opts, v.baseTerrain ?? ""]; + }); + const key = JSON.stringify(norm.filter((r) => (r as unknown[]).slice(1).some((x) => x !== "" && x !== 0 && !(Array.isArray(x) && x.length === 0)))); + return key === "[]" ? "" : key; +} + +/** + * Write (or remove) the "Submap defaults" table. Returns the content + * untouched when it already holds these defaults. + */ +export function setSubmapDefaults(content: string, defaults: Record | undefined): string { + if (submapDefaultsKey(readSubmapDefaults(content)) === submapDefaultsKey(defaults)) return content; + const text = content.replace(/\r\n?/g, "\n"); + const lines = text.split("\n"); + const span = findSubmapTable(lines); + const empty = submapDefaultsKey(defaults) === ""; + if (span) { + if (empty) { + // Drop the table, plus our heading and intro text when the nearest + // heading above the table is "## Submap defaults". + let start = span.start; + for (let i = span.start - 1; i >= 0; i--) { + if (!lines[i].startsWith("#")) continue; + if (lines[i].trim() === SUBMAP_HEADING) start = i; + break; + } + while (start > 0 && lines[start - 1].trim() === "") start--; + const rest = lines.slice(span.end); + while (rest.length && rest[0].trim() === "") rest.shift(); + const kept = [...lines.slice(0, start), ...(rest.length ? ["", ...rest] : [""])]; + return kept.join("\n"); + } + return [...lines.slice(0, span.start), serializeSubmapDefaults(defaults!), ...lines.slice(span.end)].join("\n"); + } + if (empty) return content; + const base = text.endsWith("\n") ? text : text + "\n"; + return ( + base + + `\n${SUBMAP_HEADING}\n\n` + + "New submaps made from a hex of these terrains start with these choices (generator ids: blank, procedural:star-scatter, procedural:orbits, procedural:planet-surface, wfc:).\n\n" + + serializeSubmapDefaults(defaults!) + + "\n" + ); +} + /** A complete new palette note. */ export function buildPaletteNote(terrains: TerrainColor[], childPalette?: string): string { return [ diff --git a/src/palettes/paletteOptions.ts b/src/palettes/paletteOptions.ts index 332e8cc7..4b5af6c7 100644 --- a/src/palettes/paletteOptions.ts +++ b/src/palettes/paletteOptions.ts @@ -1,5 +1,6 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import { PALETTE_PRESETS } from "./presets"; +import { isKindEnabled } from "../mapKinds"; /** * Fill a palette with the terrain types, grouped by map type (World / + * Space). Types of disabled map kinds are left out unless `current` uses + * one. The first option is "— none —" (value ""). + */ +export function fillTerrainTypeSelect( + select: HTMLSelectElement, + settings: { mapKinds?: string[] }, + current: string | undefined, + noneLabel = "— none —", +): void { + select.empty(); + select.createEl("option", { value: "", text: noneLabel }); + const on = enabledKinds(settings); + for (const kind of MAP_KINDS) { + const types = TERRAIN_TYPES.filter((t) => t.kind === kind.id && (on.has(kind.id) || t.id === current)); + if (types.length === 0) continue; + const group = select.createEl("optgroup", { attr: { label: kind.label } }); + for (const t of types) group.createEl("option", { value: t.id, text: t.label }); + } + // An unknown type typed into a note by hand still shows (and is kept). + if (current && !terrainTypeInfo(current)) select.createEl("option", { value: current, text: `${current} (unknown)` }); + select.value = current ?? ""; +} diff --git a/src/terrainTypes.ts b/src/terrainTypes.ts new file mode 100644 index 00000000..b1fa60f3 --- /dev/null +++ b/src/terrainTypes.ts @@ -0,0 +1,87 @@ +import type { MapKind } from "./mapKinds"; + +/** + * Terrain types: a fixed vocabulary every palette terrain can be tagged + * with ("dark forest" → forest, "glass desert" → desert). Unlike the free + * text `category` (a picker grouping the user owns), types have meaning + * the plugin can rely on — generators place terrain by type, the hex table + * filters by type — so custom names keep working everywhere. + */ + +export interface TerrainTypeInfo { + id: string; + label: string; + kind: MapKind; + /** Lower-case words that suggest this type in a terrain's name. */ + keywords: string[]; +} + +export const TERRAIN_TYPES: TerrainTypeInfo[] = [ + // World — water + { id: "deep-water", label: "Deep water", kind: "world", keywords: ["trench", "abyss", "deep"] }, + { id: "water", label: "Water", kind: "world", keywords: ["ocean", "sea", "water", "lake", "river"] }, + { id: "shallows", label: "Shallows", kind: "world", keywords: ["shallow", "reef", "shoal"] }, + { id: "coast", label: "Coast", kind: "world", keywords: ["beach", "coast", "shore", "salt flat", "sand"] }, + // World — land + { id: "grassland", label: "Grassland", kind: "world", keywords: ["grass", "plain", "meadow", "steppe", "prairie", "savanna", "field", "farm"] }, + { id: "forest", label: "Forest", kind: "world", keywords: ["forest", "wood", "evergreen", "pine", "taiga", "grove"] }, + { id: "jungle", label: "Jungle", kind: "world", keywords: ["jungle", "rainforest"] }, + { id: "wetland", label: "Wetland", kind: "world", keywords: ["swamp", "marsh", "bog", "fen", "mire"] }, + { id: "hills", label: "Hills", kind: "world", keywords: ["hill", "highland", "downs"] }, + { id: "mountains", label: "Mountains", kind: "world", keywords: ["mountain", "cliff", "ridge", "crag"] }, + { id: "peaks", label: "Peaks", kind: "world", keywords: ["peak", "summit", "alpine"] }, + { id: "snow", label: "Snow / ice", kind: "world", keywords: ["snow", "ice", "glacier", "tundra", "frozen"] }, + { id: "desert", label: "Desert", kind: "world", keywords: ["desert", "dune", "cactus", "arid"] }, + { id: "badlands", label: "Badlands", kind: "world", keywords: ["badland", "brokenland", "waste", "canyon", "mesa"] }, + { id: "volcanic", label: "Volcanic", kind: "world", keywords: ["volcan", "lava", "ash", "magma"] }, + { id: "settlement", label: "Settlement", kind: "world", keywords: ["urban", "city", "town", "village", "ruin"] }, + // Space + { id: "void", label: "Void / empty space", kind: "space", keywords: ["void", "empty space", "deep space", "jump limit"] }, + { id: "nebula", label: "Nebula / cloud", kind: "space", keywords: ["nebula", "dust", "cloud"] }, + { id: "rift", label: "Rift", kind: "space", keywords: ["rift"] }, + { id: "star", label: "Star", kind: "space", keywords: ["star", "sun", "dwarf", "giant star"] }, + { id: "world", label: "World / planet", kind: "space", keywords: ["world", "planet", "moon"] }, + { id: "gas-giant", label: "Gas giant", kind: "space", keywords: ["gas giant", "ice giant"] }, + { id: "asteroids", label: "Asteroids / debris", kind: "space", keywords: ["asteroid", "belt", "debris", "comet", "meteor"] }, + { id: "station", label: "Station / port", kind: "space", keywords: ["station", "starport", "port", "jump point", "gate"] }, + { id: "anomaly", label: "Anomaly / hazard", kind: "space", keywords: ["anomaly", "black hole", "radiation", "hazard"] }, +]; + +const BY_ID = new Map(TERRAIN_TYPES.map((t) => [t.id, t])); + +export function terrainTypeInfo(id: string | undefined): TerrainTypeInfo | undefined { + return id ? BY_ID.get(id) : undefined; +} + +export function isTerrainType(id: string | undefined): boolean { + return !!id && BY_ID.has(id); +} + +/** + * Best-guess type from a terrain's name (and category as a fallback), + * e.g. "dark forest" → forest, "forested hills" → hills. Longest keyword + * wins so "gas giant" beats "giant star" and "mountains snow" picks + * mountains over snow only if that keyword is longer. Returns undefined + * when nothing matches. + */ +export function inferTerrainType(name: string, category?: string, kind?: MapKind): string | undefined { + const scan = (text: string): string | undefined => { + const t = text.toLowerCase(); + let best: { id: string; len: number; pos: number } | undefined; + for (const type of TERRAIN_TYPES) { + if (kind && type.kind !== kind) continue; + for (const kw of type.keywords) { + const pos = t.lastIndexOf(kw); + if (pos < 0) continue; + // Prefer the keyword nearest the end ("forested hills" is hills), + // then the longest. + const end = pos + kw.length; + if (!best || end > best.pos || (end === best.pos && kw.length > best.len)) { + best = { id: type.id, len: kw.length, pos: end }; + } + } + } + return best?.id; + }; + return scan(name) ?? (category ? scan(category) : undefined); +} diff --git a/src/types.ts b/src/types.ts index fb4b12ac..3173a73e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -128,6 +128,10 @@ export interface TerrainColor { icon?: string; iconColor?: string; // CSS colour to tint the icon; undefined = no tint (render as-is) category?: string; + /** Terrain type id from src/terrainTypes.ts ("forest", "water", "star"…): + * what this terrain *is*, whatever it's called. Used by generators and + * the hex table. Unset = unknown (inferred from the name where needed). */ + type?: string; } export interface HexmakerPluginSettings { @@ -182,6 +186,8 @@ export interface HexmakerPluginSettings { palettesMigrated: boolean; /** Enabled map types (see src/mapKinds.ts). Unset = all. */ mapKinds: string[]; + /** True once existing palettes got terrain types (one-time seeding). */ + terrainTypesSeeded: boolean; } export const LINK_SECTIONS = ["Towns", "Dungeons", "Features", "Quests", "Factions", "Encounters Table"] as const; diff --git a/styles.css b/styles.css index ac163709..f9848342 100644 --- a/styles.css +++ b/styles.css @@ -1951,6 +1951,149 @@ input.duckmage-input-error { gap: 0.5em; } +/* ── Palette editor page ────────────────────────────────────────────── */ +.duckmage-palette-editor { + padding: 1em 1.25em 3em; +} + +.duckmage-pe-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5em; + margin-bottom: 0.5em; +} + +.duckmage-pe-palette-select { + font-weight: var(--font-semibold); + min-width: 12em; +} + +.duckmage-pe-search { + margin-left: auto; + min-width: 12em; +} + +.duckmage-pe-hint { + display: flex; + align-items: center; + gap: 0.5em; + color: var(--text-muted); + font-size: var(--font-ui-small); + margin-bottom: 0.4em; +} + +.duckmage-pe-table { + width: 100%; + border-collapse: collapse; +} + +.duckmage-pe-table th { + text-align: left; + font-size: var(--font-ui-smaller); + color: var(--text-muted); + font-weight: var(--font-normal); + padding: 0.25em 0.4em; + border-bottom: 1px solid var(--background-modifier-border); +} + +.duckmage-pe-table td { + padding: 0.2em 0.4em; + border-bottom: 1px solid var(--background-modifier-border-hover); + vertical-align: middle; +} + +.duckmage-pe-table input[type="text"], +.duckmage-pe-table select { + width: 100%; + min-width: 7em; +} + +.duckmage-pe-table input[type="color"] { + width: 2.2em; + height: 1.8em; + padding: 0; + border: none; + background: none; + cursor: pointer; +} + +.duckmage-pe-table select.is-unset { + color: var(--text-faint); +} + +.duckmage-pe-handle { + cursor: grab; + color: var(--text-faint); + width: 1.2em; + user-select: none; +} + +.duckmage-pe-table tr.is-dragging { + opacity: 0.45; +} + +.duckmage-pe-table tr.is-drop-target { + box-shadow: inset 0 2px 0 var(--interactive-accent); +} + +.duckmage-pe-icon { + width: 2.4em; + height: 2.2em; + padding: 0.15em; + display: inline-flex; + align-items: center; + justify-content: center; +} + +.duckmage-pe-icon img { + max-width: 100%; + max-height: 100%; +} + +.duckmage-pe-tint { + white-space: nowrap; +} + +.duckmage-pe-delete { + padding: 0 0.6em; + color: var(--text-muted); +} + +.duckmage-pe-delete.is-armed { + background: var(--background-modifier-error); + color: var(--text-on-accent); +} + +.duckmage-pe-size { + white-space: nowrap; +} + +.duckmage-pe-size input { + width: 4em; +} + +.duckmage-pe-add-row { + display: flex; + gap: 0.5em; + margin: 0.5em 0 1em; +} + +.duckmage-pe-field { + display: grid; + grid-template-columns: 10em minmax(0, 22em); + align-items: center; + gap: 0.25em 0.75em; +} + +.duckmage-pe-field .setting-item-description { + grid-column: 2; +} + +.duckmage-pe-defaults td.mod-warning { + color: var(--text-warning); +} + /* Onboarding: "What will you map?" checkboxes. */ .duckmage-wizard-kinds { display: flex; From 9415707d13e8f3112cb42f1884d5a17aadde091e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 13:53:24 -0400 Subject: [PATCH 041/558] feat(regions): shared grid for neighbour regions (pure logic) Maps that neighbour each other sit in slots of one "world": same width and height, slot (cx, cy). A hex's world position is slot * size + its place in the map, so walking off an edge lands on the right hex next door and east then south reaches the same map as south then east. New neighbours copy the size and offset and get the stagger that carries the column/row stagger on across the seam; existing maps that wouldn't line up are refused (changing their stagger would shift painted hexes). Linking checks palette, size, taken slots, and moves a whole group along when joining two. Tests build 10x10 worlds of 4x4 and 5x3 regions (flat odd/even, pointy), some with their own offsets, and check every hex's six flower neighbours, resolved across seams, are its neighbours on one unbroken grid; and that a 3000-step random walk through the flower, retraced, ends where it started. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/worldgen/world.ts | 221 ++++++++++++++++++++++++++++++++++++ tests/worldgenWorld.test.ts | 200 ++++++++++++++++++++++++++++++++ 3 files changed, 423 insertions(+), 2 deletions(-) create mode 100644 src/worldgen/world.ts create mode 100644 tests/worldgenWorld.test.ts diff --git a/package.json b/package.json index 9c696725..32b772e1 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenSizePresets.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenSizePresets.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/worldgenSizePresets.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/worldgenSizePresets.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/worldgen/world.ts b/src/worldgen/world.ts new file mode 100644 index 00000000..d33c406b --- /dev/null +++ b/src/worldgen/world.ts @@ -0,0 +1,221 @@ +/** + * Neighbour regions: maps placed side by side on one shared sheet of hex + * grid paper (a "world"). + * + * Every map in a world has the same width and height and sits in a slot + * (cx, cy); its neighbours are whatever maps sit in the slots around it. A + * hex's world position is its slot times the map size plus its place in the + * map, so walking off one map's edge lands on the right hex of the next, and + * going east then south reaches the same map as south then east. + * + * Hex grids also stagger every other column (flat-top) or row (pointy-top). + * Across a border the stagger has to carry on as if it were one map, or the + * hexes along the seam wouldn't line up. Each map's own stagger setting is + * chosen (new maps) or checked (existing maps) so it does. + * + * Pure: works on map-like records; callers save the changes. + */ + +export type Side = "north" | "south" | "east" | "west"; +export const SIDES: readonly Side[] = ["north", "east", "south", "west"]; +export const OPPOSITE: Record = { north: "south", south: "north", east: "west", west: "east" }; +const DELTA: Record = { north: [0, -1], south: [0, 1], east: [1, 0], west: [-1, 0] }; + +export interface WorldSlot { + /** Shared by every map in the world. */ + id: string; + cx: number; + cy: number; +} + +export interface RegionLike { + name: string; + paletteName: string; + gridSize: { cols: number; rows: number }; + gridOffset: { x: number; y: number }; + staggerOffset?: "odd" | "even"; + world?: WorldSlot; +} + +export type Orientation = "flat" | "pointy"; +export type Stagger = "odd" | "even"; + +export interface GridRules { + orientation: Orientation; + /** The plugin-wide stagger, for maps that don't set their own. */ + stagger: Stagger; +} + +const staggerOf = (m: RegionLike, rules: GridRules): Stagger => m.staggerOffset ?? rules.stagger; + +/** Whether a column (flat) / row (pointy) at coordinate n is the shifted one. */ +export const isShifted = (stagger: Stagger, n: number): boolean => (stagger === "odd" ? Math.abs(n) % 2 === 1 : Math.abs(n) % 2 === 0); + +/** World position of a map's local hex (the hex may lie outside the map). */ +export function toWorld(m: RegionLike, x: number, y: number): { wx: number; wy: number } | null { + if (!m.world) return null; + return { wx: m.world.cx * m.gridSize.cols + (x - m.gridOffset.x), wy: m.world.cy * m.gridSize.rows + (y - m.gridOffset.y) }; +} + +const floorDiv = (a: number, b: number) => Math.floor(a / b); + +export function mapAt(maps: T[], worldId: string, cx: number, cy: number): T | undefined { + return maps.find((m) => m.world?.id === worldId && m.world.cx === cx && m.world.cy === cy); +} + +export function neighbour(maps: T[], m: RegionLike, side: Side): T | undefined { + if (!m.world) return undefined; + const [dx, dy] = DELTA[side]; + return mapAt(maps, m.world.id, m.world.cx + dx, m.world.cy + dy); +} + +export function neighbours(maps: T[], m: RegionLike): Partial> { + const out: Partial> = {}; + for (const s of SIDES) { + const n = neighbour(maps, m, s); + if (n) out[s] = n; + } + return out; +} + +/** + * Which map and local hex a hex of `m` really is: itself if it's inside, the + * neighbouring map's hex if it's past an edge (any distance, any direction), + * or null if no map sits there. + */ +export function resolveHex(maps: T[], m: T, x: number, y: number): { map: T; x: number; y: number } | null { + const { cols, rows } = m.gridSize; + const inside = x >= m.gridOffset.x && x < m.gridOffset.x + cols && y >= m.gridOffset.y && y < m.gridOffset.y + rows; + if (inside) return { map: m, x, y }; + const w = toWorld(m, x, y); + if (!w || !m.world) return null; + const cx = floorDiv(w.wx, cols), cy = floorDiv(w.wy, rows); + const other = mapAt(maps, m.world.id, cx, cy); + if (!other) return null; + return { map: other, x: other.gridOffset.x + (w.wx - cx * cols), y: other.gridOffset.y + (w.wy - cy * rows) }; +} + +/** + * The stagger a map in slot (cx, cy) with this offset must use so that its + * stagger carries on from `ref`'s (another map in the same world). + */ +export function staggerToMatch(ref: RegionLike, refStagger: Stagger, cx: number, cy: number, offset: { x: number; y: number }, rules: GridRules): Stagger { + if (!ref.world) return refStagger; + const flat = rules.orientation === "flat"; + // The world coordinate along the stagger axis at the new map's first local + // column/row, and the same world coordinate seen from ref's local frame. + const size = flat ? ref.gridSize.cols : ref.gridSize.rows; + const newOrigin = flat ? offset.x : offset.y; + const refOrigin = flat ? ref.gridOffset.x : ref.gridOffset.y; + const refSlot = flat ? ref.world.cx : ref.world.cy; + const newSlot = flat ? cx : cy; + const worldAtNew = newSlot * size; // world coord of the new map's first column/row + const refLocal = refOrigin + (worldAtNew - refSlot * size); + const shifted = isShifted(refStagger, refLocal); + // Pick the stagger under which the new map's first column/row has that shift. + return isShifted("odd", newOrigin) === shifted ? "odd" : "even"; +} + +export type PlaceCheck = { ok: true } | { ok: false; reason: string }; + +/** Whether `m` could sit in (cx, cy) of the world `members` belong to. */ +export function canPlace(members: RegionLike[], m: RegionLike, cx: number, cy: number, rules: GridRules, ignore: Set = new Set()): PlaceCheck { + const others = members.filter((o) => o.name !== m.name && !ignore.has(o.name)); + const ref = others[0]; + if (!ref) return { ok: true }; + const taken = others.find((o) => o.world && o.world.cx === cx && o.world.cy === cy); + if (taken) return { ok: false, reason: `"${taken.name}" is already there` }; + if (m.paletteName !== ref.paletteName) + return { ok: false, reason: `"${m.name}" uses palette "${m.paletteName}"; neighbouring regions must all use "${ref.paletteName}"` }; + if (m.gridSize.cols !== ref.gridSize.cols || m.gridSize.rows !== ref.gridSize.rows) + return { ok: false, reason: `"${m.name}" is ${m.gridSize.cols}×${m.gridSize.rows}; neighbouring regions must all be ${ref.gridSize.cols}×${ref.gridSize.rows}` }; + const need = staggerToMatch(ref, staggerOf(ref, rules), cx, cy, m.gridOffset, rules); + if (need !== staggerOf(m, rules)) + return { + ok: false, + reason: `"${m.name}"'s ${rules.orientation === "flat" ? "columns" : "rows"} are staggered the other way, so its hexes wouldn't line up along the border. Changing that would shift every hex already painted; make a new region instead`, + }; + return { ok: true }; +} + +/** A new world id. */ +export const newWorldId = (): string => `w${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`; + +export type LinkResult = { ok: true; changes: Map } | { ok: false; reason: string }; + +/** + * Put `b` on `side` of `a`. If `b` is in a world of its own, that whole world + * moves along with it (keeping its layout), as long as nothing overlaps. + * Returns the new slot for every map that changes; nothing is changed here. + */ +export function link(maps: RegionLike[], aName: string, side: Side, bName: string, rules: GridRules, makeId = newWorldId): LinkResult { + const a = maps.find((m) => m.name === aName), b = maps.find((m) => m.name === bName); + if (!a || !b) return { ok: false, reason: "Map not found" }; + if (a.name === b.name) return { ok: false, reason: "A region can't neighbour itself" }; + const changes = new Map(); + const aSlot: WorldSlot = a.world ?? { id: makeId(), cx: 0, cy: 0 }; + if (!a.world) changes.set(a.name, aSlot); + const [dx, dy] = DELTA[side]; + const tx = aSlot.cx + dx, ty = aSlot.cy + dy; + const aWorld = maps.filter((m) => m.world?.id === aSlot.id || m.name === a.name).map((m) => (m.name === a.name ? { ...m, world: aSlot } : m)); + + if (b.world && b.world.id === aSlot.id) { + if (b.world.cx === tx && b.world.cy === ty) return { ok: true, changes }; + return { ok: false, reason: `"${b.name}" is already elsewhere in this group of regions` }; + } + // Everything that moves: b alone, or b's whole world shifted so b lands on the target. + const moving = b.world ? maps.filter((m) => m.world?.id === b.world!.id) : [b]; + const sx = tx - (b.world?.cx ?? 0), sy = ty - (b.world?.cy ?? 0); + for (const m of moving) { + const cx = (m.world?.cx ?? 0) + sx, cy = (m.world?.cy ?? 0) + sy; + const check = canPlace(aWorld, m, cx, cy, rules); + if (!check.ok) return { ok: false, reason: check.reason }; + } + for (const m of moving) changes.set(m.name, { id: aSlot.id, cx: (m.world?.cx ?? 0) + sx, cy: (m.world?.cy ?? 0) + sy }); + return { ok: true, changes }; +} + +/** + * Where a new region on `side` of `a` goes: its slot, and the offset and + * stagger it should be made with (same offset as `a`; stagger to match). + */ +export function newNeighbourSpec( + maps: RegionLike[], + a: RegionLike, + side: Side, + rules: GridRules, + makeId = newWorldId, +): { ok: true; slot: WorldSlot; aSlot: WorldSlot; cols: number; rows: number; offset: { x: number; y: number }; stagger: Stagger; paletteName: string } | { ok: false; reason: string } { + const aSlot: WorldSlot = a.world ?? { id: makeId(), cx: 0, cy: 0 }; + const [dx, dy] = DELTA[side]; + const slot = { id: aSlot.id, cx: aSlot.cx + dx, cy: aSlot.cy + dy }; + const taken = mapAt(maps, aSlot.id, slot.cx, slot.cy); + if (taken && a.world) return { ok: false, reason: `"${taken.name}" is already ${side} of "${a.name}"` }; + const placed = { ...a, world: aSlot }; + const stagger = staggerToMatch(placed, staggerOf(a, rules), slot.cx, slot.cy, a.gridOffset, rules); + return { ok: true, slot, aSlot, cols: a.gridSize.cols, rows: a.gridSize.rows, offset: { ...a.gridOffset }, stagger, paletteName: a.paletteName }; +} + +/** Depth of the neighbour "shadow" shown past each edge: 1 for small maps, 2 medium, 3 large. */ +export function shadowDepth(cols: number, rows: number): number { + const n = Math.max(cols, rows); + return n <= 20 ? 1 : n <= 30 ? 2 : 3; +} + +/** + * Hexes past `m`'s edges that belong to a neighbour, up to `depth` deep (the + * corners too, when a diagonal map exists): local key of the hex in `m`'s + * frame → which map and hex it is. + */ +export function shadowHexes(maps: T[], m: T, depth: number): Map { + const out = new Map(); + if (!m.world) return out; + const { x: ox, y: oy } = m.gridOffset, { cols, rows } = m.gridSize; + for (let y = oy - depth; y < oy + rows + depth; y++) + for (let x = ox - depth; x < ox + cols + depth; x++) { + if (x >= ox && x < ox + cols && y >= oy && y < oy + rows) continue; + const r = resolveHex(maps, m, x, y); + if (r) out.set(`${x}_${y}`, r); + } + return out; +} diff --git a/tests/worldgenWorld.test.ts b/tests/worldgenWorld.test.ts new file mode 100644 index 00000000..e1856249 --- /dev/null +++ b/tests/worldgenWorld.test.ts @@ -0,0 +1,200 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { hexNeighbors, mulberry32 } from "../packages/hex-wfc/src"; +import { + canPlace, + isShifted, + link, + neighbour, + newNeighbourSpec, + resolveHex, + shadowDepth, + shadowHexes, + staggerToMatch, + toWorld, + SIDES, + type GridRules, + type RegionLike, + type Side, +} from "../src/worldgen/world"; + +/** Neighbour regions on one shared grid (src/worldgen/world.ts). */ + +type Map_ = RegionLike & { gridOffset: { x: number; y: number } }; +const region = (name: string, cols: number, rows: number, over: Partial = {}): Map_ => ({ + name, paletteName: "Default", gridSize: { cols, rows }, gridOffset: { x: 0, y: 0 }, ...over, +}); + +/** + * Build a w×h world of cols×rows regions the way the UI does: each new region + * is made next to an existing one with newNeighbourSpec. Some get odd + * offsets (as if made elsewhere first), with the stagger worked out to match. + */ +function buildWorld(w: number, h: number, cols: number, rows: number, rules: GridRules, seed = 1): Map_[] { + const rng = mulberry32(seed); + const maps: Map_[] = [region("r0_0", cols, rows, { gridOffset: { x: -7, y: -9 } })]; + let id = ""; + for (let cy = 0; cy < h; cy++) + for (let cx = 0; cx < w; cx++) { + if (cx === 0 && cy === 0) continue; + const from = cx > 0 ? maps.find((m) => m.name === `r${cx - 1}_${cy}`)! : maps.find((m) => m.name === `r${cx}_${cy - 1}`)!; + const side: Side = cx > 0 ? "east" : "south"; + const spec = newNeighbourSpec(maps, from, side, rules, () => (id ||= "world")); + if (!spec.ok) throw new Error(spec.reason); + if (!from.world) from.world = spec.aSlot; + // Every third region: made with its own offset; stagger recomputed for it. + const offset = rng() < 0.33 ? { x: Math.floor(rng() * 21) - 10, y: Math.floor(rng() * 21) - 10 } : spec.offset; + const m = region(`r${cx}_${cy}`, cols, rows, { gridOffset: offset }); + const anchor = maps[0]; + const stagger = offset === spec.offset ? spec.stagger : undefined; + m.world = spec.slot; + if (stagger) m.staggerOffset = stagger; + else m.staggerOffset = staggerToMatch(from, from.staggerOffset ?? rules.stagger, spec.slot.cx, spec.slot.cy, offset, rules); + const placed = canPlace(maps.filter((o) => o.world?.id === spec.slot.id), m, spec.slot.cx, spec.slot.cy, rules); + expect(placed.ok ? "ok" : placed.reason).toBe("ok"); + maps.push(m); + void anchor; + } + return maps; +} + +const stg = (m: RegionLike, rules: GridRules) => m.staggerOffset ?? rules.stagger; + +/** World-frame neighbours, using the stagger of the region at slot (0,0). */ +function worldNeighbours(maps: Map_[], wx: number, wy: number, rules: GridRules): string[] { + const ref = maps.find((m) => m.world && m.world.cx === 0 && m.world.cy === 0)!; + // A world coordinate is shifted iff the same coordinate in ref's frame is. + const toRef = (wx_: number, wy_: number) => [ref.gridOffset.x + wx_, ref.gridOffset.y + wy_] as const; + const [rx, ry] = toRef(wx, wy); + return hexNeighbors(rx, ry, rules.orientation, stg(ref, rules)).map(([x, y]) => `${x - ref.gridOffset.x}_${y - ref.gridOffset.y}`); +} + +for (const rules of [ + { orientation: "flat", stagger: "odd" }, + { orientation: "flat", stagger: "even" }, + { orientation: "pointy", stagger: "odd" }, +] as GridRules[]) { + describe(`neighbour regions (${rules.orientation}, ${rules.stagger})`, () => { + for (const [cols, rows] of [[4, 4], [5, 3]]) { + it(`a 10×10 world of ${cols}×${rows} regions keeps one unbroken grid across every seam`, () => { + const maps = buildWorld(10, 10, cols, rows, rules, cols * 31 + rows); + expect(maps).toHaveLength(100); + for (const m of maps) { + for (let y = m.gridOffset.y; y < m.gridOffset.y + rows; y++) + for (let x = m.gridOffset.x; x < m.gridOffset.x + cols; x++) { + const here = toWorld(m, x, y)!; + const expected = new Set(worldNeighbours(maps, here.wx, here.wy, rules)); + // What the hex flower shows: neighbours in this map's frame, resolved across edges. + for (const [nx, ny] of hexNeighbors(x, y, rules.orientation, stg(m, rules))) { + const r = resolveHex(maps, m, nx, ny); + if (!r) continue; // off the world's edge + const w = toWorld(r.map, r.x, r.y)!; + expect(expected.has(`${w.wx}_${w.wy}`)).toBe(true); + } + } + } + }); + } + + it("a random walk through the hex flower, retraced, ends where it started", () => { + const maps = buildWorld(10, 10, 4, 4, rules, 7); + const rng = mulberry32(42); + const start = { map: maps[0], x: maps[0].gridOffset.x + 1, y: maps[0].gridOffset.y + 2 }; + let at = start; + const steps: { from: typeof start; to: typeof start }[] = []; + const visited = new Set(); + for (let i = 0; i < 3000; i++) { + const options = hexNeighbors(at.x, at.y, rules.orientation, stg(at.map, rules)) + .map(([nx, ny]) => resolveHex(maps, at.map, nx, ny)) + .filter((r): r is NonNullable => !!r); + const next = options[Math.floor(rng() * options.length)]; + steps.push({ from: at, to: next }); + visited.add(next.map.name); + at = next; + } + expect(visited.size).toBeGreaterThan(20); + // Retrace: from each hex, the way back is one of its own flower tiles. + for (const { from, to } of steps.reverse()) { + expect(at).toEqual(to); + const back = hexNeighbors(at.x, at.y, rules.orientation, stg(at.map, rules)) + .map(([nx, ny]) => resolveHex(maps, at.map, nx, ny)) + .find((r) => r && r.map.name === from.map.name && r.x === from.x && r.y === from.y); + expect(back).toBeTruthy(); + at = back!; + } + expect(at).toEqual(start); + }); + }); +} + +describe("linking regions", () => { + const rules: GridRules = { orientation: "flat", stagger: "odd" }; + + it("puts a region on a side, and neighbours are found both ways", () => { + const maps = [region("a", 10, 8), region("b", 10, 8)]; + const r = link(maps, "a", "east", "b", rules, () => "w"); + expect(r.ok).toBe(true); + if (!r.ok) return; + for (const [name, slot] of r.changes) maps.find((m) => m.name === name)!.world = slot; + expect(neighbour(maps, maps[0], "east")?.name).toBe("b"); + expect(neighbour(maps, maps[1], "west")?.name).toBe("a"); + expect(SIDES.filter((s) => neighbour(maps, maps[0], s))).toEqual(["east"]); + }); + + it("refuses a different size, palette, or a taken slot", () => { + const maps = [region("a", 10, 8, { world: { id: "w", cx: 0, cy: 0 } }), region("b", 10, 8, { world: { id: "w", cx: 1, cy: 0 } })]; + const check = (m: Map_, side: Side = "west") => link([...maps, m], "a", side, m.name, rules); + expect(check(region("c", 12, 8))).toMatchObject({ ok: false, reason: expect.stringContaining("10×8") }); + expect(check(region("d", 10, 8, { paletteName: "test" }))).toMatchObject({ ok: false, reason: expect.stringContaining("palette") }); + expect(check(region("e", 10, 8), "east")).toMatchObject({ ok: false, reason: expect.stringContaining('"b" is already there') }); + expect(check(region("f", 10, 8)).ok).toBe(true); + }); + + it("refuses an existing map whose stagger wouldn't line up, rather than changing it", () => { + // 5 wide: the region east of a starts on an odd world column, so it must stagger the other way. + const maps = [region("a", 5, 4), region("b", 5, 4, { staggerOffset: "odd" })]; + expect(link(maps, "a", "east", "b", rules)).toMatchObject({ ok: false, reason: expect.stringContaining("staggered") }); + const fits = region("c", 5, 4, { staggerOffset: "even" }); + expect(link([...maps, fits], "a", "east", "c", rules).ok).toBe(true); + }); + + it("moves a whole group along when joining two groups, if nothing overlaps", () => { + const maps = [ + region("a", 6, 6, { world: { id: "w1", cx: 0, cy: 0 } }), + region("b", 6, 6, { world: { id: "w2", cx: 5, cy: 5 } }), + region("c", 6, 6, { world: { id: "w2", cx: 5, cy: 6 } }), // south of b + ]; + const r = link(maps, "a", "east", "b", rules); + expect(r.ok).toBe(true); + if (!r.ok) return; + expect(r.changes.get("b")).toEqual({ id: "w1", cx: 1, cy: 0 }); + expect(r.changes.get("c")).toEqual({ id: "w1", cx: 1, cy: 1 }); + }); + + it("new neighbours copy the size and offset, with the stagger that lines up", () => { + const a = region("a", 5, 4, { gridOffset: { x: -7, y: -9 } }); + const spec = newNeighbourSpec([a], a, "east", rules, () => "w"); + expect(spec).toMatchObject({ ok: true, cols: 5, rows: 4, offset: { x: -7, y: -9 }, slot: { id: "w", cx: 1, cy: 0 } }); + // a's world column 5 is its local column -2 (unshifted under "odd"); the + // new map's local column -7 must be unshifted too, so it staggers "even". + if (spec.ok) { + expect(isShifted(spec.stagger, -7)).toBe(isShifted("odd", -2)); + expect(spec.stagger).toBe("even"); + } + }); +}); + +describe("shadows", () => { + it("are 1, 2 or 3 hexes deep for small, medium and large maps", () => { + expect([shadowDepth(20, 14), shadowDepth(30, 20), shadowDepth(40, 28), shadowDepth(4, 4)]).toEqual([1, 2, 3, 1]); + }); + + it("cover only the sides (and corners) where a neighbour is", () => { + const rules: GridRules = { orientation: "flat", stagger: "odd" }; + const maps = buildWorld(2, 2, 4, 4, rules); + const s = shadowHexes(maps, maps[0], 1); // r0_0: neighbours east, south, and south-east + const owners = new Set([...s.values()].map((v) => v.map.name)); + expect(owners).toEqual(new Set(["r1_0", "r0_1", "r1_1"])); + expect(s.size).toBe(4 + 4 + 1); + }); +}); From b0e32d46cfca4ee626829162af5e6099e51e0371 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 14:03:08 -0400 Subject: [PATCH 042/558] feat: terrain types in the hex table and the generators Hex table: - Type column (from the map palette entry; never inferred), muted base-terrain display for hexes with no terrain on maps with a base terrain. - Terrain filter grouped by type: click a type to include/exclude all its terrains; untyped terrains keep the old category grouping. - "Sort: type" added to the sort cycle. - Fix: the table now reacts to deleted/renamed hex notes (rows lingered after a map shrank). - Pure logic in src/hex-table/terrainTypeFilter.ts; tests in tests/hexTableTypes.test.ts. Generators (procedural): - Roles resolve by terrain type first (ofType / findByType / findRole in common.ts); a typed terrain only fills roles of its type, so a misleadingly named terrain is never misused. Name/category guesses remain the fallback for untyped terrains. - Custom-named typed palettes work in Star scatter, Orbits and Planet surface. Planet surface spreads forest variants (conifer / mixed / broadleaf / tropical, dense on wet ground) and wooded hills/mountains on Expanded; space and Limited outputs unchanged (verified over 100 seeds). Also tests/terrainTypes.test.ts (vocabulary, inference, Type column, seeding). Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/hex-table/HexTableView.ts | 181 +++++++++++++++---- src/hex-table/TerrainFilterModal.ts | 177 +++++++++++++------ src/hex-table/terrainTypeFilter.ts | 109 ++++++++++++ src/worldgen/procedural/common.ts | 69 ++++++++ src/worldgen/procedural/orbits.ts | 124 ++++++++++--- src/worldgen/procedural/planetSurface.ts | 140 ++++++++++++--- src/worldgen/procedural/starScatter.ts | 74 ++++++-- styles.css | 21 +++ tests/hexTableTypes.test.ts | 118 +++++++++++++ tests/proceduralGenerators.test.ts | 213 ++++++++++++++++++++++- tests/terrainTypes.test.ts | 98 +++++++++++ 12 files changed, 1176 insertions(+), 152 deletions(-) create mode 100644 src/hex-table/terrainTypeFilter.ts create mode 100644 tests/hexTableTypes.test.ts create mode 100644 tests/terrainTypes.test.ts diff --git a/package.json b/package.json index eece6f15..952708dc 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-table/HexTableView.ts b/src/hex-table/HexTableView.ts index 656d5a57..40e74181 100644 --- a/src/hex-table/HexTableView.ts +++ b/src/hex-table/HexTableView.ts @@ -14,6 +14,20 @@ import { HexCellModal } from "./HexCellModal"; import { MultiLinkNavModal } from "./MultiLinkNavModal"; import { HexTerrainPickerModal } from "./HexTerrainPickerModal"; import { LinkPickerModal } from "./LinkPickerModal"; +import { + compareTerrainTypes, + matchesTerrainFilter, + resolveTerrainType, + terrainTypeLabel, +} from "./terrainTypeFilter"; + +type SortMode = "x" | "y" | "type"; +const SORT_LABELS: Record = { + x: "Sort: xy", + y: "Sort: yx", + type: "Sort: type", +}; +const NEXT_SORT: Record = { x: "y", y: "type", type: "x" }; // Column definitions in template order const COLUMNS: { key: string; label: string; isLink: boolean }[] = [ @@ -47,7 +61,7 @@ export class HexTableView extends ItemView { private paletteMapCache = new Map>(); // Sort state - private sortPrimary: "x" | "y" = "x"; + private sortPrimary: SortMode = "x"; private sortAsc = true; private sortPrimaryBtn: HTMLButtonElement | null = null; private sortDirBtn: HTMLButtonElement | null = null; @@ -59,6 +73,8 @@ export class HexTableView extends ItemView { private filterYMax: number | null = null; private filterTerrains = new Set(); private filterExcludeTerrains = new Set(); + private filterTypes = new Set(); + private filterExcludeTypes = new Set(); private filterHasTown = false; private filterHasDungeon = false; private filterHasFeature = false; @@ -175,11 +191,17 @@ export class HexTableView extends ItemView { new TerrainFilterModal( this.app, palette, - new Set(this.filterTerrains), - new Set(this.filterExcludeTerrains), - (selected, excluded) => { - this.filterTerrains = selected; - this.filterExcludeTerrains = excluded; + { + terrains: new Set(this.filterTerrains), + excludeTerrains: new Set(this.filterExcludeTerrains), + types: new Set(this.filterTypes), + excludeTypes: new Set(this.filterExcludeTypes), + }, + (sets) => { + this.filterTerrains = sets.terrains; + this.filterExcludeTerrains = sets.excludeTerrains; + this.filterTypes = sets.types; + this.filterExcludeTypes = sets.excludeTypes; this.updateTerrainBtnLabel(); this.applyFilters(); }, @@ -283,16 +305,14 @@ export class HexTableView extends ItemView { // Sort controls this.sortPrimaryBtn = toolbar.createEl("button", { - text: "Sort: xy", + text: SORT_LABELS[this.sortPrimary], cls: "duckmage-filter-btn", }); this.sortPrimaryBtn.title = - "Toggle sort priority between X-first and y-first"; + "Cycle sort order: X first, y first, terrain type"; this.sortPrimaryBtn.addEventListener("click", () => { - this.sortPrimary = this.sortPrimary === "x" ? "y" : "x"; - this.sortPrimaryBtn!.setText( - this.sortPrimary === "x" ? "Sort: xy" : "Sort: yx", - ); + this.sortPrimary = NEXT_SORT[this.sortPrimary]; + this.sortPrimaryBtn!.setText(SORT_LABELS[this.sortPrimary]); void this.loadTable(); }); @@ -353,6 +373,37 @@ export class HexTableView extends ItemView { }), ); + // Hex notes are created on use and can be trashed (e.g. when the map + // shrinks), so drop rows whose note is gone instead of leaving dead rows. + const dropRow = (path: string) => { + const pending = this.updateTimers.get(path); + if (pending) { + window.clearTimeout(pending); + this.updateTimers.delete(path); + } + this.scrollEl + ?.querySelector(`tr[data-hex-path="${CSS.escape(path)}"]`) + ?.remove(); + }; + this.registerEvent( + this.app.vault.on("delete", (file) => { + if (file instanceof TFile) { + dropRow(file.path); + return; + } + // A map folder removed: its rows are all gone + const folder = normalizeFolder(this.plugin.settings.hexFolder); + if (!folder || file.path.startsWith(folder + "/")) void this.loadTable(); + }), + ); + this.registerEvent( + this.app.vault.on("rename", (file, oldPath) => { + if (!(file instanceof TFile)) return; + if (!HEX_PATTERN.test(oldPath) && !HEX_PATTERN.test(file.path)) return; + void this.loadTable(); + }), + ); + void this.loadTable(); return Promise.resolve(); } @@ -414,10 +465,23 @@ export class HexTableView extends ItemView { files = files.filter((f) => f.path.startsWith(prefix)); } + // Type sort: by terrain type (vocabulary order, untyped last), then x, y + const typeOf = new Map(); + if (this.sortPrimary === "type") { + for (const f of files) { + typeOf.set(f.path, this.resolveHexTerrain(f.path, f.region).type); + } + } files.sort((a, b) => { - const p = this.sortPrimary === "x" ? "x" : "y"; - const s = this.sortPrimary === "x" ? "y" : "x"; - const diff = a[p] !== b[p] ? a[p] - b[p] : a[s] - b[s]; + let diff = 0; + if (this.sortPrimary === "type") { + diff = compareTerrainTypes(typeOf.get(a.path)!, typeOf.get(b.path)!); + } + if (diff === 0) { + const p = this.sortPrimary === "y" ? "y" : "x"; + const s = this.sortPrimary === "y" ? "x" : "y"; + diff = a[p] !== b[p] ? a[p] - b[p] : a[s] - b[s]; + } return this.sortAsc ? diff : -diff; }); @@ -453,6 +517,7 @@ export class HexTableView extends ItemView { const headerRow = thead.createEl("tr"); headerRow.createEl("th", { text: "Hex" }); headerRow.createEl("th", { text: "Terrain" }); + headerRow.createEl("th", { text: "Type" }); for (const col of COLUMNS) { headerRow.createEl("th", { text: col.label }); } @@ -524,13 +589,13 @@ export class HexTableView extends ItemView { private updateTerrainBtnLabel(): void { if (!this.terrainFilterBtn) return; - const inc = this.filterTerrains.size; - const exc = this.filterExcludeTerrains.size; + const inc = this.filterTerrains.size + this.filterTypes.size; + const exc = this.filterExcludeTerrains.size + this.filterExcludeTypes.size; const parts: string[] = []; if (inc > 0) parts.push(`${inc} shown`); if (exc > 0) parts.push(`${exc} hidden`); this.terrainFilterBtn.setText( - parts.length ? `Terrain: ${parts.join(", ")}` : "Terrain: All", + parts.length ? `Terrain: ${parts.join(", ")}` : "Terrain: all", ); this.terrainFilterBtn.toggleClass( "duckmage-filter-active", @@ -545,6 +610,8 @@ export class HexTableView extends ItemView { this.filterYMax = null; this.filterTerrains = new Set(); this.filterExcludeTerrains = new Set(); + this.filterTypes = new Set(); + this.filterExcludeTypes = new Set(); this.filterHasTown = false; this.filterHasDungeon = false; this.filterHasFeature = false; @@ -576,10 +643,20 @@ export class HexTableView extends ItemView { const tbody = this.scrollEl.querySelector("tbody"); if (!tbody) return; + const terrainFilter = { + terrains: this.filterTerrains, + excludeTerrains: this.filterExcludeTerrains, + types: this.filterTypes, + excludeTypes: this.filterExcludeTypes, + }; for (const tr of rows ?? Array.from(tbody.rows)) { const x = Number(tr.dataset.hexX); const y = Number(tr.dataset.hexY); - const terrain = tr.dataset.terrain ?? ""; + const terrainRow = { + terrain: tr.dataset.terrain ?? "", + effectiveTerrain: tr.dataset.effectiveTerrain ?? "", + type: tr.dataset.terrainType ?? "", + }; const hasTown = tr.dataset.hasTown === "1"; const hasDungeon = tr.dataset.hasDungeon === "1"; const hasFeature = tr.dataset.hasFeature === "1"; @@ -591,13 +668,7 @@ export class HexTableView extends ItemView { if (this.filterXMax !== null && x > this.filterXMax) show = false; if (this.filterYMin !== null && y < this.filterYMin) show = false; if (this.filterYMax !== null && y > this.filterYMax) show = false; - if (this.filterTerrains.size > 0 && !this.filterTerrains.has(terrain)) - show = false; - if ( - this.filterExcludeTerrains.size > 0 && - this.filterExcludeTerrains.has(terrain) - ) - show = false; + if (!matchesTerrainFilter(terrainRow, terrainFilter)) show = false; if (this.filterHasTown && !hasTown) show = false; if (this.filterHasDungeon && !hasDungeon) show = false; if (this.filterHasFeature && !hasFeature) show = false; @@ -626,6 +697,25 @@ export class HexTableView extends ItemView { return m; } + /** + * A hex's own terrain, the terrain the map displays (own, else the map's + * base terrain) and that terrain's type ("" when the palette entry has none). + */ + private resolveHexTerrain( + path: string, + region: string, + ): { terrain: string; effective: string; isBase: boolean; type: string } { + const terrain = getTerrainFromFile(this.app, path) ?? ""; + const base = terrain ? "" : (this.plugin.getMap(region)?.baseTerrain ?? ""); + const effective = terrain || base; + return { + terrain, + effective, + isBase: !terrain && !!base, + type: resolveTerrainType(effective, this.getPaletteMap(region)), + }; + } + private fillRow( tr: HTMLTableRowElement, path: string, @@ -638,7 +728,6 @@ export class HexTableView extends ItemView { tr.empty(); const paletteMap = this.getPaletteMap(region); - const terrainName = getTerrainFromFile(this.app, path); const hasTown = (links.get("towns") ?? []).length > 0; const hasDungeon = (links.get("dungeons") ?? []).length > 0; @@ -649,7 +738,6 @@ export class HexTableView extends ItemView { // Store filter-relevant data on the row tr.dataset.hexX = String(x); tr.dataset.hexY = String(y); - tr.dataset.terrain = terrainName ?? ""; tr.dataset.hasTown = hasTown ? "1" : "0"; tr.dataset.hasDungeon = hasDungeon ? "1" : "0"; tr.dataset.hasFeature = hasFeature ? "1" : "0"; @@ -705,19 +793,43 @@ export class HexTableView extends ItemView { const terrainTd = tr.createEl("td", { cls: "duckmage-hex-table-cell-clickable", }); + const typeTd = tr.createEl("td"); + // Renders terrain + type and refreshes the row's filter data, so a pick + // shows at once (the vault modify event re-renders the row again later). const renderTerrainCell = () => { terrainTd.empty(); - const current = getTerrainFromFile(this.app, path); - const entry = current ? paletteMap.get(current) : undefined; + typeTd.empty(); + const hex = this.resolveHexTerrain(path, region); + tr.dataset.terrain = hex.terrain; + tr.dataset.effectiveTerrain = hex.effective; + tr.dataset.terrainType = hex.type; + + const entry = hex.effective ? paletteMap.get(hex.effective) : undefined; if (entry) { const swatch = terrainTd.createSpan({ cls: "duckmage-hex-table-swatch", }); - swatch.style.backgroundColor = entry.color; - terrainTd.appendText(entry.name); + swatch.setCssProps({ "--duckmage-swatch-color": entry.color }); + if (hex.isBase) { + terrainTd.createSpan({ + text: entry.name, + cls: "duckmage-hex-table-base-terrain", + attr: { title: "Map base terrain (no terrain set on this hex)" }, + }); + } else { + terrainTd.appendText(entry.name); + } } else { terrainTd.createSpan({ text: "–", cls: "duckmage-hex-table-empty" }); } + + const typeLabel = terrainTypeLabel(hex.type); + if (typeLabel) { + typeTd.setText(typeLabel); + typeTd.toggleClass("duckmage-hex-table-base-terrain", hex.isBase); + } else { + typeTd.createSpan({ text: "–", cls: "duckmage-hex-table-empty" }); + } }; renderTerrainCell(); terrainTd.addEventListener("click", () => { @@ -730,6 +842,7 @@ export class HexTableView extends ItemView { current, () => { renderTerrainCell(); + this.applyFilters([tr]); }, ).open(); }); @@ -917,9 +1030,9 @@ export class HexTableView extends ItemView { table.querySelectorAll("thead th"), ); - // Default widths (px): Hex, Terrain, then one per COLUMN entry + // Default widths (px): Hex, Terrain, Type, then one per COLUMN entry const defaultWidths = [ - 60, 110, 220, 160, 150, 150, 150, 140, 160, 160, 160, 140, + 60, 110, 100, 220, 160, 150, 150, 150, 140, 160, 160, 160, 140, ]; // elements + explicit table width is the only reliable way to drive diff --git a/src/hex-table/TerrainFilterModal.ts b/src/hex-table/TerrainFilterModal.ts index 2257e8d1..120b701c 100644 --- a/src/hex-table/TerrainFilterModal.ts +++ b/src/hex-table/TerrainFilterModal.ts @@ -1,75 +1,120 @@ import { App } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type { TerrainColor } from "../types"; +import { groupPaletteByType } from "./terrainTypeFilter"; + +/** Mutable include/exclude sets for terrain names and type ids. */ +export interface TerrainFilterSets { + terrains: Set; + excludeTerrains: Set; + types: Set; + excludeTypes: Set; +} export class TerrainFilterModal extends HexmakerModal { constructor( app: App, private palette: TerrainColor[], - private selected: Set, - private excluded: Set, - private onChange: (selected: Set, excluded: Set) => void, + private sets: TerrainFilterSets, + private onChange: (sets: TerrainFilterSets) => void, ) { super(app); } + private emit(): void { + this.onChange({ + terrains: new Set(this.sets.terrains), + excludeTerrains: new Set(this.sets.excludeTerrains), + types: new Set(this.sets.types), + excludeTypes: new Set(this.sets.excludeTypes), + }); + } + onOpen(): void { this.makeDraggable(); this.titleEl.setText("Filter by terrain"); const { contentEl } = this; contentEl.addClass("duckmage-terrain-filter-modal"); + const { groups: typeGroups, untyped } = groupPaletteByType(this.palette); + contentEl.createEl("p", { - text: "Left-click to include · right-click to exclude · click a category heading to toggle all", + text: + "Left-click to include · right-click to exclude · " + + (typeGroups.length > 0 + ? "a type row matches every terrain of that type" + : "click a category heading to toggle all"), cls: "duckmage-terrain-filter-hint", }); const list = contentEl.createDiv({ cls: "duckmage-terrain-filter-list" }); - // Map terrain name → row elements, so category headings can bulk-update them - const rowRefs = new Map(); - - const applyRowState = (lbl: HTMLElement, cb: HTMLInputElement, name: string) => { - cb.checked = this.selected.has(name); - lbl.toggleClass("duckmage-terrain-filter-excluded", this.excluded.has(name)); - }; - - const addRow = (name: string, label: string, color?: string, indented = false) => { - const lbl = list.createEl("label", { - cls: "duckmage-terrain-filter-row" + (indented ? " duckmage-terrain-filter-row-indented" : ""), - }); + // Every include/exclude row (terrains and types), so bulk actions can refresh them + const refreshers: (() => void)[] = []; + const terrainRefs = new Map void>(); + + /** + * A checkbox row bound to an include/exclude pair. Left-click (checkbox) + * toggles include; right-click toggles exclude. + */ + const addToggleRow = ( + key: string, + include: Set, + exclude: Set, + label: string, + cls: string, + color?: string, + ): (() => void) => { + const lbl = list.createEl("label", { cls }); const cb = lbl.createEl("input"); cb.type = "checkbox"; - applyRowState(lbl, cb, name); - - const swatch = lbl.createSpan({ cls: "duckmage-hex-table-swatch" }); - if (color) swatch.style.backgroundColor = color; + if (color !== undefined) { + const swatch = lbl.createSpan({ cls: "duckmage-hex-table-swatch" }); + if (color) swatch.setCssProps({ "--duckmage-swatch-color": color }); + } lbl.createSpan({ text: label }); - rowRefs.set(name, { lbl, cb }); + const refresh = () => { + cb.checked = include.has(key); + lbl.toggleClass("duckmage-terrain-filter-excluded", exclude.has(key)); + }; + refresh(); + refreshers.push(refresh); cb.addEventListener("change", () => { if (cb.checked) { - this.selected.add(name); - this.excluded.delete(name); + include.add(key); + exclude.delete(key); } else { - this.selected.delete(name); + include.delete(key); } - applyRowState(lbl, cb, name); - this.onChange(new Set(this.selected), new Set(this.excluded)); + refresh(); + this.emit(); }); - lbl.addEventListener("contextmenu", (e) => { e.preventDefault(); - if (this.excluded.has(name)) { - this.excluded.delete(name); + if (exclude.has(key)) { + exclude.delete(key); } else { - this.excluded.add(name); - this.selected.delete(name); + exclude.add(key); + include.delete(key); } - applyRowState(lbl, cb, name); - this.onChange(new Set(this.selected), new Set(this.excluded)); + refresh(); + this.emit(); }); + return refresh; + }; + + const addTerrainRow = (name: string, label: string, color?: string, indented = false) => { + const refresh = addToggleRow( + name, + this.sets.terrains, + this.sets.excludeTerrains, + label, + "duckmage-terrain-filter-row" + (indented ? " duckmage-terrain-filter-row-indented" : ""), + color ?? "", + ); + terrainRefs.set(name, refresh); }; const addCategoryHeading = (label: string, names: string[]) => { @@ -77,45 +122,57 @@ export class TerrainFilterModal extends HexmakerModal { heading.createSpan({ text: label }); const refreshRows = () => { - for (const name of names) { - const ref = rowRefs.get(name); - if (ref) applyRowState(ref.lbl, ref.cb, name); - } + for (const name of names) terrainRefs.get(name)?.(); }; + const { terrains: selected, excludeTerrains: excluded } = this.sets; // Left-click: include all (or deselect all if all already included) heading.addEventListener("click", () => { - const allIncluded = names.every(n => this.selected.has(n)); + const allIncluded = names.every(n => selected.has(n)); if (allIncluded) { - names.forEach(n => this.selected.delete(n)); + names.forEach(n => selected.delete(n)); } else { - names.forEach(n => { this.selected.add(n); this.excluded.delete(n); }); + names.forEach(n => { selected.add(n); excluded.delete(n); }); } refreshRows(); - this.onChange(new Set(this.selected), new Set(this.excluded)); + this.emit(); }); // Right-click: exclude all (or un-exclude all if all already excluded) heading.addEventListener("contextmenu", (e) => { e.preventDefault(); - const allExcluded = names.every(n => this.excluded.has(n)); + const allExcluded = names.every(n => excluded.has(n)); if (allExcluded) { - names.forEach(n => this.excluded.delete(n)); + names.forEach(n => excluded.delete(n)); } else { - names.forEach(n => { this.excluded.add(n); this.selected.delete(n); }); + names.forEach(n => { excluded.add(n); selected.delete(n); }); } refreshRows(); - this.onChange(new Set(this.selected), new Set(this.excluded)); + this.emit(); }); }; // "No terrain" is always first and never grouped - addRow("", "No terrain"); + addTerrainRow("", "No terrain"); + + // Typed terrains: one type row (filters by type) + its terrains indented + for (const group of typeGroups) { + addToggleRow( + group.typeId, + this.sets.types, + this.sets.excludeTypes, + group.label, + "duckmage-terrain-filter-row duckmage-terrain-filter-type-row", + ); + for (const entry of group.entries) { + addTerrainRow(entry.name, entry.name, entry.color, true); + } + } - // Split palette into ungrouped and category groups + // Untyped terrains keep the category grouping const groups = new Map(); const ungrouped: TerrainColor[] = []; - for (const entry of this.palette) { + for (const entry of untyped) { if (entry.category) { if (!groups.has(entry.category)) groups.set(entry.category, []); groups.get(entry.category)!.push(entry); @@ -124,9 +181,16 @@ export class TerrainFilterModal extends HexmakerModal { } } + if (typeGroups.length > 0 && untyped.length > 0) { + list.createDiv({ + text: "No type", + cls: "duckmage-terrain-filter-section-label", + }); + } + // Ungrouped terrains — no heading, not indented for (const entry of ungrouped) { - addRow(entry.name, entry.name, entry.color); + addTerrainRow(entry.name, entry.name, entry.color); } // Categorised terrains — heading + indented rows @@ -134,20 +198,19 @@ export class TerrainFilterModal extends HexmakerModal { const entries = groups.get(cat)!; addCategoryHeading(cat, entries.map(e => e.name)); for (const entry of entries) { - addRow(entry.name, entry.name, entry.color, true); + addTerrainRow(entry.name, entry.name, entry.color, true); } } const btnRow = contentEl.createDiv({ cls: "duckmage-terrain-filter-btns" }); const clearBtn = btnRow.createEl("button", { text: "Clear all" }); clearBtn.addEventListener("click", () => { - this.selected.clear(); - this.excluded.clear(); - this.onChange(new Set(this.selected), new Set(this.excluded)); - for (const { lbl, cb } of rowRefs.values()) { - cb.checked = false; - lbl.removeClass("duckmage-terrain-filter-excluded"); - } + this.sets.terrains.clear(); + this.sets.excludeTerrains.clear(); + this.sets.types.clear(); + this.sets.excludeTypes.clear(); + for (const refresh of refreshers) refresh(); + this.emit(); }); btnRow .createEl("button", { text: "Done", cls: "mod-cta" }) diff --git a/src/hex-table/terrainTypeFilter.ts b/src/hex-table/terrainTypeFilter.ts new file mode 100644 index 00000000..1758aa88 --- /dev/null +++ b/src/hex-table/terrainTypeFilter.ts @@ -0,0 +1,109 @@ +import type { TerrainColor } from "../types"; +import { TERRAIN_TYPES, terrainTypeInfo } from "../terrainTypes"; + +/** + * Pure (Obsidian-free) helpers for the hex table's terrain type column, + * type filter and type sort. + */ + +/** + * Type id of a terrain via its palette entry. Returns "" when the terrain + * is unset, not in the palette, has no type, or has an unknown type id. + * Never infers from the name: an untagged terrain shows no type. + */ +export function resolveTerrainType( + terrainName: string | null | undefined, + palette: ReadonlyMap, +): string { + if (!terrainName) return ""; + const type = palette.get(terrainName)?.type; + return terrainTypeInfo(type) ? type! : ""; +} + +/** Display label for a type id ("" for none/unknown). */ +export function terrainTypeLabel(typeId: string): string { + return terrainTypeInfo(typeId)?.label ?? ""; +} + +const TYPE_ORDER = new Map(TERRAIN_TYPES.map((t, i) => [t.id, i])); + +/** + * Compare two type ids in vocabulary order (water → land → space), so + * related types sort together. Untyped ("" or unknown) sorts last. + */ +export function compareTerrainTypes(a: string, b: string): number { + const ia = TYPE_ORDER.get(a) ?? Number.MAX_SAFE_INTEGER; + const ib = TYPE_ORDER.get(b) ?? Number.MAX_SAFE_INTEGER; + return ia - ib; +} + +export interface TerrainTypeGroup { + typeId: string; + label: string; + entries: TerrainColor[]; +} + +/** + * Split a palette into type groups (vocabulary order, only types present) + * and the entries with no valid type, which keep palette order. + */ +export function groupPaletteByType(palette: readonly TerrainColor[]): { + groups: TerrainTypeGroup[]; + untyped: TerrainColor[]; +} { + const byType = new Map(); + const untyped: TerrainColor[] = []; + for (const entry of palette) { + const info = terrainTypeInfo(entry.type); + if (!info) { + untyped.push(entry); + continue; + } + let list = byType.get(info.id); + if (!list) byType.set(info.id, (list = [])); + list.push(entry); + } + const groups = [...byType.entries()] + .sort(([a], [b]) => compareTerrainTypes(a, b)) + .map(([typeId, entries]) => ({ + typeId, + label: terrainTypeLabel(typeId), + entries, + })); + return { groups, untyped }; +} + +export interface TerrainFilterState { + /** Terrain names to include ("" = no terrain). */ + terrains: ReadonlySet; + excludeTerrains: ReadonlySet; + /** Type ids to include / exclude. */ + types: ReadonlySet; + excludeTypes: ReadonlySet; +} + +export interface TerrainFilterRow { + /** The hex's own terrain ("" when unset). */ + terrain: string; + /** The terrain the map displays: own terrain, else the map's base terrain. */ + effectiveTerrain: string; + /** Type id of the effective terrain ("" when none). */ + type: string; +} + +/** + * Whether a row passes the terrain/type filter. Include sets are a union: + * when any include set is non-empty, the row must match a selected terrain + * (own or displayed) or a selected type. Any exclude match hides the row. + */ +export function matchesTerrainFilter( + row: TerrainFilterRow, + f: TerrainFilterState, +): boolean { + const names = [row.terrain, row.effectiveTerrain]; + if (names.some((n) => f.excludeTerrains.has(n))) return false; + if (row.type && f.excludeTypes.has(row.type)) return false; + if (f.terrains.size === 0 && f.types.size === 0) return true; + if (names.some((n) => f.terrains.has(n))) return true; + return !!row.type && f.types.has(row.type); +} diff --git a/src/worldgen/procedural/common.ts b/src/worldgen/procedural/common.ts index cb4f865e..57bd6909 100644 --- a/src/worldgen/procedural/common.ts +++ b/src/worldgen/procedural/common.ts @@ -1,4 +1,5 @@ import { cellKey, hexDistance, type Orientation, type Stagger } from "../../../packages/hex-wfc/src"; +import { isTerrainType } from "../../terrainTypes"; import type { TerrainColor } from "../../types"; /** @@ -78,6 +79,74 @@ export function inCategory(terrains: TerrainColor[], category: string): string[] return terrains.filter((t) => t.category?.toLowerCase() === category).map((t) => t.name); } +/* + * Type-aware lookups. A terrain's `type` (see terrainTypes.ts) is + * authoritative: a typed terrain fills only the roles of its type, however + * it is named, so "ocean" typed desert is never used as sea. The name / + * category guesses above are the fallback for untyped terrains only. + */ + +/** Terrains with a known type id. Unknown ids count as untyped. */ +function typeOf(t: TerrainColor): string | undefined { + return isTerrainType(t.type) ? t.type : undefined; +} + +/** Terrains without a (known) type: the ones name / category guesses may use. */ +export function untyped(terrains: TerrainColor[]): TerrainColor[] { + return terrains.filter((t) => !typeOf(t)); +} + +/** Names of all terrains of the given types, in palette order. */ +export function ofType(terrains: TerrainColor[], typeIds: string[]): string[] { + return terrains.filter((t) => typeIds.includes(typeOf(t) ?? "")).map((t) => t.name); +} + +/** + * The terrain for a role among those of the given types: the first name in + * `preferNames` (case-insensitive) that is of one of the types, else the + * first terrain of `typeIds[0]`, then `typeIds[1]`, … in palette order. + * Picks "forest" over "forest heavy" for the base forest role, while a + * palette whose only forest is "Pinewood" still gets a forest. + */ +export function findByType( + terrains: TerrainColor[], + typeIds: string[], + preferNames: string[] = [], +): string | undefined { + const typed = terrains.filter((t) => typeIds.includes(typeOf(t) ?? "")); + if (typed.length === 0) return undefined; + const hinted = findTerrain(typed, preferNames); + if (hinted) return hinted; + for (const id of typeIds) { + const hit = typed.find((t) => typeOf(t) === id); + if (hit) return hit.name; + } + return undefined; +} + +/** + * Resolve a role: by type first, else by name / category among the + * untyped terrains (older or hand-made palettes). + */ +export function findRole( + terrains: TerrainColor[], + typeIds: string[], + names: string[], + category?: string, +): string | undefined { + return findByType(terrains, typeIds, names) ?? findTerrain(untyped(terrains), names, category); +} + +/** Lower-case name → type id, for weight tables keyed by type. */ +export function typeIndex(terrains: TerrainColor[]): Map { + const out = new Map(); + for (const t of terrains) { + const id = typeOf(t); + if (id) out.set(t.name.toLowerCase(), id); + } + return out; +} + /** * Weighted pick. `weights` maps lower-case terrain names to weights; names * not listed get `fallback`. Returns undefined for an empty list. diff --git a/src/worldgen/procedural/orbits.ts b/src/worldgen/procedural/orbits.ts index 8bbf3b1e..39dd8ea5 100644 --- a/src/worldgen/procedural/orbits.ts +++ b/src/worldgen/procedural/orbits.ts @@ -4,9 +4,13 @@ import { cellKey, centerHex, distance, + findByType, findTerrain, gridKeys, inCategory, + ofType, + typeIndex, + untyped, weightedPick, type ProcGrid, type ProcOption, @@ -21,9 +25,10 @@ import { * may get a moon; the mainworld may get a station or starport alongside; * a comet and a jump point sit out past the last orbit. * - * Works on any palette with a background ("void" / "empty space" / first - * `space` terrain) and at least one star and one body — by name, or the - * `stars` / `bodies` categories. + * Works on any palette with a background (type void, or "void" / "empty + * space" / first `space` terrain) and at least one star and one body — by + * type (star; world / gas-giant / asteroids), else by name or the `stars` + * / `bodies` categories. */ export const ORBITS_ID = "procedural:orbits"; @@ -63,7 +68,7 @@ const STAR_WEIGHTS: Record = { "blue giant": 0.5, }; -const ZONE_WEIGHTS: Record<"inner" | "habitable" | "outer", Record> = { +const ZONE_WEIGHTS: Record> = { inner: { "molten planet": 4, "rocky planet": 4, "desert planet": 2, "asteroid belt": 0.5 }, habitable: { "terrestrial planet": 4, "ocean planet": 3, "desert planet": 3, "rocky planet": 2, "asteroid belt": 1 }, outer: { "gas giant": 4, "ice giant": 3, "ice planet": 3, "asteroid belt": 1.5, "rocky planet": 1 }, @@ -74,6 +79,31 @@ const BODY_NAMES = [ "molten planet", "gas giant", "ice giant", "asteroid belt", ]; +type Zone = "inner" | "habitable" | "outer"; + +/** + * Zone weights for bodies the tables above don't name, by name hint (the + * type vocabulary is coarse: "world" covers lava rocks and ocean planets + * alike), else by type. + */ +const ZONE_HINTS: { re: RegExp; w: Record }[] = [ + { re: /molten|lava|magma|volcan|inferno|ember|cinder|scorch/i, w: { inner: 4, habitable: 0.5, outer: 0.2 } }, + { re: /\bice|frozen|frost|snow|glacier|\bcold/i, w: { inner: 0.2, habitable: 0.5, outer: 3 } }, + { re: /ocean|water|garden|terra|earth|jungle|green|eden|haven/i, w: { inner: 0.5, habitable: 4, outer: 0.3 } }, + { re: /desert|arid|dune|dust|sand/i, w: { inner: 2, habitable: 3, outer: 0.5 } }, + { re: /\brock|barren|stone/i, w: { inner: 4, habitable: 2, outer: 1 } }, +]; +const ZONE_TYPE_WEIGHTS: Record> = { + world: { inner: 2, habitable: 3, outer: 1 }, + "gas-giant": { inner: 0.3, habitable: 0.5, outer: 4 }, + asteroids: { inner: 0.5, habitable: 1, outer: 1.5 }, +}; + +/** Typed bodies that never take an orbit of their own. */ +const MOON = /\bmoons?\b|satellite/i; +const COMET = /comet/i; +const DEBRIS = /debris|wreck/i; + export interface OrbitRoles { background: string; stars: string[]; @@ -85,34 +115,86 @@ export interface OrbitRoles { jumpPoint?: string; jumpLimit?: string; belt?: string; + /** Bodies drawn as an arc of their ring (asteroid-type bodies, belts). */ + belts: string[]; + /** Bodies that may get a moon (gas-giant type, or "giant" in the name). */ + giants: string[]; + /** Per-zone body weights (lower-case names) for weightedPick. */ + zoneWeights: Record>; } +/** + * Roles by type first — void, star, world / gas-giant / asteroids, station + * — split by name hints where the type is coarse (moon vs planet, comet vs + * belt, starport vs jump point); untyped terrains fall back to the + * category and exact-name lookups. + */ export function orbitRoles(terrains: TerrainColor[]): OrbitRoles | undefined { - const background = findTerrain(terrains, ["void", "empty space", "deep space", "space"], "space"); - let stars = inCategory(terrains, "stars"); + const loose = untyped(terrains); + // "jump limit" is void-typed too, but it is a marker, not the background. + const background = findByType(terrains.filter((t) => !/limit/i.test(t.name)), ["void"], ["void", "empty space", "deep space", "space"]) + ?? findTerrain(loose, ["void", "empty space", "deep space", "space"], "space"); + // A sector's "star system" marker is star-typed but isn't a star. + let stars = [...ofType(terrains, ["star"]).filter((s) => !/system/i.test(s)), ...inCategory(loose, "stars")]; if (stars.length === 0) { - const s = findTerrain(terrains, ["yellow star", "star", "sun"]); + const s = findTerrain(loose, ["yellow star", "star", "sun"]); stars = s ? [s] : []; } - const names = new Set(terrains.map((t) => t.name.toLowerCase())); - let bodies = inCategory(terrains, "bodies").filter((b) => !/^(moon|comet)$/i.test(b)); - if (bodies.length === 0) bodies = terrains.map((t) => t.name).filter((n) => BODY_NAMES.includes(n.toLowerCase())); + const typedBodies = ofType(terrains, ["world", "gas-giant", "asteroids"]); + let bodies = [ + ...typedBodies.filter((b) => !MOON.test(b) && !COMET.test(b) && !DEBRIS.test(b)), + ...inCategory(loose, "bodies").filter((b) => !/^(moon|comet)$/i.test(b)), + ]; + if (bodies.length === 0) bodies = loose.map((t) => t.name).filter((n) => BODY_NAMES.includes(n.toLowerCase())); if (!background || stars.length === 0 || bodies.length === 0) return undefined; - const pick = (n: string) => (names.has(n) ? terrains.find((t) => t.name.toLowerCase() === n)!.name : undefined); + const types = typeIndex(terrains); + const exact = (n: string) => findTerrain(loose, [n]); + const station = (want: RegExp | undefined, avoid: RegExp | undefined, prefer: string[]) => + findByType(terrains.filter((t) => (!want || want.test(t.name)) && !avoid?.test(t.name)), ["station"], prefer); + const belts = bodies.filter((b) => types.get(b.toLowerCase()) === "asteroids" || /belt/i.test(b)); return { background, stars, bodies, - moon: pick("moon"), - comet: pick("comet"), - station: pick("space station"), - starport: pick("starport"), - jumpPoint: pick("jump point"), - jumpLimit: pick("jump limit"), - belt: bodies.find((b) => /belt/i.test(b)), + moon: findByType(terrains.filter((t) => MOON.test(t.name)), ["world"], ["moon"]) ?? exact("moon"), + comet: findByType(terrains.filter((t) => COMET.test(t.name)), ["asteroids"], ["comet"]) ?? exact("comet"), + station: station(undefined, /port|jump|gate/i, ["space station", "station"]) ?? exact("space station"), + starport: station(/port/i, undefined, ["starport"]) ?? exact("starport"), + jumpPoint: station(/jump|gate/i, undefined, ["jump point"]) ?? exact("jump point"), + jumpLimit: findByType(terrains.filter((t) => /limit/i.test(t.name)), ["void"], ["jump limit"]) ?? exact("jump limit"), + belt: belts[0], + belts, + giants: bodies.filter((b) => types.get(b.toLowerCase()) === "gas-giant" || /giant/i.test(b)), + zoneWeights: { + inner: zoneWeights(bodies, types, "inner"), + habitable: zoneWeights(bodies, types, "habitable"), + outer: zoneWeights(bodies, types, "outer"), + }, }; } +/** + * Weights for one zone. The shipped body names keep their table weights + * (0.5 when the zone doesn't list them); other names go by hint, then type. + */ +function zoneWeights(bodies: string[], types: Map, zone: Zone): Record { + const out: Record = {}; + for (const b of bodies) { + const k = b.toLowerCase(); + if (BODY_NAMES.includes(k)) { + out[k] = ZONE_WEIGHTS[zone][k] ?? 0.5; + continue; + } + const type = types.get(k); + // Giants go by type first: "ice giant" belongs outside, not with ice planets. + const w = (type === "gas-giant" ? ZONE_TYPE_WEIGHTS[type] : undefined) + ?? ZONE_HINTS.find((h) => h.re.test(b))?.w + ?? ZONE_TYPE_WEIGHTS[type ?? ""]; + if (w) out[k] = w[zone]; + } + return out; +} + export function orbitsFits(terrains: TerrainColor[]): boolean { return orbitRoles(terrains) !== undefined; } @@ -178,10 +260,10 @@ export function orbits( } const t = (d - first) / Math.max(1, last - first); const zone = t < 0.3 ? "inner" : t < 0.6 ? "habitable" : "outer"; - const body = weightedPick(rand, roles.bodies, ZONE_WEIGHTS[zone], 0.5)!; + const body = weightedPick(rand, roles.bodies, roles.zoneWeights[zone], 0.5)!; const hexesOnRing = ring(d); if (hexesOnRing.length === 0) continue; - if (roles.belt && body === roles.belt) { + if (roles.belts.includes(body)) { // Belts sweep an arc of the ring rather than sitting on one hex. const start = Math.floor(rand() * hexesOnRing.length); const span = Math.max(2, Math.floor(hexesOnRing.length * (0.3 + rand() * 0.4))); @@ -193,7 +275,7 @@ export function orbits( set(pos, body); if (zone === "habitable" && !mainworld) mainworld = pos; // Giants get a moon on a free neighbouring hex. - if (roles.moon && /giant/i.test(body) && rand() < 0.7) { + if (roles.moon && roles.giants.includes(body) && rand() < 0.7) { const free = hexes.filter((h) => distance(h, pos, grid) === 1 && cells.get(cellKey(h[0], h[1])) === roles.background); if (free.length) set(free[Math.floor(rand() * free.length)], roles.moon); diff --git a/src/worldgen/procedural/planetSurface.ts b/src/worldgen/procedural/planetSurface.ts index 347e5fbf..12a7923c 100644 --- a/src/worldgen/procedural/planetSurface.ts +++ b/src/worldgen/procedural/planetSurface.ts @@ -1,6 +1,15 @@ import { hexCenter, hexNeighbors, mulberry32 } from "../../../packages/hex-wfc/src"; import type { TerrainColor } from "../../types"; -import { cellKey, findTerrain, gridKeys, type ProcGrid, type ProcOption, type ProcResult } from "./common"; +import { + cellKey, + findByType, + findRole, + gridKeys, + ofType, + type ProcGrid, + type ProcOption, + type ProcResult, +} from "./common"; /** * "Planet surface": a region map of a world — seas, coasts, plains, @@ -10,8 +19,9 @@ import { cellKey, findTerrain, gridKeys, type ProcGrid, type ProcOption, type Pr * water % and climate let one generator cover ocean worlds, deserts and * ice balls (the space presets set these per planet type). * - * Terrain roles resolve by name, then category, so the Limited / Expanded - * palettes and user palettes with similar names all work. + * Terrain roles resolve by terrain type, then (for untyped terrains) by + * name and category, so the Limited / Expanded palettes and user palettes + * with any names all work. */ export const PLANET_SURFACE_ID = "procedural:planet-surface"; @@ -69,28 +79,92 @@ export interface PlanetRoles { desert?: string; badlands?: string; volcano?: string; + variants: PlanetVariants; } +/** Woodland family, chosen by temperature: conifers cold, broadleaf warm. */ +type Family = "conifer" | "mixed" | "broadleaf" | "tropical"; + +/** + * Typed extras for variety. A palette with several terrains of one type + * (Expanded: forest, forest heavy, mixed forest, evergreen, …) spreads them + * by climate instead of using only the first; name hints tell the variants + * apart since the type doesn't. Empty on untyped palettes. + */ +export interface PlanetVariants { + /** Forest per family: [open, dense]. */ + forest: Partial>; + denseJungle?: string; + /** Wooded hills / mountains per family (on moist high ground). */ + hills: Partial>; + mountain: Partial>; +} + +const WOODED = /forest|wood|evergreen|pine|conifer|taiga|jungle|rainforest|grove/i; +const FAMILY_RE: Record = { + conifer: /evergreen|pine|conifer|taiga|spruce|fir\b/i, + mixed: /mixed/i, + tropical: /jungle|rainforest/i, + broadleaf: /forest|wood|grove/i, +}; +const DENSE = /heavy|dense|thick|deep|old/i; + +/** Which family a name belongs to; broadleaf is the catch-all. */ +function familyOf(name: string): Family { + for (const f of ["conifer", "mixed", "tropical"] as const) if (FAMILY_RE[f].test(name)) return f; + return "broadleaf"; +} + +function planetVariants(terrains: TerrainColor[], forest: string | undefined): PlanetVariants { + const v: PlanetVariants = { forest: {}, hills: {}, mountain: {} }; + for (const name of ofType(terrains, ["forest"])) { + const fam = familyOf(name); + const slot = (v.forest[fam] ??= [undefined, undefined]); + const i = DENSE.test(name) ? 1 : 0; + // The base forest role stays the open broadleaf forest. + if (name === forest) slot[i] = name; + else slot[i] ??= name; + } + v.denseJungle = ofType(terrains, ["jungle"]).find((n) => DENSE.test(n)); + for (const [key, type] of [["hills", "hills"], ["mountain", "mountains"]] as const) { + for (const name of ofType(terrains, [type])) { + if (WOODED.test(name)) v[key][familyOf(name)] ??= name; + } + } + return v; +} + +/** + * Roles by terrain type first (water, grassland, forest, …), so custom + * names like "Kelp sea" or "Pinewood" work; untyped palettes fall back to + * the name and category guesses. The base hills / mountain role skips + * wooded variants ("forested hills"), which only appear on moist ground. + */ export function planetRoles(terrains: TerrainColor[]): PlanetRoles | undefined { - const sea = findTerrain(terrains, ["ocean", "sea", "water"], "sea"); - const plains = findTerrain(terrains, ["grass", "grassland", "plains", "lowland", "meadow"], "lowlands"); + const sea = findRole(terrains, ["water"], ["ocean", "sea", "water"], "sea"); + const plains = findRole(terrains, ["grassland"], ["grass", "grassland", "plains", "lowland", "meadow"], "lowlands"); if (!sea || !plains) return undefined; + const bare = terrains.filter((t) => !WOODED.test(t.name)); + const rugged = (type: string, names: string[], category?: string) => + findByType(bare, [type], names) ?? findRole(terrains, [type], names, category); + const forest = findRole(terrains, ["forest"], ["forest", "mixed forest", "woods"], "forest"); return { sea, plains, - deep: findTerrain(terrains, ["trench", "deep ocean", "deep water", "abyss"]), - shallows: findTerrain(terrains, ["shallows", "shallow water", "reef"]), - beach: findTerrain(terrains, ["beach", "coast", "shore", "sand"], "coast"), - forest: findTerrain(terrains, ["forest", "mixed forest", "woods"], "forest"), - jungle: findTerrain(terrains, ["jungle", "rainforest"]), - swamp: findTerrain(terrains, ["swamp", "marsh", "bog"], "bog"), - hills: findTerrain(terrains, ["hills", "hill", "foothills"]), - mountain: findTerrain(terrains, ["mountain", "mountains"], "mountain"), - peak: findTerrain(terrains, ["peak", "mountains snow", "mountain snow", "snowy peak"]), - snow: findTerrain(terrains, ["snow", "tundra", "ice", "glacier"], "snow"), - desert: findTerrain(terrains, ["desert", "dunes", "desert rocky"], "desert"), - badlands: findTerrain(terrains, ["badlands", "brokenlands", "wasteland"]), - volcano: findTerrain(terrains, ["volcano", "volcanic"]), + deep: findRole(terrains, ["deep-water"], ["trench", "deep ocean", "deep water", "abyss"]), + shallows: findRole(terrains, ["shallows"], ["shallows", "shallow water", "reef"]), + beach: findRole(terrains, ["coast"], ["beach", "coast", "shore", "sand"], "coast"), + forest, + jungle: findRole(terrains, ["jungle"], ["jungle", "rainforest"]), + swamp: findRole(terrains, ["wetland"], ["swamp", "marsh", "bog"], "bog"), + hills: rugged("hills", ["hills", "hill", "foothills"]), + mountain: rugged("mountains", ["mountain", "mountains"], "mountain"), + peak: findRole(terrains, ["peaks"], ["peak", "mountains snow", "mountain snow", "snowy peak"]), + snow: findRole(terrains, ["snow"], ["snow", "tundra", "ice", "glacier"], "snow"), + desert: findRole(terrains, ["desert"], ["desert", "dunes", "desert rocky"], "desert"), + badlands: findRole(terrains, ["badlands"], ["badlands", "brokenlands", "wasteland"]), + volcano: findRole(terrains, ["volcanic"], ["volcano", "volcanic"]), + variants: planetVariants(terrains, forest), }; } @@ -176,6 +250,26 @@ export function planetSurface( const tShift = climateShift[climate] ?? 0; const mShift = moistShift[climate] ?? 0; + // Woodland variety (typed palettes only): the family follows temperature, + // dense variants take the wettest ground. No rand() calls, so a seed's + // layout is the same with or without variants. + const v = roles.variants; + const familyAt = (temp: number): Family => + temp > 0.75 ? "tropical" : temp < 0.45 ? "conifer" : temp < 0.6 ? "mixed" : "broadleaf"; + const chain = (f: Family): Family[] => (f === "broadleaf" ? [f] : f === "conifer" ? [f, "mixed", "broadleaf"] : [f, "broadleaf"]); + const forestAt = (temp: number, m: number): string | undefined => { + for (const f of chain(familyAt(temp))) { + const slot = v.forest[f]; + const hit = slot && (m > 0.64 ? slot[1] ?? slot[0] : slot[0]); + if (hit) return hit; + } + return roles.forest; + }; + const wooded = (byFamily: Partial>, temp: number): string | undefined => { + for (const f of chain(familyAt(temp))) if (byFamily[f]) return byFamily[f]; + return undefined; + }; + const cells = new Map(); const isSea: boolean[] = elev.map((e) => e <= seaLevel); const index = new Map(hexes.map(([x, y], i) => [cellKey(x, y), i])); @@ -198,16 +292,16 @@ export function planetSurface( let t: string | undefined; if (e >= peakAt) t = roles.peak ?? roles.mountain; - else if (e >= mountainAt) t = roles.mountain; - else if (e >= hillAt) t = roles.hills; + else if (e >= mountainAt) t = (m > 0.6 ? wooded(v.mountain, temp) : undefined) ?? roles.mountain; + else if (e >= hillAt) t = (m > 0.5 ? wooded(v.hills, temp) : undefined) ?? roles.hills; if (t && temp < 0.2 && roles.peak) t = roles.peak; if (!t) { if (temp < 0.22) t = roles.snow; else if (climate === "volcanic" && m < 0.45) t = roles.badlands ?? roles.desert; else if (m < 0.32 && temp > 0.45) t = roles.desert ?? roles.badlands; - else if (m > 0.72 && temp > 0.75) t = roles.jungle ?? roles.forest; - else if (m > 0.68 && e - seaLevel < 0.05) t = roles.swamp ?? roles.forest; - else if (m > 0.5) t = roles.forest; + else if (m > 0.72 && temp > 0.75) t = (m > 0.85 ? v.denseJungle : undefined) ?? roles.jungle ?? forestAt(temp, m); + else if (m > 0.68 && e - seaLevel < 0.05) t = roles.swamp ?? forestAt(temp, m); + else if (m > 0.5) t = forestAt(temp, m); } cells.set(k, t ?? roles.plains); }); diff --git a/src/worldgen/procedural/starScatter.ts b/src/worldgen/procedural/starScatter.ts index c72bddb0..6c199faf 100644 --- a/src/worldgen/procedural/starScatter.ts +++ b/src/worldgen/procedural/starScatter.ts @@ -3,9 +3,13 @@ import type { TerrainColor } from "../../types"; import { cellKey, distance, + findRole, findTerrain, gridKeys, inCategory, + ofType, + typeIndex, + untyped, weightedPick, type ProcGrid, type ProcOption, @@ -20,9 +24,10 @@ import { * them, rare features (black hole, anomaly, deep-space station) are * sprinkled in, and nearby systems can be joined by jump routes. * - * Works on any palette with a background terrain ("empty space" / "void" / - * first `space` terrain) and at least one terrain in the `worlds` category - * (or a "star system" terrain). + * Works on any palette with a background terrain (type void, or "empty + * space" / "void" / first `space` terrain) and at least one world (type + * world / gas-giant / asteroids, or the `worlds` category, or a "star + * system" terrain). */ export const STAR_SCATTER_ID = "procedural:star-scatter"; @@ -88,22 +93,58 @@ export interface StarScatterRoles { features: string[]; } +/** Weights for typed terrains whose names aren't in the tables above. */ +const WORLD_TYPE_WEIGHTS: Record = { world: 2.5, "gas-giant": 1, asteroids: 1.5 }; +const FEATURE_TYPE_WEIGHTS: Record = { station: 3, anomaly: 1.5 }; + +/** Typed worlds that aren't a system's mainworld: comets, debris fields. */ +const NOT_MAINWORLD = /comet|debris/i; + +/** + * Roles by type first (void / world, gas-giant, asteroids / nebula / + * station, anomaly), then by name and category for untyped terrains. List + * roles take both, so a half-typed palette still uses everything. + */ export function starScatterRoles(terrains: TerrainColor[]): StarScatterRoles | undefined { - const background = findTerrain(terrains, ["empty space", "void", "deep space", "space"], "space"); - let worlds = inCategory(terrains, "worlds"); + const loose = untyped(terrains); + const background = findRole(terrains, ["void"], ["empty space", "void", "deep space", "space"], "space"); + let worlds = [ + ...ofType(terrains, ["world", "gas-giant", "asteroids"]).filter((t) => !NOT_MAINWORLD.test(t)), + ...inCategory(loose, "worlds"), + ]; if (worlds.length === 0) { - const system = findTerrain(terrains, ["star system", "system", "star"]); + const system = findRole(terrains, ["star"], ["star system", "system", "star"]); worlds = system ? [system] : []; } if (!background || worlds.length === 0) return undefined; - const clouds = inCategory(terrains, "space").filter( - (t) => t !== background && !/rift/i.test(t), - ); - const cloudNames = clouds.length ? clouds : [findTerrain(terrains, ["nebula", "dust cloud"])].filter((t): t is string => !!t); - const features = inCategory(terrains, "features").filter((t) => !/^star system$/i.test(t)); + const clouds = [ + ...ofType(terrains, ["nebula"]), + ...inCategory(loose, "space").filter((t) => t !== background && !/rift/i.test(t)), + ]; + const cloudNames = clouds.length ? clouds : [findTerrain(loose, ["nebula", "dust cloud"])].filter((t): t is string => !!t); + const features = [ + ...ofType(terrains, ["station", "anomaly"]), + ...inCategory(loose, "features").filter((t) => !/^star system$/i.test(t)), + ]; return { background, worlds, clouds: cloudNames, features }; } +/** Name weights, else the terrain's type weight; unknowns fall through to the default. */ +function weightsFor( + names: string[], + types: Map, + byName: Record, + byType: Record, +): Record { + const out: Record = {}; + for (const n of names) { + const k = n.toLowerCase(); + const w = byName[k] ?? byType[types.get(k) ?? ""]; + if (w !== undefined) out[k] = w; + } + return out; +} + export function starScatterFits(terrains: TerrainColor[]): boolean { return starScatterRoles(terrains) !== undefined; } @@ -120,6 +161,11 @@ export function starScatter( return { cells: new Map(), paths: [], warnings: ["This palette has no space background or world terrains."] }; } const rand = mulberry32(seed); + const types = typeIndex(terrains); + const worldWeights = weightsFor(roles.worlds, types, WORLD_WEIGHTS, WORLD_TYPE_WEIGHTS); + const featureWeights = weightsFor(roles.features, types, FEATURE_WEIGHTS, FEATURE_TYPE_WEIGHTS); + // Stations host a system (and so a route); black holes and anomalies don't. + const hostsSystem = (t: string) => types.get(t.toLowerCase()) === "station" || /station/i.test(t); const density = DENSITY[options.density ?? "standard"] ?? 0.5; const hexes = gridKeys(grid); const cells = new Map(); @@ -153,10 +199,10 @@ export function starScatter( if (rand() >= odds) continue; const roll = rand(); const feature = roles.features.length > 0 && roll < 0.04 - ? weightedPick(rand, roles.features, FEATURE_WEIGHTS) + ? weightedPick(rand, roles.features, featureWeights) : undefined; - cells.set(k, feature ?? weightedPick(rand, roles.worlds, WORLD_WEIGHTS)!); - if (!feature || /station/i.test(feature)) systems.push([x, y]); + cells.set(k, feature ?? weightedPick(rand, roles.worlds, worldWeights)!); + if (!feature || hostsSystem(feature)) systems.push([x, y]); } // Jump routes: each system links to its nearest neighbour within range. diff --git a/styles.css b/styles.css index f9848342..86b83b41 100644 --- a/styles.css +++ b/styles.css @@ -2560,12 +2560,19 @@ input.duckmage-input-error { margin-right: 4px; vertical-align: middle; flex-shrink: 0; + background-color: var(--duckmage-swatch-color, transparent); } .duckmage-hex-table-empty { color: var(--text-faint); } +/* Terrain/type shown from the map's base terrain (hex has none of its own) */ +.duckmage-hex-table-base-terrain { + color: var(--text-muted); + font-style: italic; +} + .duckmage-hex-table-cell-clickable { cursor: pointer; } @@ -2691,6 +2698,20 @@ tr.duckmage-row-hidden { padding-left: 14px; } +/* Type rows filter by terrain type; styled as headings over their terrains */ +.duckmage-terrain-filter-type-row { + margin-top: 4px; + font-weight: 600; +} + +.duckmage-terrain-filter-section-label { + margin-top: 8px; + font-size: 0.85em; + color: var(--text-faint); + border-top: 1px solid var(--background-modifier-border); + padding-top: 6px; +} + .duckmage-terrain-filter-btns { display: flex; justify-content: flex-end; diff --git a/tests/hexTableTypes.test.ts b/tests/hexTableTypes.test.ts new file mode 100644 index 00000000..ff36c3cf --- /dev/null +++ b/tests/hexTableTypes.test.ts @@ -0,0 +1,118 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import type { TerrainColor } from "../src/types"; +import { + compareTerrainTypes, + groupPaletteByType, + matchesTerrainFilter, + resolveTerrainType, + terrainTypeLabel, + type TerrainFilterState, +} from "../src/hex-table/terrainTypeFilter"; + +const PALETTE: TerrainColor[] = [ + { name: "dark forest", color: "#030", type: "forest" }, + { name: "ocean", color: "#00f", type: "water" }, + { name: "pine wood", color: "#050", type: "forest" }, + { name: "mystery", color: "#999" }, + { name: "bogus", color: "#111", type: "not-a-type" }, + { name: "void", color: "#000", type: "void" }, +]; +const BY_NAME = new Map(PALETTE.map((t) => [t.name, t])); + +const filter = (f: Partial>): TerrainFilterState => ({ + terrains: new Set(f.terrains ?? []), + excludeTerrains: new Set(f.excludeTerrains ?? []), + types: new Set(f.types ?? []), + excludeTypes: new Set(f.excludeTypes ?? []), +}); + +describe("resolveTerrainType", () => { + it("returns the palette entry's type", () => { + expect(resolveTerrainType("dark forest", BY_NAME)).toBe("forest"); + }); + it("does not infer from the name when the entry has no type", () => { + expect(resolveTerrainType("mystery", BY_NAME)).toBe(""); + // "pine" would infer forest, but only the palette counts + expect(resolveTerrainType("pine grove", BY_NAME)).toBe(""); + }); + it("ignores unknown type ids, unset and missing terrains", () => { + expect(resolveTerrainType("bogus", BY_NAME)).toBe(""); + expect(resolveTerrainType("", BY_NAME)).toBe(""); + expect(resolveTerrainType(null, BY_NAME)).toBe(""); + expect(resolveTerrainType(undefined, BY_NAME)).toBe(""); + }); +}); + +describe("terrainTypeLabel", () => { + it("labels known ids and blanks the rest", () => { + expect(terrainTypeLabel("forest")).toBe("Forest"); + expect(terrainTypeLabel("")).toBe(""); + expect(terrainTypeLabel("nope")).toBe(""); + }); +}); + +describe("compareTerrainTypes", () => { + it("orders by vocabulary with untyped last", () => { + const ids = ["", "void", "forest", "water", "nope"]; + ids.sort(compareTerrainTypes); + expect(ids.slice(0, 3)).toEqual(["water", "forest", "void"]); + expect(compareTerrainTypes("", "nope")).toBe(0); + }); +}); + +describe("groupPaletteByType", () => { + it("groups typed entries in vocabulary order and keeps the rest untyped", () => { + const { groups, untyped } = groupPaletteByType(PALETTE); + expect(groups.map((g) => g.typeId)).toEqual(["water", "forest", "void"]); + expect(groups[1].label).toBe("Forest"); + expect(groups[1].entries.map((e) => e.name)).toEqual(["dark forest", "pine wood"]); + expect(untyped.map((e) => e.name)).toEqual(["mystery", "bogus"]); + }); + it("handles an empty palette", () => { + expect(groupPaletteByType([])).toEqual({ groups: [], untyped: [] }); + }); +}); + +describe("matchesTerrainFilter", () => { + const forest = { terrain: "dark forest", effectiveTerrain: "dark forest", type: "forest" }; + const pine = { terrain: "pine wood", effectiveTerrain: "pine wood", type: "forest" }; + const ocean = { terrain: "ocean", effectiveTerrain: "ocean", type: "water" }; + const bare = { terrain: "", effectiveTerrain: "", type: "" }; + // A hex with a note but no terrain, on a map whose base terrain is void + const based = { terrain: "", effectiveTerrain: "void", type: "void" }; + + it("passes everything with an empty filter", () => { + for (const r of [forest, ocean, bare, based]) expect(matchesTerrainFilter(r, filter({}))).toBe(true); + }); + it("includes every terrain of a selected type", () => { + const f = filter({ types: ["forest"] }); + expect(matchesTerrainFilter(forest, f)).toBe(true); + expect(matchesTerrainFilter(pine, f)).toBe(true); + expect(matchesTerrainFilter(ocean, f)).toBe(false); + expect(matchesTerrainFilter(bare, f)).toBe(false); + }); + it("unions terrain and type includes", () => { + const f = filter({ types: ["water"], terrains: ["pine wood"] }); + expect(matchesTerrainFilter(ocean, f)).toBe(true); + expect(matchesTerrainFilter(pine, f)).toBe(true); + expect(matchesTerrainFilter(forest, f)).toBe(false); + }); + it("excludes by type, and exclusion beats inclusion", () => { + expect(matchesTerrainFilter(forest, filter({ excludeTypes: ["forest"] }))).toBe(false); + expect(matchesTerrainFilter(ocean, filter({ excludeTypes: ["forest"] }))).toBe(true); + expect(matchesTerrainFilter(forest, filter({ types: ["forest"], excludeTerrains: ["dark forest"] }))).toBe(false); + expect(matchesTerrainFilter(pine, filter({ types: ["forest"], excludeTerrains: ["dark forest"] }))).toBe(true); + }); + it("matches base-terrain hexes by displayed terrain, type, or 'no terrain'", () => { + expect(matchesTerrainFilter(based, filter({ types: ["void"] }))).toBe(true); + expect(matchesTerrainFilter(based, filter({ terrains: ["void"] }))).toBe(true); + expect(matchesTerrainFilter(based, filter({ terrains: [""] }))).toBe(true); + expect(matchesTerrainFilter(based, filter({ excludeTypes: ["void"] }))).toBe(false); + expect(matchesTerrainFilter(based, filter({ excludeTerrains: [""] }))).toBe(false); + }); + it("untyped rows never match a type include", () => { + expect(matchesTerrainFilter(bare, filter({ types: ["forest"] }))).toBe(false); + expect(matchesTerrainFilter(bare, filter({ excludeTypes: ["forest"] }))).toBe(true); + }); +}); diff --git a/tests/proceduralGenerators.test.ts b/tests/proceduralGenerators.test.ts index 46935012..19e3ed7e 100644 --- a/tests/proceduralGenerators.test.ts +++ b/tests/proceduralGenerators.test.ts @@ -7,9 +7,21 @@ import { import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; import { starScatter, starScatterFits, starScatterRoles } from "../src/worldgen/procedural/starScatter"; import { orbits, orbitsFits, orbitRoles } from "../src/worldgen/procedural/orbits"; -import { centerHex, distance, findTerrain, weightedPick, type ProcGrid } from "../src/worldgen/procedural/common"; +import { planetSurface, planetSurfaceFits, planetRoles } from "../src/worldgen/procedural/planetSurface"; +import { + centerHex, + distance, + findByType, + findRole, + findTerrain, + ofType, + untyped, + weightedPick, + type ProcGrid, +} from "../src/worldgen/procedural/common"; import { mulberry32 } from "../packages/hex-wfc/src"; import { suggestBaseTerrain } from "../src/worldgen/registry"; +import type { TerrainColor } from "../src/types"; const grid = (cols: number, rows: number, orientation: "flat" | "pointy" = "flat"): ProcGrid => ({ cols, rows, offset: { x: 0, y: 0 }, stagger: "odd", orientation, @@ -192,3 +204,202 @@ describe("orbits", () => { expect(r.warnings.join(" ")).toMatch(/too small/); }); }); + +describe("terrain types", () => { + const t = (name: string, type?: string, category?: string): TerrainColor => ({ name, color: "#000", type, category }); + + describe("helpers", () => { + const pal = [t("Forest heavy", "forest"), t("forest", "forest"), t("Pinewood", "forest"), t("ocean", "desert"), t("sea")]; + + it("ofType lists terrains of the given types in palette order; unknown types count as untyped", () => { + expect(ofType(pal, ["forest"])).toEqual(["Forest heavy", "forest", "Pinewood"]); + expect(ofType([t("x", "bogus")], ["bogus"])).toEqual([]); + expect(untyped([...pal, t("y", "bogus")]).map((x) => x.name)).toEqual(["sea", "y"]); + }); + + it("findByType prefers name hints within the type, then palette order, then later types", () => { + expect(findByType(pal, ["forest"], ["forest"])).toBe("forest"); + expect(findByType(pal, ["forest"])).toBe("Forest heavy"); + expect(findByType(pal, ["jungle", "forest"], ["jungle"])).toBe("Forest heavy"); + // The name hint only counts inside the type. + expect(findByType(pal, ["water"], ["ocean"])).toBeUndefined(); + }); + + it("findRole falls back to names only among untyped terrains", () => { + expect(findRole(pal, ["water"], ["ocean", "sea"])).toBe("sea"); + expect(findRole([t("ocean", "desert")], ["water"], ["ocean"])).toBeUndefined(); + }); + }); + + describe("star scatter", () => { + const custom = [ + t("Abyssal Drift", "void"), + t("Hearthworld", "world"), + t("Cinder", "world"), + t("Big Blue", "gas-giant"), + t("Shards", "asteroids"), + t("Halley", "asteroids"), + t("Veil", "nebula"), + t("Waystation", "station"), + t("The Maw", "anomaly"), + ]; + + it("resolves roles from types on a custom-named palette", () => { + const r = starScatterRoles(custom)!; + expect(r.background).toBe("Abyssal Drift"); + expect(r.worlds).toEqual(["Hearthworld", "Cinder", "Big Blue", "Shards", "Halley"]); + expect(r.clouds).toEqual(["Veil"]); + expect(r.features).toEqual(["Waystation", "The Maw"]); + }); + + it("generates only palette terrains, deterministically", () => { + const a = starScatter(custom, grid(16, 16), 4, { clouds: "many" }); + expect([...a.cells]).toEqual([...starScatter(custom, grid(16, 16), 4, { clouds: "many" }).cells]); + const names = new Set(custom.map((x) => x.name)); + for (const v of a.cells.values()) expect(names.has(v)).toBe(true); + expect(count(a.cells, (v) => v === "Hearthworld")).toBeGreaterThan(0); + }); + + it("a void-typed terrain named like a world is background, not a world", () => { + const r = starScatterRoles([t("garden world", "void"), t("Eden", "world")])!; + expect(r.background).toBe("garden world"); + expect(r.worlds).toEqual(["Eden"]); + }); + }); + + describe("orbits", () => { + const custom = [ + t("Abyssal Drift", "void"), + t("Edge", "void"), + t("Embers", "star"), + t("Hearthworld", "world"), + t("Cinderball", "world"), + t("Frostbite", "world"), + t("Big Blue", "gas-giant"), + t("Rubble ring", "asteroids"), + t("Luna", "world"), + t("Pale moon", "world"), + t("Iceball comet", "asteroids"), + t("Highport", "station"), + t("Gateway", "station"), + t("Outpost", "station"), + ]; + + it("resolves roles from types, splitting coarse types by name hints", () => { + const r = orbitRoles(custom)!; + expect(r.background).toBe("Abyssal Drift"); + expect(r.stars).toEqual(["Embers"]); + expect(r.bodies).toEqual(["Hearthworld", "Cinderball", "Frostbite", "Big Blue", "Rubble ring", "Luna"]); + expect(r.moon).toBe("Pale moon"); + expect(r.comet).toBe("Iceball comet"); + expect(r.belt).toBe("Rubble ring"); + expect(r.giants).toEqual(["Big Blue"]); + expect(r.starport).toBe("Highport"); + expect(r.jumpPoint).toBe("Gateway"); + expect(r.station).toBe("Outpost"); + }); + + it("weights custom bodies by zone: hints, then type", () => { + const w = orbitRoles(custom)!.zoneWeights; + expect(w.habitable["hearthworld"]).toBeGreaterThan(w.inner["hearthworld"]); + expect(w.outer["frostbite"]).toBeGreaterThan(w.habitable["frostbite"]); + expect(w.outer["big blue"]).toBeGreaterThan(w.inner["big blue"]); + // No hint: plain world-type weights. + expect(w.habitable["luna"]).toBe(3); + }); + + it("puts the typed star at the centre, sweeps asteroid-type belts, uses only palette terrains", () => { + const g = grid(13, 13); + const names = new Set(custom.map((x) => x.name)); + let belts = 0; + for (let seed = 1; seed <= 20; seed++) { + const r = orbits(custom, g, seed, { bodies: "crowded" }); + const [cx, cy] = centerHex(g); + expect(r.cells.get(`${cx}_${cy}`)).toBe("Embers"); + for (const v of r.cells.values()) expect(names.has(v)).toBe(true); + const n = count(r.cells, (v) => v === "Rubble ring"); + if (n > 0) { expect(n).toBeGreaterThan(1); belts++; } + } + expect(belts).toBeGreaterThan(0); + }); + + it("does not take a sector's star-system marker for a star", () => { + expect(orbitRoles([t("void", "void"), t("star system", "star"), t("Eden", "world")])).toBeUndefined(); + }); + }); + + describe("planet surface", () => { + const g = { cols: 20, rows: 14, offset: { x: 0, y: 0 }, stagger: "odd" as const, orientation: "flat" as const }; + const custom = [ + t("Kelp sea", "water"), + t("Brine deep", "deep-water"), + t("Tidepools", "shallows"), + t("Strand", "coast"), + t("Steppe-ish", "grassland"), + t("Pinewood", "forest"), + t("Fernwood", "forest"), + t("Old Fernwood dense", "forest"), + t("Crags", "mountains"), + t("Knolls", "hills"), + t("Glare", "snow"), + t("Saltpan", "desert"), + ]; + + it("resolves every role by type on a custom-named palette", () => { + const r = planetRoles(custom)!; + expect(r).toMatchObject({ + sea: "Kelp sea", deep: "Brine deep", shallows: "Tidepools", beach: "Strand", + plains: "Steppe-ish", mountain: "Crags", hills: "Knolls", snow: "Glare", desert: "Saltpan", + }); + expect(r.forest).toBe("Pinewood"); + expect(r.variants.forest.conifer).toEqual(["Pinewood", undefined]); + expect(r.variants.forest.broadleaf).toEqual(["Fernwood", "Old Fernwood dense"]); + }); + + it("generates from types alone, deterministically, with the forest variants", () => { + const a = planetSurface(custom, g, 5, { water: "30" }); + expect([...a.cells]).toEqual([...planetSurface(custom, g, 5, { water: "30" }).cells]); + const names = new Set(custom.map((x) => x.name)); + for (const v of a.cells.values()) expect(names.has(v)).toBe(true); + const used = new Set(); + for (let seed = 1; seed <= 10; seed++) for (const v of planetSurface(custom, g, seed, { water: "30" }).cells.values()) used.add(v); + for (const n of ["Kelp sea", "Steppe-ish", "Pinewood", "Fernwood", "Old Fernwood dense"]) expect(used.has(n)).toBe(true); + }); + + it("type wins over a misleading name: an \"ocean\" typed desert is never sea", () => { + const pal = [t("ocean", "desert"), t("Brine", "water"), t("grass", "grassland")]; + expect(planetRoles(pal)!.sea).toBe("Brine"); + expect(planetRoles(pal)!.desert).toBe("ocean"); + expect(planetSurfaceFits([t("ocean", "desert"), t("grass", "grassland")])).toBe(false); + }); + + it("untyped palettes still resolve by name and category", () => { + const pal = [t("ocean"), t("Lowland", undefined, "lowlands"), t("forest"), t("hills")]; + const r = planetRoles(pal)!; + expect(r).toMatchObject({ sea: "ocean", plains: "Lowland", forest: "forest", hills: "hills" }); + expect(r.variants).toEqual({ forest: {}, hills: {}, mountain: {} }); + }); + + it("spreads the Expanded palette's woodland variants by climate", () => { + const used = new Set(); + for (let seed = 1; seed <= 10; seed++) { + for (const v of planetSurface(DEFAULT_TERRAIN_PALETTE, g, seed, { water: "30", climate: "temperate" }).cells.values()) used.add(v); + } + for (const n of ["forest", "forest heavy", "evergreen", "mixed forest"]) expect(used.has(n)).toBe(true); + // The base hills role is the bare one, not a wooded variant. + expect(planetRoles(DEFAULT_TERRAIN_PALETTE)!.hills).toBe("hills"); + expect(planetRoles(DEFAULT_TERRAIN_PALETTE)!.variants.hills.conifer).toBe("evergreen hills"); + }); + }); + + describe("untyped space fallback", () => { + it("orbits still resolves from categories and exact names", () => { + const pal = [ + t("void", undefined, "space"), t("Sol", undefined, "stars"), + t("Terra", undefined, "bodies"), t("moon", undefined, "bodies"), t("jump point"), + ]; + const r = orbitRoles(pal)!; + expect(r).toMatchObject({ background: "void", stars: ["Sol"], bodies: ["Terra"], moon: "moon", jumpPoint: "jump point" }); + }); + }); +}); diff --git a/tests/terrainTypes.test.ts b/tests/terrainTypes.test.ts new file mode 100644 index 00000000..363c410a --- /dev/null +++ b/tests/terrainTypes.test.ts @@ -0,0 +1,98 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { TERRAIN_TYPES, inferTerrainType, isTerrainType, terrainTypeInfo } from "../src/terrainTypes"; +import { buildPaletteNote, parsePaletteNote, updatePaletteNote } from "../src/palettes/paletteNote"; +import { seedTerrainTypes } from "../src/palettes/PaletteStore"; +import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { PALETTE_PRESETS } from "../src/palettes/presets"; +import type { TerrainPalette } from "../src/types"; + +describe("terrain type vocabulary", () => { + it("has unique ids and both map kinds", () => { + const ids = TERRAIN_TYPES.map((t) => t.id); + expect(new Set(ids).size).toBe(ids.length); + expect(TERRAIN_TYPES.some((t) => t.kind === "world")).toBe(true); + expect(TERRAIN_TYPES.some((t) => t.kind === "space")).toBe(true); + expect(isTerrainType("forest")).toBe(true); + expect(isTerrainType("nope")).toBe(false); + expect(terrainTypeInfo("void")?.kind).toBe("space"); + }); + + it("every shipped palette terrain has a valid type", () => { + for (const p of PALETTE_PRESETS) { + for (const t of p.terrains) { + expect({ palette: p.name, terrain: t.name, ok: isTerrainType(t.type) }).toMatchObject({ ok: true }); + expect({ palette: p.name, terrain: t.name, kind: terrainTypeInfo(t.type)?.kind }).toMatchObject({ kind: p.kind }); + } + } + }); +}); + +describe("inferTerrainType", () => { + it("reads custom names", () => { + expect(inferTerrainType("dark forest")).toBe("forest"); + expect(inferTerrainType("Glass Desert")).toBe("desert"); + expect(inferTerrainType("frozen lake")).toBe("water"); + expect(inferTerrainType("salt marsh")).toBe("wetland"); + expect(inferTerrainType("ruined city")).toBe("settlement"); + }); + + it("prefers the keyword nearest the end ('forested hills' is hills)", () => { + expect(inferTerrainType("forested hills")).toBe("hills"); + expect(inferTerrainType("jungle mountains")).toBe("mountains"); + expect(inferTerrainType("hill forest")).toBe("forest"); + }); + + it("falls back to the category, respects the kind filter, and returns undefined when unsure", () => { + expect(inferTerrainType("Mirkwood", "forest")).toBe("forest"); + expect(inferTerrainType("gas giant", undefined, "space")).toBe("gas-giant"); + expect(inferTerrainType("ocean world", undefined, "space")).toBe("world"); + expect(inferTerrainType("Zorblax")).toBeUndefined(); + }); +}); + +describe("Type column in palette notes", () => { + const terrains = [ + { name: "Pinewood", color: "#123456", type: "forest" }, + { name: "Kelp sea", color: "#0000ff", category: "sea", type: "water" }, + { name: "Untyped", color: "#ffffff" }, + ]; + + it("round-trips", () => { + expect(parsePaletteNote(buildPaletteNote(terrains))).toEqual(terrains); + }); + + it("old five-column notes parse without types, and gain the column on rewrite", () => { + const old = "| Terrain | Color | Icon | Icon color | Category |\n| --- | --- | --- | --- | --- |\n| grass | #00ff00 | | | lowlands |\n"; + const parsed = parsePaletteNote(old)!; + expect(parsed).toEqual([{ name: "grass", color: "#00ff00", category: "lowlands" }]); + parsed[0].type = "grassland"; + const updated = updatePaletteNote(old, parsed); + expect(updated).toContain("| Type |"); + expect(parsePaletteNote(updated)).toEqual(parsed); + }); +}); + +describe("seedTerrainTypes", () => { + it("copies preset types by name and infers the rest, leaving typed terrains alone", () => { + const palettes: TerrainPalette[] = [{ + name: "Mine", + terrains: [ + { name: "ocean", color: "#000" }, + { name: "dark forest", color: "#000" }, + { name: "Zorblax", color: "#000" }, + { name: "grass", color: "#000", type: "desert" }, + ], + }]; + expect(seedTerrainTypes(palettes)).toBe(2); + expect(palettes[0].terrains.map((t) => t.type)).toEqual(["water", "forest", undefined, "desert"]); + }); + + it("is a no-op on the shipped palettes", () => { + const copy: TerrainPalette[] = [DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE].map((terrains, i) => ({ + name: `p${i}`, + terrains: terrains.map((t) => ({ ...t })), + })); + expect(seedTerrainTypes(copy)).toBe(0); + }); +}); From e4f292f8f62157158f760a1353816593f132850e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 14:05:34 -0400 Subject: [PATCH 043/558] feat(regions): neighbouring regions in the map, hex flower, map dialogs and generator Builds on the shared-grid logic (world.ts): - Main map: neighbours' terrain is drawn dimmed past each edge, 1-3 hexes deep for small/medium/large maps, on its own layer (spacing read from the laid-out hexes, read-then-write) so the grid and any calibrated background don't move. Clicking one asks "Go to ?" with a preview of that region and the arrival hex outlined. - Hex flower: tiles past the edge that fall in a neighbour show its terrain; clicking one asks the same, then opens the editor on that hex there. - Map list > Properties: north/east/south/west pickers (only maps that fit: same size and palette, lining up, slot free), "New region here...", and "Detach". Stagger is fixed while a map has neighbours. - New map: "Place next to , " locks size, palette, coordinates and stagger; with a generator, terrain carries on across the border. - Generator page: "Connect to , " does the same; the preview shows the neighbours' edges dimmed around it. - Growing or shrinking a map with neighbours is refused (they share a size). Generation pins a one-hex ring around the new region to the neighbours' edge terrain, then crops it; pins that clash with the generator's rules are dropped one at a time. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexEditorModal.ts | 23 +- src/hex-map/HexMapView.ts | 100 +++++++- src/hex-map/MapModal.ts | 173 +++++++++++++- src/hex-map/RegionNavigateModal.ts | 64 +++++ src/types.ts | 360 +++++++++++++++-------------- src/worldgen/GeneratorPanel.ts | 68 +++++- src/worldgen/neighbours.ts | 210 +++++++++++++++++ src/worldgen/preview.ts | 50 +++- styles.css | 45 ++++ 9 files changed, 890 insertions(+), 203 deletions(-) create mode 100644 src/hex-map/RegionNavigateModal.ts create mode 100644 src/worldgen/neighbours.ts diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index daee38aa..31d5e7f4 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -27,6 +27,8 @@ import type { LinkSection, HexEditorOptions, TerrainColor } from "../types"; import { RandomTableModal } from "../random-tables/RandomTableModal"; import { HexExportModal } from "./HexExportModal"; import { VIEW_TYPE_HEX_MAP, VIEW_TYPE_RANDOM_TABLES } from "../constants"; +import { resolveHex } from "../worldgen/world"; +import { RegionNavigateModal } from "./RegionNavigateModal"; export class HexEditorModal extends HexmakerModal { private hexExists = false; @@ -359,7 +361,26 @@ export class HexEditorModal extends HexmakerModal { }); }); } else { - tile.title = "Off map"; + // Past the edge: a neighbouring region's hex, if one sits there. + const here = this.plugin.getMap(this.mapName); + const across = here ? resolveHex(this.plugin.settings.maps, here, nx, ny) : null; + if (across && across.map.name !== this.mapName) { + const target = { map: across.map.name, x: across.x, y: across.y }; + tile.addClass("duckmage-neighbor-tile-region"); + tile.removeClass("duckmage-neighbor-tile-offmap"); + tile.title = `${target.map}: hex ${target.x}, ${target.y}`; + const t = getTerrainFromFile(this.app, this.plugin.hexPath(target.x, target.y, target.map)); + const color = t ? this.plugin.getMapPalette(target.map).find((p) => p.name === t)?.color : undefined; + if (color) tile.setCssProps({ "--duckmage-bg": color }); + tile.addEventListener("click", () => { + new RegionNavigateModal(this.app, this.plugin, target, () => { + this.close(); + this.options.onCrossToRegion?.(target.map, target.x, target.y); + }).open(); + }); + } else { + tile.title = "Off map"; + } } } diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 38baddbb..f18d5076 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -46,6 +46,8 @@ import { GeoRegionPickerModal } from "./GeoRegionPickerModal"; import { DrawingToolPanel, OverlayPanel } from "./HexSidePanel"; import { TokenModal } from "./TokenModal"; import { SubmapPickerModal } from "./SubmapPickerModal"; +import { RegionNavigateModal } from "./RegionNavigateModal"; +import { neighbourShadow } from "../worldgen/neighbours"; import { TokenInfoModal } from "./TokenInfoModal"; import { getTokenDataFromCache, @@ -1166,13 +1168,21 @@ export class HexMapView extends ItemView { }, ]; + // Neighbouring regions all share one size, so a map that has them can't grow or shrink. + const sizeLocked = (): boolean => { + if (!this.getActiveMap().world) return false; + new Notice("This map has neighbouring regions, which all share one size. Detach it from them in the map list's properties tab to resize it."); + return true; + }; for (const { groupCls, expandAction, shrinkAction, canShrink, edgePaths } of dirs) { const group = container.createDiv({ cls: `duckmage-expand-group ${groupCls}`, }); group.createEl("button", { cls: "duckmage-expand-btn", text: "+" }) - .addEventListener("click", () => void expandAction()); + .addEventListener("click", () => { + if (!sizeLocked()) void expandAction(); + }); const shrinkBtn = group.createEl("button", { cls: "duckmage-shrink-btn", @@ -1191,7 +1201,7 @@ export class HexMapView extends ItemView { let pendingPaths: string[] = []; let confirmTimer: number | null = null; shrinkBtn.addEventListener("click", () => { - if (!canShrink()) return; + if (!canShrink() || sizeLocked()) return; const paths = edgePaths(); const dirty = paths.some((p) => this.hexHasContent(p)); if (dirty && !shrinkBtn.hasClass("is-confirming")) { @@ -3375,6 +3385,7 @@ export class HexMapView extends ItemView { } } + this.renderNeighbourShadow(gridContainer, region); this.renderPathOverlay(gridContainer); this.renderRegionOverlay(gridContainer); this.renderFactionOverlay(gridContainer); @@ -3389,6 +3400,90 @@ export class HexMapView extends ItemView { this.renderTokenLayer(gridContainer); } + /** + * Neighbouring regions' terrain just past this map's edges, dimmed (1–3 + * hexes deep by map size). Clicking one asks to go to that region. + * + * Drawn on its own layer so the grid itself (and anything calibrated to + * it) doesn't move: hex spacing is read from hexes already laid out, all + * reads first, then the writes (see the read-then-write rule in CLAUDE.md). + */ + private renderNeighbourShadow(gridContainer: HTMLElement, region: MapData): void { + if (!region.world) return; + const shadow = neighbourShadow(this.plugin, region); + if (!shadow.size) return; + const { x: ox, y: oy } = region.gridOffset; + const { cols, rows } = region.gridSize; + const isFlat = this.plugin.settings.hexOrientation === "flat"; + const stagger = this.getActiveStagger(); + const shifted = (n: number) => (stagger === "odd" ? n % 2 !== 0 : n % 2 === 0) ? 1 : 0; + + // ── Reads ── + const hexAt = (x: number, y: number) => gridContainer.querySelector(`.duckmage-hex[data-x="${x}"][data-y="${y}"]`); + const origin = hexAt(ox, oy); + if (!origin) return; + const g = gridContainer.getBoundingClientRect(); + const sx = gridContainer.offsetWidth ? g.width / gridContainer.offsetWidth : 1; + const sy = gridContainer.offsetHeight ? g.height / gridContainer.offsetHeight : 1; + const centre = (el: HTMLElement) => { + const r = el.getBoundingClientRect(); + return { x: (r.left + r.width / 2 - g.left) / sx, y: (r.top + r.height / 2 - g.top) / sy, w: r.width / sx, h: r.height / sy }; + }; + const A = centre(origin); + const right = cols > 1 ? hexAt(ox + 1, oy) : null, below = rows > 1 ? hexAt(ox, oy + 1) : null; + const B = right ? centre(right) : null, C = below ? centre(below) : null; + let place: (x: number, y: number) => { x: number; y: number }; + if (isFlat) { + const colPitch = B ? B.x - A.x : A.w * 0.75; + const rowPitch = C ? C.y - A.y : A.h; + place = (x, y) => ({ x: A.x + (x - ox) * colPitch, y: A.y + (y - oy) * rowPitch + (shifted(x) - shifted(ox)) * (rowPitch / 2) }); + } else { + const colPitch = B ? B.x - A.x : A.w; + const rowPitch = C ? C.y - A.y : A.h * 0.75; + place = (x, y) => ({ x: A.x + (x - ox) * colPitch + (shifted(y) - shifted(oy)) * (colPitch / 2), y: A.y + (y - oy) * rowPitch }); + } + const palettes = new Map>(); + const colorOf = (map: string, terrain?: string) => { + if (!terrain) return undefined; + let p = palettes.get(map); + if (!p) palettes.set(map, (p = new Map(this.plugin.getMapPalette(map).map((t) => [t.name, t.color])))); + return p.get(terrain); + }; + const items = [...shadow].map(([key, s]) => { + const [x, y] = key.split("_").map(Number); + return { s, at: place(x, y), color: colorOf(s.map, s.terrain) }; + }); + + // ── Writes ── + const layer = gridContainer.createDiv({ cls: "duckmage-region-shadow-layer" }); + for (const { s, at, color } of items) { + const el = layer.createDiv({ + cls: "duckmage-hex duckmage-hex-shadow", + attr: { title: `${s.map}: hex ${s.x}, ${s.y}`, "data-region": s.map }, + }); + el.setCssProps({ + "--duckmage-shadow-x": `${at.x - A.w / 2}px`, + "--duckmage-shadow-y": `${at.y - A.h / 2}px`, + "--duckmage-shadow-w": `${A.w}px`, + "--duckmage-shadow-h": `${A.h}px`, + }); + this.setHexColor(el, color); + el.addEventListener("click", () => { + new RegionNavigateModal(this.app, this.plugin, { map: s.map, x: s.x, y: s.y }, () => this.goToRegionHex(s.map, s.x, s.y)).open(); + }); + } + } + + /** Switch to a neighbouring region and land on one of its hexes. */ + private goToRegionHex(mapName: string, x: number, y: number, openEditor = false): void { + this.navigateToMap(mapName); + window.setTimeout(() => { + this.setSelectedHex(x, y); + this.centerOnHex(x, y); + if (openEditor) this.openHexEditorModal(x, y); + }, 80); + } + private openHexEditorModal(x: number, y: number): void { this.setSelectedHex(x, y); const modal = new HexEditorModal( @@ -3418,6 +3513,7 @@ export class HexMapView extends ItemView { } }, onSwitchMap: (name: string) => this.navigateToMap(name), + onCrossToRegion: (name: string, nx: number, ny: number) => this.goToRegionHex(name, nx, ny, true), }, ); modal.open(); diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index c112cbca..d57aec84 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -1,6 +1,7 @@ import { App, Menu, Notice, TFolder } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; +import type { MapData } from "../types"; import type { HexMapView } from "./HexMapView"; import { normalizeFolder, slugify, getIconUrl, createIconEl, importBinaryFileToVault } from "../utils"; import { getSubmapFromFile, setSubmapInFile } from "../frontmatter"; @@ -20,6 +21,19 @@ import { type GeneratorFile, } from "../worldgen/generators"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "../worldgen/preview"; +import { SIDES, link, type Side } from "../worldgen/world"; +import { + detachRegion, + generateConnected, + gridRules, + linkRegions, + regionNeighbours, + neighbourSpec, + occupiedSides, + placeNewRegion, + regionNameAt, + type NewRegion, +} from "../worldgen/neighbours"; import { randomSeed } from "../../packages/hex-wfc/src"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; @@ -54,6 +68,8 @@ function clampInt(v: number, lo: number, hi: number, fallback: number): number { export class MapModal extends HexmakerModal { private confirmingDelete: string | null = null; private activeTab: ModalTab = "Maps"; + /** Set by "New region here" in Properties: prefills the New map tab's placement. */ + private newMapPlacement: { anchor: string; side: Side } | null = null; constructor( app: App, @@ -385,8 +401,14 @@ export class MapModal extends HexmakerModal { const propStaggerBtn = staggerRow.createEl("button", { cls: "duckmage-stagger-toggle" }); propStaggerBtn.setText(propStaggerVal === "odd" ? "Odd" : "Even"); propStaggerBtn.toggleClass("is-even", propStaggerVal === "even"); + // A map with neighbours can't flip its stagger: its seams would stop lining up. + const hasNeighbours = !!currentMap && Object.keys(regionNeighbours(this.plugin, currentMap.name)).length > 0; + if (hasNeighbours) { + propStaggerBtn.disabled = true; + staggerRow.createSpan({ text: "Fixed while this map has neighbouring regions (it has to line up with them).", cls: "duckmage-map-origin-desc" }); + } propStaggerBtn.addEventListener("click", () => { - if (!currentMap) return; + if (!currentMap || hasNeighbours) return; propStaggerVal = propStaggerVal === "odd" ? "even" : "odd"; propStaggerBtn.setText(propStaggerVal === "odd" ? "Odd" : "Even"); propStaggerBtn.toggleClass("is-even", propStaggerVal === "even"); @@ -394,6 +416,8 @@ export class MapModal extends HexmakerModal { void this.plugin.saveSettings().then(() => this.onChanged()); }); + if (currentMap) this.renderNeighbourBlock(el, currentMap); + // Terrain theme el.createEl("h4", { text: "Terrain theme" }); const terrainPalette = this.plugin.getMapPalette(this.view.activeMapName); @@ -501,6 +525,64 @@ export class MapModal extends HexmakerModal { } } + /** + * Neighbouring regions: which map is north, east, south and west of this + * one on their shared grid. Only maps that fit (same size and palette, + * lining up, slot free) are offered; an empty side can get a new region. + */ + private renderNeighbourBlock(el: HTMLElement, map: MapData): void { + el.createEl("h4", { text: "Neighbouring regions" }); + el.createEl("p", { + text: "Regions next to each other share one grid: walking off this map's edge (or the hex flower) leads into them. They must be the same size and use the same palette.", + cls: "duckmage-map-origin-desc", + }); + const current = regionNeighbours(this.plugin, map.name); + const rules = gridRules(this.plugin); + const grid = el.createDiv({ cls: "duckmage-neighbour-grid" }); + for (const side of SIDES) { + const row = grid.createDiv({ cls: "duckmage-region-row duckmage-neighbour-row" }); + row.createSpan({ text: side[0].toUpperCase() + side.slice(1), cls: "duckmage-map-origin-label" }); + const select = row.createEl("select"); + select.createEl("option", { value: "", text: "None" }); + const now = current[side]; + if (now) select.createEl("option", { value: now.name, text: now.name }); + for (const other of this.plugin.settings.maps) { + if (other.name === map.name || other.name === now?.name) continue; + if (link(this.plugin.settings.maps, map.name, side, other.name, rules, () => "check").ok) + select.createEl("option", { value: other.name, text: other.name }); + } + select.value = now?.name ?? ""; + select.addEventListener("change", () => { + void (async () => { + if (now && select.value !== now.name) await detachRegion(this.plugin, now.name); + if (select.value) { + const r = await linkRegions(this.plugin, map.name, side, select.value); + if (!r.ok) new Notice(r.reason); + } + this.onChanged(); + this.render(); + })(); + }); + if (!now) { + const add = row.createEl("button", { text: "New region here…", attr: { title: `Make a new map ${side} of ${map.name}` } }); + add.addEventListener("click", () => { + this.newMapPlacement = { anchor: map.name, side }; + this.activeTab = "New map"; + this.render(); + }); + } + } + if (map.world) { + const leave = el.createDiv({ cls: "duckmage-region-row" }).createEl("button", { text: "Detach from its neighbours" }); + leave.addEventListener("click", () => { + void detachRegion(this.plugin, map.name).then(() => { + this.onChanged(); + this.render(); + }); + }); + } + } + /** Compute the folder where dropped bg images should land for a given map. */ private bgImportFolder(mapName: string): string { const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); @@ -574,6 +656,26 @@ export class MapModal extends HexmakerModal { cls: "duckmage-map-new-name-input", }); + // Place next to an existing map: it becomes a neighbouring region on the + // same grid, so size, palette, stagger and coordinates follow from it. + el.createEl("label", { text: "Place next to", cls: "duckmage-map-field-label" }); + el.createEl("p", { + text: "Make this map a neighbouring region of another: it's the same size and palette, and lines up with it hex for hex.", + cls: "duckmage-map-origin-desc", + }); + const placeRow = el.createDiv({ cls: "duckmage-region-row" }); + const anchorSelect = placeRow.createEl("select"); + anchorSelect.createEl("option", { value: "", text: "Nowhere (a separate map)" }); + for (const m of this.plugin.settings.maps) anchorSelect.createEl("option", { value: m.name, text: m.name }); + const sideSelect = placeRow.createEl("select"); + for (const s of SIDES) sideSelect.createEl("option", { value: s, text: `${s} of it` }); + const placeNote = el.createEl("p", { cls: "duckmage-map-origin-desc" }); + if (this.newMapPlacement) { + anchorSelect.value = this.newMapPlacement.anchor; + sideSelect.value = this.newMapPlacement.side; + this.newMapPlacement = null; + } + // Size el.createEl("label", { text: "Size", cls: "duckmage-map-field-label" }); const sizeRow = el.createDiv({ cls: "duckmage-region-row" }); @@ -721,6 +823,46 @@ export class MapModal extends HexmakerModal { bgClearBtn.disabled = false; }); + // Placement: lock what has to match the map it goes next to. + let placement: NewRegion | null = null; + const presetBtns = Array.from(presetsRow.querySelectorAll("button")); + const applyPlacement = () => { + placement = null; + const anchor = anchorSelect.value; + const locked = !!anchor; + if (anchor) { + const spec = neighbourSpec(this.plugin, anchor, sideSelect.value as Side); + if (!spec.ok) { + placeNote.setText(`⚠ ${spec.reason}`); + } else { + placement = { slot: spec.slot, aSlot: spec.aSlot, anchor, side: sideSelect.value as Side, cols: spec.cols, rows: spec.rows, offset: spec.offset, stagger: spec.stagger, paletteName: spec.paletteName }; + colsInput.value = String(spec.cols); + rowsInput.value = String(spec.rows); + paletteSelect.value = spec.paletteName; + originXInput.value = String(spec.offset.x); + originYInput.value = String(spec.offset.y); + staggerVal = spec.stagger; + staggerBtn.setText(staggerVal === "odd" ? "Odd" : "Even"); + staggerBtn.toggleClass("is-even", staggerVal === "even"); + const borders = occupiedSides(this.plugin, placement).map((s) => `${s}: ${regionNameAt(this.plugin, placement!, s)}`); + placeNote.setText(`${spec.cols}×${spec.rows}, palette ${spec.paletteName}. Borders ${borders.join("; ")}.`); + fillGenerators(); + } + } else placeNote.setText(""); + for (const input of [colsInput, rowsInput, paletteSelect, originXInput, originYInput]) input.disabled = locked; + for (const b of presetBtns) b.disabled = locked; + staggerBtn.disabled = locked; + sideSelect.disabled = !anchor; + }; + anchorSelect.addEventListener("change", () => { + applyPlacement(); + schedulePreview(); + }); + sideSelect.addEventListener("change", () => { + applyPlacement(); + schedulePreview(); + }); + const selectedGenerator = () => generators.find((g) => g.file.path === generatorSelect.value) ?? null; const runPreview = () => { const g = selectedGenerator(); @@ -732,12 +874,14 @@ export class MapModal extends HexmakerModal { stagger: staggerVal, }; const palette = this.plugin.getPaletteByName(paletteSelect.value)?.terrains.map((t) => t.name) ?? []; - const r = generateTerrain(this.plugin, g.model, palette, grid, Number(seedInput.value) >>> 0); + const seed = Number(seedInput.value) >>> 0; + const r = placement ? generateConnected(this.plugin, g.model, palette, placement, seed) : generateTerrain(this.plugin, g.model, palette, grid, seed); if (!r.ok) { previewStatus.setText(`This generator couldn't fill the map: ${r.message}`); return; } - drawPreview(previewCanvas, r.cells, grid, this.plugin.settings.hexOrientation, paletteColors(this.plugin, paletteSelect.value), r.featureCells, r.paths, pathColors(this.plugin)); + const shadow = placement && "shadow" in r ? (r.shadow as Map) : undefined; + drawPreview(previewCanvas, r.cells, grid, this.plugin.settings.hexOrientation, paletteColors(this.plugin, paletteSelect.value), r.featureCells, r.paths, pathColors(this.plugin), 420, 14, undefined, { shadow }); previewStatus.setText(r.warnings.length ? `⚠ ${r.warnings.length}` : ""); previewStatus.setAttr("title", r.warnings.join("\n")); }; @@ -786,7 +930,9 @@ export class MapModal extends HexmakerModal { pendingBgFile, selectedGenerator(), Number(seedInput.value) >>> 0, + placement, ); + applyPlacement(); createBtn.addEventListener("click", doCreate); nameInput.addEventListener("keydown", (e: KeyboardEvent) => { if (e.key === "Enter") doCreate(); @@ -922,6 +1068,7 @@ export class MapModal extends HexmakerModal { bgImageFile: File | null, generator: GeneratorFile | null, seed: number, + placement: NewRegion | null = null, ): Promise { btn.setText("Generating…"); btn.disabled = true; @@ -934,14 +1081,25 @@ export class MapModal extends HexmakerModal { // Solve before creating anything, so a generator that can't fill the // map leaves no half-made map behind. + // Its place next to another map may have been taken since it was chosen. + if (placement?.anchor && placement.side) { + const again = neighbourSpec(this.plugin, placement.anchor, placement.side); + if (!again.ok) { + new Notice(again.reason); + reset(); + return; + } + } let terrainAt: Map | undefined; let generatedPaths: { type: string; route?: string; hexes: string[] }[] = []; if (generator) { const palette = this.plugin.getPaletteByName(paletteName)?.terrains.map((t) => t.name) ?? []; - const solved = generateTerrain( - this.plugin, generator.model, palette, - { cols, rows, offset: { x: initialX, y: initialY }, stagger: staggerOffset }, seed, - ); + const solved = placement + ? generateConnected(this.plugin, generator.model, palette, placement, seed) + : generateTerrain( + this.plugin, generator.model, palette, + { cols, rows, offset: { x: initialX, y: initialY }, stagger: staggerOffset }, seed, + ); if (!solved.ok) { new Notice(`Generator "${generator.model.name}" couldn't fill this map: ${solved.message}`); reset(); @@ -962,6 +1120,7 @@ export class MapModal extends HexmakerModal { reset(); return; } + if (placement) await placeNewRegion(this.plugin, result.name, placement); // Resolve the bg image path: a dropped File needs importing into the new // map's _bg folder first; a picked vault path is used directly. diff --git a/src/hex-map/RegionNavigateModal.ts b/src/hex-map/RegionNavigateModal.ts new file mode 100644 index 00000000..2f3357cc --- /dev/null +++ b/src/hex-map/RegionNavigateModal.ts @@ -0,0 +1,64 @@ +import { App } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { HexmakerModal } from "../HexmakerModal"; +import { paletteColors, pathColors, readMapTerrain } from "../worldgen/generators"; +import { drawPreview } from "../worldgen/preview"; + +/** + * "Go to ?" when stepping past a map's edge onto a neighbouring + * region: a preview of that region with the hex you'd arrive at outlined. + */ +export class RegionNavigateModal extends HexmakerModal { + constructor( + app: App, + private plugin: HexmakerPlugin, + private target: { map: string; x: number; y: number }, + private onGo: () => void, + ) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + const { map: name, x, y } = this.target; + this.titleEl.setText(`Go to ${name}?`); + const map = this.plugin.getMap(name); + const { contentEl } = this; + contentEl.addClass("duckmage-region-nav"); + contentEl.createEl("p", { text: `Hex ${x}, ${y} is in the neighbouring region "${name}".`, cls: "duckmage-map-origin-desc" }); + if (map) { + const canvas = contentEl.createEl("canvas", { cls: "duckmage-region-nav-preview" }); + drawPreview( + canvas, + readMapTerrain(this.plugin, name), + { cols: map.gridSize.cols, rows: map.gridSize.rows, offset: map.gridOffset, stagger: map.staggerOffset ?? this.plugin.settings.staggerOffset ?? "odd" }, + this.plugin.settings.hexOrientation, + paletteColors(this.plugin, map.paletteName), + undefined, + (map.pathChains ?? []).map((p) => ({ type: p.typeName, hexes: p.hexes })), + pathColors(this.plugin), + 360, + 12, + undefined, + { mark: `${x}_${y}` }, + ); + } + const row = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); + const go = row.createEl("button", { text: `Go to ${name}`, cls: "mod-cta" }); + go.addEventListener("click", () => { + this.close(); + this.onGo(); + }); + row.createEl("button", { text: "Stay" }).addEventListener("click", () => this.close()); + this.scope.register([], "Enter", () => { + this.close(); + this.onGo(); + return false; + }); + window.setTimeout(() => go.focus(), 0); + } + + onClose(): void { + this.contentEl.empty(); + } +} diff --git a/src/types.ts b/src/types.ts index 494a3773..a685eda1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,178 +1,182 @@ -export type TokenShape = "circle" | "square" | "hexagon"; -export type TokenSize = "sm" | "md" | "lg"; - -export interface TokenEntry { - filePath: string; - title: string; - icon: string | undefined; - hex: string; // "x_y" - map: string; - visible: boolean; - shape: TokenShape; - size: TokenSize; - color: string | undefined; // fill color - border: string | undefined; // border/ring color - tokenLink: string | undefined; // proxy → original note path - description: string | undefined; // token-description frontmatter -} - -export type PathLineStyle = "solid" | "dashed" | "dotted"; -export type PathRouting = "through" | "meander" | "edge"; - -export interface PathType { - name: string; - color: string; - width: number; // 1–10, direct SVG stroke-width - lineStyle: PathLineStyle; - routing: PathRouting; // "through" = hex centers; "meander" = edge midpoints (curved); "edge" = along hex boundary lines -} - -export interface PathChain { - typeName: string; // references PathType.name - hexes: string[]; // "x_y" keys -} - -/** - * Per-map background image. Drawn under the hex grid, sharing the viewport's - * pan/zoom transform. `offsetX`/`offsetY` translate the image relative to the - * hex-grid container's natural origin, in CSS pixels at the image's native - * resolution. `scale` is a uniform multiplier (1 = native pixel size). - * Rotation in degrees, default 0. Opacity 0..1, default 1. - */ -export interface MapBackgroundImage { - path: string; - offsetX: number; - offsetY: number; - scale: number; - rotation?: number; - opacity?: number; -} - -export interface MapData { - name: string; - /** Plugin version that created the map (see src/compat.ts). */ - createdWith?: string; - paletteName: string; - terrainType?: string; // terrain name from the map's palette; used as submap center dot color - gridSize: { cols: number; rows: number }; - gridOffset: { x: number; y: number }; - pathChains: PathChain[]; - showCoords?: boolean; // undefined = true (backwards-compatible) - showTerrainIcons?: boolean; // undefined = true - showIconOverrides?: boolean; // undefined = true - showPaths?: boolean; // undefined = true - showFactionOverlay?: boolean; // undefined = false (opt-in) - showRegionOverlay?: boolean; // undefined = false (opt-in) - showGmLayer?: boolean; // undefined = true (on by default) - showTokens?: boolean; // undefined = true (on by default) - staggerOffset?: "odd" | "even"; // undefined = inherit global setting - backgroundImage?: MapBackgroundImage; - /** Optional independent transform applied to the hex grid container, - * used during background-image calibration so the user can resize/shift - * the grid to fit features in the underlying image. - * `gridDisplayScale` is the legacy uniform-scale field, retained for - * back-compat; new code reads X/Y separately (falling back to - * `gridDisplayScale` if X/Y are missing). */ - gridDisplayScale?: number; - gridDisplayScaleX?: number; - gridDisplayScaleY?: number; - gridDisplayOffsetX?: number; - gridDisplayOffsetY?: number; - /** Persisted viewport state — restored when the view is reopened so a - * calibrated map (whose bg image / grid transforms were sized at a - * specific font-size / zoom) doesn't drift on reload. */ - savedViewport?: { - zoom: number; - panX: number; - panY: number; - /** Baked font-size as a CSS string (e.g. `"32px"`), or `""` for default. */ - fontSize: string; - }; -} - -export interface TerrainPalette { - name: string; - terrains: TerrainColor[]; -} - -export interface TerrainColor { - name: string; - color: string; - icon?: string; - iconColor?: string; // CSS colour to tint the icon; undefined = no tint (render as-is) - category?: string; -} - -export interface HexmakerPluginSettings { - mySetting: string; - /** Plugin version that last saved data.json (see src/compat.ts). */ - savedWith?: string; - worldFolder: string; - hexFolder: string; - townsFolder: string; - dungeonsFolder: string; - questsFolder: string; - featuresFolder: string; - iconsFolder: string; - templatePath: string; - hexGap: string; - terrainPalettes: TerrainPalette[]; - maps: MapData[]; - zoomLevel: number; - pathTypes: PathType[]; - hexOrientation: "pointy" | "flat"; - staggerOffset: "odd" | "even"; - tablesFolder: string; - factionsFolder: string; - regionsFolder: string; - defaultTableDice: number; - hexEditorTerrainCollapsed: boolean; - hexEditorFeaturesCollapsed: boolean; - hexEditorNotesCollapsed: boolean; - rollTableExcludedFolders: string[]; - encounterTableExcludedFolders: string[]; - defaultMap: string; - defaultNewMapCols: number; - defaultNewMapRows: number; - defaultSubmapCols: number; - defaultSubmapRows: number; - workflowsFolder: string; - exportFolder: string; - coordPlacement: "top" | "middle" | "bottom"; - /** Size of the hex coordinate label, in em units relative to the hex. */ - coordFontSize: number; - /** Which font the coord label uses. */ - coordFontFamily: "interface" | "monospace" | "serif"; - /** Coord label text color (CSS hex). */ - coordFontColor: string; - hiddenIcons: string[]; - iconOrder: string[]; - setupComplete: boolean; - setupDismissed: boolean; -} - -export const LINK_SECTIONS = ["Towns", "Dungeons", "Features", "Quests", "Factions", "Encounters Table"] as const; -export type LinkSection = typeof LINK_SECTIONS[number]; - -export const TEXT_SECTIONS = [ - { key: "description", label: "Description" }, - { key: "landmark", label: "Landmark" }, - { key: "hidden", label: "Hidden" }, - { key: "secret", label: "Secret" }, -] as const; - -/** - * Session-only flags passed from HexMapView into HexEditorModal. - * All fields are optional — modal defaults missing keys to false. - * Add new session-layer flags here; no constructor signature changes needed. - */ -export interface HexEditorOptions { - /** GM layer is active: force Notes open, highlight Hidden/Secret sections. */ - gmLayerActive?: boolean; - /** Called when the user clicks a neighbour tile to navigate to an adjacent hex. */ - onNavigate?: (x: number, y: number) => void; - /** Called when the modal closes (e.g. to clear the selected-hex highlight). */ - onModalClose?: () => void; - /** Called when the user clicks the submap centre-dot to drill into another map. */ - onSwitchMap?: (mapName: string) => void; -} +export type TokenShape = "circle" | "square" | "hexagon"; +export type TokenSize = "sm" | "md" | "lg"; + +export interface TokenEntry { + filePath: string; + title: string; + icon: string | undefined; + hex: string; // "x_y" + map: string; + visible: boolean; + shape: TokenShape; + size: TokenSize; + color: string | undefined; // fill color + border: string | undefined; // border/ring color + tokenLink: string | undefined; // proxy → original note path + description: string | undefined; // token-description frontmatter +} + +export type PathLineStyle = "solid" | "dashed" | "dotted"; +export type PathRouting = "through" | "meander" | "edge"; + +export interface PathType { + name: string; + color: string; + width: number; // 1–10, direct SVG stroke-width + lineStyle: PathLineStyle; + routing: PathRouting; // "through" = hex centers; "meander" = edge midpoints (curved); "edge" = along hex boundary lines +} + +export interface PathChain { + typeName: string; // references PathType.name + hexes: string[]; // "x_y" keys +} + +/** + * Per-map background image. Drawn under the hex grid, sharing the viewport's + * pan/zoom transform. `offsetX`/`offsetY` translate the image relative to the + * hex-grid container's natural origin, in CSS pixels at the image's native + * resolution. `scale` is a uniform multiplier (1 = native pixel size). + * Rotation in degrees, default 0. Opacity 0..1, default 1. + */ +export interface MapBackgroundImage { + path: string; + offsetX: number; + offsetY: number; + scale: number; + rotation?: number; + opacity?: number; +} + +export interface MapData { + name: string; + /** Plugin version that created the map (see src/compat.ts). */ + createdWith?: string; + paletteName: string; + terrainType?: string; // terrain name from the map's palette; used as submap center dot color + gridSize: { cols: number; rows: number }; + gridOffset: { x: number; y: number }; + pathChains: PathChain[]; + showCoords?: boolean; // undefined = true (backwards-compatible) + showTerrainIcons?: boolean; // undefined = true + showIconOverrides?: boolean; // undefined = true + showPaths?: boolean; // undefined = true + showFactionOverlay?: boolean; // undefined = false (opt-in) + showRegionOverlay?: boolean; // undefined = false (opt-in) + showGmLayer?: boolean; // undefined = true (on by default) + showTokens?: boolean; // undefined = true (on by default) + staggerOffset?: "odd" | "even"; // undefined = inherit global setting + /** Slot on a shared grid of neighbouring regions (see src/worldgen/world.ts). */ + world?: { id: string; cx: number; cy: number }; + backgroundImage?: MapBackgroundImage; + /** Optional independent transform applied to the hex grid container, + * used during background-image calibration so the user can resize/shift + * the grid to fit features in the underlying image. + * `gridDisplayScale` is the legacy uniform-scale field, retained for + * back-compat; new code reads X/Y separately (falling back to + * `gridDisplayScale` if X/Y are missing). */ + gridDisplayScale?: number; + gridDisplayScaleX?: number; + gridDisplayScaleY?: number; + gridDisplayOffsetX?: number; + gridDisplayOffsetY?: number; + /** Persisted viewport state — restored when the view is reopened so a + * calibrated map (whose bg image / grid transforms were sized at a + * specific font-size / zoom) doesn't drift on reload. */ + savedViewport?: { + zoom: number; + panX: number; + panY: number; + /** Baked font-size as a CSS string (e.g. `"32px"`), or `""` for default. */ + fontSize: string; + }; +} + +export interface TerrainPalette { + name: string; + terrains: TerrainColor[]; +} + +export interface TerrainColor { + name: string; + color: string; + icon?: string; + iconColor?: string; // CSS colour to tint the icon; undefined = no tint (render as-is) + category?: string; +} + +export interface HexmakerPluginSettings { + mySetting: string; + /** Plugin version that last saved data.json (see src/compat.ts). */ + savedWith?: string; + worldFolder: string; + hexFolder: string; + townsFolder: string; + dungeonsFolder: string; + questsFolder: string; + featuresFolder: string; + iconsFolder: string; + templatePath: string; + hexGap: string; + terrainPalettes: TerrainPalette[]; + maps: MapData[]; + zoomLevel: number; + pathTypes: PathType[]; + hexOrientation: "pointy" | "flat"; + staggerOffset: "odd" | "even"; + tablesFolder: string; + factionsFolder: string; + regionsFolder: string; + defaultTableDice: number; + hexEditorTerrainCollapsed: boolean; + hexEditorFeaturesCollapsed: boolean; + hexEditorNotesCollapsed: boolean; + rollTableExcludedFolders: string[]; + encounterTableExcludedFolders: string[]; + defaultMap: string; + defaultNewMapCols: number; + defaultNewMapRows: number; + defaultSubmapCols: number; + defaultSubmapRows: number; + workflowsFolder: string; + exportFolder: string; + coordPlacement: "top" | "middle" | "bottom"; + /** Size of the hex coordinate label, in em units relative to the hex. */ + coordFontSize: number; + /** Which font the coord label uses. */ + coordFontFamily: "interface" | "monospace" | "serif"; + /** Coord label text color (CSS hex). */ + coordFontColor: string; + hiddenIcons: string[]; + iconOrder: string[]; + setupComplete: boolean; + setupDismissed: boolean; +} + +export const LINK_SECTIONS = ["Towns", "Dungeons", "Features", "Quests", "Factions", "Encounters Table"] as const; +export type LinkSection = typeof LINK_SECTIONS[number]; + +export const TEXT_SECTIONS = [ + { key: "description", label: "Description" }, + { key: "landmark", label: "Landmark" }, + { key: "hidden", label: "Hidden" }, + { key: "secret", label: "Secret" }, +] as const; + +/** + * Session-only flags passed from HexMapView into HexEditorModal. + * All fields are optional — modal defaults missing keys to false. + * Add new session-layer flags here; no constructor signature changes needed. + */ +export interface HexEditorOptions { + /** GM layer is active: force Notes open, highlight Hidden/Secret sections. */ + gmLayerActive?: boolean; + /** Called when the user clicks a neighbour tile to navigate to an adjacent hex. */ + onNavigate?: (x: number, y: number) => void; + /** Called when the modal closes (e.g. to clear the selected-hex highlight). */ + onModalClose?: () => void; + /** Called when the user clicks the submap centre-dot to drill into another map. */ + onSwitchMap?: (mapName: string) => void; + /** Called after the user agrees to step from the hex flower into a neighbouring region's hex. */ + onCrossToRegion?: (mapName: string, x: number, y: number) => void; +} diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 9b7aaa8a..6ddd0179 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -29,6 +29,8 @@ import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; import { makeScrubbable, wheelValue } from "./scrub"; import { rebalance, toPercents } from "./regionWeights"; import { suggestImpassable } from "./impassableHint"; +import { SIDES, type Side } from "./world"; +import { generateConnected, neighbourSpec, occupiedSides, placeNewRegion, regionNameAt, type NewRegion } from "./neighbours"; import { GeneratorLibrary } from "./GeneratorLibrary"; import { sizePresets } from "./sizePresets"; import { listSaves, writeSave, readSave, applySave, renameGenerator } from "./saves"; @@ -70,6 +72,8 @@ export class GeneratorPanel { static mapName = ""; static paletteName = ""; static seedLocked = false; + /** Generate the new map as a neighbouring region of an existing one. */ + static connect: { anchor: string; side: Side } | null = null; /** Titles of the setting sections folded away. */ static collapsed = new Set(); /** Path types whose routes are shown (groups start folded). */ @@ -428,6 +432,46 @@ export class GeneratorPanel { input.addEventListener("change", markPreset); } + // Connect to: the new map becomes a neighbouring region of an existing + // one, so its size, palette, coordinates and stagger follow from it, and + // its terrain carries on across the border. + const connectRow = el.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + connectRow.createSpan({ text: "Connect to", cls: "duckmage-map-origin-label" }); + const anchorSelect = connectRow.createEl("select"); + anchorSelect.createEl("option", { value: "", text: "Nothing (a separate map)" }); + for (const m of this.plugin.settings.maps) anchorSelect.createEl("option", { value: m.name, text: m.name }); + const sideSelect = connectRow.createEl("select"); + for (const sd of SIDES) sideSelect.createEl("option", { value: sd, text: `${sd} of it` }); + anchorSelect.value = GeneratorPanel.connect?.anchor ?? ""; + sideSelect.value = GeneratorPanel.connect?.side ?? "east"; + sideSelect.disabled = !anchorSelect.value; + const connectNote = el.createEl("p", { cls: "duckmage-map-origin-desc" }); + let connected: NewRegion | null = null; + if (GeneratorPanel.connect) { + const spec = neighbourSpec(this.plugin, GeneratorPanel.connect.anchor, GeneratorPanel.connect.side); + if (!spec.ok) connectNote.setText(`⚠ ${spec.reason}`); + else { + connected = { slot: spec.slot, aSlot: spec.aSlot, anchor: GeneratorPanel.connect.anchor, side: GeneratorPanel.connect.side, cols: spec.cols, rows: spec.rows, offset: spec.offset, stagger: spec.stagger, paletteName: spec.paletteName }; + const borders = occupiedSides(this.plugin, connected).map((sd) => `${sd}: ${regionNameAt(this.plugin, connected!, sd)}`); + connectNote.setText(`Size locked to ${spec.cols}×${spec.rows} and palette to ${spec.paletteName}, so it lines up. Borders ${borders.join("; ")}.`); + colsInput.value = String(spec.cols); + rowsInput.value = String(spec.rows); + colsInput.disabled = rowsInput.disabled = true; + for (const { btn } of presetBtns) btn.disabled = true; + markPreset(); + } + } + const setConnect = () => { + GeneratorPanel.connect = anchorSelect.value ? { anchor: anchorSelect.value, side: sideSelect.value as Side } : null; + // Neighbours must share the palette. + const anchorMap = anchorSelect.value ? this.plugin.getMap(anchorSelect.value) : undefined; + if (anchorMap) GeneratorPanel.paletteName = anchorMap.paletteName; + this.host.rerender(); + }; + anchorSelect.addEventListener("change", setConnect); + sideSelect.addEventListener("change", setConnect); + if (connected) paletteSelect.disabled = true; + const showLock = () => { const locked = GeneratorPanel.seedLocked; setIcon(lockBtn, locked ? "lock" : "lock-open"); @@ -468,6 +512,7 @@ export class GeneratorPanel { fillSaves(); const previewGrid = () => { + if (connected) return { cols: connected.cols, rows: connected.rows, offset: { ...connected.offset }, stagger: connected.stagger }; const map = this.plugin.getMap(this.mapName); return { cols: Math.max(2, Math.min(200, Number(colsInput.value) || 30)), @@ -554,11 +599,12 @@ export class GeneratorPanel { this.previewRows = grid.rows; this.seed = Number(seedInput.value) >>> 0; const palette = this.paletteTerrains().length ? this.paletteTerrains() : model.terrains.map((t) => t.name); - const r = generateTerrain(this.plugin, model, palette, grid, this.seed); + const r = connected ? generateConnected(this.plugin, model, palette, connected, this.seed) : generateTerrain(this.plugin, model, palette, grid, this.seed); if (!r.ok) { status.setText(`Couldn't generate: ${r.message}`); return; } + const shadow = connected && "shadow" in r ? (r.shadow as Map) : undefined; // A loaded save shows its own map if this version generates a different one. let cells = r.cells; let rawPaths: { type: string; route?: string; hexes: string[] }[] = r.paths; @@ -579,7 +625,7 @@ export class GeneratorPanel { // Draw at the side column's device-pixel width so it stays sharp when stretched. const dpr = activeWindow.devicePixelRatio || 1; drawPreview(canvas, cells, grid, this.plugin.settings.hexOrientation, colors, r.featureCells, paths, pathColors(this.plugin), - Math.max(420, side.clientWidth) * dpr, 40 * dpr, highlight); + Math.max(420, side.clientWidth) * dpr, 40 * dpr, highlight, { shadow }); }; lastDraw(hoveredRoute); updateShares(cells, grid, palette); @@ -683,7 +729,15 @@ export class GeneratorPanel { const grid = previewGrid(); const seed = Number(seedInput.value) >>> 0; const palette = this.paletteTerrains().length ? this.paletteTerrains() : model.terrains.map((t) => t.name); - const generated = generateTerrain(this.plugin, model, palette, grid, seed); + // A neighbour slot may have been taken since this page was drawn. + if (connected?.anchor && connected.side) { + const again = neighbourSpec(this.plugin, connected.anchor, connected.side); + if (!again.ok) { + new Notice(again.reason); + return; + } + } + const generated = connected ? generateConnected(this.plugin, model, palette, connected, seed) : generateTerrain(this.plugin, model, palette, grid, seed); if (!generated.ok) { new Notice(`Couldn't generate: ${generated.message}`); return; @@ -695,7 +749,7 @@ export class GeneratorPanel { void this.plugin .createNewMap( newNameInput.value.trim() || `${model.name}-${seed}`, - grid.cols, grid.rows, GeneratorPanel.paletteName, 0, 0, grid.stagger, + grid.cols, grid.rows, GeneratorPanel.paletteName, grid.offset.x, grid.offset.y, grid.stagger, (done, total) => createBtn.setText(`Creating ${done} / ${total}…`), r.cells, ) @@ -713,7 +767,11 @@ export class GeneratorPanel { await this.plugin.saveSettings(); } if (missing.length) new Notice(`No path type named ${missing.join(", ")}, so those paths were skipped.`); - new Notice(`Created map "${result.name}".`); + if (connected) { + await placeNewRegion(this.plugin, result.name, connected); + GeneratorPanel.connect = null; + } + new Notice(`Created map "${result.name}"${connected ? ` ${connected.side} of ${connected.anchor}` : ""}.`); GeneratorPanel.mapName = result.name; await this.plugin.showMap(result.name); this.host.rerender(); diff --git a/src/worldgen/neighbours.ts b/src/worldgen/neighbours.ts new file mode 100644 index 00000000..d1cede30 --- /dev/null +++ b/src/worldgen/neighbours.ts @@ -0,0 +1,210 @@ +/** + * Neighbour regions in the vault: reading and saving where maps sit on their + * shared grid (see world.ts for the rules), the terrain just past a map's + * edges, and generating a region that carries on from its neighbours. + */ + +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { MapData } from "../types"; +import { getTerrainFromFile } from "../frontmatter"; +import { generateTerrain, type GridSpec } from "./generators"; +import type { HexWfcModel, SolveResult } from "../../packages/hex-wfc/src"; +import { + link, + neighbours, + newNeighbourSpec, + shadowDepth, + shadowHexes, + SIDES, + type GridRules, + type Side, + type WorldSlot, +} from "./world"; + +export function gridRules(plugin: HexmakerPlugin): GridRules { + return { orientation: plugin.settings.hexOrientation, stagger: plugin.settings.staggerOffset ?? "odd" }; +} + +/** Terrain of a map's hex, or undefined if unpainted. */ +export function terrainAt(plugin: HexmakerPlugin, mapName: string, x: number, y: number): string | undefined { + return getTerrainFromFile(plugin.app, plugin.hexPath(x, y, mapName)) ?? undefined; +} + +/** The map on each side of `mapName`. */ +export function regionNeighbours(plugin: HexmakerPlugin, mapName: string): Partial> { + const m = plugin.getMap(mapName); + return m ? neighbours(plugin.settings.maps, m) : {}; +} + +/** Put `other` on `side` of `mapName` (moving its group along if it has one) and save. */ +export async function linkRegions(plugin: HexmakerPlugin, mapName: string, side: Side, other: string): Promise<{ ok: true } | { ok: false; reason: string }> { + const r = link(plugin.settings.maps, mapName, side, other, gridRules(plugin)); + if (!r.ok) return r; + for (const [name, slot] of r.changes) { + const m = plugin.getMap(name); + if (m) m.world = slot; + } + await plugin.saveSettings(); + return { ok: true }; +} + +/** + * Take a map off the shared grid (its hexes are untouched). If that leaves a + * map alone in its group, it's taken off too. + */ +export async function detachRegion(plugin: HexmakerPlugin, mapName: string): Promise { + const m = plugin.getMap(mapName); + if (!m?.world) return; + const id = m.world.id; + m.world = undefined; + const left = plugin.settings.maps.filter((o) => o.world?.id === id); + if (left.length === 1) left[0].world = undefined; + await plugin.saveSettings(); +} + +/** Where a region next to `mapName` would go and how it must be made. */ +export function neighbourSpec(plugin: HexmakerPlugin, mapName: string, side: Side) { + const a = plugin.getMap(mapName); + if (!a) return { ok: false as const, reason: `Map "${mapName}" not found` }; + return newNeighbourSpec(plugin.settings.maps, a, side, gridRules(plugin)); +} + +export interface NewRegion { + slot: WorldSlot; + /** Slot to give the map it's made next to, if that map had none yet. */ + aSlot?: WorldSlot; + anchor?: string; + /** Which side of the anchor it goes on. */ + side?: Side; + cols: number; + rows: number; + offset: { x: number; y: number }; + stagger: "odd" | "even"; + paletteName: string; +} + +/** A region record for a map that doesn't exist yet, to ask world.ts about. */ +function virtualRegion(r: NewRegion): MapData { + return { + name: "\u0000new", + paletteName: r.paletteName, + gridSize: { cols: r.cols, rows: r.rows }, + gridOffset: { ...r.offset }, + staggerOffset: r.stagger, + world: r.slot, + pathChains: [], + }; +} + +/** All maps, with the anchor given its slot if it was just placed. */ +function mapsWith(plugin: HexmakerPlugin, r: NewRegion): MapData[] { + return plugin.settings.maps.map((m) => (r.aSlot && m.name === r.anchor && !m.world ? { ...m, world: r.aSlot } : m)); +} + +/** + * Neighbours' terrain just past each edge, in the frame of the map (or new + * region): local "x_y" -> terrain. Depth 0 = the map's own shadow depth. + */ +export function neighbourShadow(plugin: HexmakerPlugin, region: MapData | NewRegion, depth = 0): Map { + const virtual = "slot" in region ? virtualRegion(region) : region; + const maps = "slot" in region ? [...mapsWith(plugin, region), virtual] : plugin.settings.maps; + const d = depth || shadowDepth(virtual.gridSize.cols, virtual.gridSize.rows); + const out = new Map(); + for (const [key, r] of shadowHexes(maps, virtual, d)) { + if (r.map.name === virtual.name) continue; + out.set(key, { map: r.map.name, x: r.x, y: r.y, terrain: terrainAt(plugin, r.map.name, r.x, r.y) }); + } + return out; +} + +/** Which sides of a new region already have a neighbour. */ +export function occupiedSides(plugin: HexmakerPlugin, region: NewRegion): Side[] { + const virtual = virtualRegion(region); + const n = neighbours([...mapsWith(plugin, region), virtual], virtual); + return SIDES.filter((s) => n[s]); +} + +/** Keep the longest run of a path's hexes that stays inside the region. */ +function cropPath(hexes: string[], inside: (key: string) => boolean): string[] { + let best: string[] = [], run: string[] = []; + for (const h of hexes) { + if (inside(h)) run.push(h); + else { + if (run.length > best.length) best = run; + run = []; + } + } + return run.length > best.length ? run : best; +} + +/** + * Generate a new region so its terrain carries on from its neighbours: the + * region is solved with a one-hex ring around it, the ring pinned to the + * neighbours' edge terrain, then cropped. Pins that clash with the + * generator's rules are dropped one at a time; if it still can't fit, the + * region is generated on its own (with a warning). + */ +export function generateConnected( + plugin: HexmakerPlugin, + model: HexWfcModel, + paletteTerrains: string[], + region: NewRegion, + seed: number, +): SolveResult & { shadow: Map } { + const shadowInfo = neighbourShadow(plugin, region); + const shadow = new Map(); + for (const [k, v] of shadowInfo) if (v.terrain) shadow.set(k, v.terrain); + const { cols, rows, offset } = region; + const inside = (key: string) => { + const [x, y] = key.split("_").map(Number); + return x >= offset.x && x < offset.x + cols && y >= offset.y && y < offset.y + rows; + }; + // The ring one hex out, where a neighbour is. + const fixed = new Map(); + for (const [k, t] of shadow) { + const [x, y] = k.split("_").map(Number); + if (x >= offset.x - 1 && x <= offset.x + cols && y >= offset.y - 1 && y <= offset.y + rows) fixed.set(k, t); + } + if (!fixed.size) { + const grid: GridSpec = { cols, rows, offset, stagger: region.stagger }; + return { ...generateTerrain(plugin, model, paletteTerrains, grid, seed), shadow }; + } + const grid: GridSpec = { cols: cols + 2, rows: rows + 2, offset: { x: offset.x - 1, y: offset.y - 1 }, stagger: region.stagger }; + let dropped = 0; + let r = generateTerrain(plugin, model, paletteTerrains, grid, seed, fixed); + while (!r.ok && r.at && fixed.size && dropped < 40) { + const key = `${r.at.x}_${r.at.y}`; + if (!fixed.delete(key)) break; + dropped++; + r = generateTerrain(plugin, model, paletteTerrains, grid, seed, fixed); + } + if (!r.ok) { + const alone = generateTerrain(plugin, model, paletteTerrains, { cols, rows, offset, stagger: region.stagger }, seed); + if (alone.ok) alone.warnings.unshift("Couldn't fit this map to its neighbours' edges, so it was generated on its own"); + return { ...alone, shadow }; + } + const cells = new Map([...r.cells].filter(([k]) => inside(k))); + const featureCells = new Set([...r.featureCells].filter(inside)); + const paths = r.paths.map((p) => ({ ...p, hexes: cropPath(p.hexes, inside) })).filter((p) => p.hexes.length >= 2); + const warnings = [...r.warnings]; + if (dropped) warnings.push(`${dropped} edge hex${dropped === 1 ? "" : "es"} couldn't be matched to the neighbouring map's terrain`); + return { ...r, cells, featureCells, paths, warnings, shadow }; +} + +/** Name of the map on `side` of a region that's about to be made. */ +export function regionNameAt(plugin: HexmakerPlugin, region: NewRegion, side: Side): string { + const virtual = virtualRegion(region); + return neighbours([...mapsWith(plugin, region), virtual], virtual)[side]?.name ?? ""; +} + +/** Give a just-created map its slot (and the map it was made next to, if that had none). */ +export async function placeNewRegion(plugin: HexmakerPlugin, mapName: string, region: NewRegion): Promise { + const anchor = region.anchor ? plugin.getMap(region.anchor) : undefined; + if (anchor && !anchor.world && region.aSlot) anchor.world = region.aSlot; + const created = plugin.getMap(mapName); + if (created) { + created.world = region.slot; + created.staggerOffset = region.stagger; + } + await plugin.saveSettings(); +} diff --git a/src/worldgen/preview.ts b/src/worldgen/preview.ts index 736ef4d4..25a90070 100644 --- a/src/worldgen/preview.ts +++ b/src/worldgen/preview.ts @@ -29,19 +29,30 @@ export function drawPreview( maxScale = 14, /** Route to emphasise (others are dimmed), e.g. while its table row is hovered. */ highlightRoute?: string, + extra: { + /** Hexes outside the grid (same coordinate frame) drawn faded: neighbouring regions. */ + shadow?: Map; + /** A hex to outline (e.g. where you'll arrive). */ + mark?: string; + } = {}, ): void { const { cols, rows, offset, stagger } = grid; // Hex centres in unit space (neighbours √3 apart, circumradius 1). const pts: [string, number, number][] = []; let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + const addPoint = (x: number, y: number) => { + const [px, py] = hexCenter(x, y, orientation, stagger); + pts.push([cellKey(x, y), px, py]); + minX = Math.min(minX, px); maxX = Math.max(maxX, px); + minY = Math.min(minY, py); maxY = Math.max(maxY, py); + }; for (let j = 0; j < rows; j++) - for (let i = 0; i < cols; i++) { - const x = offset.x + i, y = offset.y + j; - const [px, py] = hexCenter(x, y, orientation, stagger); - pts.push([cellKey(x, y), px, py]); - minX = Math.min(minX, px); maxX = Math.max(maxX, px); - minY = Math.min(minY, py); maxY = Math.max(maxY, py); - } + for (let i = 0; i < cols; i++) addPoint(offset.x + i, offset.y + j); + const inside = pts.length; + for (const key of extra.shadow?.keys() ?? []) { + const [x, y] = key.split("_").map(Number); + if (Number.isFinite(x) && Number.isFinite(y)) addPoint(x, y); + } const spanX = maxX - minX + 2, spanY = maxY - minY + 2; const scale = Math.max(1, Math.min(maxWidth / spanX, maxScale)); canvas.width = Math.ceil(spanX * scale); @@ -54,8 +65,10 @@ export function drawPreview( return [Math.cos(a), Math.sin(a)]; }; const corners = [0, 1, 2, 3, 4, 5].map(corner); - for (const [key, px, py] of pts) { - const t = cells.get(key); + for (const [n, [key, px, py]] of pts.entries()) { + const shadow = n >= inside; + const t = shadow ? extra.shadow?.get(key) : cells.get(key); + ctx.globalAlpha = shadow ? 0.35 : 1; const cx = (px - minX + 1) * scale, cy = (py - minY + 1) * scale; ctx.beginPath(); corners.forEach(([dx, dy], k) => { @@ -66,12 +79,29 @@ export function drawPreview( ctx.closePath(); ctx.fillStyle = t ? (colors.get(t) ?? hashColor(t)) : "rgba(127,127,127,0.15)"; ctx.fill(); - if (featureCells?.has(key)) { + if (!shadow && featureCells?.has(key)) { ctx.strokeStyle = "rgba(0,0,0,0.35)"; ctx.lineWidth = Math.max(1, scale * 0.15); ctx.stroke(); } } + ctx.globalAlpha = 1; + if (extra.mark) { + const m = pts.find(([key]) => key === extra.mark); + if (m) { + const cx = (m[1] - minX + 1) * scale, cy = (m[2] - minY + 1) * scale; + ctx.beginPath(); + corners.forEach(([dx, dy], k) => { + const X = cx + dx * scale * 0.9, Y = cy + dy * scale * 0.9; + if (k === 0) ctx.moveTo(X, Y); + else ctx.lineTo(X, Y); + }); + ctx.closePath(); + ctx.strokeStyle = "#ffffff"; + ctx.lineWidth = Math.max(2, scale * 0.3); + ctx.stroke(); + } + } // Paths through hex centres. const centre = new Map(pts.map(([key, px, py]) => [key, [(px - minX + 1) * scale, (py - minY + 1) * scale]])); ctx.lineCap = "round"; diff --git a/styles.css b/styles.css index 6e4ac02a..ea2b23d0 100644 --- a/styles.css +++ b/styles.css @@ -5685,3 +5685,48 @@ button.duckmage-wfc-library-tab.is-active { gap: 0.4em; padding: 0.4em 0.6em 0.6em 1.6em; } + +/* Neighbouring regions (src/worldgen/world.ts): their terrain shown dimmed + past the map's edges, on a layer of its own so the grid doesn't move. */ +.duckmage-region-shadow-layer { + position: absolute; + inset: 0; + pointer-events: none; +} + +.duckmage-hex.duckmage-hex-shadow { + position: absolute; + left: var(--duckmage-shadow-x, 0px); + top: var(--duckmage-shadow-y, 0px); + width: var(--duckmage-shadow-w); + height: var(--duckmage-shadow-h); + box-sizing: border-box; + margin: 0; + opacity: 0.35; + pointer-events: auto; + filter: saturate(0.6); +} + +.duckmage-hex.duckmage-hex-shadow:hover { + opacity: 0.7; +} + +/* Hex flower: a tile past the edge that's in a neighbouring region. */ +.duckmage-neighbor-tile.duckmage-neighbor-tile-region { + opacity: 0.55; + cursor: pointer; + outline: 1px dashed var(--text-muted); + outline-offset: -2px; +} + +.duckmage-neighbor-tile.duckmage-neighbor-tile-region:hover { + opacity: 0.9; +} + +/* "Go to region?" box. */ +.duckmage-region-nav-preview { + display: block; + max-width: 100%; + margin: 0.5em auto; + border-radius: var(--radius-s); +} From a47e3c446ffaba7fd3b43494504cfee76d8106ff Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 14:14:32 -0400 Subject: [PATCH 044/558] fix(regions): shadow hexes aren't map hexes They carried the .duckmage-hex class for its shape, so the coordinate-label layer (and painting, which looks hexes up by that class) picked them up: a stray "undefined,undefined" label. They're now .duckmage-region-shadow-hex with their own hex shape and colour variable; the sentence-case fix for the resize notice rides along. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 5 +++-- styles.css | 15 ++++++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index f18d5076..b77b4077 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -3457,8 +3457,9 @@ export class HexMapView extends ItemView { // ── Writes ── const layer = gridContainer.createDiv({ cls: "duckmage-region-shadow-layer" }); for (const { s, at, color } of items) { + // Not a .duckmage-hex: painting, overlays and labels all look for those. const el = layer.createDiv({ - cls: "duckmage-hex duckmage-hex-shadow", + cls: "duckmage-region-shadow-hex", attr: { title: `${s.map}: hex ${s.x}, ${s.y}`, "data-region": s.map }, }); el.setCssProps({ @@ -3466,8 +3467,8 @@ export class HexMapView extends ItemView { "--duckmage-shadow-y": `${at.y - A.h / 2}px`, "--duckmage-shadow-w": `${A.w}px`, "--duckmage-shadow-h": `${A.h}px`, + ...(color ? { "--duckmage-shadow-color": color } : {}), }); - this.setHexColor(el, color); el.addEventListener("click", () => { new RegionNavigateModal(this.app, this.plugin, { map: s.map, x: s.x, y: s.y }, () => this.goToRegionHex(s.map, s.x, s.y)).open(); }); diff --git a/styles.css b/styles.css index ea2b23d0..b69223cc 100644 --- a/styles.css +++ b/styles.css @@ -5694,20 +5694,25 @@ button.duckmage-wfc-library-tab.is-active { pointer-events: none; } -.duckmage-hex.duckmage-hex-shadow { +.duckmage-region-shadow-hex { position: absolute; left: var(--duckmage-shadow-x, 0px); top: var(--duckmage-shadow-y, 0px); width: var(--duckmage-shadow-w); height: var(--duckmage-shadow-h); - box-sizing: border-box; - margin: 0; + clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); + background: var(--duckmage-shadow-color, var(--background-secondary)); opacity: 0.35; - pointer-events: auto; filter: saturate(0.6); + pointer-events: auto; + cursor: pointer; +} + +.duckmage-grid-flat .duckmage-region-shadow-hex { + clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%); } -.duckmage-hex.duckmage-hex-shadow:hover { +.duckmage-region-shadow-hex:hover { opacity: 0.7; } From c232757e60c577243c7c006748cb14f3bb8295c2 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 14:16:07 -0400 Subject: [PATCH 045/558] feat: submaps fit the bigger map (parent + neighbour context) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GenerationContext (procedural/common.ts): the parent hex a submap zooms into, its neighbours by compass side, and exact border cells from neighbouring regions. buildSubmapContext() reads them off the parent map (base terrain counts; off-grid neighbours are skipped). - Region detail generator (World, submaps only): Planet surface driven by per-type elevation/moisture/temperature targets — the parent's terrain fills the map, each side blends toward its neighbour within an edge band (corners only near both edges), border cells pull locally, noise adds detail. East and west neighbours both act, each on its own edge. Options: neighbour influence (edge band), variety. Default generator for world-palette submaps without a saved default. - Orbits: the sector hex picks the mainworld ("ocean world" -> an ocean planet on a habitable orbit that is never skipped; gas giant, belt, ice, desert... likewise). - Setup modal: passes the context to generators; context-only generators are offered for submaps only; the preview is framed by the parent's neighbour terrains (NW N NE / W map E / SW S SE). - Sandbox: Region detail mode with parent + N/E/S/W pickers. Tests: tests/regionContext.test.ts (side mapping, parent fill, sea on the right edge, east+west both acting, mountains raise an edge, border cells, untyped names, determinism, mainworld hints). Co-Authored-By: Claude Opus 5.5 --- dev/space-gen-preview.html | 1 + dev/space-gen-preview.ts | 42 ++++- package.json | 4 +- src/worldgen/NewMapSetupModal.ts | 36 +++- src/worldgen/procedural/common.ts | 46 ++++++ src/worldgen/procedural/orbits.ts | 46 +++++- src/worldgen/procedural/planetSurface.ts | 201 ++++++++++++++++++++--- src/worldgen/registry.ts | 35 +++- src/worldgen/submapContext.ts | 44 +++++ styles.css | 36 ++++ tests/regionContext.test.ts | 128 +++++++++++++++ 11 files changed, 576 insertions(+), 43 deletions(-) create mode 100644 src/worldgen/submapContext.ts create mode 100644 tests/regionContext.test.ts diff --git a/dev/space-gen-preview.html b/dev/space-gen-preview.html index a4b32a83..70ca94bf 100644 --- a/dev/space-gen-preview.html +++ b/dev/space-gen-preview.html @@ -18,6 +18,7 @@

Procedural space generators: Star scatter (sector) and Orbits (system)

+ diff --git a/dev/space-gen-preview.ts b/dev/space-gen-preview.ts index b3d9f5c7..92dae44d 100644 --- a/dev/space-gen-preview.ts +++ b/dev/space-gen-preview.ts @@ -7,10 +7,14 @@ import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS, SPACE_PATH_TYPES, SYSTEM_PATH_TYPES } from "../src/palettes/presets"; import { starScatter, STAR_SCATTER_OPTIONS } from "../src/worldgen/procedural/starScatter"; import { orbits, ORBITS_OPTIONS } from "../src/worldgen/procedural/orbits"; -import type { ProcGrid, ProcOption } from "../src/worldgen/procedural/common"; +import type { GenerationContext, ProcGrid, ProcOption, Side } from "../src/worldgen/procedural/common"; +import { planetSurface, REGION_DETAIL_OPTIONS } from "../src/worldgen/procedural/planetSurface"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; import { drawPreview } from "../src/worldgen/preview"; -type Gen = "sector" | "system"; +type Gen = "sector" | "system" | "region"; +/** Region detail: the parent hex and its N/E/S/W neighbours (terrain names from Expanded). */ +const region: { parent: string; sides: Partial> } = { parent: "forest", sides: { E: "ocean" } }; const state = { gen: "sector" as Gen, orientation: "flat" as "flat" | "pointy", @@ -20,14 +24,36 @@ const state = { options: {} as Record, }; -const colors = (gen: Gen) => - new Map((gen === "sector" ? SPACE_SECTOR_TERRAINS : SPACE_SYSTEM_TERRAINS).map((t) => [t.name, t.color])); +const paletteOf = (gen: Gen) => + gen === "sector" ? SPACE_SECTOR_TERRAINS : gen === "system" ? SPACE_SYSTEM_TERRAINS : DEFAULT_TERRAIN_PALETTE; +const colors = (gen: Gen) => new Map(paletteOf(gen).map((t) => [t.name, t.color])); +const typed = (name: string) => ({ terrain: name, type: DEFAULT_TERRAIN_PALETTE.find((t) => t.name === name)?.type }); +function regionContext(): GenerationContext { + const sides: GenerationContext["sides"] = {}; + for (const [s, name] of Object.entries(region.sides)) if (name) sides[s as Side] = typed(name); + return { parent: typed(region.parent), sides }; +} const pathColors = new Map([...SPACE_PATH_TYPES, ...SYSTEM_PATH_TYPES].map((p) => [p.name, p.color])); function controls(): void { const box = document.getElementById("controls")!; box.replaceChildren(); - const opts: ProcOption[] = state.gen === "sector" ? STAR_SCATTER_OPTIONS : ORBITS_OPTIONS; + const opts: ProcOption[] = state.gen === "sector" ? STAR_SCATTER_OPTIONS : state.gen === "system" ? ORBITS_OPTIONS : REGION_DETAIL_OPTIONS; + if (state.gen === "region") { + const names = ["", ...DEFAULT_TERRAIN_PALETTE.map((t) => t.name)]; + const pick = (label: string, value: string, set: (v: string) => void) => { + const l = document.createElement("label"); + l.textContent = label + " "; + const sel = document.createElement("select"); + for (const n of names) sel.add(new Option(n || "—", n)); + sel.value = value; + sel.onchange = () => { set(sel.value); render(); }; + l.append(sel); + box.append(l); + }; + pick("Parent hex", region.parent, (v) => { region.parent = v || "grass"; }); + for (const s of ["N", "E", "S", "W"] as Side[]) pick(s, region.sides[s] ?? "", (v) => { region.sides[s] = v || undefined; }); + } for (const o of opts) { const label = document.createElement("label"); label.textContent = o.label + " "; @@ -51,7 +77,9 @@ function render(): void { const seed = state.seed + i; const r = state.gen === "sector" ? starScatter(SPACE_SECTOR_TERRAINS, grid, seed, state.options, "Jump route") - : orbits(SPACE_SYSTEM_TERRAINS, grid, seed, state.options, "Orbit"); + : state.gen === "system" + ? orbits(SPACE_SYSTEM_TERRAINS, grid, seed, state.options, "Orbit") + : planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, state.options, regionContext()); const fig = document.createElement("figure"); const canvas = document.createElement("canvas"); drawPreview(canvas, r.cells, grid, state.orientation, colors(state.gen), undefined, r.paths, pathColors, 300, 18); @@ -71,7 +99,7 @@ function render(): void { function setGen(gen: Gen): void { state.gen = gen; state.options = {}; - [state.cols, state.rows] = gen === "sector" ? [8, 10] : [13, 13]; + [state.cols, state.rows] = gen === "sector" ? [8, 10] : gen === "system" ? [13, 13] : [20, 14]; (document.getElementById("cols") as HTMLInputElement).value = String(state.cols); (document.getElementById("rows") as HTMLInputElement).value = String(state.rows); document.querySelectorAll("[data-gen]").forEach((b) => b.classList.toggle("on", b.dataset.gen === gen)); diff --git a/package.json b/package.json index 952708dc..b111d11b 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index b843b548..90af7179 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -3,6 +3,8 @@ import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { SubmapDefault, TerrainColor } from "../types"; import { getTerrainFromFile } from "../frontmatter"; +import { buildSubmapContext } from "./submapContext"; +import type { GenerationContext, Side } from "./procedural/common"; import { fillPaletteSelect } from "../palettes/paletteOptions"; import { defaultSubmapName } from "../hex-map/submapNav"; import { randomSeed } from "../../packages/hex-wfc/src"; @@ -51,6 +53,8 @@ export class NewMapSetupModal extends HexmakerModal { private originTerrain: string | undefined; /** Saved setup for submaps of that terrain, applied as the starting values. */ private saved: SubmapDefault | undefined; + /** The parent hex and its neighbours, so generation fits the bigger map. */ + private context: GenerationContext | undefined; /** "Default for " checkboxes, one per option row. */ private remember = { palette: false, size: false, generator: false, base: false }; @@ -70,6 +74,7 @@ export class NewMapSetupModal extends HexmakerModal { this.originTerrain = getTerrainFromFile(app, plugin.hexPath(origin.x, origin.y, origin.map)) ?? parent?.baseTerrain ?? undefined; this.saved = plugin.submapDefaultFor(origin.map, this.originTerrain); + this.context = buildSubmapContext(plugin, origin.map, origin.x, origin.y); const d = this.saved; if (d?.cols && d.rows) { this.cols = d.cols; this.rows = d.rows; } if (d?.generator) this.kindId = d.generator; @@ -180,7 +185,25 @@ export class NewMapSetupModal extends HexmakerModal { }); // ── Preview ── - const canvas = side.createEl("canvas", { cls: "duckmage-setup-canvas" }); + // For submaps: the preview sits inside a frame of the parent's + // neighbours (N, NE, E…), so it's clear why each edge looks as it does. + const frame = side.createDiv({ cls: "duckmage-setup-context" }); + const chip = (slot: Side | "C") => { + const cell = frame.createDiv({ cls: `duckmage-setup-ctx duckmage-setup-ctx-${slot}` }); + if (slot === "C") return cell; + const t = this.context?.sides?.[slot]; + if (!t?.terrain) return cell; + const color = this.origin ? this.plugin.getMapPalette(this.origin.map).find((p) => p.name === t.terrain)?.color : undefined; + cell.createSpan({ cls: "duckmage-setup-ctx-swatch" }).setCssProps({ "--duckmage-bg": color ?? "transparent" }); + cell.createSpan({ cls: "duckmage-setup-ctx-name", text: t.terrain }); + cell.setAttr("title", `${slot}: ${t.terrain}`); + return cell; + }; + const showFrame = !!this.context && Object.keys(this.context.sides ?? {}).length > 0; + frame.toggleClass("is-empty", !showFrame); + (["NW", "N", "NE", "W"] as const).forEach((s) => chip(s)); + const canvas = chip("C").createEl("canvas", { cls: "duckmage-setup-canvas" }); + (["E", "SW", "S", "SE"] as const).forEach((s) => chip(s)); const seedRow = side.createDiv({ cls: "duckmage-setup-seed-row" }); const rerollBtn = seedRow.createEl("button", { text: "🎲 Re-roll", attr: { title: "New random seed" } }); const seedLabel = seedRow.createSpan({ cls: "duckmage-setup-seed" }); @@ -195,10 +218,13 @@ export class NewMapSetupModal extends HexmakerModal { const renderGenerators = () => { const terrains = this.terrains(paletteSelect.value); - const fitting = kindsForPalette(this.kinds, terrains); + const fitting = kindsForPalette(this.kinds, terrains, !!this.context); if (!fitting.some((k) => k.id === this.kindId)) { // Default to the first built-in generator that fits, else Blank. - this.kindId = fitting.find((k) => k.source === "built-in")?.id ?? BLANK_ID; + // Submaps zoom in: prefer the context-aware generator when it fits. + this.kindId = (this.context ? fitting.find((k) => k.needsContext)?.id : undefined) + ?? fitting.find((k) => k.source === "built-in")?.id + ?? BLANK_ID; this.options = {}; } genList.empty(); @@ -260,7 +286,7 @@ export class NewMapSetupModal extends HexmakerModal { if (this.cols * this.rows > PREVIEW_AUTO_LIMIT) { status.setText("Large map — the preview is skipped; terrain is generated on create."); } else { - const outcome = kind.generate({ terrains, grid, seed: this.seed, options: this.resolvedOptions(kind) }); + const outcome = kind.generate({ terrains, grid, seed: this.seed, options: this.resolvedOptions(kind), context: this.context }); this.lastOutcome = outcome; if (!outcome.ok) { status.setText(outcome.message); @@ -388,7 +414,7 @@ export class NewMapSetupModal extends HexmakerModal { let outcome: GenerateOutcome | undefined; if (!openGenerator && kind && kind.id !== BLANK_ID) { outcome = this.lastOutcome - ?? kind.generate({ terrains, grid: this.grid(), seed: this.seed, options: this.resolvedOptions(kind) }); + ?? kind.generate({ terrains, grid: this.grid(), seed: this.seed, options: this.resolvedOptions(kind), context: this.context }); if (!outcome.ok) { new Notice(outcome.message); return; diff --git a/src/worldgen/procedural/common.ts b/src/worldgen/procedural/common.ts index 57bd6909..2811ecdc 100644 --- a/src/worldgen/procedural/common.ts +++ b/src/worldgen/procedural/common.ts @@ -28,6 +28,52 @@ export interface ProcResult { warnings: string[]; } +/** Compass sides of a map, for what lies beyond each edge. */ +export type Side = "N" | "NE" | "E" | "SE" | "S" | "SW" | "W" | "NW"; +export const SIDES: Side[] = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]; + +/** A terrain as context: its palette name and (when known) its type. */ +export interface ContextTerrain { + terrain?: string; + type?: string; +} + +/** + * What surrounds the map being generated, so it fits into the bigger map: + * - `parent`: the hex a submap zooms into (its terrain fills the map); + * - `sides`: the parent hex's neighbours, by compass side (each pulls its + * edge of the map toward its own terrain — east *and* west neighbours + * both act, each on their side); + * - `edgeCells`: exact terrain of hexes just outside the grid, keyed in + * this map's coordinates (from neighbouring regions sharing a border). + * Every field is optional; generators ignore what they can't use. + */ +export interface GenerationContext { + parent?: ContextTerrain; + sides?: Partial>; + edgeCells?: Map; +} + +/** Unit vector (screen space: +x east, +y south) for each side. */ +export const SIDE_VECTORS: Record = { + N: [0, -1], + NE: [Math.SQRT1_2, -Math.SQRT1_2], + E: [1, 0], + SE: [Math.SQRT1_2, Math.SQRT1_2], + S: [0, 1], + SW: [-Math.SQRT1_2, Math.SQRT1_2], + W: [-1, 0], + NW: [-Math.SQRT1_2, -Math.SQRT1_2], +}; + +/** The compass side a direction vector points to (8 sectors of 45°). */ +export function sideOf(dx: number, dy: number): Side { + const angle = Math.atan2(dy, dx); // 0 = east, +π/2 = south (screen y down) + const sector = Math.round(angle / (Math.PI / 4)); + const bySector: Record = { 0: "E", 1: "SE", 2: "S", 3: "SW", 4: "W", [-4]: "W", [-3]: "NW", [-2]: "N", [-1]: "NE" }; + return bySector[sector]; +} + export interface ProcOption { key: string; label: string; diff --git a/src/worldgen/procedural/orbits.ts b/src/worldgen/procedural/orbits.ts index 39dd8ea5..8ecf61b7 100644 --- a/src/worldgen/procedural/orbits.ts +++ b/src/worldgen/procedural/orbits.ts @@ -12,6 +12,7 @@ import { typeIndex, untyped, weightedPick, + type GenerationContext, type ProcGrid, type ProcOption, type ProcPath, @@ -206,6 +207,8 @@ export function orbits( options: Record = {}, /** Path type to draw occupied orbits with (e.g. "Orbit"); none = no rings. */ orbitPathType?: string, + /** The sector hex this system sits in: its terrain picks the mainworld. */ + context?: GenerationContext, ): ProcResult { const roles = orbitRoles(terrains); if (!roles) { @@ -251,8 +254,12 @@ export function orbits( if (fullRing < 2) warnings.push("Map is too small for orbits — try Medium or Large."); let mainworld: [number, number] | undefined; const paths: ProcPath[] = []; + // The sector says what the mainworld is ("ocean world" → an ocean planet + // in the habitable zone); that orbit is never skipped. + const mainBody = mainworldFor(context?.parent?.terrain, roles.bodies); + const mainRing = mainBody ? first + Math.round(0.45 * (last - first)) : -1; for (let d = first; d <= last; d++) { - if (rand() < skip) continue; + if (d !== mainRing && rand() < skip) continue; // Draw the orbit itself: the ring, in order around the star, closed. if (orbitPathType) { const around = sortAround(ring(d), center, grid).map((h) => cellKey(h[0], h[1])); @@ -260,7 +267,7 @@ export function orbits( } const t = (d - first) / Math.max(1, last - first); const zone = t < 0.3 ? "inner" : t < 0.6 ? "habitable" : "outer"; - const body = weightedPick(rand, roles.bodies, roles.zoneWeights[zone], 0.5)!; + const body = d === mainRing ? mainBody! : weightedPick(rand, roles.bodies, roles.zoneWeights[zone], 0.5)!; const hexesOnRing = ring(d); if (hexesOnRing.length === 0) continue; if (roles.belts.includes(body)) { @@ -269,11 +276,13 @@ export function orbits( const span = Math.max(2, Math.floor(hexesOnRing.length * (0.3 + rand() * 0.4))); const sorted = sortAround(hexesOnRing, center, grid); for (let i = 0; i < span; i++) set(sorted[(start + i) % sorted.length], body); + if (d === mainRing) mainworld = sorted[start]; continue; } const pos = hexesOnRing[Math.floor(rand() * hexesOnRing.length)]; set(pos, body); - if (zone === "habitable" && !mainworld) mainworld = pos; + if (d === mainRing) mainworld = pos; + else if (zone === "habitable" && !mainworld && mainRing < 0) mainworld = pos; // Giants get a moon on a free neighbouring hex. if (roles.moon && roles.giants.includes(body) && rand() < 0.7) { const free = hexes.filter((h) => distance(h, pos, grid) === 1 @@ -312,3 +321,34 @@ function sortAround(hexes: [number, number][], center: [number, number], grid: P }; return [...hexes].sort((a, b) => angle(a) - angle(b)); } + +/** Parent-terrain words → body-name words, most specific first. */ +const MAINWORLD_HINTS: [string, string][] = [ + ["gas giant", "gas giant"], + ["ice giant", "ice giant"], + ["asteroid", "belt"], + ["ocean", "ocean"], + ["water", "ocean"], + ["garden", "terrestrial"], + ["terrestrial", "terrestrial"], + ["earth", "terrestrial"], + ["desert", "desert"], + ["ice", "ice"], + ["frozen", "ice"], + ["molten", "molten"], + ["lava", "molten"], + ["barren", "rocky"], + ["rocky", "rocky"], +]; + +/** The body that should be the system's mainworld, given the sector hex's terrain name. */ +export function mainworldFor(parentTerrain: string | undefined, bodies: string[]): string | undefined { + if (!parentTerrain) return undefined; + const p = parentTerrain.toLowerCase(); + for (const [from, to] of MAINWORLD_HINTS) { + if (!p.includes(from)) continue; + const hit = bodies.find((b) => b.toLowerCase().includes(to)); + if (hit) return hit; + } + return undefined; +} diff --git a/src/worldgen/procedural/planetSurface.ts b/src/worldgen/procedural/planetSurface.ts index 12a7923c..39518089 100644 --- a/src/worldgen/procedural/planetSurface.ts +++ b/src/worldgen/procedural/planetSurface.ts @@ -1,7 +1,14 @@ import { hexCenter, hexNeighbors, mulberry32 } from "../../../packages/hex-wfc/src"; import type { TerrainColor } from "../../types"; +import { inferTerrainType, isTerrainType } from "../../terrainTypes"; import { + SIDES, + SIDE_VECTORS, cellKey, + distance, + type ContextTerrain, + type GenerationContext, + type Side, findByType, findRole, gridKeys, @@ -209,20 +216,88 @@ function quantile(values: number[], q: number): number { return sorted[i]; } +// ── Region detail (context mode) ───────────────────────────────────────── +// +// Target [elevation, moisture, temperature] per terrain type, on the same +// 0..1 scales the classifier below uses (sea below 0.33, hills from 0.64, +// mountains 0.79, peaks 0.92). A region zooming into a "forest" hex gets +// forest-ish targets in the middle; each edge drifts toward the terrain +// beyond it, so a sea to the east puts a coast on the east edge. +const TYPE_TARGETS: Record = { + "deep-water": [0.02, 0.5, 0.6], + water: [0.14, 0.5, 0.6], + shallows: [0.27, 0.5, 0.6], + coast: [0.37, 0.4, 0.65], + grassland: [0.5, 0.42, 0.6], + settlement: [0.5, 0.42, 0.6], + forest: [0.52, 0.68, 0.55], + jungle: [0.5, 0.9, 0.9], + wetland: [0.41, 0.86, 0.6], + hills: [0.7, 0.45, 0.55], + mountains: [0.85, 0.45, 0.45], + peaks: [0.96, 0.4, 0.15], + snow: [0.55, 0.4, 0.08], + desert: [0.5, 0.1, 0.82], + badlands: [0.6, 0.15, 0.75], + volcanic: [0.82, 0.2, 0.85], +}; + +function targetOf(c: ContextTerrain | undefined): [number, number, number] | undefined { + if (!c) return undefined; + const type = isTerrainType(c.type) ? c.type : c.terrain ? inferTerrainType(c.terrain) : undefined; + return type ? TYPE_TARGETS[type] : undefined; +} + +export const REGION_DETAIL_ID = "procedural:region-detail"; + +export const REGION_DETAIL_OPTIONS: ProcOption[] = [ + { + key: "edges", + label: "Neighbour influence", + choices: [ + { value: "soft", label: "Soft (thin edges)" }, + { value: "normal", label: "Normal" }, + { value: "strong", label: "Strong (wide edges)" }, + ], + default: "normal", + }, + { + key: "variety", + label: "Variety", + choices: [ + { value: "low", label: "Low (mostly the parent terrain)" }, + { value: "normal", label: "Normal" }, + { value: "high", label: "High" }, + ], + default: "normal", + }, +]; + +/** Thresholds shared by both modes' classification. */ +interface Levels { + sea: number; + deep: number; + shelf: number; + hill: number; + mountain: number; + peak: number; +} + export function planetSurface( terrains: TerrainColor[], grid: ProcGrid, seed: number, options: Record = {}, + /** When given, generate a *region* of the bigger map (Region detail): + * the parent hex's terrain fills it and neighbours shape its edges. */ + context?: GenerationContext, ): ProcResult { const roles = planetRoles(terrains); if (!roles) return { cells: new Map(), paths: [], warnings: ["This palette has no sea or plains terrain."] }; const rand = mulberry32(seed); const elevNoise = makeNoise(rand); const moistNoise = makeNoise(rand); - const water = Math.max(0, Math.min(95, Number(options.water ?? 50))) / 100; const climate = options.climate ?? "temperate"; - const relief = options.relief ?? "normal"; const hexes = gridKeys(grid); // Feature scale: about 3 noise cells across the map whatever its size. @@ -232,23 +307,41 @@ export function planetSurface( const span = Math.max(maxX - minX, maxY - minY, 1); const scale = 3.2 / span; const ox = rand() * 100, oy = rand() * 100; + const noiseE = centers.map(([px, py]) => elevNoise(ox + px * scale, oy + py * scale)); + const noiseM = centers.map(([px, py]) => moistNoise(oy + px * scale * 1.3, ox + py * scale * 1.3)); - const elev = centers.map(([px, py]) => elevNoise(ox + px * scale, oy + py * scale)); - const moist = centers.map(([px, py]) => moistNoise(oy + px * scale * 1.3, ox + py * scale * 1.3)); - const seaLevel = water <= 0 ? -Infinity : quantile(elev, water); - const landElev = elev.filter((e) => e > seaLevel); - const hillAt = quantile(landElev.length ? landElev : [1], relief === "flat" ? 0.88 : relief === "rugged" ? 0.5 : 0.7); - const mountainAt = quantile(landElev.length ? landElev : [1], relief === "flat" ? 0.97 : relief === "rugged" ? 0.72 : 0.87); - const peakAt = quantile(landElev.length ? landElev : [1], relief === "rugged" ? 0.92 : 0.97); - const seaElev = elev.filter((e) => e <= seaLevel); - const deepAt = quantile(seaElev.length ? seaElev : [0], 0.35); - const shelfAt = quantile(seaElev.length ? seaElev : [0], 0.8); - - // Temperature: warm equator, cold poles (rows), shifted by climate. - const climateShift: Record = { temperate: 0, lush: 0.12, arid: 0.15, frozen: -0.55, volcanic: 0.3 }; - const moistShift: Record = { temperate: 0, lush: 0.25, arid: -0.35, frozen: -0.1, volcanic: -0.2 }; - const tShift = climateShift[climate] ?? 0; - const mShift = moistShift[climate] ?? 0; + let elev: number[], moistArr: number[], tempArr: number[], lv: Levels; + if (context) { + ({ elev, moist: moistArr, temp: tempArr } = regionField(grid, hexes, centers, noiseE, noiseM, context, options)); + lv = { sea: 0.33, deep: 0.08, shelf: 0.27, hill: 0.64, mountain: 0.79, peak: 0.92 }; + } else { + const water = Math.max(0, Math.min(95, Number(options.water ?? 50))) / 100; + const relief = options.relief ?? "normal"; + elev = noiseE; + const seaLevel = water <= 0 ? -Infinity : quantile(elev, water); + const landElev = elev.filter((e) => e > seaLevel); + const seaElev = elev.filter((e) => e <= seaLevel); + lv = { + sea: seaLevel, + hill: quantile(landElev.length ? landElev : [1], relief === "flat" ? 0.88 : relief === "rugged" ? 0.5 : 0.7), + mountain: quantile(landElev.length ? landElev : [1], relief === "flat" ? 0.97 : relief === "rugged" ? 0.72 : 0.87), + peak: quantile(landElev.length ? landElev : [1], relief === "rugged" ? 0.92 : 0.97), + deep: quantile(seaElev.length ? seaElev : [0], 0.35), + shelf: quantile(seaElev.length ? seaElev : [0], 0.8), + }; + // Temperature: warm equator, cold poles (rows), shifted by climate. + const climateShift: Record = { temperate: 0, lush: 0.12, arid: 0.15, frozen: -0.55, volcanic: 0.3 }; + const moistShift: Record = { temperate: 0, lush: 0.25, arid: -0.35, frozen: -0.1, volcanic: -0.2 }; + const tShift = climateShift[climate] ?? 0; + const mShift = moistShift[climate] ?? 0; + tempArr = centers.map((c, i) => { + const lat = maxY > minY ? Math.abs((c[1] - minY) / (maxY - minY) - 0.5) * 2 : 0; // 0 equator .. 1 pole + return 1 - lat * 0.9 + tShift - Math.max(0, elev[i] - seaLevel) * 0.6; + }); + moistArr = noiseM.map((m) => m + mShift); + } + const seaLevel = lv.sea, deepAt = lv.deep, shelfAt = lv.shelf; + const hillAt = lv.hill, mountainAt = lv.mountain, peakAt = lv.peak; // Woodland variety (typed palettes only): the family follows temperature, // dense variants take the wettest ground. No rand() calls, so a seed's @@ -277,9 +370,8 @@ export function planetSurface( hexes.forEach(([x, y], i) => { const k = cellKey(x, y); const e = elev[i]; - const lat = maxY > minY ? Math.abs((centers[i][1] - minY) / (maxY - minY) - 0.5) * 2 : 0; // 0 equator .. 1 pole - const temp = 1 - lat * 0.9 + tShift - Math.max(0, e - seaLevel) * 0.6; - const m = moist[i] + mShift; + const temp = tempArr[i]; + const m = moistArr[i]; if (isSea[i]) { // Frozen seas near the poles ice over. @@ -328,3 +420,70 @@ export function planetSurface( return { cells, paths: [], warnings: [] }; } + +/** + * Elevation / moisture / temperature for a region inside a bigger map: + * the parent's targets everywhere, blended toward each side's neighbour + * near that edge, and toward exact neighbour-region cells near the border; + * noise adds local detail on top. + */ +function regionField( + grid: ProcGrid, + hexes: [number, number][], + centers: [number, number][], + noiseE: number[], + noiseM: number[], + context: GenerationContext, + options: Record, +): { elev: number[]; moist: number[]; temp: number[] } { + const parent = targetOf(context.parent) ?? TYPE_TARGETS.grassland; + // Edge band: how far in from an edge its neighbour still pulls. + const band = options.edges === "soft" ? 0.3 : options.edges === "strong" ? 0.65 : 0.45; + const variety = options.variety === "low" ? 0.22 : options.variety === "high" ? 0.55 : 0.36; + + const xs = centers.map((c) => c[0]), ys = centers.map((c) => c[1]); + const midX = (Math.min(...xs) + Math.max(...xs)) / 2, midY = (Math.min(...ys) + Math.max(...ys)) / 2; + const halfW = Math.max((Math.max(...xs) - Math.min(...xs)) / 2, 1e-6); + const halfH = Math.max((Math.max(...ys) - Math.min(...ys)) / 2, 1e-6); + + const sides = SIDES + .map((s) => ({ s, t: targetOf(context.sides?.[s]) })) + .filter((x): x is { s: Side; t: [number, number, number] } => !!x.t); + const edgeCells = [...(context.edgeCells ?? new Map())] + .map(([k, c]) => ({ at: k.split("_").map(Number) as [number, number], t: targetOf(c) })) + .filter((x): x is { at: [number, number]; t: [number, number, number] } => !!x.t); + + const smooth = (t: number) => t * t * (3 - 2 * t); + const elev: number[] = [], moist: number[] = [], temp: number[] = []; + hexes.forEach((h, i) => { + const u = (centers[i][0] - midX) / halfW; // -1 west .. 1 east + const v = (centers[i][1] - midY) / halfH; // -1 north .. 1 south + let w = 1; + const acc = [parent[0], parent[1], parent[2]]; + for (const { s, t } of sides) { + const [dx, dy] = SIDE_VECTORS[s]; + // 1 on that edge, 0 at the far side. A corner neighbour (NE…) only + // reaches hexes near *both* of its edges. + const reach = s.length === 2 ? Math.min(u * Math.sign(dx), v * Math.sign(dy)) : u * dx + v * dy; + const edge = smooth(Math.max(0, Math.min(1, (reach - (1 - band)) / band))); + if (edge <= 0) continue; + const ws = edge * (s.length === 2 ? 2 : 3); + w += ws; + for (let k = 0; k < 3; k++) acc[k] += t[k] * ws; + } + // Exact border cells from a neighbouring region: strong, very local. + for (const c of edgeCells) { + const d = distance(h, c.at, grid); + if (d > 3) continue; + const ws = (4 - d) * 2; + w += ws; + for (let k = 0; k < 3; k++) acc[k] += c.t[k] * ws; + } + const target = acc.map((a) => a / w); + const e = target[0] + (noiseE[i] - 0.5) * variety * 1.4; + elev.push(e); + moist.push(target[1] + (noiseM[i] - 0.5) * 0.5); + temp.push(target[2] - Math.max(0, e - 0.6) * 0.5); + }); + return { elev, moist, temp }; +} diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index 03f019fb..1114d4f3 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -7,12 +7,14 @@ import { toPathChains, type GridSpec, } from "./generators"; -import { findTerrain, type ProcGrid, type ProcOption } from "./procedural/common"; +import { findTerrain, type GenerationContext, type ProcGrid, type ProcOption } from "./procedural/common"; import { STAR_SCATTER_ID, STAR_SCATTER_OPTIONS, starScatter, starScatterFits } from "./procedural/starScatter"; import { ORBITS_ID, ORBITS_OPTIONS, orbits, orbitsFits } from "./procedural/orbits"; import { PLANET_SURFACE_ID, PLANET_SURFACE_OPTIONS, + REGION_DETAIL_ID, + REGION_DETAIL_OPTIONS, planetSurface, planetSurfaceFits, } from "./procedural/planetSurface"; @@ -46,6 +48,8 @@ export interface GenerateRequest { grid: GridSpec; seed: number; options: Record; + /** Where the map sits in the bigger map (parent hex, neighbours). */ + context?: GenerationContext; } export interface TerrainGeneratorKind { @@ -55,6 +59,8 @@ export interface TerrainGeneratorKind { source: "blank" | "built-in" | "learned"; /** Map type that owns a built-in generator (hidden when that type is off). */ mapKind?: MapKind; + /** Only meaningful inside a bigger map (offered for submaps only). */ + needsContext?: boolean; options: ProcOption[]; /** Can this generator produce terrain for a palette with these terrains? */ fits(terrains: TerrainColor[]): boolean; @@ -123,7 +129,22 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise { - const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitPath); + const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitPath, req.context); + return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; + }, + toChains, + }, + { + id: REGION_DETAIL_ID, + label: "Region detail", + mapKind: "world", + needsContext: true, + description: "Zoom into the parent hex: its terrain fills the map, and each neighbour shapes its edge (sea to the east → coast on the east).", + source: "built-in", + options: REGION_DETAIL_OPTIONS, + fits: planetSurfaceFits, + generate: (req) => { + const r = planetSurface(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, req.context ?? {}); return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; }, toChains, @@ -165,9 +186,13 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise k.fits(terrains)); +/** Generators usable with a palette, Blank first. Context-only ones need `hasContext`. */ +export function kindsForPalette( + kinds: TerrainGeneratorKind[], + terrains: TerrainColor[], + hasContext = false, +): TerrainGeneratorKind[] { + return kinds.filter((k) => k.fits(terrains) && (hasContext || !k.needsContext)); } /** diff --git a/src/worldgen/submapContext.ts b/src/worldgen/submapContext.ts new file mode 100644 index 00000000..a6bd4220 --- /dev/null +++ b/src/worldgen/submapContext.ts @@ -0,0 +1,44 @@ +import type HexmakerPlugin from "../HexmakerPlugin"; +import { getTerrainFromFile } from "../frontmatter"; +import { hexCenter, hexNeighbors } from "../../packages/hex-wfc/src"; +import { sideOf, type ContextTerrain, type GenerationContext } from "./procedural/common"; + +/** + * Generation context for a submap of hex (x, y) on `mapName`: that hex's + * terrain as the parent, and its six neighbours by compass side. Hexes + * outside the parent map's grid are left out; hexes with no terrain count + * as the map's base terrain (e.g. "void"). + */ +export function buildSubmapContext( + plugin: HexmakerPlugin, + mapName: string, + x: number, + y: number, +): GenerationContext { + const map = plugin.getMap(mapName); + if (!map) return {}; + const palette = plugin.getMapPalette(mapName); + const orientation = plugin.settings.hexOrientation; + const stagger = map.staggerOffset ?? plugin.settings.staggerOffset ?? "odd"; + const inGrid = (hx: number, hy: number) => + hx >= map.gridOffset.x && hx < map.gridOffset.x + map.gridSize.cols && + hy >= map.gridOffset.y && hy < map.gridOffset.y + map.gridSize.rows; + + const look = (hx: number, hy: number): ContextTerrain | undefined => { + const name = getTerrainFromFile(plugin.app, plugin.hexPath(hx, hy, mapName)) ?? map.baseTerrain; + if (!name) return undefined; + const type = palette.find((t) => t.name === name)?.type; + return type ? { terrain: name, type } : { terrain: name }; + }; + + const context: GenerationContext = { parent: look(x, y), sides: {} }; + const [cx, cy] = hexCenter(x, y, orientation, stagger); + for (const [nx, ny] of hexNeighbors(x, y, orientation, stagger)) { + if (!inGrid(nx, ny)) continue; + const t = look(nx, ny); + if (!t) continue; + const [px, py] = hexCenter(nx, ny, orientation, stagger); + context.sides![sideOf(px - cx, py - cy)] = t; + } + return context; +} diff --git a/styles.css b/styles.css index 86b83b41..c8fadf06 100644 --- a/styles.css +++ b/styles.css @@ -1916,6 +1916,42 @@ input.duckmage-input-error { width: 320px; } +/* Submap preview framed by the parent's neighbours: NW N NE / W [map] E / SW S SE */ +.duckmage-setup-context { + display: grid; + grid-template-columns: minmax(3.5em, auto) auto minmax(3.5em, auto); + align-items: center; + justify-items: center; + gap: 0.25em; +} + +.duckmage-setup-context.is-empty { + grid-template-columns: auto; +} + +.duckmage-setup-context.is-empty > .duckmage-setup-ctx:not(.duckmage-setup-ctx-C) { + display: none; +} + +.duckmage-setup-ctx { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.15em; + max-width: 6em; + font-size: var(--font-ui-smaller); + color: var(--text-muted); + text-align: center; + overflow-wrap: anywhere; +} + +.duckmage-setup-ctx-swatch { + width: 1.4em; + height: 1.2em; + clip-path: polygon(25% 0, 75% 0, 100% 50%, 75% 100%, 25% 100%, 0 50%); + background: var(--duckmage-bg, transparent); +} + .duckmage-setup-canvas { max-width: 100%; border-radius: 6px; diff --git a/tests/regionContext.test.ts b/tests/regionContext.test.ts new file mode 100644 index 00000000..7972cc7e --- /dev/null +++ b/tests/regionContext.test.ts @@ -0,0 +1,128 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; +import { planetSurface } from "../src/worldgen/procedural/planetSurface"; +import { mainworldFor, orbits } from "../src/worldgen/procedural/orbits"; +import { sideOf, type GenerationContext, type ProcGrid } from "../src/worldgen/procedural/common"; + +const grid: ProcGrid = { cols: 16, rows: 12, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; +const typeOf = new Map(DEFAULT_TERRAIN_PALETTE.map((t) => [t.name, t.type])); +const WET = new Set(["water", "deep-water", "shallows"]); + +/** Share of hexes in the given columns whose terrain type is in `types`. */ +function share(cells: Map, cols: number[], types: Set): number { + let hit = 0, n = 0; + for (const [k, t] of cells) { + const x = Number(k.split("_")[0]); + if (!cols.includes(x)) continue; + n++; + if (types.has(typeOf.get(t) ?? "")) hit++; + } + return n ? hit / n : 0; +} + +const all = Array.from({ length: grid.cols }, (_, i) => i); +const westEdge = [0, 1], eastEdge = [14, 15], middle = [6, 7, 8, 9]; +const avg = (f: (seed: number) => number) => { + let s = 0; + for (let seed = 1; seed <= 12; seed++) s += f(seed); + return s / 12; +}; + +describe("sideOf", () => { + it("maps directions to compass sides (screen y down)", () => { + expect(sideOf(1, 0)).toBe("E"); + expect(sideOf(-1, 0)).toBe("W"); + expect(sideOf(0, -1)).toBe("N"); + expect(sideOf(0, 1)).toBe("S"); + expect(sideOf(1, -1)).toBe("NE"); + expect(sideOf(-1, 1)).toBe("SW"); + }); +}); + +describe("Region detail (planet surface with context)", () => { + it("the parent terrain fills the map", () => { + const forest = avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, { parent: { terrain: "forest", type: "forest" } }).cells, all, new Set(["forest"]))); + const desert = avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, { parent: { terrain: "dunes", type: "desert" } }).cells, all, new Set(["desert", "badlands"]))); + expect(forest).toBeGreaterThan(0.45); + expect(desert).toBeGreaterThan(0.45); + }); + + it("a sea to the east puts water on the east edge, not the west", () => { + const ctx: GenerationContext = { parent: { terrain: "grass", type: "grassland" }, sides: { E: { terrain: "ocean", type: "water" } } }; + const east = avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, ctx).cells, eastEdge, WET)); + const west = avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, ctx).cells, westEdge, WET)); + expect(east).toBeGreaterThan(0.6); + expect(west).toBeLessThan(0.15); + }); + + it("east AND west neighbours both act, each on its own edge", () => { + const ctx: GenerationContext = { + parent: { terrain: "grass", type: "grassland" }, + sides: { E: { terrain: "ocean", type: "water" }, W: { terrain: "ocean", type: "water" } }, + }; + const run = (cols: number[]) => avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, ctx).cells, cols, WET)); + expect(run(eastEdge)).toBeGreaterThan(0.6); + expect(run(westEdge)).toBeGreaterThan(0.6); + expect(run(middle)).toBeLessThan(0.25); + }); + + it("mountains beyond an edge raise that edge", () => { + const HIGH = new Set(["hills", "mountains", "peaks"]); + const ctx: GenerationContext = { parent: { terrain: "grass", type: "grassland" }, sides: { W: { terrain: "mountain", type: "mountains" } } }; + const west = avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, ctx).cells, westEdge, HIGH)); + const east = avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, ctx).cells, eastEdge, HIGH)); + expect(west).toBeGreaterThan(east + 0.3); + }); + + it("exact border cells from a neighbouring region pull the nearby hexes", () => { + // A column of ocean just outside the west edge (x = -1). + const edgeCells = new Map(Array.from({ length: grid.rows }, (_, y) => [`-1_${y}`, { terrain: "ocean", type: "water" }])); + const ctx: GenerationContext = { parent: { terrain: "grass", type: "grassland" }, edgeCells }; + const west = avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, ctx).cells, [0], WET)); + const east = avg((seed) => share(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, {}, ctx).cells, [15], WET)); + expect(west).toBeGreaterThan(0.6); + expect(east).toBeLessThan(0.15); + }); + + it("untyped context terrains are read from their names", () => { + const ctx: GenerationContext = { parent: { terrain: "dark forest" }, sides: { S: { terrain: "salt sea" } } }; + const r = planetSurface(DEFAULT_TERRAIN_PALETTE, grid, 2, {}, ctx); + expect(share(r.cells, all, new Set(["forest"]))).toBeGreaterThan(0.3); + }); + + it("is deterministic per seed", () => { + const ctx: GenerationContext = { parent: { type: "hills" }, sides: { N: { type: "snow" } } }; + const a = planetSurface(DEFAULT_TERRAIN_PALETTE, grid, 9, {}, ctx); + const b = planetSurface(DEFAULT_TERRAIN_PALETTE, grid, 9, {}, ctx); + expect([...a.cells]).toEqual([...b.cells]); + }); + + it("without context, planet mode is unchanged (no context argument)", () => { + const a = planetSurface(DEFAULT_TERRAIN_PALETTE, grid, 4, { water: "50" }); + expect(a.cells.size).toBe(grid.cols * grid.rows); + }); +}); + +describe("Orbits mainworld from the sector hex", () => { + const bodies = SPACE_SYSTEM_TERRAINS.filter((t) => ["world", "gas-giant", "asteroids"].includes(t.type ?? "")).map((t) => t.name); + + it("maps sector terrain names to bodies", () => { + expect(mainworldFor("ocean world", bodies)).toBe("ocean planet"); + expect(mainworldFor("garden world", bodies)).toBe("terrestrial planet"); + expect(mainworldFor("gas giant", bodies)).toBe("gas giant"); + expect(mainworldFor("ice world", bodies)).toBe("ice planet"); + expect(mainworldFor("asteroid belt", bodies)).toBe("asteroid belt"); + expect(mainworldFor("nebula", bodies)).toBeUndefined(); + expect(mainworldFor(undefined, bodies)).toBeUndefined(); + }); + + it("the system always contains the hinted mainworld, even with few planets", () => { + const g: ProcGrid = { cols: 13, rows: 13, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; + for (let seed = 1; seed <= 20; seed++) { + const r = orbits(SPACE_SYSTEM_TERRAINS, g, seed, { bodies: "few" }, undefined, { parent: { terrain: "ocean world", type: "world" } }); + expect([...r.cells.values()]).toContain("ocean planet"); + } + }); +}); From 065cbefe3e6e0a764269249aa05d8c63f636e0d9 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 14:18:14 -0400 Subject: [PATCH 046/558] =?UTF-8?q?fix:=20clean=20hex=20edges=20=E2=80=94?= =?UTF-8?q?=20drop=20the=20clipped=20box=20border?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 2px border on a hexagon clip-path only survives as bars on the straight sides and specks at the tips, and it insets the fill so the terrain colour looks smaller than the hex. Hexes now have no border; the hex gap draws an even outline. dev/hex-outline.html shows before/after. Co-Authored-By: Claude Opus 5.5 --- dev/hex-outline.html | 36 ++++++++++++++++++++++++++++++++++++ styles.css | 6 +++++- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 dev/hex-outline.html diff --git a/dev/hex-outline.html b/dev/hex-outline.html new file mode 100644 index 00000000..0c0e1017 --- /dev/null +++ b/dev/hex-outline.html @@ -0,0 +1,36 @@ + + +loading + + +
+

Before (2px border + clip-path)

+

After (current styles.css)

+
+ diff --git a/styles.css b/styles.css index c8fadf06..e26abd9d 100644 --- a/styles.css +++ b/styles.css @@ -420,7 +420,11 @@ height: calc(var(--hex-size) * 2); clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); background: var(--background-secondary); - border: 2px solid var(--background-modifier-border); + /* No border: a box border under a hexagon clip-path survives only as + bars on the straight sides and specks at the tips (and insets the + fill). The gap between hexes (--duckmage-hex-gap) draws an even + outline instead. */ + border: none; margin: var(--duckmage-hex-gap, 0.15em); display: flex; align-items: center; From beda696f6c26698d950259331af8d630e32678e2 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 14:24:41 -0400 Subject: [PATCH 047/558] feat: roads and rivers continue across submaps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The submap context now records every path through the parent hex: its type, routing and the sides it enters/leaves by (or "ends here"). - routeContextPaths (procedural/contextPaths.ts) carries each one across the new map after generation: cheapest route over the generated terrain — roads avoid water (crossing only when they must), mountains and swamps and keep to the straight line; rivers ("meander" routing) prefer low ground, run into water and wander (seeded). - Edge points are chosen by grid position (middle row of the first/last column, middle column of the first/last row, corner hexes), so the submaps of two adjacent parent hexes meet at the same spot — including on pointy-top maps, whose east/west edges are ragged (a geometric choice there drifted by a row; caught by a test). - Applies to every generator, Blank and "Open in generator" included; space maps skip it (a jump route isn't a lane inside the system). - Sandbox: Road / River pickers in Region detail mode. Tests: tests/contextPaths.test.ts. Co-Authored-By: Claude Opus 5.5 --- dev/space-gen-preview.ts | 38 ++++++- package.json | 4 +- src/worldgen/NewMapSetupModal.ts | 36 ++++++- src/worldgen/procedural/common.ts | 16 +++ src/worldgen/procedural/contextPaths.ts | 128 ++++++++++++++++++++++++ src/worldgen/submapContext.ts | 22 +++- tests/contextPaths.test.ts | 102 +++++++++++++++++++ 7 files changed, 334 insertions(+), 12 deletions(-) create mode 100644 src/worldgen/procedural/contextPaths.ts create mode 100644 tests/contextPaths.test.ts diff --git a/dev/space-gen-preview.ts b/dev/space-gen-preview.ts index 92dae44d..75cde834 100644 --- a/dev/space-gen-preview.ts +++ b/dev/space-gen-preview.ts @@ -9,12 +9,20 @@ import { starScatter, STAR_SCATTER_OPTIONS } from "../src/worldgen/procedural/st import { orbits, ORBITS_OPTIONS } from "../src/worldgen/procedural/orbits"; import type { GenerationContext, ProcGrid, ProcOption, Side } from "../src/worldgen/procedural/common"; import { planetSurface, REGION_DETAIL_OPTIONS } from "../src/worldgen/procedural/planetSurface"; -import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { DEFAULT_TERRAIN_PALETTE, DEFAULT_PATH_TYPES } from "../src/constants"; +import { routeContextPaths } from "../src/worldgen/procedural/contextPaths"; import { drawPreview } from "../src/worldgen/preview"; type Gen = "sector" | "system" | "region"; /** Region detail: the parent hex and its N/E/S/W neighbours (terrain names from Expanded). */ -const region: { parent: string; sides: Partial> } = { parent: "forest", sides: { E: "ocean" } }; +const region: { parent: string; sides: Partial>; road: string; river: string } = { + parent: "forest", sides: { E: "ocean" }, road: "W-E", river: "N-S", +}; +/** "W-E" → { from: W, to: E }; "S-" → ends in the hex. */ +const pathSpec = (v: string) => { + const [from, to] = v.split("-") as [Side | "", Side | ""]; + return { from: from || undefined, to: to || undefined }; +}; const state = { gen: "sector" as Gen, orientation: "flat" as "flat" | "pointy", @@ -33,7 +41,7 @@ function regionContext(): GenerationContext { for (const [s, name] of Object.entries(region.sides)) if (name) sides[s as Side] = typed(name); return { parent: typed(region.parent), sides }; } -const pathColors = new Map([...SPACE_PATH_TYPES, ...SYSTEM_PATH_TYPES].map((p) => [p.name, p.color])); +const pathColors = new Map([...SPACE_PATH_TYPES, ...SYSTEM_PATH_TYPES, ...DEFAULT_PATH_TYPES].map((p) => [p.name, p.color])); function controls(): void { const box = document.getElementById("controls")!; @@ -52,6 +60,19 @@ function controls(): void { box.append(l); }; pick("Parent hex", region.parent, (v) => { region.parent = v || "grass"; }); + const routes = ["", "W-E", "N-S", "NW-SE", "SW-NE", "W-", "S-"]; + const routePick = (label: string, value: string, set: (v: string) => void) => { + const l = document.createElement("label"); + l.textContent = label + " "; + const sel = document.createElement("select"); + for (const r of routes) sel.add(new Option(r ? r.replace("-", " → ").replace(/→ $/, "→ ends here") : "—", r)); + sel.value = value; + sel.onchange = () => { set(sel.value); render(); }; + l.append(sel); + box.append(l); + }; + routePick("Road", region.road, (v) => { region.road = v; }); + routePick("River", region.river, (v) => { region.river = v; }); for (const s of ["N", "E", "S", "W"] as Side[]) pick(s, region.sides[s] ?? "", (v) => { region.sides[s] = v || undefined; }); } for (const o of opts) { @@ -66,6 +87,15 @@ function controls(): void { } } +/** Region mode: carry the parent hex's road / river across the generated map. */ +function withPaths; paths: { type: string; hexes: string[] }[] }>(r: T, grid: ProcGrid, seed: number): T { + const carry = [ + ...(region.road ? [{ type: "Road", routing: "through" as const, ...pathSpec(region.road) }] : []), + ...(region.river ? [{ type: "River", routing: "meander" as const, ...pathSpec(region.river) }] : []), + ]; + return { ...r, paths: [...r.paths, ...routeContextPaths(r.cells, DEFAULT_TERRAIN_PALETTE, grid, carry, seed)] }; +} + function render(): void { const grid: ProcGrid = { cols: state.cols, rows: state.rows, offset: { x: 0, y: 0 }, stagger: "odd", orientation: state.orientation, @@ -79,7 +109,7 @@ function render(): void { ? starScatter(SPACE_SECTOR_TERRAINS, grid, seed, state.options, "Jump route") : state.gen === "system" ? orbits(SPACE_SYSTEM_TERRAINS, grid, seed, state.options, "Orbit") - : planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, state.options, regionContext()); + : withPaths(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, state.options, regionContext()), grid, seed); const fig = document.createElement("figure"); const canvas = document.createElement("canvas"); drawPreview(canvas, r.cells, grid, state.orientation, colors(state.gen), undefined, r.paths, pathColors, 300, 18); diff --git a/package.json b/package.json index b111d11b..90c6924b 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index 90af7179..9cbe7a06 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -4,6 +4,7 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import type { SubmapDefault, TerrainColor } from "../types"; import { getTerrainFromFile } from "../frontmatter"; import { buildSubmapContext } from "./submapContext"; +import { routeContextPaths } from "./procedural/contextPaths"; import type { GenerationContext, Side } from "./procedural/common"; import { fillPaletteSelect } from "../palettes/paletteOptions"; import { defaultSubmapName } from "../hex-map/submapNav"; @@ -282,11 +283,12 @@ export class NewMapSetupModal extends HexmakerModal { let cells = new Map(); let paths: { type: string; route?: string; hexes: string[] }[] = []; let featureCells: Set | undefined; - if (kind && kind.id !== BLANK_ID) { + const carriesPaths = !!this.context?.paths?.length; + if (kind && (kind.id !== BLANK_ID || carriesPaths)) { if (this.cols * this.rows > PREVIEW_AUTO_LIMIT) { status.setText("Large map — the preview is skipped; terrain is generated on create."); } else { - const outcome = kind.generate({ terrains, grid, seed: this.seed, options: this.resolvedOptions(kind), context: this.context }); + const outcome = this.generate(kind, terrains); this.lastOutcome = outcome; if (!outcome.ok) { status.setText(outcome.message); @@ -377,6 +379,27 @@ export class NewMapSetupModal extends HexmakerModal { await this.plugin.saveSubmapDefault(this.origin.map, this.originTerrain, set, clear); } + /** + * Run a generator with this map's context, then continue the parent + * hex's paths (roads, rivers…) across the result. Space maps skip the + * path carry-over (a jump route through a sector hex isn't a lane in + * the system). + */ + private generate(kind: TerrainGeneratorKind, terrains: TerrainColor[]): GenerateOutcome { + const grid = this.grid(); + const outcome = kind.generate({ terrains, grid, seed: this.seed, options: this.resolvedOptions(kind), context: this.context }); + const carry = this.context?.paths ?? []; + if (!outcome.ok || carry.length === 0 || kind.mapKind === "space") return outcome; + const routed = routeContextPaths( + outcome.cells, + terrains, + { ...grid, orientation: this.plugin.settings.hexOrientation }, + carry, + this.seed, + ); + return { ...outcome, paths: [...outcome.paths, ...routed] }; + } + private row(parent: HTMLElement, label: string): HTMLElement { const r = parent.createDiv({ cls: "duckmage-setup-row" }); r.createDiv({ cls: "duckmage-setup-label", text: label }); @@ -412,9 +435,12 @@ export class NewMapSetupModal extends HexmakerModal { const kind = this.kind(); const terrains = this.terrains(paletteName); let outcome: GenerateOutcome | undefined; - if (!openGenerator && kind && kind.id !== BLANK_ID) { - outcome = this.lastOutcome - ?? kind.generate({ terrains, grid: this.grid(), seed: this.seed, options: this.resolvedOptions(kind), context: this.context }); + // "Open in generator" makes the map blank — but still carries the + // parent's roads / rivers across it. + const blank = this.kinds.find((k) => k.id === BLANK_ID); + const effective = openGenerator ? blank : kind; + if (effective && (effective.id !== BLANK_ID || this.context?.paths?.length)) { + outcome = (!openGenerator ? this.lastOutcome : undefined) ?? this.generate(effective, terrains); if (!outcome.ok) { new Notice(outcome.message); return; diff --git a/src/worldgen/procedural/common.ts b/src/worldgen/procedural/common.ts index 2811ecdc..33fb52f9 100644 --- a/src/worldgen/procedural/common.ts +++ b/src/worldgen/procedural/common.ts @@ -52,6 +52,22 @@ export interface GenerationContext { parent?: ContextTerrain; sides?: Partial>; edgeCells?: Map; + /** Paths (roads, rivers…) crossing the parent hex, so they continue + * across the submap from the side they enter to the side they leave. */ + paths?: ContextPath[]; +} + +/** + * A path through the parent hex: its type and the sides it enters / leaves + * by. A missing side means the path ends in this hex (e.g. a road to a + * town) and is routed to the middle of the submap. + */ +export interface ContextPath { + type: string; + /** The path type's routing; "meander" paths (rivers) wander a little. */ + routing?: "through" | "meander" | "edge"; + from?: Side; + to?: Side; } /** Unit vector (screen space: +x east, +y south) for each side. */ diff --git a/src/worldgen/procedural/contextPaths.ts b/src/worldgen/procedural/contextPaths.ts new file mode 100644 index 00000000..387e6066 --- /dev/null +++ b/src/worldgen/procedural/contextPaths.ts @@ -0,0 +1,128 @@ +import { hexCenter, hexNeighbors, mulberry32 } from "../../../packages/hex-wfc/src"; +import type { TerrainColor } from "../../types"; +import { inferTerrainType, isTerrainType } from "../../terrainTypes"; +import { SIDE_VECTORS, cellKey, centerHex, gridKeys, type ContextPath, type ProcGrid, type ProcPath, type Side } from "./common"; + +/** + * Continue the parent hex's paths across a submap: each enters at the + * middle of the edge it comes from and leaves at the middle of the edge it + * goes to (or ends at the map's centre). Edge points are deterministic, so + * submaps of two adjacent parent hexes meet at the same spot on their + * shared edge and the road/river lines up across the seam. + * + * Routing is a cheapest path over the generated terrain: roads avoid + * water (crossing only if they must — a bridge), mountains and swamps; + * rivers prefer low ground, run into water happily, and meander. + */ + +/** Movement cost per terrain type, for roads and for rivers. */ +const ROAD_COST: Record = { + "deep-water": 60, water: 40, shallows: 25, wetland: 3, forest: 1.6, jungle: 2.2, + hills: 2.5, mountains: 7, peaks: 14, snow: 3, desert: 1.4, badlands: 2.5, volcanic: 9, +}; +const RIVER_COST: Record = { + "deep-water": 0.4, water: 0.3, shallows: 0.4, wetland: 0.8, hills: 2.5, mountains: 7, peaks: 12, + badlands: 1.8, volcanic: 6, +}; + +function isRiver(p: ContextPath): boolean { + return p.routing === "meander" || /river|stream|creek|brook/i.test(p.type); +} + +/** + * The hex where a path crosses a side of the grid: the middle row of the + * first/last column (W/E), the middle column of the first/last row (N/S), + * or the corner hex (NE…). Chosen by grid position, not geometry, so it's + * the same row on both sides of a seam even where pointy-top edges are + * ragged — paths in adjacent submaps meet. + */ +export function edgeHex(grid: ProcGrid, side: Side): [number, number] { + const minX = grid.offset.x, maxX = grid.offset.x + grid.cols - 1; + const minY = grid.offset.y, maxY = grid.offset.y + grid.rows - 1; + const midX = grid.offset.x + Math.floor((grid.cols - 1) / 2); + const midY = grid.offset.y + Math.floor((grid.rows - 1) / 2); + const [dx, dy] = SIDE_VECTORS[side]; + const x = dx > 0 ? maxX : dx < 0 ? minX : midX; + const y = dy > 0 ? maxY : dy < 0 ? minY : midY; + return [x, y]; +} + +/** + * Route each context path over the generated cells. `terrains` gives each + * cell's type (falling back to a name guess); unpainted cells cost 1. + */ +export function routeContextPaths( + cells: Map, + terrains: TerrainColor[], + grid: ProcGrid, + paths: ContextPath[], + seed: number, +): ProcPath[] { + const typeByName = new Map(terrains.map((t) => [t.name, isTerrainType(t.type) ? t.type : inferTerrainType(t.name, t.category)])); + const hexes = gridKeys(grid); + const inGrid = new Set(hexes.map(([x, y]) => cellKey(x, y))); + const out: ProcPath[] = []; + paths.forEach((p, n) => { + if (!p.from && !p.to) return; + const start = p.from ? edgeHex(grid, p.from) : centerHex(grid); + const end = p.to ? edgeHex(grid, p.to) : centerHex(grid); + const sk = cellKey(start[0], start[1]), ek = cellKey(end[0], end[1]); + if (sk === ek) return; + const river = isRiver(p); + const costs = river ? RIVER_COST : ROAD_COST; + // Per-path seeded jitter makes rivers wander; roads stay direct. + const rand = mulberry32((seed ^ (n + 1) * 0x9e3779b9) >>> 0); + const jitter = new Map(); + // Many routes across a hex grid tie on length; a small penalty for + // straying from the straight line between the edge points keeps roads + // direct instead of bowing to a map edge and back. + const [ax, ay] = hexCenter(start[0], start[1], grid.orientation, grid.stagger); + const [bx, by] = hexCenter(end[0], end[1], grid.orientation, grid.stagger); + const len = Math.hypot(bx - ax, by - ay) || 1; + const stray = river ? 0.04 : 0.12; + const cost = (k: string) => { + const t = cells.get(k); + const type = t ? typeByName.get(t) : undefined; + let c = (type ? costs[type] : undefined) ?? 1; + const [hx, hy] = k.split("_").map(Number); + const [px, py] = hexCenter(hx, hy, grid.orientation, grid.stagger); + c += stray * Math.abs((bx - ax) * (ay - py) - (ax - px) * (by - ay)) / len / Math.sqrt(3); + if (river) { + if (!jitter.has(k)) jitter.set(k, rand() * 0.9); + c += jitter.get(k)!; + } + return c; + }; + // Dijkstra over the grid (small maps: a linear-scan frontier is fine). + const dist = new Map([[sk, 0]]); + const prev = new Map(); + const open = new Set([sk]); + const done = new Set(); + while (open.size) { + let cur = "", curD = Infinity; + for (const k of open) { + const d = dist.get(k)!; + if (d < curD) { cur = k; curD = d; } + } + open.delete(cur); + if (cur === ek) break; + done.add(cur); + const [x, y] = cur.split("_").map(Number); + for (const [nx, ny] of hexNeighbors(x, y, grid.orientation, grid.stagger)) { + const nk = cellKey(nx, ny); + if (!inGrid.has(nk) || done.has(nk)) continue; + const nd = curD + cost(nk); + if (nd < (dist.get(nk) ?? Infinity)) { + dist.set(nk, nd); + prev.set(nk, cur); + open.add(nk); + } + } + } + if (!prev.has(ek)) return; + const chain = [ek]; + while (chain[0] !== sk) chain.unshift(prev.get(chain[0])!); + out.push({ type: p.type, hexes: chain }); + }); + return out; +} diff --git a/src/worldgen/submapContext.ts b/src/worldgen/submapContext.ts index a6bd4220..ace23767 100644 --- a/src/worldgen/submapContext.ts +++ b/src/worldgen/submapContext.ts @@ -31,8 +31,28 @@ export function buildSubmapContext( return type ? { terrain: name, type } : { terrain: name }; }; - const context: GenerationContext = { parent: look(x, y), sides: {} }; + const context: GenerationContext = { parent: look(x, y), sides: {}, paths: [] }; const [cx, cy] = hexCenter(x, y, orientation, stagger); + const sideTo = (k: string | undefined) => { + if (!k) return undefined; + const [nx, ny] = k.split("_").map(Number); + const [px, py] = hexCenter(nx, ny, orientation, stagger); + return sideOf(px - cx, py - cy); + }; + + // Paths through this hex: where each comes in and goes out, so the + // submap can carry the road / river across instead of losing it. + const key = `${x}_${y}`; + const routingOf = new Map((plugin.settings.pathTypes ?? []).map((p) => [p.name, p.routing])); + for (const chain of map.pathChains ?? []) { + chain.hexes.forEach((h, i) => { + if (h !== key) return; + const from = sideTo(chain.hexes[i - 1]); + const to = sideTo(chain.hexes[i + 1]); + if (!from && !to) return; + context.paths!.push({ type: chain.typeName, routing: routingOf.get(chain.typeName), from, to }); + }); + } for (const [nx, ny] of hexNeighbors(x, y, orientation, stagger)) { if (!inGrid(nx, ny)) continue; const t = look(nx, ny); diff --git a/tests/contextPaths.test.ts b/tests/contextPaths.test.ts new file mode 100644 index 00000000..d4e692b5 --- /dev/null +++ b/tests/contextPaths.test.ts @@ -0,0 +1,102 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { edgeHex, routeContextPaths } from "../src/worldgen/procedural/contextPaths"; +import { centerHex, distance, type ProcGrid } from "../src/worldgen/procedural/common"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; + +const flat: ProcGrid = { cols: 13, rows: 9, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; +const pointy: ProcGrid = { ...flat, orientation: "pointy" }; +const parse = (k: string) => k.split("_").map(Number) as [number, number]; + +/** All-grass cells, optionally with a band of ocean down the middle columns. */ +function cells(grid: ProcGrid, waterCols: number[] = []): Map { + const m = new Map(); + for (let x = 0; x < grid.cols; x++) + for (let y = 0; y < grid.rows; y++) m.set(`${x}_${y}`, waterCols.includes(x) ? "ocean" : "grass"); + return m; +} + +describe("edgeHex", () => { + for (const grid of [flat, pointy]) { + it(`picks the middle of each edge (${grid.orientation})`, () => { + const [ex, ey] = edgeHex(grid, "E"); + const [wx, wy] = edgeHex(grid, "W"); + const [nx, ny] = edgeHex(grid, "N"); + const [sx, sy] = edgeHex(grid, "S"); + expect(ex).toBe(grid.cols - 1); + expect(wx).toBe(0); + expect(ny).toBe(0); + expect(sy).toBe(grid.rows - 1); + // Near the middle of the edge. + expect(Math.abs(ey - (grid.rows - 1) / 2)).toBeLessThanOrEqual(1); + expect(Math.abs(wy - (grid.rows - 1) / 2)).toBeLessThanOrEqual(1); + expect(Math.abs(nx - (grid.cols - 1) / 2)).toBeLessThanOrEqual(1); + expect(Math.abs(sx - (grid.cols - 1) / 2)).toBeLessThanOrEqual(1); + }); + } + + it("adjacent submaps meet: one map's east point and the next map's west point sit on the same row", () => { + // Same-size submaps of two horizontally adjacent parent hexes. + expect(edgeHex(flat, "E")[1]).toBe(edgeHex(flat, "W")[1]); + expect(edgeHex(pointy, "E")[1]).toBe(edgeHex(pointy, "W")[1]); + // …and north/south points share a column. + expect(edgeHex(flat, "N")[0]).toBe(edgeHex(flat, "S")[0]); + }); + + it("corner sides pick a corner hex", () => { + const [x, y] = edgeHex(flat, "NE"); + expect(x).toBeGreaterThanOrEqual(flat.cols - 2); + expect(y).toBeLessThanOrEqual(1); + }); +}); + +describe("routeContextPaths", () => { + it("carries a road from the west edge to the east edge as one connected chain", () => { + const [road] = routeContextPaths(cells(flat), DEFAULT_TERRAIN_PALETTE, flat, [{ type: "Road", routing: "through", from: "W", to: "E" }], 1); + expect(road.type).toBe("Road"); + const pts = road.hexes.map(parse); + expect(pts[0]).toEqual(edgeHex(flat, "W")); + expect(pts[pts.length - 1]).toEqual(edgeHex(flat, "E")); + for (let i = 1; i < pts.length; i++) expect(distance(pts[i - 1], pts[i], flat)).toBe(1); + }); + + it("a road that ends in the parent hex runs to the map's centre", () => { + const [road] = routeContextPaths(cells(flat), DEFAULT_TERRAIN_PALETTE, flat, [{ type: "Road", from: "S" }], 1); + expect(parse(road.hexes[road.hexes.length - 1])).toEqual(centerHex(flat)); + }); + + it("roads detour around water when they can; rivers go straight into it", () => { + // A lake in the middle (columns 5–7, rows 2–6), land around it. + const m = cells(flat); + for (let x = 5; x <= 7; x++) for (let y = 2; y <= 6; y++) m.set(`${x}_${y}`, "ocean"); + const [road] = routeContextPaths(m, DEFAULT_TERRAIN_PALETTE, flat, [{ type: "Road", from: "W", to: "E" }], 3); + expect(road.hexes.filter((k) => m.get(k) === "ocean")).toEqual([]); + const [river] = routeContextPaths(m, DEFAULT_TERRAIN_PALETTE, flat, [{ type: "River", routing: "meander", from: "W", to: "E" }], 3); + expect(river.hexes.some((k) => m.get(k) === "ocean")).toBe(true); + }); + + it("a road crosses water only when there is no way around (a bridge)", () => { + const m = cells(flat, [6]); // a full-height channel + const [road] = routeContextPaths(m, DEFAULT_TERRAIN_PALETTE, flat, [{ type: "Road", from: "W", to: "E" }], 1); + expect(road.hexes.filter((k) => m.get(k) === "ocean")).toHaveLength(1); + }); + + it("rivers meander (seeded) while roads stay direct", () => { + const grid: ProcGrid = { ...flat, cols: 21, rows: 15 }; + const m = cells(grid); + const [road] = routeContextPaths(m, DEFAULT_TERRAIN_PALETTE, grid, [{ type: "Road", from: "W", to: "E" }], 7); + const rivers = [1, 2, 3, 4].map((seed) => routeContextPaths(m, DEFAULT_TERRAIN_PALETTE, grid, [{ type: "River", routing: "meander", from: "W", to: "E" }], seed)[0].hexes.join()); + expect(road.hexes.length).toBe(grid.cols); // straight across + expect(new Set(rivers).size).toBeGreaterThan(1); // seeds differ + expect(routeContextPaths(m, DEFAULT_TERRAIN_PALETTE, grid, [{ type: "River", routing: "meander", from: "W", to: "E" }], 2)[0].hexes.join()).toBe(rivers[1]); + }); + + it("routes over a blank map (no terrain) and skips paths with no sides", () => { + const out = routeContextPaths(new Map(), DEFAULT_TERRAIN_PALETTE, flat, [ + { type: "Road", from: "N", to: "S" }, + { type: "Road" }, + ], 1); + expect(out).toHaveLength(1); + expect(parse(out[0].hexes[0])).toEqual(edgeHex(flat, "N")); + }); +}); From e76c62f88aa51fc1d2c4ff2197516903fb42c9a9 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 14:40:36 -0400 Subject: [PATCH 048/558] fix(generator): don't clear a newer Connect-to choice when a map finishes creating Creating a big map can take longer than choosing the next placement. When the earlier create finished it cleared GeneratorPanel.connect and redrew the page, wiping the newer choice, so the next map was made unconnected and started a group of its own (seen building a 10x10 test world of 20x16 regions). The choice is now only cleared if it's still the one that map was made with. Co-Authored-By: Claude Opus 5.5 --- src/worldgen/GeneratorPanel.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 6ddd0179..0baca9cf 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -745,6 +745,9 @@ export class GeneratorPanel { // While a loaded save is shown, create exactly the saved map. const sv = showingSave(); const r = sv ? { ...generated, cells: sv.cells, paths: sv.paths } : generated; + // The choice this map is made with; the page may be redrawn (and the + // choice changed) while a big map is still being written. + const usedConnect = GeneratorPanel.connect; createBtn.disabled = true; void this.plugin .createNewMap( @@ -769,7 +772,8 @@ export class GeneratorPanel { if (missing.length) new Notice(`No path type named ${missing.join(", ")}, so those paths were skipped.`); if (connected) { await placeNewRegion(this.plugin, result.name, connected); - GeneratorPanel.connect = null; + // Only clear the choice if it's still the one used; a newer one stays. + if (GeneratorPanel.connect === usedConnect) GeneratorPanel.connect = null; } new Notice(`Created map "${result.name}"${connected ? ` ${connected.side} of ${connected.anchor}` : ""}.`); GeneratorPanel.mapName = result.name; From 3ba2c9163134a43228a882b7a4fd9be2d99c96f1 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:02:24 -0400 Subject: [PATCH 049/558] fix(regions): neighbour shadow stays aligned when the map is zoomed Shadow hexes were placed in px measured at render time, but zooming bakes a new font size into the grid and the em-sized hexes resize, leaving the shadow behind (seen thousands of px off after the hex-flower walk zoomed in). Positions and sizes are now written in em of the grid's font size, so they scale with the hexes; checked in Obsidian before/after zooming and fitting. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index b77b4077..1daec701 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -3430,6 +3430,9 @@ export class HexMapView extends ItemView { return { x: (r.left + r.width / 2 - g.left) / sx, y: (r.top + r.height / 2 - g.top) / sy, w: r.width / sx, h: r.height / sy }; }; const A = centre(origin); + // Positions are written in em: zooming bakes a new font size into the + // grid and the hexes (sized in em) resize with it; px would be left behind. + const em = parseFloat(getComputedStyle(gridContainer).fontSize) || 16; const right = cols > 1 ? hexAt(ox + 1, oy) : null, below = rows > 1 ? hexAt(ox, oy + 1) : null; const B = right ? centre(right) : null, C = below ? centre(below) : null; let place: (x: number, y: number) => { x: number; y: number }; @@ -3463,10 +3466,10 @@ export class HexMapView extends ItemView { attr: { title: `${s.map}: hex ${s.x}, ${s.y}`, "data-region": s.map }, }); el.setCssProps({ - "--duckmage-shadow-x": `${at.x - A.w / 2}px`, - "--duckmage-shadow-y": `${at.y - A.h / 2}px`, - "--duckmage-shadow-w": `${A.w}px`, - "--duckmage-shadow-h": `${A.h}px`, + "--duckmage-shadow-x": `${(at.x - A.w / 2) / em}em`, + "--duckmage-shadow-y": `${(at.y - A.h / 2) / em}em`, + "--duckmage-shadow-w": `${A.w / em}em`, + "--duckmage-shadow-h": `${A.h / em}em`, ...(color ? { "--duckmage-shadow-color": color } : {}), }); el.addEventListener("click", () => { From 8f465db40054415211676d5a45059929ea3693c3 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 14:18:14 -0400 Subject: [PATCH 050/558] =?UTF-8?q?fix:=20clean=20hex=20edges=20=E2=80=94?= =?UTF-8?q?=20drop=20the=20clipped=20box=20border?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 2px border on a hexagon clip-path only survives as bars on the straight sides and specks at the tips, and it insets the fill so the terrain colour looks smaller than the hex. Hexes now have no border; the hex gap draws an even outline. dev/hex-outline.html shows before/after. Co-Authored-By: Claude Opus 5.5 --- dev/hex-outline.html | 36 ++++++++++++++++++++++++++++++++++++ styles.css | 6 +++++- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 dev/hex-outline.html diff --git a/dev/hex-outline.html b/dev/hex-outline.html new file mode 100644 index 00000000..0c0e1017 --- /dev/null +++ b/dev/hex-outline.html @@ -0,0 +1,36 @@ + + +loading + + +
+

Before (2px border + clip-path)

+

After (current styles.css)

+
+ diff --git a/styles.css b/styles.css index b69223cc..61eadb12 100644 --- a/styles.css +++ b/styles.css @@ -420,7 +420,11 @@ height: calc(var(--hex-size) * 2); clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); background: var(--background-secondary); - border: 2px solid var(--background-modifier-border); + /* No border: a box border under a hexagon clip-path survives only as + bars on the straight sides and specks at the tips (and insets the + fill). The gap between hexes (--duckmage-hex-gap) draws an even + outline instead. */ + border: none; margin: var(--duckmage-hex-gap, 0.15em); display: flex; align-items: center; From 76ef7c88eb71547b3b7477b069d4d1d5c591c751 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:14:31 -0400 Subject: [PATCH 051/558] chore(dev): generator sandbox title covers all three modes Co-Authored-By: Claude Opus 5.5 --- dev/space-gen-preview.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/space-gen-preview.html b/dev/space-gen-preview.html index 70ca94bf..95c52fdf 100644 --- a/dev/space-gen-preview.html +++ b/dev/space-gen-preview.html @@ -14,7 +14,7 @@ #legend { display: flex; flex-wrap: wrap; gap: 8px 14px; margin-top: 12px; color: #aaa; font-size: 12px; } #legend i { display: inline-block; width: 12px; height: 12px; border-radius: 3px; margin-right: 4px; vertical-align: -2px; } -

Procedural space generators: Star scatter (sector) and Orbits (system)

+

Procedural generators sandbox (dev only): Star scatter, Orbits, Region detail

From 4f59337408f3fa0d2c1ad38826a3bfbbde00e614 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:20:46 -0400 Subject: [PATCH 052/558] fix(palettes): write seeded terrain types to notes in the same startup step MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found on the first live deploy: the note write after one-time type seeding was queued separately, so an unload in between (here, a double plugin reload) left notes untyped while settings said seeding was done — and notes win on the next load, which would drop the types. attach() now writes the notes itself before reporting done. Regression test asserts the types are in the notes when init() resolves. Co-Authored-By: Claude Opus 5.5 --- src/palettes/PaletteStore.ts | 14 +++++++++++--- tests/palettes.test.ts | 12 ++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index 2937af23..8c5a50dd 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -233,8 +233,11 @@ export class PaletteStore { dirty = true; } this.ready = true; + // Write seeded types into the notes now, in the same queued step. Queued + // separately, an unload in between left notes untyped while settings + // said seeding was done — and notes win on the next load. + if (seeded) await this.syncNow(); if (dirty) await this.persist(); - if (seeded) void this.sync(); } /** @@ -299,7 +302,12 @@ export class PaletteStore { /** memory → notes. Safe to call often; only touches notes that differ. */ sync(): Promise { if (!this.ready) return this.queue; - return this.enqueue(async () => { + return this.enqueue(() => this.syncNow()); + } + + /** The body of sync(); call only from inside the queue. */ + private async syncNow(): Promise { + { if (this.folder() !== this.attachedFolder) { // Folder setting changed: start over against the new folder once the // user stops typing (settings save per keystroke — attaching at once @@ -376,7 +384,7 @@ export class PaletteStore { } if (renamedInMemory) await this.persist(); - }); + } } /** The note backing a palette, if it has been written. */ diff --git a/tests/palettes.test.ts b/tests/palettes.test.ts index 798d0f60..0b8b87c6 100644 --- a/tests/palettes.test.ts +++ b/tests/palettes.test.ts @@ -445,6 +445,18 @@ describe("PaletteStore", () => { expect(h.settings.terrainPalettes[0].childPalette).toBe("Overland"); }); + it("seeded terrain types are in the notes when init() resolves (no separately queued write)", async () => { + // An existing vault: untyped palettes, never seeded. If the note write + // were queued after init, an unload in between would leave the notes + // untyped while settings say "seeded" — found on the first live deploy. + h.settings.terrainPalettes = [{ name: "Mine", terrains: [{ name: "ocean", color: "#000" }, { name: "dark forest", color: "#111" }] }]; + h.settings.maps[0].paletteName = "Mine"; + h.settings.terrainTypesSeeded = false; + await h.store.init(); + expect(h.settings.terrainTypesSeeded).toBe(true); + expect(parsePaletteNote(h.vault.files.get("world/palettes/Mine.md")!)!.map((t) => t.type)).toEqual(["water", "forest"]); + }); + it("honours a custom palettes folder", async () => { const c = makeHarness({ palettesFolder: "rpg/pal" }); await c.store.init(); From ba487e291bdc9630dd05c7151f42cdc3def3cefc Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:23:49 -0400 Subject: [PATCH 053/558] fix(palette editor): readable icon previews; tint swatch looks off when off Seen live: black glyphs on dark buttons were near-invisible. The preview now sits on the terrain's colour and uses its tint, as the map draws it, repainting as colour/tint change. A disabled tint swatch is dimmed. Co-Authored-By: Claude Opus 5.5 --- src/palettes/PaletteEditorView.ts | 22 ++++++++++++---------- styles.css | 18 +++++++++++++++--- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/palettes/PaletteEditorView.ts b/src/palettes/PaletteEditorView.ts index f448cd56..46d2ca1b 100644 --- a/src/palettes/PaletteEditorView.ts +++ b/src/palettes/PaletteEditorView.ts @@ -2,7 +2,7 @@ import { ItemView, Notice, WorkspaceLeaf } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { SubmapDefault, TerrainColor, TerrainPalette } from "../types"; import { VIEW_TYPE_PALETTE_EDITOR } from "../constants"; -import { getIconUrl, iconLabel } from "../utils"; +import { createIconEl, getIconUrl, iconLabel } from "../utils"; import { IconPickerModal } from "../hex-map/IconPickerModal"; import { fillTerrainTypeSelect } from "../terrainTypeSelect"; import { inferTerrainType, terrainTypeInfo } from "../terrainTypes"; @@ -230,7 +230,8 @@ export class PaletteEditorView extends ItemView { // Color const color = tr.createEl("td").createEl("input", { type: "color", attr: { "aria-label": `${t.name} color` } }); color.value = /^#[0-9a-f]{6}$/i.test(t.color) ? t.color : "#888888"; - color.addEventListener("input", () => { t.color = color.value; this.save(); }); + let paintIcon = () => {}; + color.addEventListener("input", () => { t.color = color.value; paintIcon(); this.save(); }); // Name (renames cascade to hex notes and terrain tables on commit) const name = tr.createEl("td").createEl("input", { type: "text", cls: "duckmage-pe-name", attr: { "aria-label": "Terrain name" } }); @@ -277,13 +278,13 @@ export class PaletteEditorView extends ItemView { // Icon const iconCell = tr.createEl("td"); const iconBtn = iconCell.createEl("button", { cls: "duckmage-pe-icon", attr: { title: t.icon ? iconLabel(t.icon) : "Choose icon" } }); - if (t.icon) { - const img = iconBtn.createEl("img"); - img.src = getIconUrl(this.plugin, t.icon); - img.alt = iconLabel(t.icon); - } else { - iconBtn.setText("—"); - } + paintIcon = () => { + iconBtn.empty(); + iconBtn.setCssProps({ "--duckmage-pe-fill": t.color }); + if (t.icon) createIconEl(iconBtn, getIconUrl(this.plugin, t.icon), iconLabel(t.icon), t.iconColor, "duckmage-pe-icon-img"); + else iconBtn.setText("—"); + }; + paintIcon(); iconBtn.addEventListener("click", () => { new IconPickerModal(this.app, this.plugin, (icon) => { if (icon) t.icon = icon; @@ -304,9 +305,10 @@ export class PaletteEditorView extends ItemView { if (tintOn.checked) t.iconColor = tint.value; else delete t.iconColor; tint.disabled = !tintOn.checked; + paintIcon(); this.save(); }); - tint.addEventListener("input", () => { if (tintOn.checked) { t.iconColor = tint.value; this.save(); } }); + tint.addEventListener("input", () => { if (tintOn.checked) { t.iconColor = tint.value; paintIcon(); this.save(); } }); // Delete (two clicks) const del = tr.createEl("td").createEl("button", { cls: "duckmage-pe-delete", text: "×", attr: { title: "Delete terrain", "aria-label": `Delete ${t.name}` } }); diff --git a/styles.css b/styles.css index 563d3017..406da760 100644 --- a/styles.css +++ b/styles.css @@ -2086,9 +2086,21 @@ input.duckmage-input-error { justify-content: center; } -.duckmage-pe-icon img { - max-width: 100%; - max-height: 100%; +/* Icon preview sits on the terrain's colour, tinted, as the map draws it. */ +.duckmage-pe-icon { + background: var(--duckmage-pe-fill, var(--interactive-normal)); +} + +.duckmage-pe-icon-img { + width: 100%; + height: 100%; + object-fit: contain; +} + +/* Tint swatch reads as "off" when tint is disabled. */ +.duckmage-pe-tint input[type="color"]:disabled { + opacity: 0.25; + cursor: default; } .duckmage-pe-tint { From e6fbfddd9db81d1dd82457a88359622b9ce88e58 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:24:31 -0400 Subject: [PATCH 054/558] fix(palette editor): icon preview background beats the theme's button styles Co-Authored-By: Claude Opus 5.5 --- styles.css | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/styles.css b/styles.css index 406da760..6278175d 100644 --- a/styles.css +++ b/styles.css @@ -2087,8 +2087,10 @@ input.duckmage-input-error { } /* Icon preview sits on the terrain's colour, tinted, as the map draws it. */ -.duckmage-pe-icon { - background: var(--duckmage-pe-fill, var(--interactive-normal)); +/* Scoped twice over so it beats the theme's button background rules. */ +.duckmage-palette-editor .duckmage-pe-table button.duckmage-pe-icon { + background-color: var(--duckmage-pe-fill, var(--interactive-normal)); + box-shadow: none; } .duckmage-pe-icon-img { From 3bf03a49500935da665ab5c72349cce89c950cd2 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:25:22 -0400 Subject: [PATCH 055/558] =?UTF-8?q?docs(CLAUDE.md):=20correct=20plugin=20r?= =?UTF-8?q?eload=20=E2=80=94=20id=20is=20hexmaker;=20CLI=20plugin:*=20is?= =?UTF-8?q?=20a=20no-op=20here?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2ad42432..2e7a529f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,8 +30,10 @@ Each coding session: 1. Run `npm run dev` in a terminal (or `/dev` from Claude Code) — esbuild watches for changes and rebuilds `main.js` on every save 2. After a rebuild, reload the plugin in Obsidian: ```bash - powershell.exe -Command "obsidian plugin:reload id=duckmage-plugin" + powershell.exe -Command "obsidian eval code=\"(async()=>{await app.plugins.disablePlugin('hexmaker'); await app.plugins.enablePlugin('hexmaker'); return 'ok'})()\"" ``` + The plugin **id is `hexmaker`** (the folder is `duckmage-plugin`). On this machine's Obsidian installer the CLI's `plugin:reload` / `plugin:disable` / `plugin:enable` and `dev:*` commands silently do nothing (exit 255, "installer out of date"); `obsidian eval` works. To check what's loaded: `obsidian eval code="Object.keys(app.commands.commands).filter(c=>c.startsWith('hexmaker:'))"`. Screenshot: `require('@electron/remote').getCurrentWebContents().capturePage()` inside `eval`. `app.plugins.plugins.hexmaker.manifest.version` is cached from startup — don't use it to tell builds apart. + **Before copying a build into this folder**, check which branch the current vault build came from — other sessions deploy from their own branches, and a deploy reverts theirs. 3. Use `/rebuild` for a final production build before committing (runs the TypeScript type-check and tests too) ## Architecture From 2accc45b9becb9cab259f24efa252daf7f7877ec Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:33:54 -0400 Subject: [PATCH 056/558] =?UTF-8?q?feat:=20"Next=20to"=20in=20new-map=20se?= =?UTF-8?q?tup=20=E2=80=94=20regions=20continue=20their=20neighbours?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The guided setup modal (new top-level maps) gets a "Next to , " row using the WFC branch's world grid (neighbourSpec / placeNewRegion). Placing a map there: - locks size, palette, offset and stagger to match the neighbour; - feeds the neighbours' border terrain (neighbourShadow depth 1) to the generators as GenerationContext.edgeCells — learned generators solve with generateConnected, Region detail blends toward the border cells; - carries roads/rivers across: every neighbour path that reaches the border becomes a crossing at the exact in-map hex next to it, and same-type crossings are paired across the map (odd one out ends at the centre) — pairCrossings + routeContextPaths fromHex/toHex; - joins the world grid on create. Also dev/decisions.html: open owner decisions as a clickable page. Co-Authored-By: Claude Opus 5.5 --- dev/decisions.html | 141 ++++++++++++++++++++++++ src/worldgen/NewMapSetupModal.ts | 71 +++++++++++- src/worldgen/procedural/common.ts | 4 + src/worldgen/procedural/contextPaths.ts | 50 ++++++++- src/worldgen/regionContext.ts | 53 +++++++++ src/worldgen/registry.ts | 9 +- tests/contextPaths.test.ts | 39 ++++++- 7 files changed, 358 insertions(+), 9 deletions(-) create mode 100644 dev/decisions.html create mode 100644 src/worldgen/regionContext.ts diff --git a/dev/decisions.html b/dev/decisions.html new file mode 100644 index 00000000..882e6d5a --- /dev/null +++ b/dev/decisions.html @@ -0,0 +1,141 @@ + + +loading + +

Hexmaker — open decisions

+

Click one option per card (add a note if you like). Picks save in this page; tell Claude when you're done and it reads them back.

+
+
+ diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index 9cbe7a06..3ee22719 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -4,6 +4,9 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import type { SubmapDefault, TerrainColor } from "../types"; import { getTerrainFromFile } from "../frontmatter"; import { buildSubmapContext } from "./submapContext"; +import { buildRegionContext } from "./regionContext"; +import { neighbourSpec, occupiedSides, placeNewRegion, regionNameAt, type NewRegion } from "./neighbours"; +import type { Side as WorldSide } from "./world"; import { routeContextPaths } from "./procedural/contextPaths"; import type { GenerationContext, Side } from "./procedural/common"; import { fillPaletteSelect } from "../palettes/paletteOptions"; @@ -56,6 +59,8 @@ export class NewMapSetupModal extends HexmakerModal { private saved: SubmapDefault | undefined; /** The parent hex and its neighbours, so generation fits the bigger map. */ private context: GenerationContext | undefined; + /** "Next to" placement in a world of neighbouring regions (top-level maps). */ + private placement: NewRegion | undefined; /** "Default for " checkboxes, one per option row. */ private remember = { palette: false, size: false, generator: false, base: false }; @@ -170,6 +175,59 @@ export class NewMapSetupModal extends HexmakerModal { rowsInput.addEventListener("change", onSize); this.rememberBox(sizeRow, "size"); + // ── Next to (new top-level maps): join a world of neighbouring regions. + // Size, palette, offset and stagger then follow the neighbour; terrain + // and roads continue across the borders. + if (!this.origin && this.plugin.settings.maps.length > 0) { + const nextRow = this.row(form, "Next to"); + const anchorSel = nextRow.createEl("select", { attr: { "aria-label": "Neighbouring map" } }); + anchorSel.createEl("option", { value: "", text: "— none (stand-alone) —" }); + for (const m of this.plugin.settings.maps) anchorSel.createEl("option", { value: m.name, text: m.name }); + const sideSel = nextRow.createEl("select", { attr: { "aria-label": "Side" } }); + for (const s of ["east", "west", "north", "south"] as const) sideSel.createEl("option", { value: s, text: `${s} of it` }); + const note = nextRow.createDiv({ cls: "setting-item-description" }); + const onPlace = () => { + this.placement = undefined; + this.context = undefined; + note.setText(""); + const anchor = anchorSel.value; + sideSel.disabled = !anchor; + if (anchor) { + const spec = neighbourSpec(this.plugin, anchor, sideSel.value as WorldSide); + if (!spec.ok) { + note.setText(`⚠ ${spec.reason}`); + } else { + this.placement = { + slot: spec.slot, aSlot: spec.aSlot, anchor, side: sideSel.value as WorldSide, + cols: spec.cols, rows: spec.rows, offset: spec.offset, stagger: spec.stagger, paletteName: spec.paletteName, + }; + this.cols = spec.cols; + this.rows = spec.rows; + colsInput.value = String(spec.cols); + rowsInput.value = String(spec.rows); + paletteSelect.value = spec.paletteName; + this.context = buildRegionContext(this.plugin, this.placement); + const roads = this.context.paths?.length ?? 0; + const borders = occupiedSides(this.plugin, this.placement).map((s) => `${s}: ${regionNameAt(this.plugin, this.placement!, s)}`); + note.setText(`${spec.cols}×${spec.rows}, palette ${spec.paletteName}. Borders ${borders.join("; ")}.` + + (roads ? ` ${roads} path${roads === 1 ? "" : "s"} continue across.` : "")); + } + } + const locked = !!this.placement; + colsInput.disabled = locked; + rowsInput.disabled = locked; + paletteSelect.disabled = locked; + presetBtns.forEach((b) => { b.disabled = locked; }); + syncPresetBtns(); + renderGenerators(); + renderBase(); + refresh(); + }; + anchorSel.addEventListener("change", onPlace); + sideSel.addEventListener("change", onPlace); + sideSel.disabled = true; + } + // ── Generator ── const genRow = this.row(form, "Generator"); this.rememberBox(genRow, "generator", "Generator and its options"); @@ -306,7 +364,7 @@ export class NewMapSetupModal extends HexmakerModal { if (this.baseTerrain) { for (let i = 0; i < this.cols; i++) for (let j = 0; j < this.rows; j++) { - const k = `${i}_${j}`; + const k = `${grid.offset.x + i}_${grid.offset.y + j}`; if (!cells.has(k)) cells.set(k, this.baseTerrain); } } @@ -387,7 +445,7 @@ export class NewMapSetupModal extends HexmakerModal { */ private generate(kind: TerrainGeneratorKind, terrains: TerrainColor[]): GenerateOutcome { const grid = this.grid(); - const outcome = kind.generate({ terrains, grid, seed: this.seed, options: this.resolvedOptions(kind), context: this.context }); + const outcome = kind.generate({ terrains, grid, seed: this.seed, options: this.resolvedOptions(kind), context: this.context, region: this.placement }); const carry = this.context?.paths ?? []; if (!outcome.ok || carry.length === 0 || kind.mapKind === "space") return outcome; const routed = routeContextPaths( @@ -417,6 +475,9 @@ export class NewMapSetupModal extends HexmakerModal { } private grid() { + if (this.placement) { + return { cols: this.cols, rows: this.rows, offset: { ...this.placement.offset }, stagger: this.placement.stagger }; + } const parent = this.origin ? this.plugin.getMap(this.origin.map) : undefined; return { cols: this.cols, @@ -456,8 +517,8 @@ export class NewMapSetupModal extends HexmakerModal { this.cols, this.rows, paletteName, - 0, - 0, + this.grid().offset.x, + this.grid().offset.y, this.grid().stagger, (done, total) => goBtn.setText(`Creating ${done} / ${total}…`), outcome?.ok ? outcome.cells : undefined, @@ -485,6 +546,8 @@ export class NewMapSetupModal extends HexmakerModal { if (missing.length) new Notice(`Skipped paths with no matching path type: ${missing.join(", ")}`); } + // Join the world grid next to the chosen neighbour. + if (this.placement) await placeNewRegion(this.plugin, result.name, this.placement); await this.saveDefaults(paletteName); this.close(); this.onCreated(result, { openGenerator }); diff --git a/src/worldgen/procedural/common.ts b/src/worldgen/procedural/common.ts index 33fb52f9..1591f527 100644 --- a/src/worldgen/procedural/common.ts +++ b/src/worldgen/procedural/common.ts @@ -68,6 +68,10 @@ export interface ContextPath { routing?: "through" | "meander" | "edge"; from?: Side; to?: Side; + /** Exact entry / exit hex ("x_y" in this map) — e.g. where a neighbouring + * region's road crosses the shared border. Wins over `from` / `to`. */ + fromHex?: string; + toHex?: string; } /** Unit vector (screen space: +x east, +y south) for each side. */ diff --git a/src/worldgen/procedural/contextPaths.ts b/src/worldgen/procedural/contextPaths.ts index 387e6066..1cba2b17 100644 --- a/src/worldgen/procedural/contextPaths.ts +++ b/src/worldgen/procedural/contextPaths.ts @@ -63,9 +63,10 @@ export function routeContextPaths( const inGrid = new Set(hexes.map(([x, y]) => cellKey(x, y))); const out: ProcPath[] = []; paths.forEach((p, n) => { - if (!p.from && !p.to) return; - const start = p.from ? edgeHex(grid, p.from) : centerHex(grid); - const end = p.to ? edgeHex(grid, p.to) : centerHex(grid); + if (!p.from && !p.to && !p.fromHex && !p.toHex) return; + const at = (k: string | undefined) => (k && inGrid.has(k) ? (k.split("_").map(Number) as [number, number]) : undefined); + const start = at(p.fromHex) ?? (p.from ? edgeHex(grid, p.from) : centerHex(grid)); + const end = at(p.toHex) ?? (p.to ? edgeHex(grid, p.to) : centerHex(grid)); const sk = cellKey(start[0], start[1]), ek = cellKey(end[0], end[1]); if (sk === ek) return; const river = isRiver(p); @@ -126,3 +127,46 @@ export function routeContextPaths( }); return out; } + +/** + * Turn the points where neighbouring regions' paths cross into this map + * ("x_y" border hexes inside it) into context paths: crossings of the same + * path type are joined in pairs, taken in order around the map's edge, so a + * road entering in the west and one entering in the east become one road + * through; an odd one out runs to the centre (it ends here, e.g. at a town). + */ +export function pairCrossings( + crossings: { type: string; routing?: ContextPath["routing"]; hex: string }[], + grid: ProcGrid, +): ContextPath[] { + const [mx, my] = hexCenter(...centerHex(grid), grid.orientation, grid.stagger); + const angle = (k: string) => { + const [x, y] = k.split("_").map(Number); + const [px, py] = hexCenter(x, y, grid.orientation, grid.stagger); + return Math.atan2(py - my, px - mx); + }; + const byType = new Map(); + const seen = new Set(); + for (const c of crossings) { + const id = `${c.type}|${c.hex}`; + if (seen.has(id)) continue; + seen.add(id); + byType.set(c.type, [...(byType.get(c.type) ?? []), c]); + } + const out: ContextPath[] = []; + for (const list of byType.values()) { + const sorted = [...list].sort((a, b) => angle(a.hex) - angle(b.hex)); + // Pair opposite-ish crossings: i with i + n/2 around the ring, so two + // roads through a map go across it rather than hugging one corner. + const half = Math.floor(sorted.length / 2); + for (let i = 0; i < half; i++) { + const a = sorted[i], b = sorted[i + half]; + out.push({ type: a.type, routing: a.routing, fromHex: a.hex, toHex: b.hex }); + } + if (sorted.length % 2 === 1) { + const last = sorted[sorted.length - 1]; + out.push({ type: last.type, routing: last.routing, fromHex: last.hex }); + } + } + return out; +} diff --git a/src/worldgen/regionContext.ts b/src/worldgen/regionContext.ts new file mode 100644 index 00000000..40851b8d --- /dev/null +++ b/src/worldgen/regionContext.ts @@ -0,0 +1,53 @@ +import type HexmakerPlugin from "../HexmakerPlugin"; +import { hexNeighbors } from "../../packages/hex-wfc/src"; +import { neighbourShadow, type NewRegion } from "./neighbours"; +import { pairCrossings } from "./procedural/contextPaths"; +import type { ContextTerrain, GenerationContext } from "./procedural/common"; + +/** + * Generation context for a new region placed next to existing ones (the + * world grid from neighbours.ts): the neighbours' terrain just past each + * border as `edgeCells`, and every neighbour path that reaches the border + * as a crossing — paired up so roads/rivers continue through the new map + * from the exact hex where they cross. + */ +export function buildRegionContext(plugin: HexmakerPlugin, region: NewRegion): GenerationContext { + const shadow = neighbourShadow(plugin, region, 1); + const typeOf = (mapName: string, terrain: string | undefined) => + terrain ? plugin.getMapPalette(mapName).find((t) => t.name === terrain)?.type : undefined; + + const edgeCells = new Map(); + for (const [key, cell] of shadow) { + if (!cell.terrain) continue; + const type = typeOf(cell.map, cell.terrain); + edgeCells.set(key, type ? { terrain: cell.terrain, type } : { terrain: cell.terrain }); + } + + // Paths: a neighbour's chain touching a border shadow hex enters this map + // at the in-grid hex next to it. + const orientation = plugin.settings.hexOrientation; + const inGrid = (x: number, y: number) => + x >= region.offset.x && x < region.offset.x + region.cols && + y >= region.offset.y && y < region.offset.y + region.rows; + const routingOf = new Map((plugin.settings.pathTypes ?? []).map((p) => [p.name, p.routing])); + const crossings: { type: string; routing?: "through" | "meander" | "edge"; hex: string }[] = []; + for (const [key, cell] of shadow) { + const map = plugin.getMap(cell.map); + if (!map) continue; + const there = `${cell.x}_${cell.y}`; + for (const chain of map.pathChains ?? []) { + if (!chain.hexes.includes(there)) continue; + const [sx, sy] = key.split("_").map(Number); + const inside = hexNeighbors(sx, sy, orientation, region.stagger).find(([nx, ny]) => inGrid(nx, ny)); + if (inside) crossings.push({ type: chain.typeName, routing: routingOf.get(chain.typeName), hex: `${inside[0]}_${inside[1]}` }); + } + } + const paths = pairCrossings(crossings, { + cols: region.cols, + rows: region.rows, + offset: region.offset, + stagger: region.stagger, + orientation, + }); + return { edgeCells, paths }; +} diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index 1114d4f3..1b760635 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -19,6 +19,7 @@ import { planetSurfaceFits, } from "./procedural/planetSurface"; import { isKindEnabled, type MapKind } from "../mapKinds"; +import { generateConnected, type NewRegion } from "./neighbours"; /** * One list of terrain generators for map creation: Blank, the built-in @@ -50,6 +51,9 @@ export interface GenerateRequest { options: Record; /** Where the map sits in the bigger map (parent hex, neighbours). */ context?: GenerationContext; + /** A new region placed next to existing ones: learned generators solve + * against the neighbours' edges (generateConnected). */ + region?: NewRegion; } export interface TerrainGeneratorKind { @@ -176,7 +180,10 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise generatorFitsPalette(g.model, terrains.map((t) => t.name)), generate: (req) => { - const res = generateTerrain(plugin, g.model, req.terrains.map((t) => t.name), req.grid, req.seed); + const names = req.terrains.map((t) => t.name); + const res = req.region + ? generateConnected(plugin, g.model, names, req.region, req.seed) + : generateTerrain(plugin, g.model, names, req.grid, req.seed); if (!res.ok) return { ok: false, message: res.message }; return { ok: true, cells: res.cells, paths: res.paths, featureCells: res.featureCells, warnings: res.warnings }; }, diff --git a/tests/contextPaths.test.ts b/tests/contextPaths.test.ts index d4e692b5..ceb61f40 100644 --- a/tests/contextPaths.test.ts +++ b/tests/contextPaths.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { edgeHex, routeContextPaths } from "../src/worldgen/procedural/contextPaths"; +import { edgeHex, pairCrossings, routeContextPaths } from "../src/worldgen/procedural/contextPaths"; import { centerHex, distance, type ProcGrid } from "../src/worldgen/procedural/common"; import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; @@ -100,3 +100,40 @@ describe("routeContextPaths", () => { expect(parse(out[0].hexes[0])).toEqual(edgeHex(flat, "N")); }); }); + +describe("pairCrossings (neighbour regions' paths crossing into a new map)", () => { + it("joins a west and an east crossing of the same type into one path through", () => { + const out = pairCrossings([ + { type: "Road", hex: "0_4" }, + { type: "Road", hex: "12_4" }, + ], flat); + expect(out).toHaveLength(1); + expect(new Set([out[0].fromHex, out[0].toHex])).toEqual(new Set(["0_4", "12_4"])); + }); + + it("keeps types apart, sends an odd one out to the centre, and dedupes", () => { + const out = pairCrossings([ + { type: "Road", hex: "0_4" }, + { type: "Road", hex: "0_4" }, + { type: "River", routing: "meander", hex: "6_0" }, + ], flat); + expect(out).toHaveLength(2); + const river = out.find((p) => p.type === "River")!; + expect(river.fromHex).toBe("6_0"); + expect(river.toHex).toBeUndefined(); + expect(river.routing).toBe("meander"); + }); + + it("four crossings pair across the map, not around a corner", () => { + const out = pairCrossings(["0_4", "12_4", "6_0", "6_8"].map((hex) => ({ type: "Road", hex })), flat); + expect(out).toHaveLength(2); + const pairs = out.map((p) => [p.fromHex, p.toHex].sort().join(" ")).sort(); + expect(pairs).toEqual(["0_4 12_4", "6_0 6_8"]); + }); + + it("routeContextPaths uses exact entry hexes over sides", () => { + const [road] = routeContextPaths(cells(flat), DEFAULT_TERRAIN_PALETTE, flat, [{ type: "Road", fromHex: "0_1", toHex: "12_7", from: "N", to: "S" }], 1); + expect(road.hexes[0]).toBe("0_1"); + expect(road.hexes[road.hexes.length - 1]).toBe("12_7"); + }); +}); From f0127f7f986703ac7b8d2dbee19477641ee6ca55 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:41:43 -0400 Subject: [PATCH 057/558] feat: Star scatter only on sector palettes (not where Orbits fits) Owner decision 2026-10-09. With typed terrains a system palette also 'fit' Star scatter; a palette Orbits fits (stars + bodies) is a system. Co-Authored-By: Claude Opus 5.5 --- src/worldgen/procedural/starScatter.ts | 11 +++++++++++ src/worldgen/registry.ts | 4 ++-- tests/proceduralGenerators.test.ts | 9 +++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/worldgen/procedural/starScatter.ts b/src/worldgen/procedural/starScatter.ts index 6c199faf..5771fe3a 100644 --- a/src/worldgen/procedural/starScatter.ts +++ b/src/worldgen/procedural/starScatter.ts @@ -1,4 +1,5 @@ import { mulberry32 } from "../../../packages/hex-wfc/src"; +import { orbitsFits } from "./orbits"; import type { TerrainColor } from "../../types"; import { cellKey, @@ -234,3 +235,13 @@ export function starScatter( if (systems.length === 0) warnings.push("No systems rolled — try a higher density or another seed."); return { cells, paths, warnings }; } + +/** + * Offer Star scatter on sector-style palettes only. Once terrains are + * typed, a system palette also "fits" (its bodies are world-typed), but + * scattering planets across a star system makes no sense — so a palette + * that Orbits fits (stars + bodies) is a system, not a sector. + */ +export function starScatterOffered(terrains: TerrainColor[]): boolean { + return starScatterFits(terrains) && !orbitsFits(terrains); +} diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index 1b760635..e8bc193e 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -8,7 +8,7 @@ import { type GridSpec, } from "./generators"; import { findTerrain, type GenerationContext, type ProcGrid, type ProcOption } from "./procedural/common"; -import { STAR_SCATTER_ID, STAR_SCATTER_OPTIONS, starScatter, starScatterFits } from "./procedural/starScatter"; +import { STAR_SCATTER_ID, STAR_SCATTER_OPTIONS, starScatter, starScatterOffered } from "./procedural/starScatter"; import { ORBITS_ID, ORBITS_OPTIONS, orbits, orbitsFits } from "./procedural/orbits"; import { PLANET_SURFACE_ID, @@ -117,7 +117,7 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise { const r = starScatter(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, jumpRoute); return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; diff --git a/tests/proceduralGenerators.test.ts b/tests/proceduralGenerators.test.ts index 19e3ed7e..8fdb8b42 100644 --- a/tests/proceduralGenerators.test.ts +++ b/tests/proceduralGenerators.test.ts @@ -403,3 +403,12 @@ describe("terrain types", () => { }); }); }); + +describe("Star scatter offering (owner decision 2026-10-09: sectors only)", () => { + it("is offered on the sector palette but not on the system palette", async () => { + const { starScatterOffered } = await import("../src/worldgen/procedural/starScatter"); + const { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } = await import("../src/palettes/presets"); + expect(starScatterOffered(SPACE_SECTOR_TERRAINS)).toBe(true); + expect(starScatterOffered(SPACE_SYSTEM_TERRAINS)).toBe(false); + }); +}); From 43a7bacbc7e81be0bae5d3ca680fcf5c38e908d2 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 15:48:24 -0400 Subject: [PATCH 058/558] fix(dev): no innerHTML in the generator sandbox (Obsidian review scans dev files) The review bot flagged 'Unsafe assignment to innerHTML' in dev/space-gen-preview.ts (legend). Also adds dev/region-notes.html, the design-choices page for region notes. Co-Authored-By: Claude Opus 5.5 --- dev/region-notes.html | 167 +++++++++++++++++++++++++++++++++++++++ dev/space-gen-preview.ts | 5 +- 2 files changed, 171 insertions(+), 1 deletion(-) create mode 100644 dev/region-notes.html diff --git a/dev/region-notes.html b/dev/region-notes.html new file mode 100644 index 00000000..96e69ddb --- /dev/null +++ b/dev/region-notes.html @@ -0,0 +1,167 @@ + + +loading + +

Region notes — design choices

+

Your idea: one note per map holds the per-hex data; hex notes only appear when a hex gets real content. Pick one option per card, add notes, then Submit (Claude is watching for it).

+
+ Where things stand in your vault: +
    +
  • 9,438 hex notes across 14 maps (chult 2,130 · aaaabab 1,374 · the-coast 960 …). In the-coast, only 686 of 960 differ from the template.
  • +
  • Per-hex data today lives in each hex note's frontmatter (terrain, icon, GM icons, region, submap) and 12 source files read it from there.
  • +
  • Map-level data (size, palette, paths, overlays, viewport…) lives in the plugin's data.json, not in notes.
  • +
+ Sketch of a region note (format is question 4): +
---
+hexmaker-map: 1
+palette: Default
+size: 38x25
+base-terrain: ocean
+---
+# the-coast
+
+| Hex  | Terrain | Icon | Region | Submap |
+| ---- | ------- | ---- | ------ | ------ |
+| 3_4  | dunes   |      | Basin  |        |
+| 12_9 | forest  | bw-castle.png | Fellwood | the-coast-12-9 |
+
+
+
+ diff --git a/dev/space-gen-preview.ts b/dev/space-gen-preview.ts index 75cde834..b04f6f4c 100644 --- a/dev/space-gen-preview.ts +++ b/dev/space-gen-preview.ts @@ -120,8 +120,11 @@ function render(): void { } const legend = document.getElementById("legend")!; legend.replaceChildren(...[...colors(state.gen)].map(([name, color]) => { + // DOM calls, not innerHTML: the Obsidian review scans dev files too. const s = document.createElement("span"); - s.innerHTML = `${name}`; + const swatch = document.createElement("i"); + swatch.style.setProperty("background", color); + s.append(swatch, document.createTextNode(name)); return s; })); } From 9827cfdf36fb36906e73e5e41000e8669443098c Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 16:00:02 -0400 Subject: [PATCH 059/558] =?UTF-8?q?feat(worldgen):=20near=20rules,=205?= =?UTF-8?q?=C3=975=20layouts,=20side=20anchors,=20border-shy=20paths?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Near rules: a terrain can be kept within N hexes of another ("lava near volcano 3"), set in the Terrains table's Near column or per generator in the Terrain mix table. The solver steers toward it with a strength tied to Clumping and repaints any stray hexes afterwards. - Layouts can be 5×5 as well as 3×3, blended between cell centres. Blob/line growth now follows the layout too (strength from Directional bias), so patches no longer spill into areas it rules out. - Path ends can name a side: edge-N, edge-E, edge-S, edge-W. - Paths keep off the map border between their ends, under the existing "Avoid impassable terrain" switch (now "...and the map border"). - dev/wfc-compare.mts: border-hugging and layout fit, old vs new library. Co-Authored-By: Claude Opus 5.5 --- dev/wfc-compare.mts | 50 ++++++++ package.json | 4 +- packages/hex-wfc/src/format.ts | 76 +++++++++--- packages/hex-wfc/src/index.ts | 11 +- packages/hex-wfc/src/merge.ts | 11 +- packages/hex-wfc/src/model.ts | 68 ++++++++++- packages/hex-wfc/src/paths.ts | 29 ++++- packages/hex-wfc/src/post.ts | 62 +++++++++- packages/hex-wfc/src/solve.ts | 65 ++++++---- src/worldgen/GeneratorPanel.ts | 42 ++++++- styles.css | 10 +- tests/hexWfcPlacement.test.ts | 210 +++++++++++++++++++++++++++++++++ 12 files changed, 577 insertions(+), 61 deletions(-) create mode 100644 dev/wfc-compare.mts create mode 100644 tests/hexWfcPlacement.test.ts diff --git a/dev/wfc-compare.mts b/dev/wfc-compare.mts new file mode 100644 index 00000000..534a9a2e --- /dev/null +++ b/dev/wfc-compare.mts @@ -0,0 +1,50 @@ +// Compare generators between two copies of the hex-wfc library (e.g. before +// and after a change): paths running along the map border, and how well +// terrain follows its layout. Read-only. +// npx tsx dev/wfc-compare.mts ... (env SEEDS, COLS, ROWS) +import { readFileSync } from "node:fs"; +import { basename } from "node:path"; +import { pathToFileURL } from "node:url"; + +const [libDir, ...files] = process.argv.slice(2); +const lib = await import(pathToFileURL(`${libDir}/index.ts`).href); +const seeds = Number(process.env.SEEDS ?? 12), cols = Number(process.env.COLS ?? 38), rows = Number(process.env.ROWS ?? 25); + +for (const file of files) { + const parsed = lib.parseModelMarkdown(readFileSync(file, "utf8")); + if (!("model" in parsed)) { console.log(basename(file), "parse failed"); continue; } + const model = parsed.model; + let pathHexes = 0, borderHexes = 0, paths = 0, fails = 0, warnings = 0; + // Layout fit: mean layout value at the hexes each terrain lands on (1 = no better than chance). + let fitSum = 0, fitN = 0; + const layouts = new Map(model.terrains.filter((t: { layout?: number[] }) => t.layout).map((t: { name: string; layout: number[] }) => [t.name, t.layout])); + const valueAt = (lay: number[], fx: number, fy: number): number => { + if (lib.layoutValue) return lib.layoutValue(lay, fx, fy); + const bx = Math.min(2, Math.floor(fx * 3)), by = Math.min(2, Math.floor(fy * 3)); + return lay[by * 3 + bx]; + }; + for (let seed = 1; seed <= seeds; seed++) { + const r = lib.solve(model, { cols, rows, orientation: "flat", stagger: "odd", seed }); + if (!r.ok) { fails++; continue; } + warnings += r.warnings.length; + for (const p of r.paths) { + paths++; + for (const h of p.hexes.slice(1, -1)) { + const [x, y] = h.split("_").map(Number); + pathHexes++; + if (x === 0 || y === 0 || x === cols - 1 || y === rows - 1) borderHexes++; + } + } + for (const [k, t] of r.cells) { + const lay = layouts.get(t); + if (!lay) continue; + const [x, y] = k.split("_").map(Number); + fitSum += valueAt(lay, (x + 0.5) / cols, (y + 0.5) / rows); + fitN++; + } + } + const pct = (a: number, b: number) => (b ? ((100 * a) / b).toFixed(1) + "%" : "–"); + console.log( + `${basename(file, ".md").padEnd(24)} paths ${String(paths).padStart(3)} on-border ${pct(borderHexes, pathHexes).padStart(6)} layout-fit ${fitN ? (fitSum / fitN).toFixed(2) : " – "} fails ${fails} warnings ${warnings}`, + ); +} diff --git a/package.json b/package.json index 32b772e1..71b13267 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/worldgenSizePresets.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/worldgenSizePresets.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/hexWfcPlacement.test.ts tests/worldgenSizePresets.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/hexWfcPlacement.test.ts tests/worldgenSizePresets.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index 390fa40d..1724e465 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -10,14 +10,17 @@ * feature-size: 1 <- solver settings (all optional) * palette: Default <- any other keys are kept as `meta` * --- - * ## Terrains | Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge | + * ## Terrains | Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge | Near | * ## Adjacency | Terrain | Next to | Weight | * ## Features | Terrain | From | To | Count | (optional) - * ## Layout | Terrain | NW | N | NE | W | C | E | SW | S | SE | (optional) + * ## Layout | Terrain | NW | N | NE | W | C | E | SW | S | SE | (optional; or R1C1 … R5C5 for 5×5) */ import { LAYOUT_BINS, + LAYOUT_BINS_5, + layoutSize, + layoutTo5, GROWTH_SHAPES, SYMMETRIES, type HexWfcModel, @@ -27,14 +30,23 @@ import { type CountRange, type PathTweak, type PathTypeTweak, + type NearRule, type TerrainEntry, } from "./model"; export const FORMAT_VERSION = 1; + +/** "volcano 3" -> { terrain: "volcano", distance: 3 }; null if malformed. */ +export function parseNear(text: string): NearRule | null { + const m = /^(.*\S)\s+(\d+(?:\.\d+)?)$/.exec(text.trim()); + if (!m) return null; + const distance = Number(m[2]); + return distance >= 1 && distance <= 50 ? { terrain: m[1], distance } : null; +} const MARKER = "hex-wfc"; const EXAMPLE_KEY = "example-hexes"; -type SettingKind = "number" | "string" | "symmetry" | "boolean" | "list" | "mix" | "counts" | "paths" | "pathTypes"; +type SettingKind = "number" | "string" | "symmetry" | "boolean" | "list" | "mix" | "counts" | "paths" | "pathTypes" | "near"; /** Frontmatter key for each saved solver setting. */ export const SETTING_KEYS: Record = { @@ -61,6 +73,7 @@ export const SETTING_KEYS: Record = { drawPaths: "draw-paths", paths: "paths", pathTypes: "path-types", + near: "near", }; const SETTING_KINDS: Record = { @@ -87,6 +100,7 @@ const SETTING_KINDS: Record = { drawPaths: "boolean", paths: "paths", pathTypes: "pathTypes", + near: "near", }; const num = (n: number) => String(Math.round(n * 1000) / 1000); @@ -128,6 +142,10 @@ export function encodeSetting(field: keyof GeneratorSettings, value: unknown): s }) .filter((e) => !e.endsWith("= ")) .join("; "); + case "near": + return Object.entries(value as Record) + .map(([t, rule]) => `${t} = ${rule ? `${rule.terrain} ${num(rule.distance)}` : "off"}`) + .join("; "); case "pathTypes": return Object.entries(value as Record) .map(([type, t]) => { @@ -215,6 +233,20 @@ export function decodeSetting(field: keyof GeneratorSettings, raw: string): { va } return { value: out }; } + case "near": { + const out: Record = {}; + for (const item of items()) { + const eq = item.indexOf(" = "); + if (eq < 0) return { error: `has "${item}"; write it like "brokenlands = volcano 3" or "brokenlands = off"` }; + const terrain = item.slice(0, eq).trim(); + const rest = item.slice(eq + 3).trim(); + if (rest === "off") { out[terrain] = null; continue; } + const rule = parseNear(rest); + if (!rule) return { error: `has "${rest}" for ${terrain}; write a terrain and a distance, e.g. "volcano 3"` }; + out[terrain] = rule; + } + return { value: out }; + } case "pathTypes": { const out: Record = {}; for (const item of items()) { @@ -270,7 +302,9 @@ export function modelToMarkdown(model: HexWfcModel): string { if (reserved.has(k)) continue; fm.push(`${k}: ${yamlValue(v)}`); } - const withLayout = model.terrains.filter((t) => t.layout?.length === 9); + const withLayout = model.terrains.filter((t) => layoutSize(t.layout)); + const layout5 = withLayout.some((t) => layoutSize(t.layout) === 5); + const layoutCols: readonly string[] = layout5 ? LAYOUT_BINS_5 : LAYOUT_BINS; const features = model.features ?? []; const lines = [ "---", @@ -288,30 +322,35 @@ export function modelToMarkdown(model: HexWfcModel): string { " *Turn* is how often a `line` changes direction (0 to 1) and *Width* its", " thickness (1 to 3). *Spacing* is the closest two `scatter` hexes may be.", " *Edge* is how common the terrain is along the map border (1 = as anywhere).", + " *Near* keeps a terrain within some hexes of another, e.g. `volcano 3` for lava", + " fields (steered while generating, strength from `clumping`, then enforced).", "- **Adjacency**: pairs that may touch, and how often (higher is more likely).", " A pair that isn't listed can never touch, including a terrain next to itself.", " Order doesn't matter, so *A | B* also covers *B | A*.", "- **Features** (optional): lines of terrain that are always placed. *From* and *To*", " are `edge`, `none` or a terrain name.", "- **Paths** (optional): paths drawn over the terrain. *From* and *To* are `edge`,", - " `none`, `path` (joins another path of the same type) or a terrain. *Through*", + " `edge-N`, `edge-E`, `edge-S`, `edge-W` (one side of the map), `none`, `path`", + " (joins another path of the same type) or a terrain. *Through*", " is the share of the path on each terrain.", "- **Layout** (optional): where each terrain sat in the example map, in a 3×3", - " grid. 1 means as common there as anywhere; 3 means three times as common.", + " grid (NW … SE) or a finer 5×5 one (R1C1 … R5C5). 1 means as common there as", + " anywhere; 3 means three times as common. Values blend smoothly between cells", + " and `directional-bias` sets how strongly they apply (patches grow along them too).", "- Frontmatter settings (optional): `feature-size`, `directional-bias`, `clumping`,", " `mix-strength`, `scatter`, `randomness`, `edge-strength`, `edge-terrain`,", " `line-width`, `edge-smoothing`, `speck-size`, `keep-rare`, `symmetry`, `spacing`,", - " `connected`, `impassable`,", + " `connected`, `impassable`, `near`,", " `mix`, `counts`, `features`, `draw-paths` and `paths` (per route, e.g.", " `Road: edge > peak = count 2, wiggle 1.5, as Trade road`).", "", "## Terrains", "", - "| Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge |", - "| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: |", + "| Terrain | Weight | Patch % | Shape | Turn | Width | Spacing | Edge | Near |", + "| --- | ---: | ---: | --- | ---: | ---: | ---: | ---: | --- |", ...model.terrains.map( (t) => - `| ${cell(t.name)} | ${num(t.weight)} | ${opt(t.patch, 100)} | ${t.shape ?? ""} | ${opt(t.turn)} | ${opt(t.width)} | ${opt(t.spacing)} | ${opt(t.edge)} |`, + `| ${cell(t.name)} | ${num(t.weight)} | ${opt(t.patch, 100)} | ${t.shape ?? ""} | ${opt(t.turn)} | ${opt(t.width)} | ${opt(t.spacing)} | ${opt(t.edge)} | ${t.near ? cell(`${t.near.terrain} ${num(t.near.distance)}`) : ""} |`, ), "", "## Adjacency", @@ -349,9 +388,9 @@ export function modelToMarkdown(model: HexWfcModel): string { ? [ "## Layout", "", - `| Terrain | ${LAYOUT_BINS.join(" | ")} |`, - `| --- |${" ---: |".repeat(9)}`, - ...withLayout.map((t) => `| ${cell(t.name)} | ${t.layout!.map(num).join(" | ")} |`), + `| Terrain | ${layoutCols.join(" | ")} |`, + `| --- |${" ---: |".repeat(layoutCols.length)}`, + ...withLayout.map((t) => `| ${cell(t.name)} | ${(layout5 ? layoutTo5(t.layout!) : t.layout!).map(num).join(" | ")} |`), "", ] : []), @@ -504,6 +543,12 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par numberCol("width", 1, 3, (n) => (entry.width = n)); numberCol("spacing", 0, 1000, (n) => (entry.spacing = n)); numberCol("edge", 0, 1000, (n) => (entry.edge = n)); + const near = col("near"); + if (near !== undefined) { + const rule = parseNear(near); + if (rule) entry.near = rule; + else warnings.push(`${where}: near "${near}" should be a terrain and a distance, e.g. "volcano 3", ignored`); + } model.terrains.push(entry); } else if (section === "adjacency") { if (!cells[1]) { @@ -540,9 +585,10 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par through, }); } else { - const values = LAYOUT_BINS.map((b) => Number(cells[columns.get(b.toLowerCase()) ?? -1])); + const bins: readonly string[] = columns.has("r1c1") ? LAYOUT_BINS_5 : LAYOUT_BINS; + const values = bins.map((b) => Number(cells[columns.get(b.toLowerCase()) ?? -1])); if (values.every((v) => Number.isFinite(v) && v >= 0)) layouts.set(cells[0], values); - else warnings.push(`${where}: needs 9 numbers ≥ 0 under ${LAYOUT_BINS.join(", ")}, row skipped`); + else warnings.push(`${where}: needs ${bins.length} numbers ≥ 0 under ${bins[0]} … ${bins[bins.length - 1]}, row skipped`); } } diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index d7a2fa99..a0ed673d 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -16,6 +16,12 @@ export { resolveSettings, DEFAULT_SETTINGS, LAYOUT_BINS, + LAYOUT_BINS_5, + layoutSize, + layoutValue, + layoutTo5, + nearRules, + type NearRule, GROWTH_SHAPES, SYMMETRIES, type HexWfcModel, @@ -35,11 +41,12 @@ export { export { mergeModels } from "./merge"; export { learnModel, measurePatches, measureLayout, SHAPE_THRESHOLDS, type LearnOptions, type TerrainAnalysis } from "./learn"; export { solve, findViolation, cleanupStrengths, pathsEnabled, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; -export { countPatches, smoothEdges, removeSpecks, untouchableTerrains, type GridInfo } from "./post"; -export { learnPaths, routePaths, type PathInput, type PathOutput, type RouteStat } from "./paths"; +export { countPatches, smoothEdges, removeSpecks, untouchableTerrains, enforceNear, type GridInfo } from "./post"; +export { learnPaths, routePaths, edgeSide, isEdgeAnchor, type PathInput, type PathOutput, type RouteStat } from "./paths"; export { modelToMarkdown, parseModelMarkdown, + parseNear, isModelMarkdown, encodeSetting, decodeSetting, diff --git a/packages/hex-wfc/src/merge.ts b/packages/hex-wfc/src/merge.ts index 932ebfdc..30e017eb 100644 --- a/packages/hex-wfc/src/merge.ts +++ b/packages/hex-wfc/src/merge.ts @@ -8,7 +8,7 @@ * turning) are averaged, weighted by how much of that terrain each region had. */ -import { pathRouteKey, type AdjacencyEntry, type HexWfcModel, type LineFeature, type PathFeature, type TerrainEntry } from "./model"; +import { layoutSize, layoutTo5, pathRouteKey, type AdjacencyEntry, type HexWfcModel, type LineFeature, type PathFeature, type TerrainEntry } from "./model"; type Weighted = { value: number; weight: number }; @@ -41,10 +41,13 @@ function mergeTerrain(entries: TerrainEntry[]): TerrainEntry { if (spacing !== undefined) merged.spacing = spacing; const edge = mean((t) => t.edge); if (edge !== undefined) merged.edge = edge; - const layouts = entries.filter((t) => t.layout?.length === 9); + // Layouts of different grid sizes are compared on the finer (5×5) grid. + const withLayout = entries.filter((t) => layoutSize(t.layout)); + const fine = withLayout.some((t) => layoutSize(t.layout) === 5); + const layouts = withLayout.map((t) => ({ lay: fine ? layoutTo5(t.layout!) : t.layout!, weight: t.weight })); if (layouts.length) { - merged.layout = Array.from({ length: 9 }, (_, i) => - weightedMean(layouts.map((t) => ({ value: t.layout![i], weight: t.weight })))!); + merged.layout = Array.from({ length: fine ? 25 : 9 }, (_, i) => + weightedMean(layouts.map((l) => ({ value: l.lay[i], weight: l.weight })))!); } return merged; } diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index 9c42257a..00ef01a7 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -48,14 +48,68 @@ export interface TerrainEntry { edge?: number; /** * Where the terrain sat in the example, as relative density in a 3×3 grid - * (row-major: NW, N, NE, W, C, E, SW, S, SE). 1 = as common as anywhere, - * 3 = three times as common there. Used by directional bias. + * (row-major: NW, N, NE, W, C, E, SW, S, SE) or a 5×5 one (row-major, + * R1C1 … R5C5). 1 = as common as anywhere, 3 = three times as common + * there. Values blend smoothly between grid cells. Used by directional bias. */ layout?: number[]; + /** + * The terrain only appears within `distance` hexes of `terrain`, e.g. lava + * fields near a volcano. Steered while solving and enforced afterwards. + */ + near?: NearRule; +} + +export interface NearRule { + terrain: string; + /** Most hexes away from the nearest hex of `terrain` (1 = touching). */ + distance: number; } /** Layout bin names, in the order of TerrainEntry.layout. */ export const LAYOUT_BINS = ["NW", "N", "NE", "W", "C", "E", "SW", "S", "SE"] as const; +/** Column names of a 5×5 layout grid, row-major. */ +export const LAYOUT_BINS_5 = Array.from({ length: 25 }, (_, i) => `R${Math.floor(i / 5) + 1}C${(i % 5) + 1}`); + +/** A layout's grid size: 3 (9 values) or 5 (25 values); 0 if neither. */ +export const layoutSize = (lay: number[] | undefined): number => (lay?.length === 9 ? 3 : lay?.length === 25 ? 5 : 0); + +/** + * A layout's value at a point of the map (fx, fy from 0 to 1), bilinear + * between grid-cell centres, so preferences change smoothly across the map. + */ +export function layoutValue(lay: number[], fx: number, fy: number): number { + const n = layoutSize(lay); + if (!n) return 1; + const axis = (f: number): [number, number, number] => { + const pos = f * n - 0.5; // in cell-centre units + if (pos <= 0) return [0, 0, 0]; + if (pos >= n - 1) return [n - 1, n - 1, 0]; + const i = Math.floor(pos); + return [i, i + 1, pos - i]; + }; + const [x0, x1, tx] = axis(fx), [y0, y1, ty] = axis(fy); + const top = lay[y0 * n + x0] * (1 - tx) + lay[y0 * n + x1] * tx; + const bottom = lay[y1 * n + x0] * (1 - tx) + lay[y1 * n + x1] * tx; + return top * (1 - ty) + bottom * ty; +} + +/** A 3×3 layout as 5×5 (sampled at the 5×5 cell centres); 5×5 is returned as is. */ +export function layoutTo5(lay: number[]): number[] { + if (layoutSize(lay) !== 3) return lay; + return Array.from({ length: 25 }, (_, i) => layoutValue(lay, ((i % 5) + 0.5) / 5, (Math.floor(i / 5) + 0.5) / 5)); +} + +/** Each terrain's near rule: the model's, with settings overriding (null = off). */ +export function nearRules(model: HexWfcModel, settings: GeneratorSettings = {}): Map { + const out = new Map(); + for (const t of model.terrains) if (t.near) out.set(t.name, t.near); + for (const [t, rule] of Object.entries(settings.near ?? {})) { + if (rule) out.set(t, rule); + else out.delete(t); + } + return out; +} /** * A guaranteed line feature, e.g. a river from a map edge to a lake. Placed @@ -245,6 +299,8 @@ export interface GeneratorSettings { paths?: Record; /** Per path type adjustments (all Roads, all Rivers), on top of `paths`. */ pathTypes?: Record; + /** Near rules per terrain, over the model's (null turns a model rule off). */ + near?: Record; } export const DEFAULT_SETTINGS: Required = { @@ -271,6 +327,7 @@ export const DEFAULT_SETTINGS: Required = { drawPaths: true, paths: {}, pathTypes: {}, + near: {}, }; export interface AdjacencyEntry { @@ -330,10 +387,13 @@ export function validateModel(model: HexWfcModel): string[] { problems.push(`Terrain "${t.name}" has a turn rate outside 0–1`); if (t.width !== undefined && !(t.width >= 1 && t.width <= 3)) problems.push(`Terrain "${t.name}" has a width outside 1–3`); - if (t.layout !== undefined && (t.layout.length !== 9 || t.layout.some((v) => !(v >= 0)))) - problems.push(`Terrain "${t.name}" needs 9 layout values ≥ 0`); + if (t.layout !== undefined && (!layoutSize(t.layout) || t.layout.some((v) => !(v >= 0)))) + problems.push(`Terrain "${t.name}" needs 9 or 25 layout values ≥ 0`); } if (model.terrains.length === 0) problems.push("No terrains listed"); + for (const t of model.terrains) + if (t.near !== undefined && !(names.has(t.near.terrain) && t.near.distance >= 1)) + problems.push(`Terrain "${t.name}" has a near rule on an unknown terrain or a distance under 1`); for (const { a, b, weight } of model.adjacency) { for (const n of [a, b]) if (!names.has(n)) problems.push(`Adjacency row "${a} | ${b}" uses unknown terrain "${n}"`); diff --git a/packages/hex-wfc/src/paths.ts b/packages/hex-wfc/src/paths.ts index b9cdf85f..cfe4cb80 100644 --- a/packages/hex-wfc/src/paths.ts +++ b/packages/hex-wfc/src/paths.ts @@ -47,6 +47,20 @@ const MIN_PATH_HEXES = 3; * of it (a coast). At 1.2 a favoured terrain is at most ~5x cheaper. */ const PREF_CAP = 1.2; +/** + * Extra cost of a border hex for routes that avoid impassable terrain (the + * default): without it, cheap terrain along the edge drew routes into + * running down the map border. + */ +const BORDER_COST = 3; + +/** "edge-N" / "edge-E" / "edge-S" / "edge-W" (any case): which side; null for anything else. */ +export function edgeSide(anchor: string): "N" | "E" | "S" | "W" | null { + const m = /^edge-([nesw])$/i.exec(anchor.trim()); + return m ? (m[1].toUpperCase() as "N" | "E" | "S" | "W") : null; +} +/** Any edge anchor: `edge` or one side of it. */ +export const isEdgeAnchor = (anchor: string): boolean => anchor === "edge" || edgeSide(anchor) !== null; /** Remove consecutive duplicates (repeat clicks). */ function clean(hexes: string[]): string[] { @@ -180,11 +194,18 @@ export function routePaths( return d.indexOf(Math.min(...d)); }; + /** Is c on the given side's border row/column? */ + const onSide = (c: number, side: "N" | "E" | "S" | "W"): boolean => { + const i = c % cols, j = Math.floor(c / cols); + return side === "N" ? j === 0 : side === "S" ? j === rows - 1 : side === "W" ? i === 0 : i === cols - 1; + }; const candidates = (anchor: string, taken: Set, avoidSide: number | null): number[] => { const all: number[] = []; + const side = edgeSide(anchor); for (let c = 0; c < N; c++) { const ok = - anchor === "edge" ? border(c) && (avoidSide === null || sideOf(c) !== avoidSide) + side ? onSide(c, side) + : anchor === "edge" ? border(c) && (avoidSide === null || sideOf(c) !== avoidSide) : anchor === "path" ? taken.has(c) : anchor === "none" ? !border(c) : terrainOf(c) === anchor; @@ -266,7 +287,7 @@ export function routePaths( targets = new Set(candidates(f.to, taken, f.to === "edge" ? startSide : null).filter((c) => endOk(f.to)(c) && reachable(c))); // Edge-to-edge: don't let it cut a corner; it should run at least most // of the learned length (or as far as the land allows). - if (f.to === "edge") { + if (isEdgeAnchor(f.to)) { const minLen = Math.round(0.6 * f.length * Math.max(cols, rows)); const far = [...targets].filter((c) => dist(start, c) >= minLen); if (far.length) targets = new Set(far); @@ -326,6 +347,7 @@ export function routePaths( const i = c % cols, j = Math.floor(c / cols); const noise = (Math.sin(i * freq + phase[0]) * Math.cos(j * freq * 0.8 + phase[1]) + Math.sin((i + j) * freq * 0.7 + phase[2])) / 2; cost[c] = Math.max(0.05, 1.5 - pref(terrainOf(c)) + noiseAmp * (0.5 + 0.5 * noise)); + if (!tw.crossImpassable && border(c)) cost[c] *= BORDER_COST; } // Impassable hexes this route may not cross (unless it's allowed to). @@ -352,7 +374,8 @@ export function routePaths( } stat.placed = made; if (made < count) { - const end = (e: string) => (e === "edge" ? "a map edge" : e === "path" ? `another ${f.type}` : e); + const sideName = { N: "the north edge", E: "the east edge", S: "the south edge", W: "the west edge" } as const; + const end = (e: string) => (e === "edge" ? "a map edge" : edgeSide(e) ? sideName[edgeSide(e)!] : e === "path" ? `another ${f.type}` : e); warnings.push(`Placed ${made} of ${count} ${f.type} paths (${end(f.from)} to ${end(f.to)})`); } } diff --git a/packages/hex-wfc/src/post.ts b/packages/hex-wfc/src/post.ts index 1a6f2067..0719d834 100644 --- a/packages/hex-wfc/src/post.ts +++ b/packages/hex-wfc/src/post.ts @@ -5,7 +5,7 @@ */ import { hexNeighbors, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; -import { adjacencyLookup, type HexWfcModel, type CountRange } from "./model"; +import { adjacencyLookup, type HexWfcModel, type CountRange, type NearRule } from "./model"; export interface GridInfo { cols: number; @@ -333,3 +333,63 @@ export function topUpCounts( } return changed; } + +/** + * Near rules: a hex of a ruled terrain with no hex of its anchor terrain + * within the rule's distance is repainted with the commonest neighbouring + * terrain that fits (or, failing that, any terrain that fits, most common + * first). Replacements never use a ruled terrain, so they can't break a + * rule themselves. Returns how many hexes changed. + */ +export function enforceNear( + cells: Map, + model: HexWfcModel, + grid: GridInfo, + rules: Map, + protect: Set, +): number { + if (!rules.size) return 0; + const adj = adjacencyLookup(model); + const byWeight = [...model.terrains].sort((a, b) => b.weight - a.weight).map((t) => t.name); + /** Hexes within `distance` of any hex of `anchor`. */ + const covered = (anchor: string, distance: number): Set => { + const seen = new Set(); + let frontier: string[] = []; + for (const [k, t] of cells) if (t === anchor) { seen.add(k); frontier.push(k); } + for (let d = 0; d < distance && frontier.length; d++) { + const next: string[] = []; + for (const k of frontier) + for (const n of neighbourKeys(k, grid, cells)) + if (!seen.has(n)) { seen.add(n); next.push(n); } + frontier = next; + } + return seen; + }; + let changed = 0; + for (let round = 0; round < 4; round++) { + let changedThisRound = 0; + for (const [terrain, rule] of rules) { + const ok = covered(rule.terrain, rule.distance); + for (const [key, t] of cells) { + if (t !== terrain || ok.has(key) || protect.has(key)) continue; + const tally = new Map(); + for (const n of neighbourKeys(key, grid, cells)) { + const u = cells.get(n)!; + if (!rules.has(u)) tally.set(u, (tally.get(u) ?? 0) + 1); + } + const candidates = [ + ...[...tally].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([u]) => u), + ...byWeight.filter((u) => !rules.has(u) && !tally.has(u)), + ]; + const u = candidates.find((c) => fits(key, c, cells, grid, adj)); + if (u) { + cells.set(key, u); + changed++; + changedThisRound++; + } + } + } + if (!changedThisRound) break; + } + return changed; +} diff --git a/packages/hex-wfc/src/solve.ts b/packages/hex-wfc/src/solve.ts index 24b012cd..2e5a49d4 100644 --- a/packages/hex-wfc/src/solve.ts +++ b/packages/hex-wfc/src/solve.ts @@ -25,6 +25,9 @@ import { hexNeighbors, directionRing, cellKey, parseCellKey, toCellMap, type Ori import { adjacencyLookup, effectivePathTweaks, + layoutSize, + layoutValue, + nearRules, resolveSettings, type HexWfcModel, type GeneratorSettings, @@ -40,6 +43,7 @@ import { countPatches, countsPenalty, topUpCounts, + enforceNear, type GridInfo, } from "./post"; @@ -218,6 +222,7 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { const { edges, speckSize } = cleanupStrengths(s); total.postChanges += smoothEdges(cells, model, grid, edges, protect, keep, rng); total.postChanges += removeSpecks(cells, model, grid, speckSize, protect, keep); + total.postChanges += enforceNear(cells, model, grid, nearRules(model, s), protect); let penalty = 0; if (s.connected && impassable.size) { const { changed, stranded } = connectLand(cells, model, grid, impassable, protect); @@ -240,6 +245,7 @@ export function solve(model: HexWfcModel, opts: SolveOptions): SolveResult { if (hasCounts) { const protect = new Set([...toCellMap(opts.fixed ?? {}).keys(), ...best.featureCells]); total.postChanges += topUpCounts(best.cells, model, grid, s.counts, protect, mulberry32(opts.seed ^ 0x2545f491)); + total.postChanges += enforceNear(best.cells, model, grid, nearRules(model, s), protect); const counted = countPatches(best.cells, grid); for (const [t, range] of Object.entries(s.counts)) { const n = counted.get(t) ?? 0; @@ -306,6 +312,9 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required t.name))]; const T = terrains.length; @@ -344,30 +353,20 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required (logPos ??= new Float32Array(N * T)); - if (bias > 0 && model.terrains.some((e) => e.layout?.length === 9)) { + if (bias > 0 && model.terrains.some((e) => layoutSize(e.layout))) { const pos = ensurePos(); - const centre = [1 / 6, 1 / 2, 5 / 6]; - const axis = (f: number): [number, number, number] => { - if (f <= centre[0]) return [0, 0, 0]; - if (f >= centre[2]) return [2, 2, 0]; - const i = f < centre[1] ? 0 : 1; - return [i, i + 1, (f - centre[i]) * 3]; - }; for (const entry of model.terrains) { const lay = entry.layout; - if (lay?.length !== 9) continue; + if (!lay || !layoutSize(lay)) continue; const t = tIndex.get(entry.name)!; for (let c = 0; c < N; c++) { - const [cx0, cx1, fx] = axis(((c % cols) + 0.5) / cols); - const [cy0, cy1, fy] = axis((Math.floor(c / cols) + 0.5) / rows); - const top = lay[cy0 * 3 + cx0] * (1 - fx) + lay[cy0 * 3 + cx1] * fx; - const bottom = lay[cy1 * 3 + cx0] * (1 - fx) + lay[cy1 * 3 + cx1] * fx; - pos[c * T + t] += bias * Math.log(Math.max(0.02, top * (1 - fy) + bottom * fy)); + const v = layoutValue(lay, ((c % cols) + 0.5) / cols, (Math.floor(c / cols) + 0.5) / rows); + pos[c * T + t] += bias * Math.log(Math.max(0.02, v)); } } } @@ -685,6 +684,24 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required anchor index and distance. + const nearAnchor = new Int32Array(T).fill(-1); + const nearDist = new Int32Array(T); + for (const [name, rule] of nearRules(model, s)) { + const t = tIndex.get(name), a = tIndex.get(rule.terrain); + if (t === undefined || a === undefined) continue; + nearAnchor[t] = a; + nearDist[t] = Math.max(1, Math.round(rule.distance)); + } + /** Would t at c keep its near rule (an anchor hex within reach)? */ + const nearOk = (c: number, t: number): boolean => nearAnchor[t] < 0 || nearTerrain(c, nearAnchor[t], nearDist[t]); + // Growth follows directional bias: below this position score (a layout + // density of about a quarter, scaled by the bias) a patch doesn't spread. + const growFloor = bias > 0 ? bias * Math.log(0.25) : -Infinity; + /** May a growing patch of t take hex c? Position and near rules both say yes. */ + const growOk = (c: number, t: number): boolean => + c >= 0 && (!logPos || logPos[c * T + t] >= growFloor) && nearOk(c, t); + const growBlob = (seed: number, t: number, rng: () => number) => { let budget = growMoves[t]; const inPatch = new Set([seed]); @@ -709,14 +726,15 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required bs) { bs = sc; bi = i; } } const n = frontier[bi]; frontier[bi] = frontier[frontier.length - 1]; frontier.pop(); if (inPatch.has(n) || rejected.has(n)) continue; - if (tryPlace(n, t)) { + if (growOk(n, t) && tryPlace(n, t)) { inPatch.add(n); budget--; addNeighbours(n); @@ -731,8 +749,9 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required { - if (width >= 2 && budget > 0 && tryPlace(nbr[c * 6 + ring[(h + 2) % 6]], t)) budget--; - if (width >= 3 && budget > 0 && tryPlace(nbr[c * 6 + ring[(h + 4) % 6]], t)) budget--; + const side1 = nbr[c * 6 + ring[(h + 2) % 6]], side2 = nbr[c * 6 + ring[(h + 4) % 6]]; + if (width >= 2 && budget > 0 && growOk(side1, t) && tryPlace(side1, t)) budget--; + if (width >= 3 && budget > 0 && growOk(side2, t) && tryPlace(side2, t)) budget--; }; const h0 = Math.floor(rng() * 6); widen(seed, h0); @@ -751,7 +770,7 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required= 0 && tryPlace(n, t)) { + if (n >= 0 && growOk(n, t) && tryPlace(n, t)) { end.c = n; end.h = hh; end.alive = true; @@ -841,6 +860,8 @@ function solveOnce(model: HexWfcModel, opts: SolveOptions, s: Required= 0 && patchCount[t] >= maxPatches[t]) scores[t] = 0; if (spacingOf[t] > 1 && scores[t] > 0 && nearTerrain(best, t, spacingOf[t] - 1)) scores[t] = 0; + // Near rules: likelier close to the anchor, much less likely away from it. + if (nearAnchor[t] >= 0 && scores[t] > 0) scores[t] *= nearOk(best, t) ? 1 + nearPull : Math.exp(-2 * nearPull); if (feedback > 0 && scores[t] > 0) { const ratio = Math.min(FEEDBACK_CAP, Math.max(1 / FEEDBACK_CAP, (share[t] * decidedCount + 1) / (placed[t] + 1))); scores[t] *= Math.pow(ratio, feedback); diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 0baca9cf..b3d494fb 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -45,7 +45,10 @@ import { type PathTweak, type PathTypeTweak, type PathFeature, + type NearRule, effectivePathTweaks, + edgeSide, + parseNear, type RouteStat, randomSeed, SYMMETRIES, @@ -868,7 +871,7 @@ export class GeneratorPanel { // Terrain mix: per-terrain controls and what they do to the preview el = this.section(main, "Terrain mix"); el.createEl("p", { - text: "Mix scales how common each terrain is. Min and max limit how many separate patches it forms; leave blank for no limit. Example is each terrain's share of the region it was learned from; Map is its share of the preview, with the change your mix and min/max make to it.", + text: "Mix scales how common each terrain is. Min and max limit how many separate patches it forms; leave blank for no limit. Near keeps a terrain within some hexes of another, such as lava fields near a volcano. Example is each terrain's share of the region it was learned from; Map is its share of the preview, with the change your mix and min/max make to it.", cls: "duckmage-map-origin-desc", }); const table = el.createDiv({ cls: "duckmage-wfc-terrains" }); @@ -878,6 +881,7 @@ export class GeneratorPanel { ["Mix", ""], ["Min", "Fewest separate patches"], ["Max", "Most separate patches"], + ["Near", "Keep this terrain within some hexes of another, e.g. \"volcano 3\" (how hard it steers follows Clumping). Blank = the generator's own rule; \"off\" = none"], ["Example", "Share of the region this generator was learned from"], ["Map", "Share of the preview; the change is what mix and min/max add or remove (same seed)"], ]; @@ -885,6 +889,8 @@ export class GeneratorPanel { const example = exampleShares(model); const mix = { ...s().mix }; const counts: Record = Object.fromEntries(Object.entries(s().counts).map(([k, r]) => [k, { ...r }])); + const near: Record = { ...s().near }; + const terrainNames = new Set(model.terrains.map((t) => t.name)); for (const t of model.terrains) { const row = table.createDiv({ cls: "duckmage-wfc-terrain-row" }); // Guaranteed line features are laid down before the solver runs, so @@ -924,6 +930,29 @@ export class GeneratorPanel { save({ counts: Object.keys(counts).length ? { ...counts } : undefined }); }); } + // Near rule: blank = the generator's own (shown as the placeholder). + const nearInput = row.createEl("input", { + type: "text", + cls: "duckmage-wfc-near", + attr: { placeholder: t.near ? `${t.near.terrain} ${t.near.distance}` : "–", "aria-label": `${t.name} near rule` }, + }); + const own = near[t.name]; + nearInput.value = own === undefined ? "" : own === null ? "off" : `${own.terrain} ${own.distance}`; + nearInput.addEventListener("change", () => { + const raw = nearInput.value.trim(); + if (!raw) delete near[t.name]; + else if (/^(off|none)$/i.test(raw)) near[t.name] = null; + else { + const rule = parseNear(raw); + if (!rule || !terrainNames.has(rule.terrain) || rule.terrain === t.name) { + new Notice(`Write a terrain from this generator and a distance, e.g. "${model.terrains.find((x) => x.name !== t.name)?.name ?? "volcano"} 3", or "off".`); + nearInput.value = own === undefined ? "" : own === null ? "off" : `${own.terrain} ${own.distance}`; + return; + } + near[t.name] = rule; + } + save({ near: Object.keys(near).length ? { ...near } : undefined }); + }); row.createSpan({ text: formatShare(example.get(t.name) ?? 0), cls: "duckmage-wfc-share" }); const mapCell = row.createSpan({ cls: "duckmage-wfc-share" }); shareCells.set(t.name, { @@ -1042,21 +1071,22 @@ export class GeneratorPanel { cls: "duckmage-wfc-toggle duckmage-wfc-path-avoid", attr: { title: impassableList.length - ? `${type} paths never start, run or end on ${impassableList.join(", ")}, except where an end is that terrain (a river into the shallows). Set the list under Guarantees.` - : "No terrain is marked impassable yet (Guarantees, Impassable terrain).", + ? `${type} paths never start, run or end on ${impassableList.join(", ")}, except where an end is that terrain (a river into the shallows), and keep off the map border except at their ends. Set the list under Guarantees.` + : "Paths keep off the map border except at their ends. No terrain is marked impassable yet (Guarantees, Impassable terrain).", }, }); const avoidBox = avoid.createEl("input", { type: "checkbox" }); avoidBox.checked = !types[type]?.crossImpassable; - avoidBox.disabled = !impassableList.length; - avoid.createSpan({ text: "Avoid impassable terrain" }); + + avoid.createSpan({ text: "Avoid impassable terrain and the map border" }); avoidBox.addEventListener("change", () => saveType(type, { crossImpassable: avoidBox.checked ? undefined : true })); const body = group.createDiv({ cls: "duckmage-wfc-path-group-body" }); const rowEls: { route: string; row: HTMLElement; on: HTMLInputElement; why: HTMLElement }[] = []; for (const f of [...routes].sort((a, b) => b.count - a.count || pathRouteKey(a).localeCompare(pathRouteKey(b)))) { const route = pathRouteKey(f); - const end = (e: string) => (e === "edge" ? "map edge" : e === "path" ? `a ${f.type}` : e === "none" ? "anywhere" : e); + const sides = { N: "north edge", E: "east edge", S: "south edge", W: "west edge" } as const; + const end = (e: string) => (e === "edge" ? "map edge" : edgeSide(e) ? sides[edgeSide(e)!] : e === "path" ? `a ${f.type}` : e === "none" ? "anywhere" : e); const tw = tweaks[route] ?? {}; const row = body.createDiv({ cls: "duckmage-wfc-path-row" }); row.addEventListener("mouseenter", () => { diff --git a/styles.css b/styles.css index 61eadb12..634ca73f 100644 --- a/styles.css +++ b/styles.css @@ -5191,8 +5191,8 @@ tr:hover .duckmage-rt-entry-copy-btn:hover { .duckmage-wfc-terrain-row { display: grid; - /* Terrain, Mix, Min, Max, Example, Map */ - grid-template-columns: minmax(7em, 1.3fr) minmax(8em, 2fr) 3.75em 3.75em 3.5em 5.5em; + /* Terrain, Mix, Min, Max, Near, Example, Map */ + grid-template-columns: minmax(7em, 1.3fr) minmax(8em, 2fr) 3.75em 3.75em minmax(6em, 1fr) 3.5em 5.5em; align-items: center; gap: 0.5em; } @@ -5739,3 +5739,9 @@ button.duckmage-wfc-library-tab.is-active { margin: 0.5em auto; border-radius: var(--radius-s); } + +/* Terrain mix: the Near rule field ("volcano 3"). */ +.duckmage-wfc-near { + width: 100%; + min-width: 0; +} diff --git a/tests/hexWfcPlacement.test.ts b/tests/hexWfcPlacement.test.ts new file mode 100644 index 00000000..8e87510d --- /dev/null +++ b/tests/hexWfcPlacement.test.ts @@ -0,0 +1,210 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + cellKey, + decodeSetting, + encodeSetting, + hexNeighbors, + layoutTo5, + layoutValue, + modelToMarkdown, + mulberry32, + parseCellKey, + parseModelMarkdown, + routePaths, + solve, + type HexWfcModel, +} from "../packages/hex-wfc/src"; + +/** Near rules, 5×5 layouts, growth along layouts, side anchors, border-shy paths. */ + +const flat = { orientation: "flat" as const, stagger: "odd" as const }; + +/** Hex distance by breadth-first search over the solved map. */ +function withinOf(cells: Map, anchor: string, distance: number): Set { + const seen = new Set(); + let frontier = [...cells].filter(([, t]) => t === anchor).map(([k]) => k); + frontier.forEach((k) => seen.add(k)); + for (let d = 0; d < distance; d++) { + const next: string[] = []; + for (const k of frontier) { + const [x, y] = parseCellKey(k)!; + for (const [nx, ny] of hexNeighbors(x, y, "flat", "odd")) { + const n = cellKey(nx, ny); + if (cells.has(n) && !seen.has(n)) { seen.add(n); next.push(n); } + } + } + frontier = next; + } + return seen; +} + +describe("layout grids", () => { + const three = [1, 2, 3, 1, 2, 3, 1, 2, 3]; // rises west to east + + it("take each cell's value at its centre and blend between centres", () => { + expect(layoutValue(three, 1 / 6, 0.5)).toBeCloseTo(1); + expect(layoutValue(three, 0.5, 0.5)).toBeCloseTo(2); + expect(layoutValue(three, 1 / 3, 0.5)).toBeCloseTo(1.5); + expect(layoutValue(three, 0, 0)).toBeCloseTo(1); // clamped past the outer centres + }); + + it("work on a 5×5 grid, and a 3×3 one scales up to the same values", () => { + const five = Array.from({ length: 25 }, (_, i) => (i % 5) + 1); + expect(layoutValue(five, 0.9, 0.5)).toBeCloseTo(5); + expect(layoutValue(five, 0.5, 0.5)).toBeCloseTo(3); + const up = layoutTo5(three); + expect(up).toHaveLength(25); + for (const f of [0.1, 0.3, 0.5, 0.7, 0.9]) expect(layoutValue(up, f, 0.5)).toBeCloseTo(layoutValue(three, f, 0.5), 1); + }); +}); + +describe("format", () => { + const model: HexWfcModel = { + name: "m", + meta: {}, + terrains: [ + { name: "ash", weight: 80, layout: Array.from({ length: 25 }, (_, i) => 1 + (i % 5) / 4) }, + { name: "lava", weight: 15, near: { terrain: "volcano", distance: 3 } }, + { name: "volcano", weight: 5, shape: "scatter", spacing: 6 }, + ], + adjacency: [{ a: "ash", b: "ash", weight: 5 }], + }; + + it("round-trips the Near column and a 5×5 layout", () => { + const back = parseModelMarkdown(modelToMarkdown(model)); + if (!("model" in back)) throw new Error("parse failed"); + expect(back.warnings).toEqual([]); + expect(back.model.terrains.find((t) => t.name === "lava")?.near).toEqual({ terrain: "volcano", distance: 3 }); + expect(back.model.terrains[0].layout).toHaveLength(25); + expect(back.model.terrains[0].layout![4]).toBeCloseTo(2); + }); + + it("writes 3×3 rows as 5×5 when another terrain has a 5×5 layout", () => { + const mixed = { ...model, terrains: [...model.terrains, { name: "rock", weight: 1, layout: [1, 1, 1, 1, 3, 1, 1, 1, 1] }] }; + const back = parseModelMarkdown(modelToMarkdown(mixed)); + if (!("model" in back)) throw new Error("parse failed"); + expect(back.model.terrains.find((t) => t.name === "rock")?.layout).toHaveLength(25); + }); + + it("round-trips the near setting, including turning a rule off", () => { + const value = { lava: { terrain: "volcano dormant", distance: 2 }, ash: null }; + expect(decodeSetting("near", String(encodeSetting("near", value)))).toEqual({ value }); + expect(decodeSetting("near", "lava = volcano")).toHaveProperty("error"); + }); +}); + +describe("near rules", () => { + // Lava may sit anywhere ash may; only the near rule keeps it by volcanoes. + const model: HexWfcModel = { + name: "lava", + meta: {}, + terrains: [ + { name: "ash", weight: 70 }, + { name: "lava", weight: 25, near: { terrain: "volcano", distance: 2 } }, + { name: "volcano", weight: 5, shape: "scatter", spacing: 8 }, + ], + adjacency: [ + { a: "ash", b: "ash", weight: 5 }, + { a: "ash", b: "lava", weight: 3 }, + { a: "lava", b: "lava", weight: 4 }, + { a: "lava", b: "volcano", weight: 3 }, + { a: "ash", b: "volcano", weight: 1 }, + ], + }; + + it("leave no hex of the terrain out of reach of its anchor, on every seed", () => { + let lavaSeen = 0; + for (let seed = 1; seed <= 8; seed++) { + const r = solve(model, { cols: 24, rows: 16, ...flat, seed }); + expect(r.ok).toBe(true); + if (!r.ok) continue; + const ok = withinOf(r.cells, "volcano", 2); + const lava = [...r.cells].filter(([, t]) => t === "lava").map(([k]) => k); + lavaSeen += lava.length; + expect(lava.filter((k) => !ok.has(k))).toEqual([]); + } + expect(lavaSeen).toBeGreaterThan(0); + }); + + it("can be turned off from the settings", () => { + const off = { ...model, settings: { near: { lava: null } } }; + let far = 0; + for (let seed = 1; seed <= 4; seed++) { + const r = solve(off, { cols: 24, rows: 16, ...flat, seed }); + if (!r.ok) continue; + const ok = withinOf(r.cells, "volcano", 2); + far += [...r.cells].filter(([k, t]) => t === "lava" && !ok.has(k)).length; + } + expect(far).toBeGreaterThan(0); + }); +}); + +describe("growth follows the layout", () => { + // Forest grows in big blobs; its layout wants the west and not the east. + const model = (bias: number): HexWfcModel => ({ + name: "w", + meta: {}, + settings: { directionalBias: bias }, + terrains: [ + { name: "grass", weight: 60 }, + { name: "forest", weight: 40, shape: "blob", patch: 0.08, layout: [3, 1, 0.05, 3, 1, 0.05, 3, 1, 0.05] }, + ], + adjacency: [ + { a: "grass", b: "grass", weight: 5 }, + { a: "grass", b: "forest", weight: 2 }, + { a: "forest", b: "forest", weight: 5 }, + ], + }); + const eastShare = (bias: number) => { + let east = 0, all = 0; + for (let seed = 1; seed <= 6; seed++) { + const r = solve(model(bias), { cols: 30, rows: 20, ...flat, seed }); + if (!r.ok) continue; + for (const [k, t] of r.cells) { + if (t !== "forest") continue; + all++; + if (parseCellKey(k)![0] >= 20) east++; + } + } + return east / Math.max(1, all); + }; + + it("keeps patches out of the third the layout rules out", () => { + expect(eastShare(2)).toBeLessThan(0.08); + expect(eastShare(2)).toBeLessThan(eastShare(0)); + }); +}); + +describe("paths: sides and the border", () => { + const cols = 24, rows = 14; + const cells = new Map(); + for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) cells.set(cellKey(x, y), "grass"); + const grid = { cols, rows, ox: 0, oy: 0, ...flat }; + const borderHexes = (hexes: string[]) => + hexes.slice(1, -1).filter((h) => { const [x, y] = parseCellKey(h)!; return x === 0 || y === 0 || x === cols - 1 || y === rows - 1; }).length; + + it("start and end on the named sides", () => { + const river = { type: "River", from: "edge-W", to: "edge-E", count: 3, turn: 0.3, length: 1, through: { grass: 1 } }; + for (let seed = 1; seed <= 5; seed++) { + const r = routePaths([river], cells, grid, mulberry32(seed), 1, {}, []); + expect(r.paths.length).toBeGreaterThan(0); + for (const p of r.paths) { + expect(parseCellKey(p.hexes[0])![0]).toBe(0); + expect(parseCellKey(p.hexes[p.hexes.length - 1])![0]).toBe(cols - 1); + } + } + }); + + it("keep off the border between their ends, unless allowed to cross", () => { + const road = { type: "Road", from: "edge-N", to: "edge-S", count: 3, turn: 0.4, length: 1, through: { grass: 1 } }; + let shy = 0, free = 0; + for (let seed = 1; seed <= 6; seed++) { + for (const p of routePaths([road], cells, grid, mulberry32(seed), 1, {}, []).paths) shy += borderHexes(p.hexes); + for (const p of routePaths([road], cells, grid, mulberry32(seed), 1, { "Road: edge-N > edge-S": { crossImpassable: true } }, []).paths) + free += borderHexes(p.hexes); + } + expect(shy).toBeLessThanOrEqual(free); + expect(shy).toBeLessThan(4); + }); +}); From 992b2e768a6fc8eb0e30288d37f4b6aeae3c7187 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 16:06:22 -0400 Subject: [PATCH 060/558] fix(worldgen): keep side-anchored routes when fitting a model to a palette restrictModel only knew the bare "edge" anchor, so on the generator page (which fits every model to the palette) edge-N/E/S/W routes were dropped, and any route branching off them failed with "Placed 0 of N". edgeSide / isEdgeAnchor now live in model.ts (re-exported from paths.ts). Co-Authored-By: Claude Opus 5.5 --- packages/hex-wfc/src/model.ts | 10 +++++++++- packages/hex-wfc/src/paths.ts | 10 ++-------- tests/hexWfcPlacement.test.ts | 12 ++++++++++++ 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/packages/hex-wfc/src/model.ts b/packages/hex-wfc/src/model.ts index 00ef01a7..13fb0dd9 100644 --- a/packages/hex-wfc/src/model.ts +++ b/packages/hex-wfc/src/model.ts @@ -414,13 +414,21 @@ export function validateModel(model: HexWfcModel): string[] { return problems; } +/** "edge-N" / "edge-E" / "edge-S" / "edge-W" (any case): which side; null for anything else. */ +export function edgeSide(anchor: string): "N" | "E" | "S" | "W" | null { + const m = /^edge-([nesw])$/i.exec(anchor.trim()); + return m ? (m[1].toUpperCase() as "N" | "E" | "S" | "W") : null; +} +/** Any edge anchor: `edge` or one side of it. */ +export const isEdgeAnchor = (anchor: string): boolean => anchor === "edge" || edgeSide(anchor) !== null; + /** * Drop terrains that aren't in `allowed` (and their adjacency rows and * features). Use it to fit a model to a palette that lacks some terrains. */ export function restrictModel(model: HexWfcModel, allowed: Iterable): HexWfcModel { const keep = new Set(allowed); - const ok = (end: string) => end === "edge" || end === "none" || keep.has(end); + const ok = (end: string) => isEdgeAnchor(end) || end === "none" || keep.has(end); return { ...model, terrains: model.terrains.filter((t) => keep.has(t.name)), diff --git a/packages/hex-wfc/src/paths.ts b/packages/hex-wfc/src/paths.ts index cfe4cb80..926285b4 100644 --- a/packages/hex-wfc/src/paths.ts +++ b/packages/hex-wfc/src/paths.ts @@ -11,7 +11,8 @@ */ import { hexNeighbors, hexDistance, directionRing, cellKey, parseCellKey, type Orientation, type Stagger } from "./grid"; -import { pathRouteKey, type PathFeature, type PathTweak } from "./model"; +import { edgeSide, isEdgeAnchor, pathRouteKey, type PathFeature, type PathTweak } from "./model"; +export { edgeSide, isEdgeAnchor }; import type { GridInfo } from "./post"; export interface PathInput { @@ -54,13 +55,6 @@ const PREF_CAP = 1.2; */ const BORDER_COST = 3; -/** "edge-N" / "edge-E" / "edge-S" / "edge-W" (any case): which side; null for anything else. */ -export function edgeSide(anchor: string): "N" | "E" | "S" | "W" | null { - const m = /^edge-([nesw])$/i.exec(anchor.trim()); - return m ? (m[1].toUpperCase() as "N" | "E" | "S" | "W") : null; -} -/** Any edge anchor: `edge` or one side of it. */ -export const isEdgeAnchor = (anchor: string): boolean => anchor === "edge" || edgeSide(anchor) !== null; /** Remove consecutive duplicates (repeat clicks). */ function clean(hexes: string[]): string[] { diff --git a/tests/hexWfcPlacement.test.ts b/tests/hexWfcPlacement.test.ts index 8e87510d..efde4961 100644 --- a/tests/hexWfcPlacement.test.ts +++ b/tests/hexWfcPlacement.test.ts @@ -11,6 +11,7 @@ import { mulberry32, parseCellKey, parseModelMarkdown, + restrictModel, routePaths, solve, type HexWfcModel, @@ -196,6 +197,17 @@ describe("paths: sides and the border", () => { } }); + it("survive fitting the model to a palette", () => { + const m: HexWfcModel = { + name: "p", + meta: {}, + terrains: [{ name: "grass", weight: 1 }], + adjacency: [{ a: "grass", b: "grass", weight: 1 }], + paths: [{ type: "River", from: "edge-W", to: "edge-E", count: 1, turn: 0.3, length: 1, through: { grass: 1 } }], + }; + expect(restrictModel(m, ["grass"]).paths).toHaveLength(1); + }); + it("keep off the border between their ends, unless allowed to cross", () => { const road = { type: "Road", from: "edge-N", to: "edge-S", count: 3, turn: 0.4, length: 1, through: { grass: 1 } }; let shy = 0, free = 0; From a216afcd7656def833a929fc84a7469c63538fd0 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 16:18:09 -0400 Subject: [PATCH 061/558] =?UTF-8?q?feat(worldgen):=20learn=20near=20rules?= =?UTF-8?q?=20and=205=C3=975=20layouts=20from=20painted=20maps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generators learned from a map now pick up the new placement features: - near rules: a terrain that only ever sits within a few hexes of a rarer one (two or more anchor hexes; its reach covering under 45% of the map) gets "near "; - examples of 600+ hexes learn a 5×5 layout instead of 3×3. dev/wfc-learn-compare.mts re-learns real vault maps with two library versions and scores layout error and near-rule fidelity. On the user's maps, near relationships now hold 92-100% (was 66-88%); layout error is about level overall. Co-Authored-By: Claude Opus 5.5 --- dev/wfc-learn-compare.mts | 91 +++++++++++++++++++++++++++++++++++ packages/hex-wfc/src/index.ts | 2 +- packages/hex-wfc/src/learn.ts | 90 ++++++++++++++++++++++++++++++++-- tests/hexWfc.test.ts | 8 +-- tests/hexWfcPlacement.test.ts | 28 +++++++++++ 5 files changed, 209 insertions(+), 10 deletions(-) create mode 100644 dev/wfc-learn-compare.mts diff --git a/dev/wfc-learn-compare.mts b/dev/wfc-learn-compare.mts new file mode 100644 index 00000000..60379aa4 --- /dev/null +++ b/dev/wfc-learn-compare.mts @@ -0,0 +1,91 @@ +// How faithfully generators learned from real vault maps reproduce them, for +// two copies of the hex-wfc library (e.g. before and after a change). Read-only. +// npx tsx dev/wfc-learn-compare.mts ... (env SEEDS; PLUGIN_DIR = folder with data.json) +// layout-err: mean gap between where each terrain sits in the source map and +// in generated maps, on a 5×5 grid (lower is closer). +// near-held: of the source map's near rules ("lava within 2 of volcano"), +// the share of generated hexes that keep them (the source map is 100%). +import { readFileSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import * as cur from "../packages/hex-wfc/src"; + +const [oldDir, ...names] = process.argv.slice(2); +const old = await import(pathToFileURL(`${oldDir}/index.ts`).href); +const seeds = Number(process.env.SEEDS ?? 6); +const pluginDir = process.env.PLUGIN_DIR ?? (existsSync("data.json") ? "." : join(process.cwd(), "../../../.obsidian/plugins/duckmage-plugin")); +const data = JSON.parse(readFileSync(join(pluginDir, "data.json"), "utf8")); +const vaultRoot = join(pluginDir, "../../.."); + +function load(name: string) { + const map = data.maps.find((m: { name: string }) => m.name === name); + if (!map) throw new Error(`no map ${name}`); + const cells = new Map(); + for (let x = map.gridOffset.x; x < map.gridOffset.x + map.gridSize.cols; x++) + for (let y = map.gridOffset.y; y < map.gridOffset.y + map.gridSize.rows; y++) { + const f = join(vaultRoot, data.hexFolder, name, `${x}_${y}.md`); + if (!existsSync(f)) continue; + const t = /^---[\s\S]*?\nterrain:\s*(.*)\n/.exec(readFileSync(f, "utf8"))?.[1].trim().replace(/^"|"$/g, ""); + if (t) cells.set(cur.cellKey(x, y), t); + } + return { map, cells }; +} + +/** Share of each terrain in each cell of a 5×5 grid over the map. */ +function grid5(cells: Map): Map { + let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; + for (const k of cells.keys()) { + const [x, y] = cur.parseCellKey(k)!; + minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); + } + const w = maxX - minX + 1, h = maxY - minY + 1; + const out = new Map(); + for (const [k, t] of cells) { + const [x, y] = cur.parseCellKey(k)!; + const b = Math.min(4, Math.floor((5 * (y - minY)) / h)) * 5 + Math.min(4, Math.floor((5 * (x - minX)) / w)); + let a = out.get(t); + if (!a) out.set(t, (a = new Array(25).fill(0))); + a[b] += 1 / cells.size; + } + return out; +} + +function nearHeld(cells: Map, rules: Map, o: cur.Orientation, s: cur.Stagger) { + let ok = 0, all = 0; + for (const [t, r] of rules) { + const anchors = [...cells].filter(([, u]) => u === r.terrain).map(([k]) => cur.parseCellKey(k)!); + for (const [k, u] of cells) { + if (u !== t) continue; + all++; + const xy = cur.parseCellKey(k)!; + if (anchors.some((a) => cur.hexDistance(xy, a, o, s) <= r.distance)) ok++; + } + } + return all ? ok / all : NaN; +} + +for (const name of names) { + const { map, cells } = load(name); + const orientation = data.hexOrientation ?? "flat"; + const stagger = map.staggerOffset ?? data.staggerOffset ?? "odd"; + const src = grid5(cells); + const rules = cur.measureNear(cells, orientation, stagger); + const row: string[] = []; + for (const [label, lib] of [["old", old], ["new", cur]] as const) { + const model = lib.learnModel(cells, { name, orientation, stagger }); + let err = 0, held = 0, n = 0; + for (let seed = 1; seed <= seeds; seed++) { + const r = lib.solve(model, { cols: map.gridSize.cols, rows: map.gridSize.rows, orientation, stagger, seed }); + if (!r.ok) continue; + const gen = grid5(r.cells); + for (const t of new Set([...src.keys(), ...gen.keys()])) { + const a = src.get(t) ?? new Array(25).fill(0), b = gen.get(t) ?? new Array(25).fill(0); + for (let i = 0; i < 25; i++) err += Math.abs(a[i] - b[i]); + } + held += nearHeld(r.cells, rules, orientation, stagger) || 0; + n++; + } + row.push(`${label}: layout-err ${(err / Math.max(1, n)).toFixed(3)} near-held ${rules.size ? ((100 * held) / Math.max(1, n)).toFixed(0) + "%" : " –"}`); + } + console.log(`${name.padEnd(14)} ${String(cells.size).padStart(5)} hexes, ${String(rules.size).padStart(2)} near rules | ${row.join(" | ")}`); +} diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index a0ed673d..c53eabb5 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -39,7 +39,7 @@ export { pathRouteKey, } from "./model"; export { mergeModels } from "./merge"; -export { learnModel, measurePatches, measureLayout, SHAPE_THRESHOLDS, type LearnOptions, type TerrainAnalysis } from "./learn"; +export { learnModel, measurePatches, measureLayout, measureNear, LAYOUT_5_MIN_HEXES, NEAR_THRESHOLDS, SHAPE_THRESHOLDS, type LearnOptions, type TerrainAnalysis } from "./learn"; export { solve, findViolation, cleanupStrengths, pathsEnabled, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; export { countPatches, smoothEdges, removeSpecks, untouchableTerrains, enforceNear, type GridInfo } from "./post"; export { learnPaths, routePaths, edgeSide, isEdgeAnchor, type PathInput, type PathOutput, type RouteStat } from "./paths"; diff --git a/packages/hex-wfc/src/learn.ts b/packages/hex-wfc/src/learn.ts index 2d419df6..e4aefa07 100644 --- a/packages/hex-wfc/src/learn.ts +++ b/packages/hex-wfc/src/learn.ts @@ -8,7 +8,7 @@ import { type Orientation, type Stagger, } from "./grid"; -import type { HexWfcModel, GrowthShape, LineFeature, TerrainEntry } from "./model"; +import type { HexWfcModel, GrowthShape, LineFeature, NearRule, TerrainEntry } from "./model"; import { learnPaths, type PathInput } from "./paths"; export interface LearnOptions { @@ -30,6 +30,8 @@ export interface LearnOptions { * from measuring each terrain's patches (see measurePatches). * - Line patches anchored to a map edge or another terrain become guaranteed * features (e.g. a river from the edge to a lake). + * - A terrain that only ever appears close to a rarer one gets a near rule + * (lava within 3 of a volcano); see measureNear. * * Cells that are missing (unpainted) are ignored, along with their edges. */ @@ -60,6 +62,7 @@ export function learnModel( const analysis = analysePatches(map, opts.orientation, stagger); const layouts = measureLayout(map); + const near = measureNear(map, opts.orientation, stagger); const terrains: TerrainEntry[] = [...terrainCount] .map(([name, weight]) => { const a = analysis.terrains.get(name); @@ -74,6 +77,8 @@ export function learnModel( } const layout = layouts.get(name); if (layout) entry.layout = layout; + const rule = near.get(name); + if (rule) entry.near = rule; return entry; }) .sort((p, q) => q.weight - p.weight || p.name.localeCompare(q.name)); @@ -377,7 +382,9 @@ function minSpacing(list: Patch[], orientation: Orientation, stagger: Stagger): * common as across the whole map. Smoothed toward 1 so a bin with few hexes * doesn't forbid a terrain outright. */ -export function measureLayout(cells: Map): Map { +export function measureLayout(cells: Map, size?: 3 | 5): Map { + // Finer grid once there are enough hexes for ~24 per cell. + const n = size ?? (cells.size >= LAYOUT_5_MIN_HEXES ? 5 : 3); let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; const pts: [number, number, string][] = []; for (const [key, t] of cells) { @@ -391,14 +398,14 @@ export function measureLayout(cells: Map): Map if (!pts.length) return out; const w = maxX - minX + 1, h = maxY - minY + 1; const bin = (x: number, y: number) => - Math.min(2, Math.floor((3 * (y - minY)) / h)) * 3 + Math.min(2, Math.floor((3 * (x - minX)) / w)); - const binTotal = new Array(9).fill(0); + Math.min(n - 1, Math.floor((n * (y - minY)) / h)) * n + Math.min(n - 1, Math.floor((n * (x - minX)) / w)); + const binTotal = new Array(n * n).fill(0); const counts = new Map(); for (const [x, y, t] of pts) { const b = bin(x, y); binTotal[b]++; let c = counts.get(t); - if (!c) counts.set(t, (c = new Array(9).fill(0))); + if (!c) counts.set(t, (c = new Array(n * n).fill(0))); c[b]++; } const PSEUDO = 4; // pseudo-hexes per bin pulling the estimate toward 1 @@ -414,3 +421,76 @@ export function measureLayout(cells: Map): Map } return out; } + +/** Examples with at least this many hexes learn a 5×5 layout instead of 3×3. */ +export const LAYOUT_5_MIN_HEXES = 600; + +/** Limits for learning near rules. Exported for tests and tuning. */ +export const NEAR_THRESHOLDS = { + /** Only terrains with at least this many hexes get a rule. */ + minHexes: 6, + /** ...and only to an anchor with at least this many; one stray hex is too + * little to go on (and generated maps often lack it, wiping the terrain). */ + minAnchorHexes: 2, + /** Furthest a rule reaches, in hexes. */ + maxDistance: 4, + /** The anchor's reach may cover at most this share of the map; any more + * and the rule says little (everything is near grass). */ + maxCoverage: 0.45, +}; + +/** + * Near rules from an example: terrain T gets "near A d" when every T hex is + * within d hexes of some A hex, and A's reach at d covers only a small part + * of the map. Of several anchors, the tightest one (least coverage) wins. + */ +export function measureNear(cells: Map, orientation: Orientation, stagger: Stagger): Map { + const out = new Map(); + const total = cells.size; + if (!total) return out; + const byTerrain = new Map(); + for (const [k, t] of cells) { + if (!t) continue; + let list = byTerrain.get(t); + if (!list) byTerrain.set(t, (list = [])); + list.push(k); + } + const { minHexes, minAnchorHexes, maxDistance, maxCoverage } = NEAR_THRESHOLDS; + const best = new Map(); + for (const [anchor, seeds] of byTerrain) { + if (seeds.length < minAnchorHexes || seeds.length / total > maxCoverage) continue; + // Distance from the anchor, up to maxDistance. + const dist = new Map(seeds.map((k) => [k, 0])); + let frontier = seeds; + const reach = [seeds.length]; // hexes within d, for d = 0..maxDistance + for (let d = 1; d <= maxDistance; d++) { + const next: string[] = []; + for (const k of frontier) { + const xy = parseCellKey(k)!; + for (const [nx, ny] of hexNeighbors(xy[0], xy[1], orientation, stagger)) { + const nk = cellKey(nx, ny); + if (cells.has(nk) && !dist.has(nk)) { dist.set(nk, d); next.push(nk); } + } + } + reach.push(reach[d - 1] + next.length); + frontier = next; + } + for (const [t, hexes] of byTerrain) { + if (t === anchor || hexes.length < minHexes) continue; + let far = 0; + for (const k of hexes) { + const d = dist.get(k); + if (d === undefined) { far = Infinity; break; } + far = Math.max(far, d); + } + if (far < 1 || far > maxDistance) continue; + const coverage = reach[far] / total; + if (coverage > maxCoverage) continue; + const prev = best.get(t); + if (!prev || coverage < prev.coverage) best.set(t, { rule: { terrain: anchor, distance: far }, coverage }); + } + } + for (const [t, b] of best) out.set(t, b.rule); + return out; +} + diff --git a/tests/hexWfc.test.ts b/tests/hexWfc.test.ts index a8ab2ced..e784b311 100644 --- a/tests/hexWfc.test.ts +++ b/tests/hexWfc.test.ts @@ -418,9 +418,9 @@ describe("directional bias, randomness and saved settings", () => { it("learns where each terrain sat", () => { const ocean = model.terrains.find((t) => t.name === "Ocean")!.layout!; - expect(ocean).toHaveLength(9); - expect(ocean[7]).toBeGreaterThan(2); // S: much more ocean than average - expect(ocean[1]).toBeLessThan(0.2); // N: almost none + expect(ocean).toHaveLength(25); // a big example learns the 5×5 grid + expect(ocean[22]).toBeGreaterThan(2); // bottom middle: much more ocean than average + expect(ocean[2]).toBeLessThan(0.2); // top middle: almost none }); it("bias 1 keeps the ocean along the bottom; bias 0 doesn't care", () => { @@ -469,7 +469,7 @@ describe("directional bias, randomness and saved settings", () => { const text = modelToMarkdown(m); expect(text).toContain("feature-size: 1.5"); expect(text).toContain("directional-bias: 0.75"); - expect(text).toContain("| Terrain | NW | N | NE | W | C | E | SW | S | SE |"); + expect(text).toContain("| Terrain | R1C1 | R1C2 | R1C3 | R1C4 | R1C5 |"); const back = parseModelMarkdown(text); expect(back.warnings).toEqual([]); expect(back.model).toEqual(m); diff --git a/tests/hexWfcPlacement.test.ts b/tests/hexWfcPlacement.test.ts index efde4961..7000e39a 100644 --- a/tests/hexWfcPlacement.test.ts +++ b/tests/hexWfcPlacement.test.ts @@ -4,9 +4,12 @@ import { cellKey, decodeSetting, encodeSetting, + hexDistance, hexNeighbors, layoutTo5, layoutValue, + learnModel, + measureNear, modelToMarkdown, mulberry32, parseCellKey, @@ -220,3 +223,28 @@ describe("paths: sides and the border", () => { expect(shy).toBeLessThan(4); }); }); + +describe("learning from an example", () => { + // Grass everywhere, a few volcanoes, lava only right around them. + const example = new Map(); + const volcanoes = [[5, 5], [20, 12], [32, 4]]; + for (let y = 0; y < 18; y++) + for (let x = 0; x < 40; x++) { + const d = Math.min(...volcanoes.map(([vx, vy]) => hexDistance([x, y], [vx, vy], "flat", "odd"))); + example.set(cellKey(x, y), d === 0 ? "volcano" : d <= 2 ? "lava" : "grass"); + } + + it("finds near rules: lava only ever sits by a volcano", () => { + const rules = measureNear(example, "flat", "odd"); + expect(rules.get("lava")).toEqual({ terrain: "volcano", distance: 2 }); + expect(rules.has("grass")).toBe(false); // grass is everywhere + }); + + it("puts them in the learned model, with a 5×5 layout on a big example", () => { + const m = learnModel(example, { name: "v", orientation: "flat" }); + expect(m.terrains.find((t) => t.name === "lava")?.near).toEqual({ terrain: "volcano", distance: 2 }); + expect(m.terrains[0].layout).toHaveLength(25); + const small = learnModel(new Map([...example].filter(([k]) => parseCellKey(k)![0] < 12)), { name: "s", orientation: "flat" }); + expect(small.terrains[0].layout).toHaveLength(9); + }); +}); From d193ab07e9215204716c641fc822921282ba1f06 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 16:29:58 -0400 Subject: [PATCH 062/558] feat(worldgen): blend generators with a compass direction per source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tick two or more generators and press Blend: the new generator combines their terrains, rules and paths, each leaning toward its own side of the map (two run west to east by default), giving the border country between two biomes (a valley fading into deep forest). - mergeModels takes a compass point per source (NW..SE, or C for everywhere); its terrains' layouts are multiplied by a 5×5 gradient toward that side. Sharpness follows Directional bias (switched on if it was off). Merging now keeps near rules, and carries the lead model's settings plus every model's counts / near / impassable lists. - Blends record blend-of / source-influence / source-direction and can be re-blended from their sources' current files. - The influence sliders on the generator page gain a 3×3 compass joystick per source, for blends and region combos alike. - dev/wfc-blend.mts blends generator files from the command line. Co-Authored-By: Claude Opus 5.5 --- dev/wfc-blend.mts | 19 +++++ packages/hex-wfc/src/index.ts | 2 +- packages/hex-wfc/src/merge.ts | 82 +++++++++++++++++- src/worldgen/GeneratorLibrary.ts | 24 +++++- src/worldgen/GeneratorPanel.ts | 83 +++++++++++++----- src/worldgen/generators.ts | 140 ++++++++++++++++++++++++++++++- styles.css | 27 +++++- tests/hexWfcPlacement.test.ts | 38 +++++++++ 8 files changed, 382 insertions(+), 33 deletions(-) create mode 100644 dev/wfc-blend.mts diff --git a/dev/wfc-blend.mts b/dev/wfc-blend.mts new file mode 100644 index 00000000..f75a4a00 --- /dev/null +++ b/dev/wfc-blend.mts @@ -0,0 +1,19 @@ +// Blend generator files with compass directions and write the result. +// npx tsx dev/wfc-blend.mts :[:] ... +// e.g. dev/wfc-blend.mts /tmp/b.md preset-valley.md:W preset-deep-forest.md:E +import { readFileSync, writeFileSync } from "node:fs"; +import { basename } from "node:path"; +import { isCompass, mergeModels, modelToMarkdown, parseModelMarkdown, type Compass } from "../packages/hex-wfc/src"; + +const [out, ...specs] = process.argv.slice(2); +const models = [], dirs: Compass[] = [], influence: number[] = []; +for (const spec of specs) { + const [file, dir = "C", inf = "50"] = spec.split(":"); + const parsed = parseModelMarkdown(readFileSync(file, "utf8")); + if (!("model" in parsed)) throw new Error(`can't read ${file}`); + if (!isCompass(dir)) throw new Error(`bad direction ${dir}`); + models.push(parsed.model); dirs.push(dir); influence.push(Number(inf)); +} +const name = specs.map((s) => basename(s.split(":")[0], ".md")).join("-to-"); +writeFileSync(out, modelToMarkdown(mergeModels(models, name, { palette: "Default" }, influence, dirs))); +console.log("wrote", out); diff --git a/packages/hex-wfc/src/index.ts b/packages/hex-wfc/src/index.ts index c53eabb5..9390f565 100644 --- a/packages/hex-wfc/src/index.ts +++ b/packages/hex-wfc/src/index.ts @@ -38,7 +38,7 @@ export { effectivePathTweaks, pathRouteKey, } from "./model"; -export { mergeModels } from "./merge"; +export { mergeModels, compassLayout, isCompass, COMPASS, type Compass } from "./merge"; export { learnModel, measurePatches, measureLayout, measureNear, LAYOUT_5_MIN_HEXES, NEAR_THRESHOLDS, SHAPE_THRESHOLDS, type LearnOptions, type TerrainAnalysis } from "./learn"; export { solve, findViolation, cleanupStrengths, pathsEnabled, type SolveOptions, type SolveResult, type SolveStats } from "./solve"; export { countPatches, smoothEdges, removeSpecks, untouchableTerrains, enforceNear, type GridInfo } from "./post"; diff --git a/packages/hex-wfc/src/merge.ts b/packages/hex-wfc/src/merge.ts index 30e017eb..778fb1ed 100644 --- a/packages/hex-wfc/src/merge.ts +++ b/packages/hex-wfc/src/merge.ts @@ -6,9 +6,14 @@ * that are already relative to their region (patch size as a share of the * map, where terrain sat in a 3×3 grid, edge preference, line width and * turning) are averaged, weighted by how much of that terrain each region had. + * + * Each model can also be given a compass direction: its terrains then lean + * toward that side of the map (a valley in the west fading into forest in the + * east), by multiplying their layouts with a gradient. How sharp the change + * is follows the merged generator's directional bias. */ -import { layoutSize, layoutTo5, pathRouteKey, type AdjacencyEntry, type HexWfcModel, type LineFeature, type PathFeature, type TerrainEntry } from "./model"; +import { layoutSize, layoutTo5, pathRouteKey, type GeneratorSettings, type AdjacencyEntry, type HexWfcModel, type LineFeature, type PathFeature, type TerrainEntry } from "./model"; type Weighted = { value: number; weight: number }; @@ -41,6 +46,9 @@ function mergeTerrain(entries: TerrainEntry[]): TerrainEntry { if (spacing !== undefined) merged.spacing = spacing; const edge = mean((t) => t.edge); if (edge !== undefined) merged.edge = edge; + // Near rule: the one from the entry with the most of this terrain. + const near = [...entries].sort((a, b) => b.weight - a.weight).find((t) => t.near)?.near; + if (near) merged.near = { ...near }; // Layouts of different grid sizes are compared on the finer (5×5) grid. const withLayout = entries.filter((t) => layoutSize(t.layout)); const fine = withLayout.some((t) => layoutSize(t.layout) === 5); @@ -69,6 +77,44 @@ function mergePaths(paths: PathFeature[]): PathFeature { }; } +/** Compass points a merged model can lean toward; "C" = no direction. */ +export const COMPASS = ["NW", "N", "NE", "W", "C", "E", "SW", "S", "SE"] as const; +export type Compass = (typeof COMPASS)[number]; + +export const isCompass = (v: string): v is Compass => (COMPASS as readonly string[]).includes(v); + +/** Strength of the direction gradient: about 3.6× at the favoured edge, 0.28× at the far one. */ +const LEAN = 1.6; + +/** + * A 5×5 layout leaning toward `dir`, averaging 1 over the grid (so a terrain's + * overall share is unchanged); all 1s for "C". + */ +export function compassLayout(dir: Compass): number[] { + const i = COMPASS.indexOf(dir); + const dx = (i % 3) - 1, dy = Math.floor(i / 3) - 1; + const len = Math.hypot(dx, dy) || 1; + const raw = Array.from({ length: 25 }, (_, k) => { + const u = (((k % 5) + 0.5) / 5) * 2 - 1, v = ((Math.floor(k / 5) + 0.5) / 5) * 2 - 1; + return Math.exp((LEAN * (u * dx + v * dy)) / len); + }); + const mean = raw.reduce((a, b) => a + b, 0) / raw.length; + return raw.map((x) => Math.round((x / mean) * 100) / 100); +} + +/** `m` with every terrain's layout multiplied by the compass gradient. */ +function leanModel(m: HexWfcModel, dir: Compass): HexWfcModel { + if (dir === "C") return m; + const ramp = compassLayout(dir); + return { + ...m, + terrains: m.terrains.map((t) => { + const own = t.layout && layoutSize(t.layout) ? layoutTo5(t.layout) : null; + return { ...t, layout: ramp.map((r, i) => Math.round(r * (own ? own[i] : 1) * 100) / 100) }; + }), + }; +} + /** Every count in a model multiplied by `f`; relative measures unchanged. */ function scaleModel(m: HexWfcModel, f: number): HexWfcModel { return { @@ -87,7 +133,20 @@ function scaleModel(m: HexWfcModel, f: number): HexWfcModel { * scaled so its share of the total is its share of the influence; a model * with 0 influence is left out. */ -export function mergeModels(models: HexWfcModel[], name: string, meta: Record = {}, influence?: number[]): HexWfcModel { +export function mergeModels( + models: HexWfcModel[], + name: string, + meta: Record = {}, + influence?: number[], + /** One compass point per model ("C" = none); see compassLayout. */ + directions?: Compass[], +): HexWfcModel { + if (directions && directions.length === models.length && directions.some((d) => d !== "C")) { + const merged = mergeModels(models.map((m, i) => leanModel(m, directions[i])), name, meta, influence); + // Directions only work through directional bias; make sure it's on. + merged.settings = { ...merged.settings, directionalBias: Math.max(1, merged.settings?.directionalBias ?? 0) }; + return merged; + } if (influence && influence.length === models.length) { const size = (m: HexWfcModel) => m.exampleHexes ?? m.terrains.reduce((n, t) => n + t.weight, 0); const totalSize = models.reduce((n, m) => n + size(m), 0); @@ -150,7 +209,26 @@ export function mergeModels(models: HexWfcModel[], name: string, meta: Record totalWeight(b) - totalWeight(a)).find((m) => m.settings); + if (lead?.settings) merged.settings = mergeSettings(lead.settings, models); if (features.size) merged.features = [...features.values()]; if (routes.size) merged.paths = [...routes.values()].map(mergePaths); return merged; } + +const totalWeight = (m: HexWfcModel) => m.terrains.reduce((n, t) => n + t.weight, 0); + +/** + * Settings for a merged model: the lead model's, plus the per-terrain lists + * (counts, near, impassable) of every model, the lead's winning on clashes. + */ +function mergeSettings(lead: GeneratorSettings, models: HexWfcModel[]): GeneratorSettings { + const out: GeneratorSettings = { ...lead }; + const others = models.map((m) => m.settings).filter((x): x is GeneratorSettings => !!x && x !== lead); + for (const o of others) { + if (o.counts) out.counts = { ...o.counts, ...out.counts }; + if (o.near) out.near = { ...o.near, ...out.near }; + if (o.impassable) out.impassable = [...new Set([...(out.impassable ?? []), ...o.impassable])]; + } + return out; +} diff --git a/src/worldgen/GeneratorLibrary.ts b/src/worldgen/GeneratorLibrary.ts index 2dfc8823..bcc91cbc 100644 --- a/src/worldgen/GeneratorLibrary.ts +++ b/src/worldgen/GeneratorLibrary.ts @@ -1,12 +1,12 @@ /** * The generator page's file list: a Generators tab (load one, or tick several - * to open, re-learn or delete them) and a Regions tab (tick one or more maps + * to open, re-learn, blend or delete them) and a Regions tab (tick one or more maps * and learn a generator from them, combined when there are several). */ import { App, Notice } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; -import { deleteGenerators, relearnGenerator, saveGeneratorFromMaps, sourceMapsOf, type GeneratorFile } from "./generators"; +import { blendSourcesOf, deleteGenerators, relearnGenerator, saveBlendedGenerator, saveGeneratorFromMaps, sourceMapsOf, type GeneratorFile } from "./generators"; import { combinedName, generatorRows, regionRows, type RegionRow } from "./libraryRows"; import { ConfirmModal } from "./ConfirmModal"; @@ -121,9 +121,27 @@ export class GeneratorLibrary { actions.createSpan({ text: selected.length ? `${selected.length} selected` : "Tick generators to act on them", cls: "duckmage-map-origin-desc" }); const open = actions.createEl("button", { text: "Open file" }); const relearn = actions.createEl("button", { text: "Re-learn", attr: { title: "Learn again from the regions they came from, keeping their settings" } }); + const blend = actions.createEl("button", { + text: selected.length > 1 ? `Blend (${selected.length})` : "Blend", + attr: { title: "Make a new generator that blends these, each leaning toward its own side of the map: the border country between them" }, + }); const del = actions.createEl("button", { text: "Delete", cls: "mod-warning" }); for (const b of [open, relearn, del]) b.disabled = !selected.length; - relearn.disabled ||= !selected.some((g) => sourceMapsOf(g.model).length); + relearn.disabled ||= !selected.some((g) => sourceMapsOf(g.model).length || blendSourcesOf(g.model).length); + blend.disabled = selected.length < 2; + blend.addEventListener("click", () => { + blend.disabled = true; + void saveBlendedGenerator(this.plugin, selected, "").then((r) => { + if ("error" in r) { + new Notice(r.error); + blend.disabled = false; + return; + } + new Notice(`Blended ${selected.map((g) => g.model.name).join(" + ")} into "${r.model.name}".`); + checked.clear(); + this.host.changed(r.file.path); + }); + }); open.addEventListener("click", () => { for (const g of selected) void this.app.workspace.getLeaf("tab").openFile(g.file); }); diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index b3d494fb..0f97f886 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -21,6 +21,8 @@ import { relearnGenerator, regionSizes, sourceInfluenceOf, + combinedSourcesOf, + sourceDirectionsOf, setGeneratorPalette, toPathChains, type GeneratorFile, @@ -55,6 +57,8 @@ import { type GeneratorSettings, type Symmetry, type CountRange, + COMPASS, + type Compass, } from "../../packages/hex-wfc/src"; export interface GeneratorPanelHost { @@ -276,11 +280,16 @@ export class GeneratorPanel { }); }); - const sources = sourceMapsOf(model); + const combo = combinedSourcesOf(model); + const isBlend = combo.kind === "blend"; + const sources = combo.names; const sourceRow = el.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); - sourceRow.createSpan({ text: "From", cls: "duckmage-map-origin-label" }); + sourceRow.createSpan({ text: isBlend ? "Blend of" : "From", cls: "duckmage-map-origin-label" }); sourceRow.createSpan({ text: sources.length ? sources.join(" + ") : "No region recorded", cls: "duckmage-wfc-source" }); - const relearnBtn = sourceRow.createEl("button", { text: "Re-learn", attr: { title: "Learn again from these regions, keeping the settings below" } }); + const relearnBtn = sourceRow.createEl("button", { + text: isBlend ? "Re-blend" : "Re-learn", + attr: { title: isBlend ? "Blend again from these generators' current files, keeping the settings below" : "Learn again from these regions, keeping the settings below" }, + }); relearnBtn.disabled = !sources.length; relearnBtn.addEventListener("click", () => { relearnBtn.disabled = true; @@ -290,43 +299,73 @@ export class GeneratorPanel { relearnBtn.disabled = false; return; } - new Notice(`Re-learned "${model.name}" from ${sources.join(" + ")}.`); + new Notice(`${isBlend ? "Re-blended" : "Re-learned"} "${model.name}" from ${sources.join(" + ")}.`); this.host.rerender(); }); }); const openBtn = sourceRow.createEl("button", { text: "Open file" }); openBtn.addEventListener("click", () => void this.app.workspace.getLeaf("tab").openFile(g.file)); - // A combined generator: how much each region counts. The sliders always - // add up to 100%; letting go of one re-learns with the new mix. + // A combined generator (regions learned together, or a blend of + // generators): how much each source counts, and which side of the map + // it leans toward. The sliders always add up to 100%; letting go of one, + // or picking a direction, re-makes the generator with the new mix. if (sources.length > 1) { const box = el.createDiv({ cls: "duckmage-wfc-influence" }); - box.createEl("label", { text: "Region influence", cls: "duckmage-map-field-label" }); + box.createEl("label", { text: isBlend ? "Blend" : "Region influence", cls: "duckmage-map-field-label" }); const stored = sourceInfluenceOf(model); - let weights = toPercents(stored ?? regionSizes(this.plugin, sources)); - const rows = sources.map((name) => { + let weights = toPercents(stored ?? (isBlend ? sources.map(() => 1) : regionSizes(this.plugin, sources))); + let dirs: Compass[] = sourceDirectionsOf(model) ?? sources.map((): Compass => "C"); + const arrows: Record = { NW: "↖", N: "↑", NE: "↗", W: "←", C: "•", E: "→", SW: "↙", S: "↓", SE: "↘" }; + const names: Record = { + NW: "north-west", N: "north", NE: "north-east", W: "west", C: "everywhere", E: "east", SW: "south-west", S: "south", SE: "south-east", + }; + const rows = sources.map((name, i) => { const row = box.createDiv({ cls: "duckmage-wfc-influence-row" }); row.createSpan({ text: name, cls: "duckmage-wfc-influence-name", attr: { title: name } }); const slider = row.createEl("input", { type: "range", attr: { min: "0", max: "100", step: "1", "aria-label": `${name} influence` } }); const value = row.createSpan({ cls: "duckmage-wfc-influence-value" }); - return { slider, value }; + // Compass: which side of the map this source leans toward. + const compass = row.createDiv({ cls: "duckmage-wfc-compass", attr: { role: "group", "aria-label": `${name} direction` } }); + const points = COMPASS.map((d) => { + const b = compass.createEl("button", { + text: arrows[d], + cls: "duckmage-wfc-compass-point", + attr: { title: d === "C" ? `${name}: everywhere (no direction)` : `${name}: lean ${names[d]}`, "aria-label": names[d] }, + }); + b.addEventListener("click", () => { + if (dirs[i] === d) return; + dirs = dirs.map((x, j) => (j === i ? d : x)); + showDirs(); + // A direction alone keeps a by-size mix by size. + remake(stored || isBlend ? weights : undefined, dirs); + }); + return { d, b }; + }); + return { slider, value, points }; }); const showWeights = () => rows.forEach((r, i) => { r.slider.value = String(weights[i]); r.value.setText(`${weights[i]}%`); }); + const showDirs = () => rows.forEach((r, i) => r.points.forEach((p) => p.b.toggleClass("is-active", p.d === dirs[i]))); showWeights(); + showDirs(); const note = box.createEl("p", { - text: stored - ? "Each region's share of what the generator learns." - : "Set by each region's size (painted hexes). Move a slider to choose your own mix.", + text: (stored || isBlend + ? `Each ${isBlend ? "generator" : "region"}'s share of the mix.` + : "Set by each region's size (painted hexes). Move a slider to choose your own mix.") + + " The arrows set which side of the map each one leans toward (• = everywhere); Directional bias sets how sharp the change is.", cls: "duckmage-map-origin-desc", }); - const relearnWith = (next: number[] | null) => { - note.setText("Re-learning…"); - for (const r of rows) r.slider.disabled = true; - void relearnGenerator(this.plugin, g, next).then((res) => { + const remake = (next: number[] | null | undefined, nextDirs: Compass[]) => { + note.setText(isBlend ? "Blending…" : "Re-learning…"); + for (const r of rows) { + r.slider.disabled = true; + for (const p of r.points) p.b.disabled = true; + } + void relearnGenerator(this.plugin, g, next, nextDirs).then((res) => { if ("error" in res) new Notice(res.error); this.host.rerender(); }); @@ -337,19 +376,19 @@ export class GeneratorPanel { weights = rebalance(weights, i, Number(r.slider.value)); showWeights(); }); - r.slider.addEventListener("change", () => relearnWith(weights)); - // Scroll to nudge by 5%; re-learn once the wheel stops. + r.slider.addEventListener("change", () => remake(weights, dirs)); + // Scroll to nudge by 5%; re-make once the wheel stops. r.slider.addEventListener("wheel", (e) => { e.preventDefault(); weights = rebalance(weights, i, wheelValue(weights[i], e.deltaY, { min: 0, max: 100, step: 5 })); showWeights(); if (wheelTimer !== null) window.clearTimeout(wheelTimer); - wheelTimer = window.setTimeout(() => relearnWith(weights), 500); + wheelTimer = window.setTimeout(() => remake(weights, dirs), 500); }, { passive: false }); }); - if (stored) { + if (stored && !isBlend) { const bySize = box.createEl("button", { text: "Back to region size", attr: { title: "Let each region count by how many hexes it has painted" } }); - bySize.addEventListener("click", () => relearnWith(null)); + bySize.addEventListener("click", () => remake(null, dirs)); } } diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index d7212c54..3ea6a9c6 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -31,6 +31,8 @@ import { type GeneratorSettings, resolveSettings, pathRouteKey, + isCompass, + type Compass, } from "../../packages/hex-wfc/src"; /** Frontmatter key that keeps a hex's terrain when a map is regenerated. */ @@ -161,12 +163,41 @@ const SOURCE_MAPS_JOIN = " + "; */ export const SOURCE_INFLUENCE_KEY = "source-influence"; +/** + * Meta key with the compass point each source leans toward, in source order: + * `source-direction: W + E` ("C" = everywhere). Missing means no direction. + */ +export const SOURCE_DIRECTION_KEY = "source-direction"; + +/** Meta key listing the generators a blend was made from: `blend-of: valley + deep-forest`. */ +export const BLEND_OF_KEY = "blend-of"; + +/** The generators a blend was made from (by name), or [] if it isn't one. */ +export function blendSourcesOf(model: HexWfcModel): string[] { + return model.meta[BLEND_OF_KEY]?.split(SOURCE_MAPS_JOIN).map((s) => s.trim()).filter(Boolean) ?? []; +} + +/** What a combined generator was made from: blended generators, else regions. */ +export function combinedSourcesOf(model: HexWfcModel): { kind: "blend" | "regions"; names: string[] } { + const blend = blendSourcesOf(model); + return blend.length ? { kind: "blend", names: blend } : { kind: "regions", names: sourceMapsOf(model) }; +} + +/** Each source's compass direction, or undefined when none is set. */ +export function sourceDirectionsOf(model: HexWfcModel): Compass[] | undefined { + const raw = model.meta[SOURCE_DIRECTION_KEY]; + if (!raw) return undefined; + const list = raw.split(SOURCE_MAPS_JOIN).map((v) => v.trim().toUpperCase()); + if (list.length !== combinedSourcesOf(model).names.length || !list.every(isCompass)) return undefined; + return list; +} + /** A combined generator's region influence (percent, one per region), or undefined if by size. */ export function sourceInfluenceOf(model: HexWfcModel): number[] | undefined { const raw = model.meta[SOURCE_INFLUENCE_KEY]; if (!raw) return undefined; const list = raw.split(SOURCE_MAPS_JOIN).map((v) => Number(v.trim())); - if (list.length !== sourceMapsOf(model).length || list.some((v) => !Number.isFinite(v) || v < 0)) return undefined; + if (list.length !== combinedSourcesOf(model).names.length || list.some((v) => !Number.isFinite(v) || v < 0)) return undefined; return list.reduce((n, v) => n + v, 0) > 0 ? list : undefined; } @@ -211,6 +242,7 @@ function learnFromMaps( name: string, meta: Record, influence?: number[], + directions?: Compass[], ): { model: HexWfcModel } | { error: string } { const models: HexWfcModel[] = []; for (const mapName of mapNames) { @@ -229,7 +261,7 @@ function learnFromMaps( meta, })); } - const model = models.length === 1 ? models[0] : mergeModels(models, name, meta, influence); + const model = models.length === 1 ? models[0] : mergeModels(models, name, meta, influence, directions); if (model.adjacency.length === 0) return { error: "No painted hexes touch each other, so there is nothing to learn yet." }; return { model }; @@ -471,7 +503,10 @@ export async function relearnGenerator( g: GeneratorFile, /** New influence per region; null = by region size; omitted = as stored. */ influence?: number[] | null, + /** New direction per region; omitted = as stored. */ + directions?: Compass[], ): Promise<{ model: HexWfcModel } | { error: string }> { + if (blendSourcesOf(g.model).length) return reblendGenerator(plugin, g, influence, directions); const mapNames = sourceMapsOf(g.model); if (!mapNames.length) return { error: "This generator doesn't record the region it came from." }; const missing = mapNames.filter((m) => !plugin.getMap(m)); @@ -480,10 +515,107 @@ export async function relearnGenerator( const meta = { ...g.model.meta, ...sourceMeta(plugin, mapNames) }; if (weights && mapNames.length > 1) meta[SOURCE_INFLUENCE_KEY] = weights.join(SOURCE_MAPS_JOIN); else delete meta[SOURCE_INFLUENCE_KEY]; - const learned = learnFromMaps(plugin, mapNames, g.model.name, meta, mapNames.length > 1 ? weights : undefined); + const dirs = directions ?? sourceDirectionsOf(g.model); + setDirections(meta, mapNames.length > 1 ? dirs : undefined); + const learned = learnFromMaps(plugin, mapNames, g.model.name, meta, mapNames.length > 1 ? weights : undefined, mapNames.length > 1 ? dirs : undefined); if ("error" in learned) return learned; const { model } = learned; - if (g.model.settings) model.settings = { ...g.model.settings }; + keepSettings(model, g.model, dirs); + await plugin.app.vault.modify(g.file, modelToMarkdown(model)); + return { model }; +} + +/** Record directions in meta, or drop the key when none lean anywhere. */ +function setDirections(meta: Record, dirs: Compass[] | undefined): void { + if (dirs?.some((d) => d !== "C")) meta[SOURCE_DIRECTION_KEY] = dirs.join(SOURCE_MAPS_JOIN); + else delete meta[SOURCE_DIRECTION_KEY]; +} + +/** + * Carry the old generator's settings onto a re-made one. Directions only + * work through directional bias, so it's switched on (1) if it was off. + */ +function keepSettings(model: HexWfcModel, old: HexWfcModel, dirs: Compass[] | undefined): void { + if (old.settings) model.settings = { ...old.settings }; + if (dirs?.some((d) => d !== "C") && !(model.settings?.directionalBias ?? 0)) + model.settings = { ...model.settings, directionalBias: 1 }; +} + +/** Default directions for a new blend: two sources run west to east; more start everywhere. */ +export function defaultBlendDirections(n: number): Compass[] { + return n === 2 ? ["W", "E"] : Array.from({ length: n }, (): Compass => "C"); +} + +/** Merge generators into one model (see mergeModels), with blend meta. */ +function blendModels( + plugin: HexmakerPlugin, + sources: HexWfcModel[], + name: string, + meta: Record, + influence: number[], + directions: Compass[], +): HexWfcModel { + const full: Record = { + ...meta, + [BLEND_OF_KEY]: sources.map((m) => m.name).join(SOURCE_MAPS_JOIN), + [SOURCE_INFLUENCE_KEY]: influence.join(SOURCE_MAPS_JOIN), + [VERSION_KEY]: pluginVersion(plugin), + }; + setDirections(full, directions); + return mergeModels(sources, name, full, influence, directions); +} + +/** + * Blend generators into a new one: their terrains, rules and paths combined, + * each leaning toward its own side of the map (two run west to east by + * default), so the result is the border country between them. Never + * overwrites: a name clash gets a numeric suffix. + */ +export async function saveBlendedGenerator( + plugin: HexmakerPlugin, + sources: GeneratorFile[], + rawName: string, +): Promise<{ file: TFile; model: HexWfcModel } | { error: string }> { + if (sources.length < 2) return { error: "Tick two or more generators to blend." }; + const name = slugify(rawName) || slugify(sources.map((g) => g.model.name).join("-to-")); + if (!name) return { error: "Enter a generator name." }; + const influence = sources.map(() => Math.round(100 / sources.length)); + const model = blendModels(plugin, sources.map((g) => g.model), name, { + palette: sources[0].model.meta.palette ?? "", + created: new Date().toISOString().slice(0, 10), + }, influence, defaultBlendDirections(sources.length)); + const folder = generatorsFolder(plugin); + let path = `${folder}/${name}.md`; + for (let n = 2; plugin.app.vault.getAbstractFileByPath(path); n++) { + path = `${folder}/${name}-${n}.md`; + model.name = `${name}-${n}`; + } + const file = await plugin.app.vault.create(path, modelToMarkdown(model)); + return { file, model }; +} + +/** + * Blend a blended generator again from its sources' current files, with new + * influence or directions (omitted = as stored; null influence = even). + * Keeps its name, settings and other metadata. Rewrites the file. + */ +export async function reblendGenerator( + plugin: HexmakerPlugin, + g: GeneratorFile, + influence?: number[] | null, + directions?: Compass[], +): Promise<{ model: HexWfcModel } | { error: string }> { + const names = blendSourcesOf(g.model); + const all = await listGenerators(plugin); + const sources = names.map((n) => all.find((x) => x.model.name === n || x.file.basename === n)); + const missing = names.filter((_, i) => !sources[i]); + if (missing.length) return { error: `Can't find the generator${missing.length === 1 ? "" : "s"} this blend came from: ${missing.join(", ")}.` }; + const stored = influence === null ? undefined : (influence ?? sourceInfluenceOf(g.model)); + const weights = stored ?? names.map(() => Math.round(100 / names.length)); + const dirs = directions ?? sourceDirectionsOf(g.model) ?? names.map((): Compass => "C"); + const found = sources.filter((x): x is GeneratorFile => !!x); + const model = blendModels(plugin, found.map((x) => x.model), g.model.name, { ...g.model.meta }, weights, dirs); + keepSettings(model, g.model, dirs); await plugin.app.vault.modify(g.file, modelToMarkdown(model)); return { model }; } diff --git a/styles.css b/styles.css index 634ca73f..e15967ee 100644 --- a/styles.css +++ b/styles.css @@ -5508,7 +5508,7 @@ button.duckmage-wfc-library-tab.is-active { .duckmage-wfc-influence-row { display: grid; - grid-template-columns: minmax(6em, 10em) 1fr 3.5em; + grid-template-columns: minmax(6em, 10em) 1fr 3.5em auto; align-items: center; gap: 0.6em; margin: 0.2em 0; @@ -5529,6 +5529,31 @@ button.duckmage-wfc-library-tab.is-active { font-variant-numeric: tabular-nums; } +/* Which side of the map a blended source leans toward: a 3×3 compass. */ +.duckmage-wfc-compass { + display: grid; + grid-template-columns: repeat(3, 1.4em); + grid-template-rows: repeat(3, 1.4em); + gap: 1px; +} + +.duckmage-wfc-compass-point { + width: 1.4em; + height: 1.4em; + min-width: 0; + padding: 0; + font-size: 0.75em; + line-height: 1; + box-shadow: none; + color: var(--text-muted); + background: var(--background-modifier-hover); +} + +.duckmage-wfc-compass-point.is-active { + color: var(--text-on-accent); + background: var(--interactive-accent); +} + .duckmage-wfc-preset-size { color: var(--text-muted); font-size: 0.85em; diff --git a/tests/hexWfcPlacement.test.ts b/tests/hexWfcPlacement.test.ts index 7000e39a..4ab5faff 100644 --- a/tests/hexWfcPlacement.test.ts +++ b/tests/hexWfcPlacement.test.ts @@ -2,6 +2,7 @@ import { describe, it } from "node:test"; import expect from "expect"; import { cellKey, + compassLayout, decodeSetting, encodeSetting, hexDistance, @@ -10,6 +11,7 @@ import { layoutValue, learnModel, measureNear, + mergeModels, modelToMarkdown, mulberry32, parseCellKey, @@ -248,3 +250,39 @@ describe("learning from an example", () => { expect(small.terrains[0].layout).toHaveLength(9); }); }); + +describe("blending generators toward compass points", () => { + const biome = (name: string, own: string): HexWfcModel => ({ + name, + meta: {}, + exampleHexes: 100, + terrains: [{ name: "grass", weight: 50 }, { name: own, weight: 50, shape: "blob", patch: 0.05, near: { terrain: "grass", distance: 3 } }], + adjacency: [{ a: "grass", b: "grass", weight: 5 }, { a: "grass", b: own, weight: 2 }, { a: own, b: own, weight: 5 }], + }); + const valley = biome("valley", "marsh"), forest = biome("forest", "forest heavy"); + + it("compass layouts average 1 and lean the right way", () => { + const east = compassLayout("E"); + expect(east.reduce((a, b) => a + b, 0) / 25).toBeCloseTo(1, 1); + expect(east[4]).toBeGreaterThan(east[0] * 5); // R1C5 vs R1C1 + expect(compassLayout("C").every((v) => v === 1)).toBe(true); + }); + + it("puts each source's own terrain on its side, and keeps near rules", () => { + const m = mergeModels([valley, forest], "v-to-f", {}, [50, 50], ["W", "E"]); + expect(m.settings?.directionalBias).toBeGreaterThanOrEqual(1); + expect(m.terrains.find((t) => t.name === "marsh")?.near).toEqual({ terrain: "grass", distance: 3 }); + let marshWest = 0, marshAll = 0, forestEast = 0, forestAll = 0; + for (let seed = 1; seed <= 4; seed++) { + const r = solve(m, { cols: 30, rows: 18, ...flat, seed }); + if (!r.ok) continue; + for (const [k, t] of r.cells) { + const x = parseCellKey(k)![0]; + if (t === "marsh") { marshAll++; if (x < 15) marshWest++; } + if (t === "forest heavy") { forestAll++; if (x >= 15) forestEast++; } + } + } + expect(marshWest / Math.max(1, marshAll)).toBeGreaterThan(0.75); + expect(forestEast / Math.max(1, forestAll)).toBeGreaterThan(0.75); + }); +}); From 719312cbdd9b69084ed377a147b1bbe765e2aadc Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 16:40:59 -0400 Subject: [PATCH 063/558] feat(worldgen): connected regions lean toward their neighbours blendFromNeighbours(plugin, own, {side: region}) learns each neighbouring region's painted terrain and blends it in (40% between them), leaning toward its side, so a new region next to deep forest turns to forest on that side. "Connect to" gains a "Lean toward neighbours" switch (on by default). Exported for the new-map setup's "Next to" as well. Co-Authored-By: Claude Opus 5.5 --- src/worldgen/GeneratorPanel.ts | 23 +++++++++++++--- src/worldgen/generators.ts | 2 +- src/worldgen/neighbours.ts | 49 +++++++++++++++++++++++++++++++--- 3 files changed, 67 insertions(+), 7 deletions(-) diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 0f97f886..f4e559b4 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -32,7 +32,7 @@ import { makeScrubbable, wheelValue } from "./scrub"; import { rebalance, toPercents } from "./regionWeights"; import { suggestImpassable } from "./impassableHint"; import { SIDES, type Side } from "./world"; -import { generateConnected, neighbourSpec, occupiedSides, placeNewRegion, regionNameAt, type NewRegion } from "./neighbours"; +import { blendFromNeighbours, generateConnected, neighbourSpec, NEIGHBOUR_SHARE, occupiedSides, placeNewRegion, regionNameAt, regionNeighbourNames, type NewRegion } from "./neighbours"; import { GeneratorLibrary } from "./GeneratorLibrary"; import { sizePresets } from "./sizePresets"; import { listSaves, writeSave, readSave, applySave, renameGenerator } from "./saves"; @@ -81,6 +81,8 @@ export class GeneratorPanel { static seedLocked = false; /** Generate the new map as a neighbouring region of an existing one. */ static connect: { anchor: string; side: Side } | null = null; + /** When connected: blend toward the neighbours' terrain (see blendFromNeighbours). */ + static leanToNeighbours = true; /** Titles of the setting sections folded away. */ static collapsed = new Set(); /** Path types whose routes are shown (groups start folded). */ @@ -513,6 +515,21 @@ export class GeneratorPanel { anchorSelect.addEventListener("change", setConnect); sideSelect.addEventListener("change", setConnect); if (connected) paletteSelect.disabled = true; + // Blend toward the neighbours, so the region is the border country + // between this generator and what's next door. + let genModel = model; + if (connected) { + const lean = el.createEl("label", { cls: "duckmage-region-row duckmage-wfc-toggle" }); + const box = lean.createEl("input", { type: "checkbox" }); + box.checked = GeneratorPanel.leanToNeighbours; + lean.createSpan({ text: "Lean toward neighbours" }); + lean.setAttr("title", `Blend in what the neighbouring regions look like (${NEIGHBOUR_SHARE}% between them), each toward its own side. Directional bias sets how sharp the change is.`); + box.addEventListener("change", () => { + GeneratorPanel.leanToNeighbours = box.checked; + this.host.rerender(); + }); + if (GeneratorPanel.leanToNeighbours) genModel = blendFromNeighbours(this.plugin, model, regionNeighbourNames(this.plugin, connected)); + } const showLock = () => { const locked = GeneratorPanel.seedLocked; @@ -641,7 +658,7 @@ export class GeneratorPanel { this.previewRows = grid.rows; this.seed = Number(seedInput.value) >>> 0; const palette = this.paletteTerrains().length ? this.paletteTerrains() : model.terrains.map((t) => t.name); - const r = connected ? generateConnected(this.plugin, model, palette, connected, this.seed) : generateTerrain(this.plugin, model, palette, grid, this.seed); + const r = connected ? generateConnected(this.plugin, genModel, palette, connected, this.seed) : generateTerrain(this.plugin, model, palette, grid, this.seed); if (!r.ok) { status.setText(`Couldn't generate: ${r.message}`); return; @@ -779,7 +796,7 @@ export class GeneratorPanel { return; } } - const generated = connected ? generateConnected(this.plugin, model, palette, connected, seed) : generateTerrain(this.plugin, model, palette, grid, seed); + const generated = connected ? generateConnected(this.plugin, genModel, palette, connected, seed) : generateTerrain(this.plugin, model, palette, grid, seed); if (!generated.ok) { new Notice(`Couldn't generate: ${generated.message}`); return; diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index 3ea6a9c6..c99352e9 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -82,7 +82,7 @@ export function generatorFitsPalette(model: HexWfcModel, paletteTerrains: string return placeable.length > 0 && placeable.every((t) => names.has(t.name)); } -function mapStagger(plugin: HexmakerPlugin, mapName: string): "odd" | "even" { +export function mapStagger(plugin: HexmakerPlugin, mapName: string): "odd" | "even" { return plugin.getMap(mapName)?.staggerOffset ?? plugin.settings.staggerOffset ?? "odd"; } diff --git a/src/worldgen/neighbours.ts b/src/worldgen/neighbours.ts index d1cede30..0025e561 100644 --- a/src/worldgen/neighbours.ts +++ b/src/worldgen/neighbours.ts @@ -1,14 +1,15 @@ /** * Neighbour regions in the vault: reading and saving where maps sit on their * shared grid (see world.ts for the rules), the terrain just past a map's - * edges, and generating a region that carries on from its neighbours. + * edges, and generating a region that carries on from its neighbours (its + * edge terrain, and optionally its whole character: blendFromNeighbours). */ import type HexmakerPlugin from "../HexmakerPlugin"; import type { MapData } from "../types"; import { getTerrainFromFile } from "../frontmatter"; -import { generateTerrain, type GridSpec } from "./generators"; -import type { HexWfcModel, SolveResult } from "../../packages/hex-wfc/src"; +import { generateTerrain, readMapTerrain, type GridSpec } from "./generators"; +import { learnModel, mergeModels, type Compass, type HexWfcModel, type SolveResult } from "../../packages/hex-wfc/src"; import { link, neighbours, @@ -208,3 +209,45 @@ export async function placeNewRegion(plugin: HexmakerPlugin, mapName: string, re } await plugin.saveSettings(); } + +/** How much of a blended region its neighbours make up between them (percent). */ +export const NEIGHBOUR_SHARE = 40; + +const SIDE_COMPASS: Record = { north: "N", east: "E", south: "S", west: "W" }; + +/** + * The generator for a region next to others, blended toward them: each + * neighbour's painted terrain is learned and leans toward its side, the + * region's own generator covers the rest (see mergeModels). A valley region + * with deep forest to the east comes out as valley turning to forest in the + * east. `neighbours` maps a side of the new region to the neighbour there; + * sides with nothing painted are skipped. Returns `own` when none are left. + */ +export function blendFromNeighbours( + plugin: HexmakerPlugin, + own: HexWfcModel, + neighbours: Partial>, + share = NEIGHBOUR_SHARE, +): HexWfcModel { + const models: HexWfcModel[] = [own]; + const dirs: Compass[] = ["C"]; + for (const side of SIDES) { + const name = neighbours[side]; + const map = name ? plugin.getMap(name) : undefined; + if (!name || !map) continue; + const cells = readMapTerrain(plugin, name); + if (cells.size < 2) continue; + models.push(learnModel(cells, { name, orientation: plugin.settings.hexOrientation, stagger: map.staggerOffset ?? "odd" })); + dirs.push(SIDE_COMPASS[side]); + } + if (models.length === 1) return own; + const each = share / (models.length - 1); + return mergeModels(models, own.name, { ...own.meta }, [100 - share, ...models.slice(1).map(() => each)], dirs); +} + +/** The neighbours of a new region by side (see occupiedSides), for blendFromNeighbours. */ +export function regionNeighbourNames(plugin: HexmakerPlugin, region: NewRegion): Partial> { + const out: Partial> = {}; + for (const side of occupiedSides(plugin, region)) out[side] = regionNameAt(plugin, region, side); + return out; +} From 806e2458a9246e29f4e77fc8117538bbd3136a6d Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 16:46:08 -0400 Subject: [PATCH 064/558] =?UTF-8?q?feat:=20map=20notes=20=E2=80=94=20per-h?= =?UTF-8?q?ex=20map=20data=20in=20one=20note=20per=20map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Terrain, icon, GM icons, region, submap and locked move out of hex-note frontmatter into hexes//_.md (settings in frontmatter, a sparse hex table and a paths table). Hex notes are created only when a hex gets content; new maps, generators and the paint tools write map data only. Migration runs once per map at startup: extract from hex frontmatter, write the map note, read it back and compare, back up as JSON, then strip the data keys from hex notes (bodies untouched; a hexmaker-map link is left). A failed read-back leaves that map's hex notes alone. Hex notes that still carry data on later starts (an interrupted cleanup, or an edit synced from an older device) are folded back in and cleaned. The frontmatter getters/setters route to MapStore once it is ready, so most call sites are unchanged; the grid render, hex table, exporters, submap links, map rename/delete and terrain rename read the store. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 159 +++++----- src/export/exporters/hexcrawlManual.ts | 7 +- src/export/mapPngRenderer.ts | 5 +- src/frontmatter.ts | 42 +++ src/hex-map/HexMapView.ts | 40 +-- src/hex-map/MapModal.ts | 14 +- src/hex-table/HexTableView.ts | 23 ++ src/hex-table/HexTerrainPickerModal.ts | 2 +- src/maps/MapStore.ts | 388 +++++++++++++++++++++++++ src/maps/mapNote.ts | 322 ++++++++++++++++++++ src/worldgen/generators.ts | 2 +- tests/__mocks__/obsidian.ts | 8 +- tests/helpers/memVault.ts | 127 ++++++++ tests/helpers/miniYaml.ts | 40 +++ tests/mapNote.test.ts | 123 ++++++++ tests/mapStore.test.ts | 201 +++++++++++++ 17 files changed, 1392 insertions(+), 115 deletions(-) create mode 100644 src/maps/MapStore.ts create mode 100644 src/maps/mapNote.ts create mode 100644 tests/helpers/memVault.ts create mode 100644 tests/helpers/miniYaml.ts create mode 100644 tests/mapNote.test.ts create mode 100644 tests/mapStore.test.ts diff --git a/package.json b/package.json index 9efdf37c..2283e1b3 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index e9e8f4f3..63f3b0c9 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -44,7 +44,8 @@ import type { } from "./types"; import DEFAULT_HEX_TEMPLATE from "./defaultHexTemplate.md"; import { migrateMapData, pluginVersion } from "./compat"; -import { getTerrainFromFile, setTerrainInFile, setSubmapInFile, withFrontmatterField, notePendingTerrain, clearPendingTerrain } from "./frontmatter"; +import { getTerrainFromFile, getHexRegionFromFile, clearPendingTerrain, setHexDataSource } from "./frontmatter"; +import { MapStore } from "./maps/MapStore"; import { addLinkToSection, getLinksInSection, @@ -58,16 +59,21 @@ export default class HexmakerPlugin extends Plugin { availableIcons: string[] = []; vaultIconsSet: Set = new Set(); paletteStore = new PaletteStore(this); + /** Per-hex map data, backed by one map note per map (src/maps). */ + mapStore = new MapStore(this); async onload() { await this.loadSettings(); + setHexDataSource(this.mapStore); // Notes written by this plugin are read from memory until indexed (see frontmatter.ts). this.registerEvent(this.app.metadataCache.on("changed", (file) => clearPendingTerrain(file.path))); // Defer until vault metadata cache is ready; calling before layout-ready // returns null for all vault paths so custom icons are silently dropped. this.app.workspace.onLayoutReady(() => { this.loadAvailableIcons(); - void this.paletteStore.init(); + // Palettes first (maps reference them), then map notes — which may + // migrate per-hex data out of hex notes on the first run. + void this.paletteStore.init().then(() => this.mapStore.init()); void this.autoRegisterMapsFromVault(); if (!this.settings.setupComplete && !this.settings.setupDismissed) { this.openSetupWizard(); @@ -105,7 +111,10 @@ export default class HexmakerPlugin extends Plugin { ); // Palette notes edited by hand (or by sync) flow back into the palettes. this.registerEvent( - this.app.vault.on("modify", (f) => this.paletteStore.onModify(f)), + this.app.vault.on("modify", (f) => { + this.paletteStore.onModify(f); + this.mapStore.onModify(f); + }), ); await this.migrateHexFilesToDefaultRegion(); @@ -530,6 +539,7 @@ export default class HexmakerPlugin extends Plugin { await this.saveData(this.settings); // Mirror palette edits (from any editor) into the palette notes. void this.paletteStore.sync(); + void this.mapStore.sync(); // Settings hold map-level state (paths, palette, grid size, overlays). // A save made from one view/window leaves sibling map views stale — // flag them so they re-render on next activation (issue #32). The @@ -720,14 +730,10 @@ export default class HexmakerPlugin extends Plugin { /** Update duckmage-submap frontmatter in all hex notes when a map is renamed. */ async updateSubmapReferences(oldName: string, newName: string): Promise { - const hexFolder = normalizeFolder(this.settings.hexFolder); - const files = this.app.vault.getMarkdownFiles().filter( - (f) => !hexFolder || f.path.startsWith(hexFolder + "/"), - ); - for (const file of files) { - const submap: unknown = this.app.metadataCache.getFileCache(file)?.frontmatter?.["duckmage-submap"]; - if (submap !== oldName) continue; - await setSubmapInFile(this.app, file.path, newName); + for (const m of this.settings.maps) { + for (const [key, h] of this.mapStore.all(m.name)) { + if (h.submap === oldName) this.mapStore.set(m.name, key, { submap: newName }); + } } this.noParentMaps.clear(); // Children of the renamed map keep their breadcrumb. @@ -958,6 +964,9 @@ export default class HexmakerPlugin extends Plugin { hexFilePath: string, terrain: string | null, ): Promise { + // The link lives in the hex note's body; a hex without a note gets it + // when its note is created (createHexNote adds it). + if (!(this.app.vault.getAbstractFileByPath(hexFilePath) instanceof TFile)) return; const tablesFolder = normalizeFolder(this.settings.tablesFolder); const subfolder = tablesFolder ? `${tablesFolder}/terrain` : "terrain"; @@ -1122,9 +1131,8 @@ export default class HexmakerPlugin extends Plugin { let linked = 0; for (const file of hexFiles) { - const cache = this.app.metadataCache.getFileCache(file); - const region: unknown = cache?.frontmatter?.["region"]; - if (typeof region !== "string" || !region) continue; + const region = getHexRegionFromFile(this.app, file.path); + if (!region) continue; await this.syncHexRegionTableLink(file.path, region); linked++; } @@ -1142,27 +1150,19 @@ export default class HexmakerPlugin extends Plugin { oldName: string, newName: string, ): Promise> { - const hexFolder = normalizeFolder(this.settings.hexFolder); - const candidates = this.app.vault.getMarkdownFiles().filter((f) => { - if (hexFolder && !f.path.startsWith(hexFolder + "/")) return false; - return /^(-?\d+)_(-?\d+)\.md$/.test(f.name); - }); + // Terrain lives in map notes: rename it there (in memory now, notes + // follow). Hex notes no longer carry terrain. const overrides = new Map(); - const CHUNK = 10; - for (let i = 0; i < candidates.length; i += CHUNK) { - await Promise.all( - candidates.slice(i, i + CHUNK).map(async (f) => { - // Read raw content — don't trust the stale metadata cache - const content = await this.app.vault.read(f); - const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/); - if (!fmMatch) return; - const terrainLine = fmMatch[1].match(/^\s*terrain:\s*(.+)$/m); - if (!terrainLine || terrainLine[1].trim() !== oldName) return; - await setTerrainInFile(this.app, f.path, newName); - overrides.set(f.path, newName); - }), - ); + for (const m of this.settings.maps) { + for (const [key, h] of this.mapStore.all(m.name)) { + if (h.terrain !== oldName) continue; + this.mapStore.set(m.name, key, { terrain: newName }); + const [x, y] = key.split("_").map(Number); + overrides.set(this.hexPath(x, y, m.name), newName); + } + if (m.baseTerrain === oldName) m.baseTerrain = newName; } + await this.mapStore.flush(); return overrides; } @@ -1246,9 +1246,9 @@ export default class HexmakerPlugin extends Plugin { .replace(/\{\{y\}\}/g, String(y)) .replace(/\{\{title\}\}/g, `Hex ${x}, ${y}`); if (terrain) { - content = withFrontmatterField(content, "terrain", terrain); - // Add the terrain's encounter-table link now rather than reading the - // note back and rewriting it after it's created. + // Terrain is map data (map note); the note only gets the terrain's + // encounter-table link, added now rather than patched in later. + this.mapStore.set(mapName, `${x}_${y}`, { terrain }); const table = this.terrainEncounterTable(terrain); if (table) { const linkText = `[[${this.app.metadataCache.fileToLinktext(table, path)}]]`; @@ -1268,9 +1268,7 @@ export default class HexmakerPlugin extends Plugin { } try { - const file = await this.app.vault.create(path, content); - if (terrain) notePendingTerrain(path, terrain); - return file; + return await this.app.vault.create(path, content); } catch { // A concurrent worker may have created this file between our existence check and // this create call. If the file now exists, use it rather than treating it as an error. @@ -1372,38 +1370,36 @@ export default class HexmakerPlugin extends Plugin { }); await this.saveSettings(); - let created: number; - if (extra.baseTerrain) { - // Notes on use: write only hexes that differ from the base terrain. - const painted = [...(terrainAt ?? new Map())] - .filter(([, t]) => t && t !== extra.baseTerrain); - created = await this.generateHexNotesAt(name, painted, (done) => onProgress?.(done, painted.length)); - } else { - const xs = Array.from({ length: cols }, (_, i) => i + initialX); - const ys = Array.from({ length: rows }, (_, i) => i + initialY); - const total = cols * rows; - created = await this.generateHexNotes( - name, - xs, - ys, - (done) => onProgress?.(done, total), - terrainAt, - ); - } - if (created > 0 && !extra.quiet) - new Notice( - `Hexmaker: generated ${created} hex note${created !== 1 ? "s" : ""} for "${name}".`, - ); + // Notes on use: a new map writes no hex notes — terrain goes into the + // map note, and a hex note appears when the hex first gets content. + const cells = [...(terrainAt ?? new Map())] + .filter(([, t]) => t && t !== extra.baseTerrain) + .map(([k, t]): [string, { terrain: string }] => [k, { terrain: t }]); + this.mapStore.setMany(name, cells); + onProgress?.(cols * rows, cols * rows); + await this.mapStore.flush(); + if (!extra.quiet) new Notice(`Hexmaker: created map "${name}".`); return { name }; } - /** Create notes for specific hexes ("x_y" → terrain), skipping ones that exist. */ + /** + * Set terrain for specific hexes ("x_y" → terrain). With map notes this + * writes map data only — hex notes are created when a hex gets content — + * so it returns 0 notes created. Falls back to creating notes only if the + * map store isn't ready yet. + */ async generateHexNotesAt( mapName: string, cells: [string, string][], onProgress?: (done: number) => void, ): Promise { + if (this.mapStore.isReady()) { + this.mapStore.setMany(mapName, cells.filter(([, t]) => t).map(([k, t]) => [k, { terrain: t }])); + onProgress?.(cells.length); + await this.mapStore.flush(); + return 0; + } const template = await this.loadHexTemplate(); if (template === null) return 0; let created = 0; @@ -1431,6 +1427,16 @@ export default class HexmakerPlugin extends Plugin { onProgress?: (done: number) => void, terrainAt?: Map, ): Promise { + if (this.mapStore.isReady()) { + const cells: [string, string][] = []; + for (const x of xs) for (const y of ys) { + const t = terrainAt?.get(`${x}_${y}`); + if (t) cells.push([`${x}_${y}`, t]); + } + if (cells.length) return this.generateHexNotesAt(mapName, cells); + onProgress?.(xs.length * ys.length); + return 0; + } // Read template once — avoids N vault reads for the same file const template = await this.loadHexTemplate(); if (template === null) return 0; @@ -1517,11 +1523,7 @@ export default class HexmakerPlugin extends Plugin { * second hex doesn't move its breadcrumb). */ async linkSubmap(parentMap: string, x: number, y: number, childMap: string): Promise { - const hexPath = this.hexPath(x, y, parentMap); - if (!this.app.vault.getAbstractFileByPath(hexPath)) { - await this.createHexNote(x, y, parentMap); - } - await setSubmapInFile(this.app, hexPath, childMap); + this.mapStore.set(parentMap, `${x}_${y}`, { submap: childMap }); this.noParentMaps.clear(); const child = this.getMap(childMap); if (child && !child.parent && childMap !== parentMap) { @@ -1532,9 +1534,8 @@ export default class HexmakerPlugin extends Plugin { /** Remove the submap link from hex (x, y); clears the child's parent if it pointed here. */ async unlinkSubmap(parentMap: string, x: number, y: number): Promise { - const hexPath = this.hexPath(x, y, parentMap); - const fm: unknown = this.app.metadataCache.getCache(hexPath)?.frontmatter?.["duckmage-submap"]; - await setSubmapInFile(this.app, hexPath, null); + const fm = this.mapStore.get(parentMap, `${x}_${y}`)?.submap; + this.mapStore.set(parentMap, `${x}_${y}`, { submap: null }); this.noParentMaps.clear(); const child = typeof fm === "string" ? this.getMap(fm) : undefined; if (child?.parent?.map === parentMap && child.parent.hex === `${x}_${y}`) { @@ -1554,16 +1555,14 @@ export default class HexmakerPlugin extends Plugin { if (map.parent && this.getMap(map.parent.map)) return map.parent; // Root maps have no parent; don't rescan the hex notes on every switch. if (this.noParentMaps.has(mapName)) return undefined; - const hexFolder = normalizeFolder(this.settings.hexFolder); - for (const file of this.app.vault.getMarkdownFiles()) { - if (hexFolder && !file.path.startsWith(hexFolder + "/")) continue; - const submap: unknown = this.app.metadataCache.getFileCache(file)?.frontmatter?.["duckmage-submap"]; - if (submap !== mapName) continue; - const parentMap = file.parent?.name; - if (!parentMap || parentMap === mapName || !this.getMap(parentMap)) continue; - map.parent = { map: parentMap, hex: file.basename }; - void this.saveSettings(); - return map.parent; + for (const m of this.settings.maps) { + if (m.name === mapName) continue; + for (const [key, h] of this.mapStore.all(m.name)) { + if (h.submap !== mapName) continue; + map.parent = { map: m.name, hex: key }; + void this.saveSettings(); + return map.parent; + } } this.noParentMaps.add(mapName); return undefined; diff --git a/src/export/exporters/hexcrawlManual.ts b/src/export/exporters/hexcrawlManual.ts index d54db44f..1850bb22 100644 --- a/src/export/exporters/hexcrawlManual.ts +++ b/src/export/exporters/hexcrawlManual.ts @@ -15,7 +15,7 @@ import { exportToPdfBytes } from "../pdfExporter"; import { ensureExportFolder } from "../exportFolder"; import { renderMapToPngBlob } from "../mapPngRenderer"; import { getAllSectionData } from "../../sections"; -import { getFrontMatter, terrainFromFm } from "../../frontmatter"; +import { getHexRegionFromFile, getTerrainFromFile } from "../../frontmatter"; import { getIconUrl, normalizeFolder } from "../../utils"; import { parseRandomTable, getDieRanges } from "../../random-tables/randomTable"; import DEFAULT_HEX_TEMPLATE from "../../defaultHexTemplate.md"; @@ -134,9 +134,8 @@ export async function collectManualData( const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) continue; hexCount++; - const fm = getFrontMatter(app, path); - const terrain = terrainFromFm(fm) ?? ""; - const region = typeof fm?.region === "string" ? fm.region : ""; + const terrain = getTerrainFromFile(app, path) ?? ""; + const region = getHexRegionFromFile(app, path) ?? ""; if (terrain) terrainCounts.set(terrain, (terrainCounts.get(terrain) ?? 0) + 1); if (region) regionCounts.set(region, (regionCounts.get(region) ?? 0) + 1); diff --git a/src/export/mapPngRenderer.ts b/src/export/mapPngRenderer.ts index e6d9755d..3379115f 100644 --- a/src/export/mapPngRenderer.ts +++ b/src/export/mapPngRenderer.ts @@ -31,6 +31,7 @@ import { getRegionColorFromFile, getFactionStyleFromFile, getRegionStyleFromFile, + getHexRegionFromFile, type OverlayStyle, } from "../frontmatter"; import { getIconUrl, normalizeFolder } from "../utils"; @@ -789,9 +790,7 @@ function getHexFactionLinks(app: App, file: TFile): string[] { /** Read the `region:` frontmatter of a hex note via metadata cache. */ function getHexRegionName(app: App, file: TFile): string | null { - const cache = app.metadataCache.getFileCache(file); - const region: unknown = cache?.frontmatter?.["region"]; - return typeof region === "string" ? region : null; + return getHexRegionFromFile(app, file.path); } function dashFor(style: "solid" | "dashed" | "dotted"): number[] { diff --git a/src/frontmatter.ts b/src/frontmatter.ts index 891463a2..e68dbf63 100644 --- a/src/frontmatter.ts +++ b/src/frontmatter.ts @@ -67,6 +67,28 @@ export function withFrontmatterField(content: string, key: string, value: string return `---\n${newBody}\n---${m[2]}${content.slice(m[0].length)}`; } +/** + * Per-hex map data (terrain, icon, GM icons, region, submap) lives in map + * notes (see src/maps/MapStore.ts), not in hex-note frontmatter. Once the + * store is ready, the hex getters/setters below route to it; before that + * (startup) and for non-hex paths they fall back to frontmatter. + */ +export interface HexDataSource { + isReady(): boolean; + resolve(path: string): { map: string; key: string } | null; + get(map: string, key: string): import("./maps/mapNote").HexData | undefined; + set(map: string, key: string, patch: Record): void; +} +let hexSource: HexDataSource | null = null; +export function setHexDataSource(src: HexDataSource | null): void { + hexSource = src; +} +/** The store location for a hex-note path, when the store is serving it. */ +function hexLoc(path: string): { map: string; key: string } | null { + if (!hexSource?.isReady()) return null; + return hexSource.resolve(path); +} + export function getFrontMatter(app: App, path: string) { const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return null; @@ -124,6 +146,8 @@ export function pendingTerrainOf(path: string): string | null { } export function getTerrainFromFile(app: App, path: string): string | null { + const loc = hexLoc(path); + if (loc) return hexSource!.get(loc.map, loc.key)?.terrain ?? null; const fm = getFrontMatter(app, path); return fm ? terrainFromFm(fm) : pendingTerrainOf(path); } @@ -133,6 +157,8 @@ export async function setTerrainInFile( path: string, terrainKey: string | null, ): Promise { + const loc = hexLoc(path); + if (loc) { hexSource!.set(loc.map, loc.key, { terrain: terrainKey }); return true; } const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { @@ -206,6 +232,8 @@ export async function setFactionStyleInFile( } export function getHexRegionFromFile(app: App, path: string): string | null { + const loc = hexLoc(path); + if (loc) return hexSource!.get(loc.map, loc.key)?.region ?? null; const region = getFrontMatter(app, path)?.["region"]; return typeof region === "string" ? region : null; } @@ -215,6 +243,8 @@ export async function setHexRegionInFile( path: string, regionName: string | null, ): Promise { + const loc = hexLoc(path); + if (loc) { hexSource!.set(loc.map, loc.key, { region: regionName }); return true; } const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { @@ -288,6 +318,8 @@ export async function setRegionStyleInFile( } export function getIconOverrideFromFile(app: App, path: string): string | null { + const loc = hexLoc(path); + if (loc) return hexSource!.get(loc.map, loc.key)?.icon ?? null; return iconOverrideFromFm(getFrontMatter(app, path)); } @@ -296,6 +328,8 @@ export async function setIconOverrideInFile( path: string, icon: string | null, ): Promise { + const loc = hexLoc(path); + if (loc) { hexSource!.set(loc.map, loc.key, { icon }); return true; } const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { @@ -326,6 +360,8 @@ export function getGmIconFromFile(app: App, path: string): string | null { * singular key `gm-icon` if present so existing notes Just Work. */ export function getGmIconsFromFile(app: App, path: string): string[] { + const loc = hexLoc(path); + if (loc) return [...(hexSource!.get(loc.map, loc.key)?.gmIcons ?? [])]; return gmIconsFromFm(getFrontMatter(app, path)); } @@ -354,6 +390,8 @@ export async function setGmIconsInFile( path: string, icons: string[], ): Promise { + const loc = hexLoc(path); + if (loc) { hexSource!.set(loc.map, loc.key, { gmIcons: [...icons] }); return true; } const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { @@ -499,6 +537,8 @@ export async function applyTokenFrontmatter( } export function getSubmapFromFile(app: App, path: string): string | undefined { + const loc = hexLoc(path); + if (loc) return hexSource!.get(loc.map, loc.key)?.submap; const val = getFrontMatter(app, path)?.["duckmage-submap"]; return typeof val === "string" ? val : undefined; } @@ -508,6 +548,8 @@ export async function setSubmapInFile( path: string, mapName: string | null, ): Promise { + const loc = hexLoc(path); + if (loc) { hexSource!.set(loc.map, loc.key, { submap: mapName }); return true; } const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 3c239dd6..7119d351 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -18,7 +18,7 @@ import { HexEditorModal } from "./HexEditorModal"; import { TerrainPickerModal } from "./TerrainPickerModal"; import { IconPickerModal } from "./IconPickerModal"; import { addLinkToSection, getLinksInSection, removeLinkFromSection } from "../sections"; -import { getFactionColorFromFile, getRegionColorFromFile, getFactionStyleFromFile, getRegionStyleFromFile, setHexRegionInFile, getSubmapFromFile, type OverlayStyle } from "../frontmatter"; +import { getFactionColorFromFile, getRegionColorFromFile, getFactionStyleFromFile, getRegionStyleFromFile, setHexRegionInFile, getHexRegionFromFile, getSubmapFromFile, type OverlayStyle } from "../frontmatter"; import { buildSvgPattern, colorToIdToken, type OverlayPatternKey } from "../overlayPatterns"; import { renderHexPreview } from "./overlayPatternControls"; import { @@ -1373,13 +1373,11 @@ export class HexMapView extends ItemView { } private hexHasContent(path: string): boolean { + if (getTerrainFromFile(this.app, path)) return true; const file = this.app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; const cache = this.app.metadataCache.getFileCache(file); - if (!cache) return false; - if (cache.frontmatter?.terrain) return true; - if (cache.links && cache.links.length > 0) return true; - return false; + return !!cache?.links && cache.links.length > 0; } private buildDrawingToolbarContent(toolbar: HTMLElement): void { @@ -3396,11 +3394,15 @@ export class HexMapView extends ItemView { // getGmIconsFromFile separately would re-run getAbstractFileByPath + // getFileCache three times per hex (~11.5k redundant lookups on a // 3843-hex map). - const fm = getFrontMatter(this.app, path); - // A note this plugin just wrote may not be indexed yet (new maps write - // thousands at once); its terrain is held in memory until it is. + // Before the map store is ready (startup), fall back to frontmatter. + const fromStore = this.plugin.mapStore.isReady(); + const fm = fromStore ? null : getFrontMatter(this.app, path); + const stored = fromStore ? this.plugin.mapStore.get(this.activeMapName, `${x}_${y}`) : undefined; + // A note this plugin just wrote may not be indexed yet; its terrain is + // held in memory until it is. const terrainKey = terrainOverrides?.has(path) ? terrainOverrides.get(path)! + : fromStore ? stored?.terrain ?? null : fm ? terrainFromFm(fm) : pendingTerrainOf(path); // Hexes with no terrain (often no note at all — notes are created on // use) show the map's base terrain, e.g. "void" on a system map. @@ -3418,7 +3420,7 @@ export class HexMapView extends ItemView { const iconOverride = iconOverrides?.has(path) ? iconOverrides.get(path)! - : iconOverrideFromFm(fm); + : fromStore ? stored?.icon ?? null : iconOverrideFromFm(fm); if (iconOverride) { // Render terrain icon as hidden fallback — shown by CSS when overrides are off if (terrainEntry?.icon) { @@ -3459,7 +3461,7 @@ export class HexMapView extends ItemView { // list lands on the dataset immediately, no race. const gmIcons = gmIconsOverrides?.has(path) ? gmIconsOverrides.get(path)! - : gmIconsFromFm(fm); + : fromStore ? [...(stored?.gmIcons ?? [])] : gmIconsFromFm(fm); if (gmIcons.length > 0) hexEl.dataset.gmIcons = JSON.stringify(gmIcons); if (this.selectedHex?.x === x && this.selectedHex?.y === y) @@ -4583,7 +4585,9 @@ export class HexMapView extends ItemView { window.setTimeout(r, Math.min(200 * (1 << (attempt - 1)), 2000)), ); try { - const onDisk = !!this.app.vault.getAbstractFileByPath(path); + // Map data lives in the map note once the store is ready, so + // painting never needs (or creates) a hex note. + const onDisk = this.plugin.mapStore.isReady() || !!this.app.vault.getAbstractFileByPath(path); if (terrain === null) { if (onDisk) { await setTerrainInFile(this.app, path, null); @@ -4650,7 +4654,9 @@ export class HexMapView extends ItemView { window.setTimeout(r, Math.min(200 * (1 << (attempt - 1)), 2000)), ); try { - const onDisk = !!this.app.vault.getAbstractFileByPath(path); + // Map data lives in the map note once the store is ready, so + // painting never needs (or creates) a hex note. + const onDisk = this.plugin.mapStore.isReady() || !!this.app.vault.getAbstractFileByPath(path); if (icon === null) { if (onDisk) await setIconOverrideInFile(this.app, path, null); } else { @@ -4719,7 +4725,9 @@ export class HexMapView extends ItemView { window.setTimeout(r, Math.min(200 * (1 << (attempt - 1)), 2000)), ); try { - const onDisk = !!this.app.vault.getAbstractFileByPath(path); + // Map data lives in the map note once the store is ready, so + // painting never needs (or creates) a hex note. + const onDisk = this.plugin.mapStore.isReady() || !!this.app.vault.getAbstractFileByPath(path); if (list.length === 0) { if (onDisk) await setGmIconsInFile(this.app, path, []); } else { @@ -5702,11 +5710,7 @@ export class HexMapView extends ItemView { if (this.erasedRegions.has(hexFilePath)) return null; const pending = this.pendingRegions.get(hexFilePath); if (pending !== undefined) return pending; - const file = this.app.vault.getAbstractFileByPath(hexFilePath); - if (!(file instanceof TFile)) return null; - const cache = this.app.metadataCache.getFileCache(file); - const region: unknown = cache?.frontmatter?.["region"]; - return typeof region === "string" ? region : null; + return getHexRegionFromFile(this.app, hexFilePath); } private updateRegionOverlay(): void { diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 731192c3..9ceec085 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -4,7 +4,6 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import type { MapData } from "../types"; import type { HexMapView } from "./HexMapView"; import { normalizeFolder, slugify, getIconUrl, createIconEl, importBinaryFileToVault } from "../utils"; -import { getSubmapFromFile, setSubmapInFile } from "../frontmatter"; import { exportMapAsPng } from "../export/mapPngRenderer"; import { exportMapAsPdf } from "../export/exporters/mapWithTable"; import { exportMapAsManual } from "../export/exporters/hexcrawlManual"; @@ -1013,10 +1012,13 @@ export class MapModal extends HexmakerModal { this.view.activeMapName = this.plugin.settings.maps[0]?.name ?? ""; } - const submapRefs = this.app.vault.getMarkdownFiles().filter( - (f) => getSubmapFromFile(this.app, f.path) === name, - ); - await Promise.all(submapRefs.map((f) => setSubmapInFile(this.app, f.path, null))); + // Hexes pointing at the deleted map lose their submap link. + this.plugin.mapStore.forgetMap(name); + for (const m of this.plugin.settings.maps) { + for (const [key, h] of this.plugin.mapStore.all(m.name)) { + if (h.submap === name) this.plugin.mapStore.set(m.name, key, { submap: null }); + } + } this.confirmingDelete = null; await this.plugin.saveSettings(); @@ -1061,6 +1063,8 @@ export class MapModal extends HexmakerModal { const oldName = this.view.activeMapName; const map = this.plugin.getMap(oldName); if (map) map.name = newName; + // The map note moved with its folder; give it the new name too. + await this.plugin.mapStore.renameMap(oldName, newName); if (this.plugin.settings.defaultMap === oldName) { this.plugin.settings.defaultMap = newName; } diff --git a/src/hex-table/HexTableView.ts b/src/hex-table/HexTableView.ts index 40e74181..06959482 100644 --- a/src/hex-table/HexTableView.ts +++ b/src/hex-table/HexTableView.ts @@ -404,6 +404,18 @@ export class HexTableView extends ItemView { }), ); + // Map data (terrain, region, …) changes in the map store, not in hex + // notes: reload once painting settles. + let storeTimer: number | undefined; + const offStore = this.plugin.mapStore.onChange(() => { + window.clearTimeout(storeTimer); + storeTimer = window.setTimeout(() => void this.loadTable(), 500); + }); + this.register(() => { + offStore(); + window.clearTimeout(storeTimer); + }); + void this.loadTable(); return Promise.resolve(); } @@ -457,6 +469,17 @@ export class HexTableView extends ItemView { return; } + // Hexes with map data (terrain, region, …) but no note yet — notes are + // created on use, so the map note is the other half of the list. + const seen = new Set(files.map((f) => f.path)); + for (const m of this.plugin.settings.maps) { + for (const key of this.plugin.mapStore.all(m.name).keys()) { + const [x, y] = key.split("_").map(Number); + const path = this.plugin.hexPath(x, y, m.name); + if (!seen.has(path)) files.push({ path, x, y, region: m.name }); + } + } + // Apply region filter if (this.mapFilter !== "all") { const prefix = hexFolder diff --git a/src/hex-table/HexTerrainPickerModal.ts b/src/hex-table/HexTerrainPickerModal.ts index f56a709d..40a7be1c 100644 --- a/src/hex-table/HexTerrainPickerModal.ts +++ b/src/hex-table/HexTerrainPickerModal.ts @@ -37,7 +37,7 @@ export class HexTerrainPickerModal extends HexmakerModal { btn.createSpan({ text: entry.name, cls: "duckmage-terrain-option-name" }); btn.addEventListener("click", () => { void (async () => { - if (!this.app.vault.getAbstractFileByPath(this.hexPath)) { + if (!this.plugin.mapStore.isReady() && !this.app.vault.getAbstractFileByPath(this.hexPath)) { const basename = this.hexPath.replace(/\.md$/, "").split("/").pop()!; const [hx, hy] = basename.split("_").map(Number); const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts new file mode 100644 index 00000000..20e53b8c --- /dev/null +++ b/src/maps/MapStore.ts @@ -0,0 +1,388 @@ +import { Notice, TAbstractFile, TFile, TFolder, parseYaml } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { MapData } from "../types"; +import { normalizeFolder } from "../utils"; +import { + buildMapNote, + mapNoteKey, + parseMapNote, + updateMapNote, + type HexData, + type MapNoteData, +} from "./mapNote"; + +/** Hex-note frontmatter keys that hold map data (moved into the map note). */ +export const HEX_DATA_KEYS = ["terrain", "icon", "gm-icons", "gm-icon", "region", "duckmage-submap", "locked"] as const; +/** Pointer left in a cleaned hex note's frontmatter. */ +export const MAP_LINK_KEY = "hexmaker-map"; + +const HEX_FILE = /^(-?\d+)_(-?\d+)\.md$/; + +/** Read map data out of a hex note's frontmatter (pre-migration notes). */ +export function hexDataFromFrontmatter(fm: Record | null | undefined): HexData { + const h: HexData = {}; + if (!fm) return h; + if (typeof fm.terrain === "string" && fm.terrain) h.terrain = fm.terrain; + if (typeof fm.icon === "string" && fm.icon) h.icon = fm.icon; + const gm = Array.isArray(fm["gm-icons"]) ? fm["gm-icons"].filter((v): v is string => typeof v === "string") + : typeof fm["gm-icon"] === "string" ? [fm["gm-icon"]] : []; + if (gm.length) h.gmIcons = gm; + if (typeof fm.region === "string" && fm.region) h.region = fm.region; + if (typeof fm["duckmage-submap"] === "string" && fm["duckmage-submap"]) h.submap = fm["duckmage-submap"]; + if (fm.locked === true || fm.locked === "true") h.locked = true; + return h; +} + +/** + * Per-hex map data for every map, backed by one map note per map + * ("//_.md"). Reads are synchronous from memory; + * writes update memory at once and reach the note debounced, so painting a + * hundred hexes is one write, not a hundred. + * + * The map's settings (MapData) stay in settings.maps as the working copy + * (every reader is synchronous) and data.json keeps a cache; the note wins + * on load, like palette notes. + */ +export class MapStore { + private hexes = new Map>(); + /** Content we last wrote/read per note path (echo suppression). */ + private lastContent = new Map(); + /** Map-data key we last wrote per map (skip no-op writes). */ + private lastKey = new Map(); + private dirty = new Set(); + private writeTimer: number | undefined; + private ready = false; + private queue: Promise = Promise.resolve(); + private listeners = new Set<(map: string) => void>(); + + constructor(private plugin: HexmakerPlugin) {} + + isReady(): boolean { + return this.ready; + } + + // ── paths ──────────────────────────────────────────────────────────── + + private hexFolder(): string { + return normalizeFolder(this.plugin.settings.hexFolder ?? ""); + } + + mapFolder(map: string): string { + const root = this.hexFolder(); + return root ? `${root}/${map}` : map; + } + + notePath(map: string): string { + return `${this.mapFolder(map)}/_${map}.md`; + } + + /** Which map and hex a hex-note path belongs to, if any. */ + resolve(path: string): { map: string; key: string } | null { + const root = this.hexFolder(); + const rel = root ? (path.startsWith(root + "/") ? path.slice(root.length + 1) : null) : path; + if (!rel) return null; + const parts = rel.split("/"); + if (parts.length !== 2) return null; + const m = HEX_FILE.exec(parts[1]); + if (!m) return null; + return { map: parts[0], key: `${m[1]}_${m[2]}` }; + } + + // ── reads / writes ─────────────────────────────────────────────────── + + private table(map: string): Map { + let t = this.hexes.get(map); + if (!t) { t = new Map(); this.hexes.set(map, t); } + return t; + } + + get(map: string, key: string): HexData | undefined { + return this.hexes.get(map)?.get(key); + } + + /** All hexes of a map with data (read-only view). */ + all(map: string): ReadonlyMap { + return this.hexes.get(map) ?? new Map(); + } + + /** + * Patch one hex. `undefined`/`null`/empty values clear that field. The + * note write is debounced; listeners hear about the change at once. + */ + set(map: string, key: string, patch: { [K in keyof HexData]?: HexData[K] | null }): void { + const t = this.table(map); + const h: HexData = { ...(t.get(key) ?? {}) }; + for (const [k, v] of Object.entries(patch) as [keyof HexData, unknown][]) { + const empty = v === undefined || v === null || v === "" || v === false || (Array.isArray(v) && v.length === 0); + if (empty) delete h[k]; + else (h as Record)[k] = v; + } + if (Object.keys(h).length) t.set(key, h); else t.delete(key); + this.markDirty(map); + this.emit(map); + } + + /** Bulk set (generators, map creation): one dirty mark, one event. */ + setMany(map: string, cells: Iterable<[string, Partial]>): void { + const t = this.table(map); + for (const [key, patch] of cells) { + const h: HexData = { ...(t.get(key) ?? {}), ...patch }; + for (const k of Object.keys(h) as (keyof HexData)[]) if (h[k] === undefined || h[k] === "") delete h[k]; + if (Object.keys(h).length) t.set(key, h); else t.delete(key); + } + this.markDirty(map); + this.emit(map); + } + + onChange(fn: (map: string) => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + private emit(map: string): void { + for (const fn of this.listeners) { + try { fn(map); } catch (e) { console.error("Hexmaker: map listener failed", e); } + } + } + + private markDirty(map: string): void { + this.dirty.add(map); + if (!this.ready) return; + window.clearTimeout(this.writeTimer); + this.writeTimer = window.setTimeout(() => void this.flush(), 500); + } + + private enqueue(task: () => Promise): Promise { + this.queue = this.queue.then(task).catch((e) => console.error("Hexmaker: map note sync failed", e)); + return this.queue; + } + + /** Write every dirty map's note now. */ + flush(): Promise { + window.clearTimeout(this.writeTimer); + return this.enqueue(async () => { + const maps = [...this.dirty]; + this.dirty.clear(); + for (const name of maps) { + const map = this.plugin.getMap(name); + if (map) await this.writeNote(map); + } + }); + } + + /** Settings changed (saveSettings): write notes whose data differs. */ + sync(): Promise { + if (!this.ready) return this.queue; + for (const m of this.plugin.settings.maps) { + if (this.lastKey.get(m.name) !== mapNoteKey(this.dataFor(m))) this.dirty.add(m.name); + } + return this.flush(); + } + + dataFor(map: MapData): MapNoteData { + const { name: _n, pathChains, savedViewport: _v, ...settings } = map; + return { settings: settings, hexes: this.table(map.name), paths: pathChains ?? [] }; + } + + private async writeNote(map: MapData): Promise { + const { vault } = this.plugin.app; + const data = this.dataFor(map); + const key = mapNoteKey(data); + const path = this.notePath(map.name); + const file = vault.getAbstractFileByPath(path); + if (file instanceof TFile) { + const current = await vault.read(file); + const next = updateMapNote(current, map.name, data); + if (next !== current) { + this.lastContent.set(path, next); + await vault.modify(file, next); + } + } else { + const folder = this.mapFolder(map.name); + if (!vault.getAbstractFileByPath(folder)) { + try { await vault.createFolder(folder); } catch { /* exists */ } + } + const content = buildMapNote(map.name, data); + this.lastContent.set(path, content); + await vault.create(path, content); + } + this.lastKey.set(map.name, key); + } + + // ── load / hand edits ──────────────────────────────────────────────── + + /** Apply a parsed note to a map: settings + paths onto MapData, hexes into memory. */ + private apply(map: MapData, data: MapNoteData): void { + Object.assign(map, data.settings); + map.pathChains = data.paths; + this.hexes.set(map.name, new Map(data.hexes)); + this.lastKey.set(map.name, mapNoteKey(this.dataFor(map))); + } + + private async loadMap(map: MapData): Promise { + const file = this.plugin.app.vault.getAbstractFileByPath(this.notePath(map.name)); + if (!(file instanceof TFile)) return false; + const content = await this.plugin.app.vault.read(file); + const data = parseMapNote(content); + if (!data) return false; + this.lastContent.set(file.path, content); + this.apply(map, data); + return true; + } + + /** A map note edited by hand (or synced in): reload that map. */ + onModify(file: TAbstractFile): void { + if (!this.ready || !(file instanceof TFile)) return; + const m = /\/?_([^/]+)\.md$/.exec(file.path); + if (!m || file.path !== this.notePath(m[1])) return; + const map = this.plugin.getMap(m[1]); + if (!map) return; + void this.enqueue(async () => { + const content = await this.plugin.app.vault.read(file); + if (this.lastContent.get(file.path) === content) return; // our own write + const data = parseMapNote(content); + if (!data) return; + this.lastContent.set(file.path, content); + this.apply(map, data); + await this.plugin.saveData(this.plugin.settings); + this.emit(map.name); + this.plugin.refreshHexMap(); + }); + } + + /** A map was renamed (folder already moved): move its note too. */ + async renameMap(oldName: string, newName: string): Promise { + const t = this.hexes.get(oldName); + if (t) { this.hexes.delete(oldName); this.hexes.set(newName, t); } + const { vault, fileManager } = this.plugin.app; + const moved = vault.getAbstractFileByPath(`${this.mapFolder(newName)}/_${oldName}.md`); + if (moved instanceof TFile) await fileManager.renameFile(moved, this.notePath(newName)); + this.lastKey.delete(oldName); + this.dirty.add(newName); + await this.flush(); + } + + forgetMap(name: string): void { + this.hexes.delete(name); + this.lastKey.delete(name); + this.dirty.delete(name); + } + + // ── startup + migration ────────────────────────────────────────────── + + /** + * Call at layout ready. Maps that already have a note load from it. + * Maps that don't are migrated: their hex notes' map data is copied into + * a new map note (verified by reading it back), backed up as JSON, and + * only then cleaned out of the hex notes (which keep all their prose and + * get a link to the map note). Notes are never deleted. + */ + init(): Promise { + return this.enqueue(async () => { + const toMigrate: MapData[] = []; + for (const map of this.plugin.settings.maps) { + if (!(await this.loadMap(map))) toMigrate.push(map); + } + this.ready = true; + if (toMigrate.length) await this.migrate(toMigrate); + // Hex notes still carrying map data after a load (an interrupted + // cleanup, or notes synced in from an older device) get cleaned now. + await this.cleanHexNotes(this.plugin.settings.maps.filter((m) => !toMigrate.includes(m)), false); + this.plugin.refreshHexMap(); + }); + } + + private hexFiles(map: string): TFile[] { + const folder = this.plugin.app.vault.getAbstractFileByPath(this.mapFolder(map)); + if (!(folder instanceof TFolder)) return []; + return folder.children.filter((f): f is TFile => f instanceof TFile && HEX_FILE.test(f.name)); + } + + private async frontmatterOf(file: TFile): Promise | undefined> { + const cache = this.plugin.app.metadataCache.getFileCache(file); + if (cache) return cache.frontmatter; + // Not indexed yet: parse it ourselves. + const text = await this.plugin.app.vault.cachedRead(file); + const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text); + if (!m) return undefined; + try { return (parseYaml(m[1]) ?? undefined) as Record | undefined; } catch { return undefined; } + } + + private async migrate(maps: MapData[]): Promise { + const notice = new Notice(`Hexmaker: moving map data into map notes (0/${maps.length} maps)…`, 0); + const backupDir = `${this.plugin.manifest.dir}/backups/map-notes-${new Date().toISOString().slice(0, 10)}`; + const adapter = this.plugin.app.vault.adapter; + let done = 0; + const failed: string[] = []; + for (const map of maps) { + const hexes = new Map(); + for (const file of this.hexFiles(map.name)) { + const h = hexDataFromFrontmatter(await this.frontmatterOf(file)); + if (Object.keys(h).length) hexes.set(file.basename, h); + } + this.hexes.set(map.name, hexes); + // Write, then read back and compare before touching any hex note. + await this.writeNote(map); + const written = this.plugin.app.vault.getAbstractFileByPath(this.notePath(map.name)); + const back = written instanceof TFile ? parseMapNote(await this.plugin.app.vault.read(written)) : null; + const expected = mapNoteKey(this.dataFor(map)); + if (!back || mapNoteKey({ ...back, settings: this.dataFor(map).settings }) !== expected) { + failed.push(map.name); + continue; + } + try { + if (!(await adapter.exists(backupDir))) await adapter.mkdir(backupDir); + await adapter.write(`${backupDir}/${map.name}.json`, JSON.stringify({ map: map.name, hexes: [...hexes] }, null, 1)); + } catch (e) { + console.error("Hexmaker: map-note backup failed", e); + failed.push(map.name); + continue; + } + await this.cleanHexNotes([map], true); + done++; + notice.setMessage(`Hexmaker: moving map data into map notes (${done}/${maps.length} maps)…`); + } + notice.hide(); + if (failed.length) { + new Notice(`Hexmaker: couldn't move map data for ${failed.join(", ")} — their hex notes were left untouched.`, 0); + } else { + new Notice(`Hexmaker: map data for ${done} map${done === 1 ? "" : "s"} now lives in map notes (_.md). Hex notes keep their text.`); + } + await this.plugin.saveData(this.plugin.settings); + } + + /** + * Remove map-data keys from hex notes whose data the map note already + * holds, leaving a link to the map note. Only keys whose value matches + * the map note are removed unless `trustNote` (fresh migration) — so a + * hex note edited on an old device isn't silently overwritten. + */ + private async cleanHexNotes(maps: MapData[], trustNote: boolean): Promise { + const { fileManager } = this.plugin.app; + for (const map of maps) { + const link = `[[_${map.name}]]`; + for (const file of this.hexFiles(map.name)) { + const fm = await this.frontmatterOf(file); + if (!fm || !HEX_DATA_KEYS.some((k) => k in fm)) continue; + const fromNote = hexDataFromFrontmatter(fm); + const stored = this.get(map.name, file.basename) ?? {}; + if (!trustNote && JSON.stringify(fromNote) !== JSON.stringify(pick(stored, fromNote))) { + // The hex note disagrees with the map note: take the hex note's + // values (it was edited elsewhere), then clean it. + this.set(map.name, file.basename, fromNote); + } + await fileManager.processFrontMatter(file, (f: Record) => { + for (const k of HEX_DATA_KEYS) delete f[k]; + f[MAP_LINK_KEY] = link; + }); + } + } + } +} + +/** The fields of `a` that `like` has, for comparing partial hex data. */ +function pick(a: HexData, like: HexData): HexData { + const out: HexData = {}; + for (const k of Object.keys(like) as (keyof HexData)[]) (out as Record)[k] = a[k]; + return out; +} diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts new file mode 100644 index 00000000..52287ce3 --- /dev/null +++ b/src/maps/mapNote.ts @@ -0,0 +1,322 @@ +import type { MapData, PathChain } from "../types"; + +/** + * Map notes: one note per map ("hexes//_.md") holding the map's + * settings in frontmatter, every hex's map data in a "Hexes" table, and its + * roads/rivers in a "Paths" table. Hex notes only hold prose and links — + * a hex without content has no note at all. + * + * --- + * hexmaker-map: 1 + * palette: Default + * cols: 38 + * rows: 25 + * … + * --- + * ## Hexes + * | Hex | Terrain | Icon | GM icons | Region | Submap | Locked | + * | 3_4 | dunes | | | Basin | | | + * ## Paths + * | Type | Hexes | + * | Road | 3_4 4_4 5_4 | + * + * Text outside the two tables, and frontmatter keys this file doesn't own, + * are the user's and survive rewrites. + */ + +export const MAP_NOTE_MARKER = "hexmaker-map"; + +/** Map data for one hex. Absent fields = nothing set. */ +export interface HexData { + terrain?: string; + icon?: string; + gmIcons?: string[]; + region?: string; + submap?: string; + locked?: boolean; +} + +/** Settings stored in a map note: MapData minus its name, paths and the + * per-session viewport (which stays in data.json). */ +export type MapSettings = Omit; + +export interface MapNoteData { + settings: Partial; + hexes: Map; + paths: PathChain[]; +} + +// ── frontmatter ────────────────────────────────────────────────────────── + +/** MapData field ↔ frontmatter key for the fields given their own line. */ +const SCALAR_KEYS: [keyof MapSettings, string][] = [ + ["paletteName", "palette"], + ["staggerOffset", "stagger"], + ["baseTerrain", "base-terrain"], + ["terrainType", "terrain-theme"], + ["createdWith", "created-with"], + ["showCoords", "show-coords"], + ["showTerrainIcons", "show-terrain-icons"], + ["showIconOverrides", "show-icon-overrides"], + ["showPaths", "show-paths"], + ["showFactionOverlay", "show-faction-overlay"], + ["showRegionOverlay", "show-region-overlay"], + ["showGmLayer", "show-gm-layer"], + ["showTokens", "show-tokens"], + ["gridDisplayScale", "grid-display-scale"], + ["gridDisplayScaleX", "grid-display-scale-x"], + ["gridDisplayScaleY", "grid-display-scale-y"], + ["gridDisplayOffsetX", "grid-display-offset-x"], + ["gridDisplayOffsetY", "grid-display-offset-y"], +]; +/** Fields written as one JSON value each (objects). */ +const JSON_KEYS: [keyof MapSettings, string][] = [ + ["parent", "parent"], + ["world", "world"], + ["backgroundImage", "background-image"], +]; +/** Catch-all for MapData fields this file doesn't know (future/other branches). */ +const EXTRA_KEY = "hexmaker-extra"; +const OWNED = new Set([ + MAP_NOTE_MARKER, "cols", "rows", "offset-x", "offset-y", EXTRA_KEY, + ...SCALAR_KEYS.map(([, k]) => k), ...JSON_KEYS.map(([, k]) => k), +]); +const SKIP_FIELDS = new Set(["name", "pathChains", "savedViewport", "gridSize", "gridOffset"]); + +/** A YAML scalar (JSON is valid YAML, so anything non-trivial is JSON-quoted). */ +function yamlValue(v: unknown): string { + if (typeof v === "boolean" || typeof v === "number") return String(v); + if (typeof v === "string") return /^[\w][\w .()/@-]*$/.test(v) && !v.endsWith(" ") && !/^(true|false|null|yes|no|\d[\d.eE+-]*)$/i.test(v) ? v : JSON.stringify(v); + return JSON.stringify(v); +} + +function parseValue(raw: string): unknown { + const t = raw.trim(); + if (t === "") return undefined; + if (t === "true") return true; + if (t === "false") return false; + if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t); + if (/^["{[]/.test(t)) { + try { return JSON.parse(t); } catch { /* fall through */ } + } + if (/^'.*'$/.test(t)) return t.slice(1, -1).replace(/''/g, "'"); + return t; +} + +function frontmatterLines(settings: Partial): string[] { + const s = settings as Record; + const lines = [`${MAP_NOTE_MARKER}: 1`]; + if (settings.gridSize) lines.push(`cols: ${settings.gridSize.cols}`, `rows: ${settings.gridSize.rows}`); + if (settings.gridOffset) lines.push(`offset-x: ${settings.gridOffset.x}`, `offset-y: ${settings.gridOffset.y}`); + for (const [field, key] of SCALAR_KEYS) if (s[field] !== undefined) lines.push(`${key}: ${yamlValue(s[field])}`); + for (const [field, key] of JSON_KEYS) if (s[field] !== undefined) lines.push(`${key}: ${JSON.stringify(s[field])}`); + const known = new Set([...SCALAR_KEYS, ...JSON_KEYS].map(([f]) => f as string)); + const extra: Record = {}; + for (const [k, v] of Object.entries(s)) { + if (v === undefined || known.has(k) || SKIP_FIELDS.has(k)) continue; + extra[k] = v; + } + if (Object.keys(extra).length) lines.push(`${EXTRA_KEY}: ${JSON.stringify(extra)}`); + return lines; +} + +const FRONTMATTER = /^---\n([\s\S]*?)\n---(\n|$)/; + +function parseFrontmatter(body: string): Partial { + const raw = new Map(); + for (const line of body.split("\n")) { + const m = /^([\w-]+):(.*)$/.exec(line); + if (m) raw.set(m[1], m[2]); + } + const out: Record = {}; + const num = (k: string) => { + const v = parseValue(raw.get(k) ?? ""); + return typeof v === "number" ? v : undefined; + }; + const cols = num("cols"), rows = num("rows"); + if (cols !== undefined && rows !== undefined) out.gridSize = { cols, rows }; + const ox = num("offset-x"), oy = num("offset-y"); + if (ox !== undefined && oy !== undefined) out.gridOffset = { x: ox, y: oy }; + for (const [field, key] of [...SCALAR_KEYS, ...JSON_KEYS]) { + if (!raw.has(key)) continue; + const v = parseValue(raw.get(key)!); + if (v !== undefined) out[field] = v; + } + const extra = parseValue(raw.get(EXTRA_KEY) ?? ""); + if (extra && typeof extra === "object" && !Array.isArray(extra)) { + for (const [k, v] of Object.entries(extra as Record)) if (!(k in out)) out[k] = v; + } + return out; +} + +// ── tables ─────────────────────────────────────────────────────────────── + +const HEX_HEADERS = ["Hex", "Terrain", "Icon", "GM icons", "Region", "Submap", "Locked"]; +const PATH_HEADERS = ["Type", "Hexes"]; +const SEPARATOR_ROW = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/; + +function splitRow(line: string): string[] { + let s = line.trim(); + if (s.startsWith("|")) s = s.slice(1); + if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1); + const cells: string[] = []; + let cur = ""; + for (let i = 0; i < s.length; i++) { + if (s[i] === "\\" && s[i + 1] === "|") { cur += "|"; i++; } + else if (s[i] === "|") { cells.push(cur.trim()); cur = ""; } + else cur += s[i]; + } + cells.push(cur.trim()); + return cells; +} + +const esc = (v: string | undefined) => (v ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " ").trim(); + +/** First table whose header has all of `need` (case-insensitive). */ +function findTable(lines: string[], need: string[]): { start: number; end: number; cols: string[] } | null { + for (let i = 0; i < lines.length - 1; i++) { + if (!lines[i].trim().startsWith("|") || !SEPARATOR_ROW.test(lines[i + 1])) continue; + const cols = splitRow(lines[i]).map((c) => c.toLowerCase()); + if (!need.every((n) => cols.includes(n))) continue; + let end = i + 2; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { start: i, end, cols }; + } + return null; +} + +/** Sort "x_y" keys by row then column, like reading a map. */ +export function compareHexKeys(a: string, b: string): number { + const [ax, ay] = a.split("_").map(Number); + const [bx, by] = b.split("_").map(Number); + return ay - by || ax - bx; +} + +function isEmptyHex(h: HexData): boolean { + return !h.terrain && !h.icon && !(h.gmIcons && h.gmIcons.length) && !h.region && !h.submap && !h.locked; +} + +/** Rows worth writing: hexes with any data, minus "just the base terrain". */ +export function hexRowsToWrite(hexes: Map, baseTerrain?: string): [string, HexData][] { + return [...hexes] + .filter(([, h]) => { + if (isEmptyHex(h)) return false; + const onlyBase = h.terrain === baseTerrain && !h.icon && !(h.gmIcons && h.gmIcons.length) && !h.region && !h.submap && !h.locked; + return !(baseTerrain && onlyBase); + }) + .sort(([a], [b]) => compareHexKeys(a, b)); +} + +function hexTable(hexes: Map, baseTerrain?: string): string { + const lines = [`| ${HEX_HEADERS.join(" | ")} |`, `| ${HEX_HEADERS.map(() => "---").join(" | ")} |`]; + for (const [k, h] of hexRowsToWrite(hexes, baseTerrain)) { + lines.push(`| ${[k, h.terrain, h.icon, h.gmIcons?.join(", "), h.region, h.submap, h.locked ? "yes" : ""].map(esc).join(" | ")} |`); + } + return lines.join("\n"); +} + +function pathTable(paths: PathChain[]): string { + const lines = [`| ${PATH_HEADERS.join(" | ")} |`, `| ${PATH_HEADERS.map(() => "---").join(" | ")} |`]; + for (const p of paths) lines.push(`| ${esc(p.typeName)} | ${p.hexes.join(" ")} |`); + return lines.join("\n"); +} + +function parseHexTable(lines: string[]): Map { + const out = new Map(); + const t = findTable(lines, ["hex", "terrain"]); + if (!t) return out; + const col = (name: string) => t.cols.indexOf(name); + const ci = { hex: col("hex"), terrain: col("terrain"), icon: col("icon"), gm: col("gm icons"), region: col("region"), submap: col("submap"), locked: col("locked") }; + for (let i = t.start + 2; i < t.end; i++) { + const c = splitRow(lines[i]); + const key = c[ci.hex]; + if (!key || !/^-?\d+_-?\d+$/.test(key)) continue; + const h: HexData = {}; + const get = (j: number) => (j >= 0 ? c[j] : "") || undefined; + if (get(ci.terrain)) h.terrain = get(ci.terrain); + if (get(ci.icon)) h.icon = get(ci.icon); + const gm = get(ci.gm); + if (gm) h.gmIcons = gm.split(",").map((s) => s.trim()).filter(Boolean); + if (get(ci.region)) h.region = get(ci.region); + if (get(ci.submap)) h.submap = get(ci.submap); + if (/^(yes|true|x|✓)$/i.test(get(ci.locked) ?? "")) h.locked = true; + out.set(key, h); + } + return out; +} + +function parsePathTable(lines: string[]): PathChain[] { + const t = findTable(lines, ["type", "hexes"]); + if (!t) return []; + const ti = t.cols.indexOf("type"), hi = t.cols.indexOf("hexes"); + const out: PathChain[] = []; + for (let i = t.start + 2; i < t.end; i++) { + const c = splitRow(lines[i]); + const hexes = (c[hi] ?? "").split(/[\s,]+/).filter((k) => /^-?\d+_-?\d+$/.test(k)); + if (c[ti] && hexes.length) out.push({ typeName: c[ti], hexes }); + } + return out; +} + +// ── whole note ─────────────────────────────────────────────────────────── + +/** Parse a map note, or null if it isn't one. */ +export function parseMapNote(content: string): MapNoteData | null { + const text = content.replace(/\r\n?/g, "\n"); + const fm = FRONTMATTER.exec(text); + if (!fm || !new RegExp(`^${MAP_NOTE_MARKER}:`, "m").test(fm[1])) return null; + const lines = text.split("\n"); + return { settings: parseFrontmatter(fm[1]), hexes: parseHexTable(lines), paths: parsePathTable(lines) }; +} + +/** A fresh map note. */ +export function buildMapNote(name: string, data: MapNoteData): string { + return [ + "---", + ...frontmatterLines(data.settings), + "---", + `# ${name}`, + "", + "Hexmaker map. Each hex's terrain, icons, region and submap live in the table below — edit it here or paint on the map. Hex notes hold descriptions and links, and only exist once a hex has some.", + "", + "## Hexes", + "", + hexTable(data.hexes, data.settings.baseTerrain), + "", + "## Paths", + "", + pathTable(data.paths), + "", + ].join("\n"); +} + +/** + * Rewrite our parts of an existing map note — owned frontmatter keys and + * the two tables — keeping everything else the user added. + */ +export function updateMapNote(content: string, name: string, data: MapNoteData): string { + const text = content.replace(/\r\n?/g, "\n"); + const fm = FRONTMATTER.exec(text); + if (!fm) return buildMapNote(name, data); + const userFm = fm[1].split("\n").filter((l) => { + const m = /^([\w-]+):/.exec(l); + return !m || !OWNED.has(m[1]); + }); + let lines = text.slice(fm[0].length).split("\n"); + const replace = (need: string[], table: string, heading: string) => { + const t = findTable(lines, need); + if (t) lines = [...lines.slice(0, t.start), ...table.split("\n"), ...lines.slice(t.end)]; + else lines = [...lines, "", heading, "", ...table.split("\n")]; + }; + replace(["hex", "terrain"], hexTable(data.hexes, data.settings.baseTerrain), "## Hexes"); + replace(["type", "hexes"], pathTable(data.paths), "## Paths"); + return ["---", ...frontmatterLines(data.settings), ...userFm.filter((l) => l.trim()), "---", ...lines].join("\n"); +} + +/** Comparison key: same key ⇔ same map data (ignores formatting). */ +export function mapNoteKey(data: MapNoteData): string { + const s = data.settings as Record; + const settings = Object.keys(s).filter((k) => s[k] !== undefined && !SKIP_FIELDS.has(k) || k === "gridSize" || k === "gridOffset").sort().map((k) => [k, s[k]]); + const hexes = hexRowsToWrite(data.hexes, data.settings.baseTerrain); + return JSON.stringify([settings, hexes, data.paths.map((p) => [p.typeName, p.hexes])]); +} diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index d7212c54..70e6e657 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -448,7 +448,7 @@ async function writeTerrain( const [x, y] = key.split("_").map(Number); const path = plugin.hexPath(x, y, mapName); const before = getTerrainFromFile(plugin.app, path); - if (plugin.app.vault.getAbstractFileByPath(path) instanceof TFile) { + if (plugin.mapStore?.isReady() || plugin.app.vault.getAbstractFileByPath(path) instanceof TFile) { await setTerrainInFile(plugin.app, path, terrain); } else { await plugin.createHexNote(x, y, mapName, undefined, terrain); diff --git a/tests/__mocks__/obsidian.ts b/tests/__mocks__/obsidian.ts index 37864855..274457a1 100644 --- a/tests/__mocks__/obsidian.ts +++ b/tests/__mocks__/obsidian.ts @@ -1,5 +1,7 @@ /** Minimal Obsidian API stubs for unit tests. */ +import { parseMiniYaml } from "../helpers/miniYaml"; + export class TAbstractFile { path = ""; name = ""; @@ -20,9 +22,13 @@ export class TFolder extends TAbstractFile { export class App {} export class Modal { app: App; contentEl = { empty() {}, addClass() {}, createDiv() { return this; }, createEl() { return this; }, createSpan() { return this; }, setText() { return this; }, style: {} } as any; constructor(app: App) { this.app = app; } } export class SuggestModal { constructor(_app: App) {} getSuggestions(_q: string): T[] { return []; } renderSuggestion(_v: T, _el: HTMLElement): void {} onChooseSuggestion(_v: T, _e: MouseEvent | KeyboardEvent): void {} } -export class Notice { constructor(_msg: string) {} } +export class Notice { constructor(_msg: string, _timeout?: number) {} setMessage(_msg: string) { return this; } hide() {} } export class Plugin { constructor(_app: App, _manifest: any) {} } export function normalizePath(path: string): string { return path.replace(/[\\/]+/g, "/").replace(/\u00A0/g, " ").normalize().replace(/^\/+|\/+$/g, ""); } + +export function parseYaml(src: string): unknown { + return parseMiniYaml(src); +} diff --git a/tests/helpers/memVault.ts b/tests/helpers/memVault.ts new file mode 100644 index 00000000..b1822f77 --- /dev/null +++ b/tests/helpers/memVault.ts @@ -0,0 +1,127 @@ +/** + * In-memory vault for store/migration tests: just enough of App (vault, + * adapter, metadataCache, fileManager) for MapStore. Frontmatter uses a + * small YAML subset (scalars, quoted strings, inline and dash lists) — + * the shapes hex notes actually carry. + */ +import { TFile, TFolder } from "obsidian"; +import { parseMiniYaml } from "./miniYaml"; + +export { parseMiniYaml }; + +function dumpMiniYaml(fm: Record): string { + const lines: string[] = []; + for (const [k, v] of Object.entries(fm)) { + if (v === undefined) continue; + if (Array.isArray(v)) { + lines.push(`${k}:`); + for (const i of v) lines.push(` - ${String(i)}`); + } else if (typeof v === "string" && /^\[\[|[:#]/.test(v)) { + lines.push(`${k}: ${JSON.stringify(v)}`); + } else { + lines.push(`${k}: ${String(v)}`); + } + } + return lines.join("\n"); +} + +const FM = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/; + +export class MemVault { + files = new Map(); + folders = new Set([""]); + writes: string[] = []; + /** Test hook: mangle content on its way to disk (simulates a bad write). */ + corrupt: ((path: string, content: string) => string) | null = null; + + constructor(initial: Record = {}) { + for (const [p, c] of Object.entries(initial)) this.put(p, c); + } + + private ensureFolder(path: string): void { + const parts = path.split("/"); + for (let i = 1; i <= parts.length; i++) this.folders.add(parts.slice(0, i).join("/")); + } + + private put(path: string, content: string): void { + const slash = path.lastIndexOf("/"); + if (slash > 0) this.ensureFolder(path.slice(0, slash)); + this.files.set(path, this.corrupt ? this.corrupt(path, content) : content); + } + + private node(path: string): TFile | TFolder | null { + if (this.files.has(path)) { + const f = new TFile(); + f.path = path; + f.name = path.slice(path.lastIndexOf("/") + 1); + f.basename = f.name.replace(/\.md$/, ""); + return f; + } + if (this.folders.has(path)) { + const d = new TFolder(); + d.path = path; + d.name = path.slice(path.lastIndexOf("/") + 1); + const prefix = path ? path + "/" : ""; + const kids = [...this.files.keys(), ...this.folders] + .filter((p) => p && p.startsWith(prefix) && !p.slice(prefix.length).includes("/")); + d.children = kids.map((k) => this.node(k)!); + return d; + } + return null; + } + + frontmatter(path: string): Record | undefined { + const c = this.files.get(path); + const m = c ? FM.exec(c) : null; + return m ? parseMiniYaml(m[1]) : undefined; + } + + body(path: string): string { + return (this.files.get(path) ?? "").replace(FM, ""); + } + + app() { + const v = this; + return { + vault: { + getAbstractFileByPath: (p: string) => v.node(p), + getMarkdownFiles: () => [...v.files.keys()].filter((p) => p.endsWith(".md")).map((p) => v.node(p) as TFile), + read: async (f: TFile) => v.files.get(f.path) ?? "", + cachedRead: async (f: TFile) => v.files.get(f.path) ?? "", + modify: async (f: TFile, c: string) => { v.writes.push(f.path); v.put(f.path, c); }, + create: async (p: string, c: string) => { + if (v.files.has(p)) throw new Error("exists " + p); + v.writes.push(p); + v.put(p, c); + return v.node(p); + }, + createFolder: async (p: string) => { v.ensureFolder(p); }, + adapter: { + exists: async (p: string) => v.files.has(p) || v.folders.has(p), + mkdir: async (p: string) => { v.ensureFolder(p); }, + write: async (p: string, c: string) => { v.put(p, c); }, + }, + }, + metadataCache: { + getFileCache: (f: TFile) => (v.files.has(f.path) ? { frontmatter: v.frontmatter(f.path) } : null), + getCache: (p: string) => (v.files.has(p) ? { frontmatter: v.frontmatter(p) } : null), + }, + fileManager: { + processFrontMatter: async (f: TFile, fn: (fm: Record) => void) => { + const c = v.files.get(f.path) ?? ""; + const fm = v.frontmatter(f.path) ?? {}; + fn(fm); + const body = c.replace(FM, ""); + const yaml = dumpMiniYaml(fm); + v.writes.push(f.path); + v.put(f.path, (yaml ? `---\n${yaml}\n---\n` : "") + body); + }, + renameFile: async (f: TFile, to: string) => { + const c = v.files.get(f.path)!; + v.files.delete(f.path); + v.put(to, c); + }, + }, + }; + } +} diff --git a/tests/helpers/miniYaml.ts b/tests/helpers/miniYaml.ts new file mode 100644 index 00000000..38477257 --- /dev/null +++ b/tests/helpers/miniYaml.ts @@ -0,0 +1,40 @@ +/** A small YAML subset (scalars, quoted strings, inline and dash lists) for tests. */ +export function parseMiniYaml(src: string): Record { + const out: Record = {}; + let listKey: string | null = null; + for (const raw of src.split(/\r?\n/)) { + if (!raw.trim()) continue; + const item = /^\s+-\s*(.*)$/.exec(raw); + if (item && listKey) { + (out[listKey] as unknown[]).push(scalar(item[1])); + continue; + } + const kv = /^([^:#\s][^:]*):\s*(.*)$/.exec(raw); + if (!kv) continue; + const [, key, value] = kv; + if (value === "") { + out[key] = []; + listKey = key; + } else { + out[key] = scalar(value); + listKey = null; + } + } + // "key:" with no items is null in YAML + for (const [k, v] of Object.entries(out)) if (Array.isArray(v) && v.length === 0) out[k] = null; + return out; +} + +function scalar(v: string): unknown { + v = v.trim(); + if (v.startsWith("[") && v.endsWith("]") && !v.startsWith("[[")) { + return v.slice(1, -1).split(",").map((s) => s.trim()).filter(Boolean).map(scalar); + } + if (/^".*"$/.test(v)) return JSON.parse(v); + if (/^'.*'$/.test(v)) return v.slice(1, -1).replace(/''/g, "'"); + if (v === "true") return true; + if (v === "false") return false; + if (v === "null" || v === "~") return null; + if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v); + return v; +} diff --git a/tests/mapNote.test.ts b/tests/mapNote.test.ts new file mode 100644 index 00000000..bd8abffa --- /dev/null +++ b/tests/mapNote.test.ts @@ -0,0 +1,123 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + buildMapNote, + hexRowsToWrite, + mapNoteKey, + parseMapNote, + updateMapNote, + type HexData, + type MapNoteData, +} from "../src/maps/mapNote"; + +const sample = (): MapNoteData => ({ + settings: { + paletteName: "Default", + gridSize: { cols: 38, rows: 25 }, + gridOffset: { x: -2, y: 0 }, + staggerOffset: "even", + terrainType: "grass", + createdWith: "1.5.6", + showCoords: false, + showFactionOverlay: true, + parent: { map: "the-north", hex: "3_4" }, + world: { id: "wabc", cx: 1, cy: -1 }, + backgroundImage: { path: "maps/bg.png", offsetX: 10, offsetY: -5, scale: 1.5, rotation: 0, opacity: 0.8 }, + gridDisplayScaleX: 1.02, + }, + hexes: new Map([ + ["3_4", { terrain: "dunes", region: "Basin" }], + ["-1_0", { terrain: "ocean" }], + ["12_9", { terrain: "forest", icon: "bw-castle.png", gmIcons: ["skull.png", "skull.png"], submap: "the-coast-12-9", locked: true }], + ["5_5", {}], + ]), + paths: [ + { typeName: "Road", hexes: ["3_4", "4_4", "5_4"] }, + { typeName: "River | big", hexes: ["0_0", "0_1"] }, + ], +}); + +describe("map notes", () => { + it("round-trips settings, hexes and paths", () => { + const data = sample(); + const back = parseMapNote(buildMapNote("the-coast", data))!; + expect(back.settings).toEqual(data.settings); + expect([...back.hexes].sort()).toEqual(hexRowsToWrite(data.hexes).sort()); + expect(back.paths).toEqual(data.paths); + expect(mapNoteKey(back)).toBe(mapNoteKey(data)); + }); + + it("keeps unknown MapData fields in a catch-all instead of dropping them", () => { + const data = sample(); + (data.settings as Record).futureThing = { a: [1, 2] }; + const back = parseMapNote(buildMapNote("m", data))!; + expect((back.settings as Record).futureThing).toEqual({ a: [1, 2] }); + }); + + it("never stores the name, viewport or paths in frontmatter", () => { + const data = sample(); + const s = data.settings as Record; + s.name = "x"; s.savedViewport = { zoom: 2, panX: 0, panY: 0, fontSize: "" }; s.pathChains = []; + const note = buildMapNote("m", data); + expect(note).not.toContain("savedViewport"); + expect(note).not.toContain("hexmaker-extra"); + }); + + it("is not fooled by notes that aren't map notes", () => { + expect(parseMapNote("# just a note")).toBeNull(); + expect(parseMapNote("---\ntags: x\n---\n| Hex | Terrain |\n|---|---|\n| 1_1 | a |")).toBeNull(); + }); + + it("handles CRLF and hand-edited tables (reordered columns, blank cells)", () => { + const note = "---\r\nhexmaker-map: 1\r\ncols: 3\r\nrows: 2\r\n---\r\n| Terrain | Hex | Locked |\r\n|---|---|---|\r\n| ocean | 0_0 | |\r\n| hills | 2_1 | yes |\r\n| | 1_1 | |\r\n"; + const d = parseMapNote(note)!; + expect(d.settings.gridSize).toEqual({ cols: 3, rows: 2 }); + expect(d.hexes.get("0_0")).toEqual({ terrain: "ocean" }); + expect(d.hexes.get("2_1")).toEqual({ terrain: "hills", locked: true }); + expect(d.hexes.get("1_1")).toEqual({}); + }); + + it("rewrites only its own parts, keeping the user's prose and frontmatter", () => { + const data = sample(); + const user = buildMapNote("m", data) + .replace("---\n# m", "tags: [campaign]\n---\n# m\n\nMy notes about this region.") + + "\n## Session log\nWe crossed the river.\n"; + data.hexes.set("3_4", { terrain: "forest" }); + data.settings.showCoords = true; + const out = updateMapNote(user, "m", data); + expect(out).toContain("tags: [campaign]"); + expect(out).toContain("My notes about this region."); + expect(out).toContain("## Session log\nWe crossed the river."); + const back = parseMapNote(out)!; + expect(back.hexes.get("3_4")).toEqual({ terrain: "forest" }); + expect(back.settings.showCoords).toBe(true); + expect(out.match(/## Hexes/g)).toHaveLength(1); + }); + + it("sparse rows: hexes with only the base terrain (or nothing) aren't written", () => { + const hexes = new Map([ + ["0_0", { terrain: "void" }], + ["1_0", { terrain: "star" }], + ["2_0", { terrain: "void", icon: "x.png" }], + ["3_0", {}], + ]); + expect(hexRowsToWrite(hexes, "void").map(([k]) => k)).toEqual(["1_0", "2_0"]); + expect(hexRowsToWrite(hexes).map(([k]) => k)).toEqual(["0_0", "1_0", "2_0"]); + }); + + it("strings that look like YAML specials survive", () => { + const data: MapNoteData = { settings: { paletteName: "true", terrainType: "123", createdWith: "1.5" }, hexes: new Map(), paths: [] }; + const back = parseMapNote(buildMapNote("m", data))!; + expect(back.settings.paletteName).toBe("true"); + expect(back.settings.terrainType).toBe("123"); + }); + + it("handles a big map quickly (chult-sized)", () => { + const hexes = new Map(); + for (let x = 0; x < 63; x++) for (let y = 0; y < 61; y++) hexes.set(`${x}_${y}`, { terrain: (x + y) % 3 ? "grass" : "forest" }); + const t0 = Date.now(); + const back = parseMapNote(buildMapNote("chult", { settings: { gridSize: { cols: 63, rows: 61 } }, hexes, paths: [] }))!; + expect(back.hexes.size).toBe(3843); + expect(Date.now() - t0).toBeLessThan(1500); + }); +}); diff --git a/tests/mapStore.test.ts b/tests/mapStore.test.ts new file mode 100644 index 00000000..4d3fcaa2 --- /dev/null +++ b/tests/mapStore.test.ts @@ -0,0 +1,201 @@ +import { describe, it, beforeEach } from "node:test"; +import expect from "expect"; +import { MapStore, HEX_DATA_KEYS } from "../src/maps/MapStore"; +import { parseMapNote } from "../src/maps/mapNote"; +import { MemVault } from "./helpers/memVault"; +import type { MapData } from "../src/types"; + +(globalThis as Record).window ??= globalThis; + +const HEX = (fm: string, body = "# Hex\n\n### Description\nA ruined tower.\n") => `---\n${fm}\n---\n${body}`; + +/** Old-format vault: map data in hex-note frontmatter. */ +function oldVault(): MemVault { + return new MemVault({ + "world/hexes/coast/1_2.md": HEX("terrain: ocean\ntags: [sea]"), + "world/hexes/coast/3_4.md": HEX("terrain: forest\nicon: castle.png\ngm-icons:\n - skull.png\n - skull.png\nregion: Basin\nduckmage-submap: coast-3-4\nlocked: true"), + "world/hexes/coast/0_0.md": HEX("gm-icon: trap.png"), + "world/hexes/coast/5_5.md": "# No frontmatter at all\n", + "world/hexes/coast/notes.md": HEX("terrain: lava"), // not a hex note + "world/hexes/coast-3-4/0_0.md": HEX("terrain: hills"), + }); +} + +function plugin(vault: MemVault, maps: MapData[]) { + const saved: unknown[] = []; + const p = { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", maps }, + getMap: (n: string) => maps.find((m) => m.name === n), + saveData: async (s: unknown) => { saved.push(s); }, + refreshHexMap: () => {}, + saved, + }; + return p; +} + +const maps = (): MapData[] => [ + { name: "coast", gridSize: { cols: 6, rows: 6 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "Road", hexes: ["1_2", "3_4"] }] } as MapData, + { name: "coast-3-4", gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 0, y: 0 }, parent: { map: "coast", hex: "3_4" } } as MapData, +]; + +async function boot(vault: MemVault, m = maps()) { + const p = plugin(vault, m); + const store = new MapStore(p as never); + await store.init(); + return { p, store }; +} + +describe("map store: migration from hex-note frontmatter", () => { + let vault: MemVault; + beforeEach(() => { vault = oldVault(); }); + + it("moves every per-hex field into the map note", async () => { + const { store } = await boot(vault); + expect(store.get("coast", "1_2")).toEqual({ terrain: "ocean" }); + expect(store.get("coast", "3_4")).toEqual({ + terrain: "forest", icon: "castle.png", gmIcons: ["skull.png", "skull.png"], + region: "Basin", submap: "coast-3-4", locked: true, + }); + expect(store.get("coast", "0_0")).toEqual({ gmIcons: ["trap.png"] }); + expect(store.get("coast-3-4", "0_0")).toEqual({ terrain: "hills" }); + + const note = parseMapNote(vault.files.get("world/hexes/coast/_coast.md")!)!; + expect(note.hexes.get("3_4")?.submap).toBe("coast-3-4"); + expect(note.paths).toEqual([{ typeName: "Road", hexes: ["1_2", "3_4"] }]); + expect(note.settings.gridSize).toEqual({ cols: 6, rows: 6 }); + }); + + it("cleans hex notes: data keys gone, a link to the map note, bodies untouched", async () => { + const before = new Map([...vault.files.keys()].map((p) => [p, vault.body(p)])); + await boot(vault); + for (const p of ["world/hexes/coast/1_2.md", "world/hexes/coast/3_4.md", "world/hexes/coast/0_0.md"]) { + const fm = vault.frontmatter(p)!; + for (const k of HEX_DATA_KEYS) expect(fm).not.toHaveProperty(k); + expect(fm["hexmaker-map"]).toBe("[[_coast]]"); + expect(vault.body(p)).toBe(before.get(p)); + } + // User frontmatter survives + expect(vault.frontmatter("world/hexes/coast/1_2.md")!.tags).toEqual(["sea"]); + // Notes without map data, and non-hex notes, are left alone + expect(vault.files.get("world/hexes/coast/5_5.md")).toBe("# No frontmatter at all\n"); + expect(vault.frontmatter("world/hexes/coast/notes.md")!.terrain).toBe("lava"); + // No note is deleted + expect(vault.files.has("world/hexes/coast/5_5.md")).toBe(true); + }); + + it("writes a JSON backup per map before cleaning", async () => { + await boot(vault); + const backups = [...vault.files.keys()].filter((p) => p.includes("/backups/map-notes-")); + expect(backups.map((p) => p.split("/").pop()).sort()).toEqual(["coast-3-4.json", "coast.json"]); + const b = JSON.parse(vault.files.get(backups.find((p) => p.endsWith("/coast.json"))!)!); + expect(new Map(b.hexes).get("3_4")).toMatchObject({ terrain: "forest", locked: true }); + }); + + it("leaves hex notes untouched if the map note doesn't read back the same", async () => { + // A write that drops the last table row simulates a bad save. + vault.corrupt = (path, c) => (path.endsWith("_coast.md") ? c.replace(/\n\| 3_4 [^\n]*/, "") : c); + const original = new Map(vault.files); + const { store } = await boot(vault); + for (const p of ["world/hexes/coast/1_2.md", "world/hexes/coast/3_4.md"]) { + expect(vault.files.get(p)).toBe(original.get(p)); + } + // The other map still migrated + expect(vault.frontmatter("world/hexes/coast-3-4/0_0.md")!.terrain).toBeUndefined(); + expect(store.get("coast-3-4", "0_0")).toEqual({ terrain: "hills" }); + }); + + it("restarting after a migration is a no-op (no hex note rewritten)", async () => { + const m = maps(); + await boot(vault, m); + vault.writes = []; + const { store } = await boot(vault, m); + expect(vault.writes).toEqual([]); + expect(store.get("coast", "3_4")?.terrain).toBe("forest"); + }); + + it("finishes an interrupted cleanup on the next start", async () => { + const m = maps(); + await boot(vault, m); + // Crash mid-cleanup: one hex note still carries its (same) data. + vault.files.set("world/hexes/coast/1_2.md", HEX("terrain: ocean\ntags: [sea]")); + const { store } = await boot(vault, m); + expect(vault.frontmatter("world/hexes/coast/1_2.md")!.terrain).toBeUndefined(); + expect(store.get("coast", "1_2")).toEqual({ terrain: "ocean" }); + }); + + it("an edit synced in from an older device wins, then gets cleaned", async () => { + const m = maps(); + await boot(vault, m); + // Old plugin version painted 1_2 swamp and gave 0_0 terrain + vault.files.set("world/hexes/coast/1_2.md", HEX("terrain: swamp")); + vault.files.set("world/hexes/coast/0_0.md", HEX("terrain: hills\ngm-icons:\n - trap.png")); + const { store } = await boot(vault, m); + await store.flush(); + expect(store.get("coast", "1_2")).toEqual({ terrain: "swamp" }); + expect(store.get("coast", "0_0")).toEqual({ terrain: "hills", gmIcons: ["trap.png"] }); + expect(parseMapNote(vault.files.get("world/hexes/coast/_coast.md")!)!.hexes.get("1_2")).toEqual({ terrain: "swamp" }); + expect(vault.frontmatter("world/hexes/coast/1_2.md")!.terrain).toBeUndefined(); + }); + + it("a fresh install (no maps, no hex notes) writes nothing", async () => { + const empty = new MemVault(); + await boot(empty, []); + expect(empty.writes).toEqual([]); + }); + + it("a map with no hex notes at all still gets a map note", async () => { + const v = new MemVault(); + const { store } = await boot(v, [{ name: "blank", gridSize: { cols: 3, rows: 3 }, gridOffset: { x: 0, y: 0 } } as MapData]); + expect(v.files.has("world/hexes/blank/_blank.md")).toBe(true); + expect(store.all("blank").size).toBe(0); + }); +}); + +describe("map store: edits", () => { + it("set/clear reach the map note; no hex note is created", async () => { + const v = new MemVault(); + const { store } = await boot(v, [{ name: "m", gridSize: { cols: 3, rows: 3 }, gridOffset: { x: 0, y: 0 } } as MapData]); + store.set("m", "1_1", { terrain: "grass", icon: "tree.png" }); + store.set("m", "2_2", { terrain: "hills" }); + store.set("m", "1_1", { icon: null }); + await store.flush(); + const note = parseMapNote(v.files.get("world/hexes/m/_m.md")!)!; + expect(note.hexes.get("1_1")).toEqual({ terrain: "grass" }); + expect(note.hexes.get("2_2")).toEqual({ terrain: "hills" }); + expect([...v.files.keys()].filter((p) => /\/\d+_\d+\.md$/.test(p))).toEqual([]); + }); + + it("a hand edit of the map note reloads that map", async () => { + const v = new MemVault(); + const m = [{ name: "m", gridSize: { cols: 3, rows: 3 }, gridOffset: { x: 0, y: 0 } } as MapData]; + const { store, p } = await boot(v, m); + store.set("m", "0_0", { terrain: "grass" }); + await store.flush(); + const path = "world/hexes/m/_m.md"; + v.files.set(path, v.files.get(path)!.replace("| 0_0 | grass |", "| 0_0 | desert |").replace("cols: 3", "cols: 5")); + store.onModify(p.app.vault.getAbstractFileByPath(path) as never); + await store.flush(); + expect(store.get("m", "0_0")?.terrain).toBe("desert"); + expect(m[0].gridSize.cols).toBe(5); + }); + + it("rename moves the note with the map", async () => { + const v = oldVault(); + const m = maps(); + const { store } = await boot(v, m); + // Simulate the folder move the modal does, then rename. + for (const [path, c] of [...v.files]) { + if (path.startsWith("world/hexes/coast/")) { + v.files.delete(path); + v.files.set(path.replace("world/hexes/coast/", "world/hexes/shore/"), c); + } + } + m[0].name = "shore"; + await store.renameMap("coast", "shore"); + expect(v.files.has("world/hexes/shore/_shore.md")).toBe(true); + expect(v.files.has("world/hexes/shore/_coast.md")).toBe(false); + expect(store.get("shore", "3_4")?.terrain).toBe("forest"); + }); +}); From 94764e5ba0fc232fff2ca70ec02a3b2d28d4242d Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 16:51:38 -0400 Subject: [PATCH 065/558] feat: hide space generators unless space maps are on Space generators (Star scatter, Orbits, Planet surface, learned generators with map-kind: planet/space) are only offered when the Space map type is on, when the map is in space (its palette or a parent map's has space terrains, so planet submaps of a system still get them), or when they're the current/saved choice. Applied to new-map setup, the New map tab, the generator library (with an "N hidden" note) and the palette editor's submap defaults. Installed space palettes are hidden from palette dropdowns while Space is off, unless selected. New installs start with world only; settings without mapKinds keep space when a palette already has space terrains. Toggling map types re-renders open palette editor / generator pages. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 37 +++++- src/HexmakerSettingTab.ts | 2 +- src/SetupWizardView.ts | 2 +- src/constants.ts | 5 +- src/hex-map/MapModal.ts | 12 +- src/mapKinds.ts | 58 +++++++++- src/palettes/PaletteEditorView.ts | 11 +- src/palettes/paletteOptions.ts | 6 +- src/worldgen/GeneratorPanel.ts | 17 ++- src/worldgen/NewMapSetupModal.ts | 19 ++- src/worldgen/registry.ts | 28 ++++- tests/mapKinds.test.ts | 185 ++++++++++++++++++++++++++++++ 13 files changed, 358 insertions(+), 28 deletions(-) create mode 100644 tests/mapKinds.test.ts diff --git a/package.json b/package.json index 9efdf37c..e827b786 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index e9e8f4f3..6201e383 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -25,7 +25,8 @@ import { import { SetupWizardView } from "./SetupWizardView"; import { PaletteStore } from "./palettes/PaletteStore"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; -import { ALL_MAP_KINDS, isIconHiddenByKind } from "./mapKinds"; +import { isIconHiddenByKind, isSpacePalette, resolveMapKinds } from "./mapKinds"; +import { mapAncestors } from "./hex-map/submapNav"; import { getPreset, mergePathTypes, @@ -519,10 +520,10 @@ export default class HexmakerPlugin extends Plugin { if (!this.settings.defaultMap) { this.settings.defaultMap = this.settings.maps[0]?.name ?? "default"; } - // Own copy (never alias DEFAULT_SETTINGS); unset in older data = all types. - this.settings.mapKinds = Array.isArray(this.settings.mapKinds) - ? [...this.settings.mapKinds] - : [...ALL_MAP_KINDS]; + // Own copy (never alias DEFAULT_SETTINGS). Read from the raw data: unset + // (new install / older data) = world, plus space if a palette has space + // terrains already. + this.settings.mapKinds = resolveMapKinds(data["mapKinds"], this.settings.terrainPalettes); } async saveSettings() { @@ -597,6 +598,19 @@ export default class HexmakerPlugin extends Plugin { } } + /** + * Map types turned on/off (settings, setup wizard): reload the icon + * pickers and re-render open pages that list palettes or generators so + * the change shows at once. Modals read the setting when they open. + */ + onMapKindsChanged(): void { + this.loadAvailableIcons(); + this.refreshPaletteEditors(); + for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_GENERATOR)) { + if (leaf.view instanceof GeneratorView) leaf.view.refresh(); + } + } + refreshHexMap(): void { this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP).forEach((leaf) => { (leaf.view as HexMapView).renderGrid(); @@ -1628,6 +1642,19 @@ export default class HexmakerPlugin extends Plugin { ); } + /** + * Is `mapName` in space: its palette, or any ancestor map's (a planet + * submap of a star system), is a space palette? Space generators are + * offered there even when the Space map type is off. + */ + isSpaceMap(mapName: string): boolean { + const chain = [...mapAncestors(mapName, (m) => this.parentOf(m)?.map), mapName]; + return chain.some((m) => { + const paletteName = this.getMap(m)?.paletteName; + return !!paletteName && isSpacePalette(this.getPaletteOrPresetTerrains(paletteName)); + }); + } + getAllTerrains(): TerrainColor[] { const seen = new Set(); const result: TerrainColor[] = []; diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index e14b6a36..4a9a12e6 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -746,7 +746,7 @@ export class HexmakerSettingTab extends PluginSettingTab { } this.plugin.settings.mapKinds = MAP_KINDS.map((k) => k.id).filter((id) => kinds.has(id)); await this.plugin.saveSettings(); - this.plugin.loadAvailableIcons(); + this.plugin.onMapKindsChanged(); } /** "Open note" button for a palette row — opens the palette's note in a new tab. */ diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index 859934c9..017667f0 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -124,7 +124,7 @@ function makeWelcomeStep(): WizardStep { ctx.paletteName = SPACE_SECTOR_PALETTE_NAME; } await plugin.saveSettings(); - plugin.loadAvailableIcons(); + plugin.onMapKindsChanged(); }, }; } diff --git a/src/constants.ts b/src/constants.ts index ed09ccd9..0a6e6496 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -383,6 +383,9 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { setupDismissed: false, palettesFolder: "", palettesMigrated: false, - mapKinds: ["world", "space"], + // Space is opt-in (setup wizard / settings → Map types). Upgrades without + // the setting get space too if they already have space palettes + // (resolveMapKinds in src/mapKinds.ts). + mapKinds: ["world"], terrainTypesSeeded: false, }; diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 731192c3..282778cf 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -36,6 +36,7 @@ import { } from "../worldgen/neighbours"; import { randomSeed } from "../../packages/hex-wfc/src"; import { fillPaletteSelect } from "../palettes/paletteOptions"; +import { generatorMapKind, isGeneratorShown, isSpacePalette } from "../mapKinds"; import { NewMapSetupModal } from "../worldgen/NewMapSetupModal"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; @@ -745,9 +746,16 @@ export class MapModal extends HexmakerModal { const current = generatorSelect.value; generatorSelect.empty(); generatorSelect.createEl("option", { value: "", text: "Blank" }); - const names = this.plugin.getPaletteOrPresetTerrains(paletteSelect.value).map((t) => t.name); + const terrains = this.plugin.getPaletteOrPresetTerrains(paletteSelect.value); + const names = terrains.map((t) => t.name); + // Planet generators (map-kind: planet) only for space users or on a space palette. + const spaceContext = isSpacePalette(terrains); for (const g of generators) { - if (generatorFitsPalette(g.model, names)) + const shown = isGeneratorShown(this.plugin.settings, generatorMapKind(g.model.meta), { + spaceContext, + selected: g.file.path === current, + }); + if (shown && generatorFitsPalette(g.model, names)) generatorSelect.createEl("option", { value: g.file.path, text: g.model.name }); } generatorSelect.value = Array.from(generatorSelect.options).some((o) => o.value === current) ? current : ""; diff --git a/src/mapKinds.ts b/src/mapKinds.ts index 2b38f385..6043a41e 100644 --- a/src/mapKinds.ts +++ b/src/mapKinds.ts @@ -5,6 +5,8 @@ * palettes, maps or icons already in use. */ +import { terrainTypeInfo } from "./terrainTypes"; + export type MapKind = "world" | "space"; export interface MapKindInfo { @@ -19,12 +21,12 @@ export const MAP_KINDS: MapKindInfo[] = [ { id: "world", label: "World / fantasy overland", - description: "Continents, regions and local areas: forests, mountains, coasts. Includes the Limited and Expanded palettes and the Planet surface generator.", + description: "Continents, regions and local areas: forests, mountains, coasts. Includes the Limited and Expanded palettes and the Region detail generator.", }, { id: "space", label: "Space", - description: "Sector charts and star systems: Space - Sector / Space - System palettes, Star scatter and Orbits generators, the space icon pack.", + description: "Sector charts, star systems and planets: Space - Sector / Space - System palettes, Star scatter, Orbits and Planet surface generators, planet generators, the space icon pack.", iconPrefix: "space-", }, ]; @@ -46,3 +48,55 @@ export function isIconHiddenByKind(settings: { mapKinds?: string[] }, icon: stri const on = enabledKinds(settings); return MAP_KINDS.some((k) => k.iconPrefix && !on.has(k.id) && icon.startsWith(k.iconPrefix)); } + +/** + * Map type of a learned generator, from its note's `map-kind` frontmatter: + * "planet" / "space" → space, "world" → world, anything else → none + * (always shown). + */ +export function generatorMapKind(meta: Record | undefined): MapKind | undefined { + const raw = meta?.["map-kind"]?.trim().toLowerCase(); + if (raw === "planet" || raw === "space") return "space"; + if (raw === "world") return "world"; + return undefined; +} + +/** A space palette: at least one terrain has a space terrain type ("void", "star"…). */ +export function isSpacePalette(terrains: readonly { type?: string }[] | undefined): boolean { + return (terrains ?? []).some((t) => terrainTypeInfo(t.type)?.kind === "space"); +} + +export interface GeneratorShowContext { + /** The map being made is in space: its palette, or a parent map's, is a + * space palette (planet submaps of a system still get planet generators). */ + spaceContext?: boolean; + /** The current / saved choice: always shown so the value stays visible. */ + selected?: boolean; +} + +/** + * Should a generator of map type `kind` be offered? Yes when its type is on + * (no type = always), when it's a space generator and the map is in space, + * or when it's the current choice. + */ +export function isGeneratorShown( + settings: { mapKinds?: string[] }, + kind: MapKind | undefined, + ctx: GeneratorShowContext = {}, +): boolean { + return !!ctx.selected || isKindEnabled(settings, kind) || (kind === "space" && !!ctx.spaceContext); +} + +/** + * Map types for settings loaded from data.json. A saved list always wins. + * Missing (new install, or an upgrade from before map types): world, plus + * space if a palette already has space terrains — space users keep their + * options, everyone else isn't shown space ones. + */ +export function resolveMapKinds( + saved: unknown, + palettes: readonly { terrains: readonly { type?: string }[] }[], +): MapKind[] { + if (Array.isArray(saved)) return saved.filter((k): k is MapKind => (ALL_MAP_KINDS as unknown[]).includes(k)); + return palettes.some((p) => isSpacePalette(p.terrains)) ? ["world", "space"] : ["world"]; +} diff --git a/src/palettes/PaletteEditorView.ts b/src/palettes/PaletteEditorView.ts index 46d2ca1b..1226a59b 100644 --- a/src/palettes/PaletteEditorView.ts +++ b/src/palettes/PaletteEditorView.ts @@ -8,7 +8,8 @@ import { fillTerrainTypeSelect } from "../terrainTypeSelect"; import { inferTerrainType, terrainTypeInfo } from "../terrainTypes"; import { AddPaletteModal } from "./AddPaletteModal"; import { fillPaletteSelect } from "./paletteOptions"; -import { listGeneratorKinds, type TerrainGeneratorKind } from "../worldgen/registry"; +import { listGeneratorKinds, visibleKinds, type TerrainGeneratorKind } from "../worldgen/registry"; +import { isSpacePalette } from "../mapKinds"; /** * Palette editor page: the "advanced view" of palette editing. One row per @@ -372,7 +373,13 @@ export class PaletteEditorView extends ItemView { const genSel = tr.createEl("td").createEl("select"); genSel.createEl("option", { value: "", text: "—" }); - for (const g of this.generators) genSel.createEl("option", { value: g.id, text: g.label }); + // Space generators while Space is off: only for a space palette or a + // space submap palette (or the saved value). + const spaceContext = isSpacePalette(pal.terrains) + || (!!d.palette && isSpacePalette(this.plugin.getPaletteOrPresetTerrains(d.palette))); + for (const g of visibleKinds(this.generators, this.plugin.settings, spaceContext, d.generator)) { + genSel.createEl("option", { value: g.id, text: g.label }); + } if (d.generator && !this.generators.some((g) => g.id === d.generator)) { genSel.createEl("option", { value: d.generator, text: `${d.generator} (not available)` }); } diff --git a/src/palettes/paletteOptions.ts b/src/palettes/paletteOptions.ts index 4b5af6c7..eca8674f 100644 --- a/src/palettes/paletteOptions.ts +++ b/src/palettes/paletteOptions.ts @@ -1,6 +1,6 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import { PALETTE_PRESETS } from "./presets"; -import { isKindEnabled } from "../mapKinds"; +import { isKindEnabled, isSpacePalette } from "../mapKinds"; /** * Fill a palette with the installed palettes, then any built-in * presets not installed yet (labelled "(preset)"). Picking a preset is - * enough: createNewMap() installs it on first use. + * enough: createNewMap() installs it on first use. With no `selected`, + * the default for the enabled map types is picked (defaultPaletteFor). */ export function fillPaletteSelect( plugin: HexmakerPlugin, @@ -32,5 +55,10 @@ export function fillPaletteSelect( group.createEl("option", { value: p.name, text: `${p.name} (preset)`, attr: { title: p.description } }); } } - if (selected) select.value = selected; + if (selected) { + select.value = selected; + } else { + const fallback = defaultPaletteFor(plugin.settings); + if (Array.from(select.options).some((o) => o.value === fallback)) select.value = fallback; + } } diff --git a/src/setupPlaceholder.ts b/src/setupPlaceholder.ts new file mode 100644 index 00000000..9dfac950 --- /dev/null +++ b/src/setupPlaceholder.ts @@ -0,0 +1,37 @@ +/** + * The "default" map: DEFAULT_SETTINGS ships one so a fresh install has a + * map to open, and the map-note store writes its note + * (`{hexFolder}/default/_default.md`) at startup. Once the setup wizard + * has made the user's own first map, an untouched "default" is just a + * mystery entry in the map list, so the wizard removes it. + */ + +export const PLACEHOLDER_MAP_NAME = "default"; + +/** + * Is this the shipped placeholder, never used? True only when it has no + * hex data, paths, parent / world slot or background, no other map + * points at it, and its folder holds nothing but its own map note. + */ +export function isUnusedPlaceholderMap( + map: { + name: string; + pathChains?: unknown[]; + parent?: unknown; + world?: unknown; + backgroundImage?: unknown; + }, + usage: { + /** Hexes with data in the map store. */ + hexCount: number; + /** File / folder names directly inside the map's folder. */ + folderEntries: string[]; + /** Another map has it as parent, neighbour or submap. */ + referenced: boolean; + }, +): boolean { + if (map.name !== PLACEHOLDER_MAP_NAME) return false; + if (usage.hexCount > 0 || usage.referenced) return false; + if ((map.pathChains?.length ?? 0) > 0 || map.parent || map.world || map.backgroundImage) return false; + return usage.folderEntries.every((n) => n === `_${PLACEHOLDER_MAP_NAME}.md`); +} diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index 478a5d6c..a0b8ffab 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -9,7 +9,7 @@ import { neighbourSpec, occupiedSides, placeNewRegion, regionNameAt, type NewReg import type { Side as WorldSide } from "./world"; import { routeContextPaths } from "./procedural/contextPaths"; import type { GenerationContext, Side } from "./procedural/common"; -import { fillPaletteSelect } from "../palettes/paletteOptions"; +import { defaultPaletteFor, fillPaletteSelect } from "../palettes/paletteOptions"; import { isSpacePalette } from "../mapKinds"; import { defaultSubmapName } from "../hex-map/submapNav"; import { randomSeed } from "../../packages/hex-wfc/src"; @@ -65,6 +65,7 @@ export class NewMapSetupModal extends HexmakerModal { private placement: NewRegion | undefined; /** "Default for " checkboxes, one per option row. */ private remember = { palette: false, size: false, generator: false, base: false }; + private stopKeepInViewport?: () => void; constructor( app: App, @@ -99,6 +100,7 @@ export class NewMapSetupModal extends HexmakerModal { onOpen(): void { this.makeDraggable(); this.modalEl.addClass("duckmage-setup-modal"); + this.stopKeepInViewport = this.keepInViewport(); this.titleEl.setText( this.origin ? `New submap — ${this.originTerrain ? `${this.originTerrain}, ` : ""}${this.origin.map} hex ${this.origin.x}, ${this.origin.y}` @@ -112,6 +114,7 @@ export class NewMapSetupModal extends HexmakerModal { } onClose(): void { + this.stopKeepInViewport?.(); this.contentEl.empty(); } @@ -141,7 +144,7 @@ export class NewMapSetupModal extends HexmakerModal { this.plugin, paletteSelect, this.saved?.palette - ?? (this.origin ? this.plugin.childPaletteFor(this.origin.map) : this.plugin.settings.terrainPalettes[0]?.name), + ?? (this.origin ? this.plugin.childPaletteFor(this.origin.map) : defaultPaletteFor(this.plugin.settings)), ); this.rememberBox(palRow, "palette"); diff --git a/styles.css b/styles.css index 6278175d..d28cae77 100644 --- a/styles.css +++ b/styles.css @@ -6314,3 +6314,91 @@ button.duckmage-wfc-library-tab.is-active { margin: 0.5em auto; border-radius: var(--radius-s); } + +/* ── New map / submap setup modal: never taller than the window ────── + The form scrolls; the preview stays in view beside it and the + Generate / Cancel row is pinned to the bottom (fresh-eyes G11). + The draggable-modal rules (.duckmage-editor-modal-drag: 620px, flex + column) out-ranked the two-column setup layout, so it is restated at + higher specificity. NewMapSetupModal also keeps the modal on screen + as it grows (HexmakerModal.keepInViewport). */ +.modal.duckmage-setup-modal.duckmage-editor-modal-drag { + width: min(860px, 94vw); + max-height: calc(100vh - 16px); + display: flex; + flex-direction: column; + overflow: hidden; +} + +.duckmage-setup-modal > .modal-content.duckmage-setup-layout { + display: grid; + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + align-items: start; +} + +.duckmage-setup-layout > .duckmage-setup-preview { + position: sticky; + top: 0; +} + +.duckmage-setup-layout > .duckmage-setup-actions { + position: sticky; + bottom: 0; + z-index: 1; + padding: 0.6em 0 0.2em; + border-top: 1px solid var(--background-modifier-border); + background: var(--modal-background, var(--background-primary)); +} + +@media (max-width: 700px) { + .duckmage-setup-layout > .duckmage-setup-preview { + position: static; + } +} + +/* The preview canvas sits in the neighbour frame's centre cell; the 6em cap + on the frame's name cells shrank it to a thumbnail (fresh-eyes T8). */ +.duckmage-setup-ctx.duckmage-setup-ctx-C { + max-width: 100%; +} + +/* ── Setup wizard: first-map generator choice + preview ─────────────── */ +.duckmage-wizard-generator-body { + display: flex; + flex-wrap: wrap; + gap: 1em; + align-items: flex-start; +} + +.duckmage-wizard-generator-choices { + flex: 1 1 18em; + min-width: 0; + display: flex; + flex-direction: column; + gap: 0.6em; +} + +.duckmage-wizard-generator-options { + display: flex; + flex-wrap: wrap; + gap: 0.5em 1em; +} + +.duckmage-wizard-generator-option { + display: flex; + flex-direction: column; + gap: 0.2em; + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} + +.duckmage-wizard-generator-preview { + flex: 0 0 auto; + display: flex; + flex-direction: column; + align-items: center; + gap: 0.4em; + width: 240px; +} diff --git a/tests/worldgenFirstMap.test.ts b/tests/worldgenFirstMap.test.ts new file mode 100644 index 00000000..21f0aa40 --- /dev/null +++ b/tests/worldgenFirstMap.test.ts @@ -0,0 +1,204 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; +import { + OVERLAND_OPTIONS, + planetRoles, + planetSurface, + resolveSeaSide, + OVERLAND_ID, +} from "../src/worldgen/procedural/planetSurface"; +import { STAR_SCATTER_ID } from "../src/worldgen/procedural/starScatter"; +import { BLANK_ID, firstMapGenerator } from "../src/worldgen/registry"; +import { defaultPaletteFor } from "../src/palettes/paletteOptions"; +import { isUnusedPlaceholderMap } from "../src/setupPlaceholder"; +import type { ProcGrid } from "../src/worldgen/procedural/common"; +import type { TerrainColor } from "../src/types"; + +/** Fresh-eyes 2026-10-09 (#36): first-run wizard, Overland, Frozen, palette defaults. */ + +const grid: ProcGrid = { cols: 20, rows: 14, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; +const SEEDS = Array.from({ length: 12 }, (_, i) => i + 1); +const overland = (seed: number, options: Record, terrains: TerrainColor[] = DEFAULT_TERRAIN_PALETTE) => + planetSurface(terrains, grid, seed, options, undefined, "overland").cells; + +const typeOf = (terrains: TerrainColor[]) => new Map(terrains.map((t) => [t.name, t.type])); +const WET_TYPES = new Set(["water", "deep-water", "shallows"]); +const isWet = (types: Map) => (t: string | undefined) => !!t && WET_TYPES.has(types.get(t) ?? ""); + +/** Share of `cells` in the hexes picked by `where` that satisfy `pred`, averaged over seeds. */ +function share( + gen: (seed: number) => Map, + where: (x: number, y: number) => boolean, + pred: (t: string | undefined) => boolean, +): number { + let hit = 0, n = 0; + for (const seed of SEEDS) { + const cells = gen(seed); + for (let x = 0; x < grid.cols; x++) + for (let y = 0; y < grid.rows; y++) { + if (!where(x, y)) continue; + n++; + if (pred(cells.get(`${x}_${y}`))) hit++; + } + } + return hit / n; +} + +describe("Overland: a region, not a planet", () => { + const roles = planetRoles(DEFAULT_TERRAIN_PALETTE)!; + const edgeRows = (_x: number, y: number) => y === 0 || y === grid.rows - 1; + + it("has no polar ice on its top and bottom rows (temperate)", () => { + const icy = share((s) => overland(s, { climate: "temperate", sea: "scattered" }), edgeRows, (t) => t === roles.snow); + expect(icy).toBe(0); + }); + + it("Planet surface keeps its polar caps", () => { + const icy = share((s) => planetSurface(DEFAULT_TERRAIN_PALETTE, grid, s, { climate: "temperate" }).cells, edgeRows, (t) => t === roles.snow); + expect(icy).toBeGreaterThan(0.2); + }); + + it("puts the sea along the chosen side", () => { + const wet = isWet(typeOf(DEFAULT_TERRAIN_PALETTE)); + const bands: Record boolean, (x: number, y: number) => boolean]> = { + west: [(x) => x < 3, (x) => x >= grid.cols - 3], + east: [(x) => x >= grid.cols - 3, (x) => x < 3], + north: [(_x, y) => y < 2, (_x, y) => y >= grid.rows - 2], + south: [(_x, y) => y >= grid.rows - 2, (_x, y) => y < 2], + }; + for (const [side, [near, far]] of Object.entries(bands)) { + const gen = (s: number) => overland(s, { water: "30", sea: side }); + expect(share(gen, near, wet)).toBeGreaterThan(0.7); + expect(share(gen, far, wet)).toBeLessThan(0.1); + } + }); + + it("'around' makes an island; 'none' has no sea", () => { + const wet = isWet(typeOf(DEFAULT_TERRAIN_PALETTE)); + const border = (x: number, y: number) => x === 0 || y === 0 || x === grid.cols - 1 || y === grid.rows - 1; + const middle = (x: number, y: number) => Math.abs(x - grid.cols / 2) < 3 && Math.abs(y - grid.rows / 2) < 2; + const island = (s: number) => overland(s, { water: "50", sea: "around" }); + expect(share(island, border, wet)).toBeGreaterThan(0.8); + expect(share(island, middle, wet)).toBeLessThan(0.1); + expect(share((s) => overland(s, { water: "50", sea: "none" }), () => true, wet)).toBe(0); + }); + + it("'none' still makes ordinary land (no all-snow map from the lapse rate)", () => { + const cells = overland(3, { water: "50", sea: "none", climate: "temperate" }); + const snow = [...cells.values()].filter((t) => t === roles.snow).length; + expect(snow / cells.size).toBeLessThan(0.05); + expect(cells.size).toBe(grid.cols * grid.rows); + }); + + it("still hits the water fraction with a sea side", () => { + const wet = isWet(typeOf(DEFAULT_TERRAIN_PALETTE)); + for (const water of ["10", "50", "85"]) { + const frac = share((s) => overland(s, { water, sea: "east" }), () => true, wet); + expect(frac).toBeGreaterThanOrEqual(Number(water) / 100 - 0.06); + } + }); + + it("the Sea option defaults to a random side, picked from the seed", () => { + const opt = OVERLAND_OPTIONS.find((o) => o.key === "sea")!; + expect(opt.default).toBe("random"); + const sides = new Set(SEEDS.map((s) => resolveSeaSide("random", s))); + for (const s of sides) expect(["north", "east", "south", "west"]).toContain(s); + expect(sides.size).toBeGreaterThan(1); + expect(resolveSeaSide("random", 7)).toBe(resolveSeaSide(undefined, 7)); + expect(resolveSeaSide("west", 7)).toBe("west"); + expect(resolveSeaSide("bogus", 7)).toBe(resolveSeaSide("random", 7)); + }); + + it("is deterministic per seed", () => { + expect([...overland(9, {})]).toEqual([...overland(9, {})]); + }); +}); + +describe("Frozen climate: no temperate belt", () => { + const GREEN = new Set(["forest", "jungle", "grassland", "wetland"]); + for (const [label, terrains] of [["Expanded", DEFAULT_TERRAIN_PALETTE], ["Limited", LIMITED_TERRAIN_PALETTE]] as const) { + it(`Planet surface and Overland on ${label}: no forest, grass or swamp`, () => { + const types = typeOf(terrains); + for (const seed of SEEDS) { + const runs = [ + planetSurface(terrains, grid, seed, { water: "30", climate: "frozen" }).cells, + planetSurface(terrains, grid, seed, { water: "30", climate: "frozen" }, undefined, "overland").cells, + ]; + for (const cells of runs) { + for (const t of cells.values()) expect(GREEN.has(types.get(t) ?? "")).toBe(false); + } + } + }); + } + + it("temperate still grows forests (the fix is frozen-only)", () => { + const types = typeOf(DEFAULT_TERRAIN_PALETTE); + const forest = share((s) => planetSurface(DEFAULT_TERRAIN_PALETTE, grid, s, { water: "30", climate: "temperate" }).cells, + () => true, (t) => types.get(t ?? "") === "forest"); + expect(forest).toBeGreaterThan(0.05); + }); +}); + +describe("defaultPaletteFor (new-map palette by map type)", () => { + const pal = (name: string, terrains: TerrainColor[]) => ({ name, terrains }); + const fresh = [pal("Limited", LIMITED_TERRAIN_PALETTE), pal("Expanded", DEFAULT_TERRAIN_PALETTE)]; + + it("world users get their first overland palette", () => { + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: fresh })).toBe("Limited"); + expect(defaultPaletteFor({ mapKinds: ["world", "space"], terrainPalettes: fresh })).toBe("Limited"); + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [pal("Space - Sector", SPACE_SECTOR_TERRAINS), ...fresh] })).toBe("Limited"); + }); + + it("space-only users get a space palette, Space - Sector first", () => { + expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: fresh })).toBe("Space - Sector"); + expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: [...fresh, pal("Space - System", SPACE_SYSTEM_TERRAINS)] })).toBe("Space - System"); + expect(defaultPaletteFor({ + mapKinds: ["space"], + terrainPalettes: [...fresh, pal("Space - System", SPACE_SYSTEM_TERRAINS), pal("Space - Sector", SPACE_SECTOR_TERRAINS)], + })).toBe("Space - Sector"); + }); + + it("world users with no overland palette installed get the Limited preset", () => { + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [pal("Space - Sector", SPACE_SECTOR_TERRAINS)] })).toBe("Limited"); + }); +}); + +describe("firstMapGenerator (setup wizard default)", () => { + const k = (...ids: string[]) => ids.map((id) => ({ id })); + + it("world → Overland, space only → Star scatter", () => { + expect(firstMapGenerator(k(BLANK_ID, OVERLAND_ID), ["world"])).toBe(OVERLAND_ID); + expect(firstMapGenerator(k(BLANK_ID, OVERLAND_ID, STAR_SCATTER_ID), ["world", "space"])).toBe(OVERLAND_ID); + expect(firstMapGenerator(k(BLANK_ID, STAR_SCATTER_ID), ["space"])).toBe(STAR_SCATTER_ID); + }); + + it("follows the palette: a space palette for a world+space user → Star scatter", () => { + expect(firstMapGenerator(k(BLANK_ID, STAR_SCATTER_ID), ["world", "space"])).toBe(STAR_SCATTER_ID); + }); + + it("falls back to Blank", () => { + expect(firstMapGenerator(k(BLANK_ID), ["world"])).toBe(BLANK_ID); + expect(firstMapGenerator([], ["space"])).toBe(BLANK_ID); + }); +}); + +describe("isUnusedPlaceholderMap (the shipped 'default' map)", () => { + const map = { name: "default", pathChains: [] }; + const unused = { hexCount: 0, folderEntries: ["_default.md"], referenced: false }; + + it("an untouched default (just its map note, or no folder) is a placeholder", () => { + expect(isUnusedPlaceholderMap(map, unused)).toBe(true); + expect(isUnusedPlaceholderMap(map, { ...unused, folderEntries: [] })).toBe(true); + }); + + it("any use keeps it", () => { + expect(isUnusedPlaceholderMap({ ...map, name: "my-world" }, unused)).toBe(false); + expect(isUnusedPlaceholderMap(map, { ...unused, hexCount: 1 })).toBe(false); + expect(isUnusedPlaceholderMap(map, { ...unused, folderEntries: ["_default.md", "3_4.md"] })).toBe(false); + expect(isUnusedPlaceholderMap(map, { ...unused, referenced: true })).toBe(false); + expect(isUnusedPlaceholderMap({ ...map, pathChains: [{}] }, unused)).toBe(false); + expect(isUnusedPlaceholderMap({ ...map, world: { id: "w", cx: 0, cy: 0 } }, unused)).toBe(false); + }); +}); From 10a6bc619dc03c03b7c37854b082a29f6861ce70 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 19:45:38 -0400 Subject: [PATCH 080/558] feat: Simple and Advanced feature levels, with hints to ramp up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Simple covers running a hexcrawl: paint maps, hex notes, random tables, submaps, factions/regions, tokens, GM layer, background tracing, all exports. Advanced adds four features, each of which a Simple user can turn on by itself from where it would appear: - terrain generators (generator page, generator cards/lists in New map, learn-from-map, "Open in generator"); - workflows (random tables' Workflows tab, "Workflows using this table"); - custom palettes (palette editor); - neighbouring regions (Place next to / Next to / Connect to, Properties' neighbour block, the hex flower's new-land tile). Space stays its own switch (mapKinds) and brings its generators at either level. - src/featureLevel.ts: isAdvanced / hasFeature / enableFeature (all four on = Advanced), resolveFeatureLevel (saved wins; existing data = Advanced so updates lose nothing; fresh install = Simple, saved at once so the first save isn't mistaken for an update), shouldNudge. - src/advancedHints.ts: inline "✦ More" hints (closable per spot), "Turn on …?" when reaching for a feature (openTerrainGenerator and openPaletteEditor ask first), and a one-time "Ready for more?" check-in after two maps or two weeks. - Setup wizard: "How much do you want to start with?" next to map types; in Simple the first map still gets the starter generator. - Settings: Features section (level, per-feature toggles, show hints again) in both the declarative and fallback renderers. Help: a short Simple/Advanced section. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 60 +++++++++++++ src/HexmakerSettingTab.ts | 65 ++++++++++++++ src/SetupWizardView.ts | 41 ++++++++- src/advancedHints.ts | 127 +++++++++++++++++++++++++++ src/constants.ts | 5 ++ src/featureLevel.ts | 124 ++++++++++++++++++++++++++ src/hex-map/HexEditorModal.ts | 24 +++-- src/hex-map/MapModal.ts | 48 ++++++++-- src/hex-map/help.md | 6 ++ src/random-tables/RandomTableView.ts | 20 ++++- src/types.ts | 32 ++++--- src/worldgen/GeneratorPanel.ts | 9 ++ src/worldgen/NewMapSetupModal.ts | 13 ++- src/worldgen/registry.ts | 11 ++- styles.css | 34 +++++++ tests/featureLevel.test.ts | 63 +++++++++++++ 17 files changed, 651 insertions(+), 35 deletions(-) create mode 100644 src/advancedHints.ts create mode 100644 src/featureLevel.ts create mode 100644 tests/featureLevel.test.ts diff --git a/package.json b/package.json index d730c875..464960e4 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/featureLevel.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/featureLevel.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 9dca6317..7729d1f8 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -26,6 +26,8 @@ import { SetupWizardView } from "./SetupWizardView"; import { PaletteStore } from "./palettes/PaletteStore"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; import { isIconHiddenByKind, isSpacePalette, resolveMapKinds } from "./mapKinds"; +import { enableFeature, hasFeature, resolveFeatureLevel, shouldNudge, type AdvancedFeature, type FeatureLevel } from "./featureLevel"; +import { AdvancedNudgeModal, EnableFeatureModal } from "./advancedHints"; import { mapAncestors } from "./hex-map/submapNav"; import { getPreset, @@ -79,6 +81,11 @@ export default class HexmakerPlugin extends Plugin { void this.autoRegisterMapsFromVault(); if (!this.settings.setupComplete && !this.settings.setupDismissed) { this.openSetupWizard(); + } else if (shouldNudge(this.settings, this.settings.maps.length)) { + // A Simple user who's been at it a while: offer Advanced, once. + this.settings.advancedNudgeAt = new Date().toISOString().slice(0, 10); + void this.saveSettings(); + new AdvancedNudgeModal(this.app, this).open(); } }); @@ -445,6 +452,11 @@ export default class HexmakerPlugin extends Plugin { * region and generator selected. */ async openTerrainGenerator(select: { mapName?: string; generatorPath?: string; paletteName?: string } = {}): Promise { + // An Advanced feature: in Simple, offer to turn it on first. + if (!hasFeature(this.settings, "generators")) { + new EnableFeatureModal(this.app, this, "generators", () => void this.openTerrainGenerator(select)).open(); + return; + } if (select.mapName) GeneratorPanel.mapName = select.mapName; if (select.paletteName) GeneratorPanel.paletteName = select.paletteName; if (select.generatorPath) GeneratorPanel.selectedPath = select.generatorPath; @@ -534,6 +546,17 @@ export default class HexmakerPlugin extends Plugin { // (new install / older data) = world, plus space if a palette has space // terrains already. this.settings.mapKinds = resolveMapKinds(data["mapKinds"], this.settings.terrainPalettes); + // Feature level, also from the raw data: an install that already had + // settings (an update) gets Advanced so nothing it used disappears; a + // fresh one starts Simple. Saved right away, so the next load doesn't + // mistake a fresh install's first save for an update. + const rawData = (await this.loadData()) as Record | null; + this.settings.featureLevel = resolveFeatureLevel(rawData); + this.settings.advancedFeatures = Array.isArray(data["advancedFeatures"]) ? (data["advancedFeatures"] as unknown[]).filter((f): f is string => typeof f === "string") : []; + this.settings.dismissedHints = Array.isArray(data["dismissedHints"]) ? (data["dismissedHints"] as unknown[]).filter((f): f is string => typeof f === "string") : []; + const firstLevel = rawData?.["featureLevel"] === undefined; + if (!this.settings.installedAt) this.settings.installedAt = new Date().toISOString().slice(0, 10); + if (firstLevel || !rawData?.["installedAt"]) await this.saveData(this.settings); } async saveSettings() { @@ -592,6 +615,11 @@ export default class HexmakerPlugin extends Plugin { /** Open (or focus) the palette editor page, optionally on one palette. */ async openPaletteEditor(paletteName?: string): Promise { + // An Advanced feature: in Simple, offer to turn it on first. + if (!hasFeature(this.settings, "palettes")) { + new EnableFeatureModal(this.app, this, "palettes", () => void this.openPaletteEditor(paletteName)).open(); + return; + } if (paletteName) PaletteEditorView.paletteName = paletteName; const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_PALETTE_EDITOR)[0]; if (existing) { @@ -614,6 +642,38 @@ export default class HexmakerPlugin extends Plugin { * pickers and re-render open pages that list palettes or generators so * the change shows at once. Modals read the setting when they open. */ + /** Switch between Simple and Advanced (settings, wizard, hints). */ + async setFeatureLevel(level: FeatureLevel): Promise { + this.settings.featureLevel = level; + await this.saveSettings(); + this.onFeaturesChanged(); + } + + /** Turn on one Advanced feature while in Simple (see enableFeature). */ + async enableAdvancedFeature(f: AdvancedFeature): Promise { + enableFeature(this.settings, f); + await this.saveSettings(); + this.onFeaturesChanged(); + } + + /** Turn off one Advanced feature that was turned on by itself (Simple only). */ + async disableAdvancedFeature(f: AdvancedFeature): Promise { + this.settings.advancedFeatures = this.settings.advancedFeatures.filter((x) => x !== f); + await this.saveSettings(); + this.onFeaturesChanged(); + } + + /** + * Feature level or an Advanced feature changed: re-render open pages that + * show or hide features (modals read the setting when they open). + */ + onFeaturesChanged(): void { + this.onMapKindsChanged(); + for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_RANDOM_TABLES)) { + if (leaf.view instanceof RandomTableView) leaf.view.refreshFeatures(); + } + } + onMapKindsChanged(): void { this.loadAvailableIcons(); this.refreshPaletteEditors(); diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index 4a9a12e6..d095961b 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -3,6 +3,7 @@ import type HexmakerPlugin from "./HexmakerPlugin"; import { normalizeFolder } from "./utils"; import { AddPaletteModal } from "./palettes/AddPaletteModal"; import { MAP_KINDS, enabledKinds, type MapKind } from "./mapKinds"; +import { ADVANCED_FEATURES, hasFeature, isAdvanced } from "./featureLevel"; const PALETTES_FOLDER_DESC = "Vault-relative folder for terrain palette notes (one note per palette — edit as text, copy between vaults to share). Defaults to a palettes folder inside the world folder."; @@ -226,6 +227,11 @@ export class HexmakerSettingTab extends PluginSettingTab { ); }, }, + { + type: "group", + heading: "Features", + items: this.featureItems(), + }, { name: "Default die for new tables", desc: "Die size used when creating new random table notes (d6, d20, d100, etc.).", @@ -765,6 +771,58 @@ export class HexmakerSettingTab extends PluginSettingTab { }); } + /** + * Feature level (src/featureLevel.ts): Simple or Advanced, each Advanced + * feature on its own while in Simple, and a way to bring closed hints back. + */ + private featureItems(): LocalSettingDefinition[] { + const s = this.plugin.settings; + const refresh = () => { + if (typeof (this as unknown as { update?: () => void }).update === "function") this.requestDeclarativeRerender(); + else this.renderSettings(); + }; + const items: LocalSettingDefinition[] = [ + { + name: "Feature level", + desc: "Simple: paint maps, write hex notes, roll on encounter tables, export. Advanced: also terrain generators, workflows, custom palettes and neighbouring regions. Nothing you've made is touched either way.", + aliases: ["simple", "advanced", "mode"], + render: (setting: Setting) => { + setting.addDropdown((d) => + d.addOption("simple", "Simple").addOption("advanced", "Advanced") + .setValue(s.featureLevel) + .onChange((v) => void this.plugin.setFeatureLevel(v === "simple" ? "simple" : "advanced").then(refresh)), + ); + }, + }, + ]; + for (const f of ADVANCED_FEATURES) { + items.push({ + name: f.label, + desc: isAdvanced(s) ? `${f.pitch} (On with Advanced.)` : f.pitch, + render: (setting: Setting) => { + setting.addToggle((t) => { + t.setValue(hasFeature(s, f.id)).setDisabled(isAdvanced(s)); + t.onChange((on) => void (on ? this.plugin.enableAdvancedFeature(f.id) : this.plugin.disableAdvancedFeature(f.id)).then(refresh)); + }); + }, + }); + } + if (s.dismissedHints.length) + items.push({ + name: "Hints", + desc: `${s.dismissedHints.length} hint${s.dismissedHints.length === 1 ? "" : "s"} about Advanced features hidden.`, + render: (setting: Setting) => { + setting.addButton((b) => + b.setButtonText("Show hints again").onClick(() => { + s.dismissedHints = []; + void this.plugin.saveSettings().then(refresh); + }), + ); + }, + }); + return items; + } + private requestDeclarativeRerender(): void { const tab = this as unknown as { update?: () => void }; if (typeof tab.update !== "function") return; @@ -859,6 +917,13 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); + new Setting(containerEl).setName("Features").setHeading(); + for (const item of this.featureItems()) { + const s = new Setting(containerEl).setName(item.name ?? ""); + if (typeof item.desc === "string") s.setDesc(item.desc); + item.render?.(s); + } + new Setting(containerEl) .setName("Default die for new tables") .setDesc( diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index b2839190..bfa56eeb 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -6,6 +6,7 @@ import { normalizeFolder, slugify } from "./utils"; import { VIEW_TYPE_SETUP_WIZARD, VIEW_TYPE_HEX_MAP } from "./constants"; import { defaultPaletteFor, fillPaletteSelect } from "./palettes/paletteOptions"; import { MAP_KINDS, enabledKinds, isSpacePalette, type MapKind } from "./mapKinds"; +import { FEATURE_LEVEL_CHOICES, type FeatureLevel } from "./featureLevel"; import { randomSeed } from "../packages/hex-wfc/src"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "./worldgen/preview"; import { pathColors } from "./worldgen/generators"; @@ -46,6 +47,8 @@ interface WizardContext { hexOrientation: "flat" | "pointy"; /** Map types to enable (src/mapKinds.ts). */ mapKinds: MapKind[]; + /** Simple or Advanced (src/featureLevel.ts). */ + featureLevel: FeatureLevel; /** Generator for the first map (registry id); undefined = pick the * default for the map types and palette (firstMapGenerator). */ generatorId?: string; @@ -140,11 +143,17 @@ function wizardKinds( ctx: WizardContext, terrains: TerrainColor[], ): { fitting: TerrainGeneratorKind[]; selected: string } { - const shown = visibleKinds(kinds, { mapKinds: ctx.mapKinds }, isSpacePalette(terrains), ctx.generatorId); - const fitting = kindsForPalette(shown, terrains); + // Choose among every generator the map types allow, then (in Simple) keep + // just Blank and the default starter, so a Simple first map still gets + // terrain without a wall of choices. + const all = kindsForPalette(visibleKinds(kinds, { mapKinds: ctx.mapKinds, featureLevel: "advanced" }, isSpacePalette(terrains), ctx.generatorId), terrains); + const starter = firstMapGenerator(all, ctx.mapKinds); + const fitting = ctx.featureLevel === "simple" + ? all.filter((k) => k.id === BLANK_ID || k.id === starter || k.mapKind === "space") + : all; const selected = ctx.generatorId && fitting.some((k) => k.id === ctx.generatorId) ? ctx.generatorId - : firstMapGenerator(fitting, ctx.mapKinds); + : starter; return { fitting, selected }; } @@ -215,10 +224,28 @@ function makeWelcomeStep(): WizardStep { cbs.onUpdate(); }); } + + // How much to start with. Changeable any time in settings, and + // any one Advanced feature can be turned on from where it would appear. + const level = container.createDiv({ cls: "duckmage-wizard-field duckmage-wizard-kinds" }); + level.createEl("label", { text: "How much do you want to start with?", cls: "duckmage-wizard-label" }); + for (const opt of FEATURE_LEVEL_CHOICES) { + const row = level.createEl("label", { cls: "duckmage-wizard-kind" }); + const radio = row.createEl("input", { type: "radio", attr: { name: "duckmage-feature-level" } }); + radio.checked = ctx.featureLevel === opt.id; + const text = row.createDiv(); + text.createDiv({ text: opt.label, cls: "duckmage-wizard-kind-title" }); + text.createDiv({ text: opt.description, cls: "duckmage-wizard-kind-desc" }); + radio.addEventListener("change", () => { + if (radio.checked) ctx.featureLevel = opt.id; + cbs.onUpdate(); + }); + } }, canProceed: (ctx) => ctx.mapKinds.length > 0, async onNext(ctx, plugin) { plugin.settings.mapKinds = [...ctx.mapKinds]; + plugin.settings.featureLevel = ctx.featureLevel; // Start the first map on a palette of a chosen map type: Space // only → a sector chart (Space - Sector, installed on create). const palIsSpace = isSpacePalette(plugin.getPaletteOrPresetTerrains(ctx.paletteName)); @@ -476,6 +503,13 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { const genBody = genField.createDiv({ cls: "duckmage-wizard-generator-body" }); const genSide = genBody.createDiv({ cls: "duckmage-wizard-generator-choices" }); const genList = genSide.createDiv({ cls: "duckmage-setup-generators", text: "Loading generators…" }); + // Simple offers just the starter generator; say there's more. + if (ctx.featureLevel === "simple") { + genSide.createDiv({ + text: "More generators (learned from your own maps, biome presets, blends) come with the advanced features; turn them on any time.", + cls: "duckmage-wizard-kind-desc", + }); + } const optsBox = genSide.createDiv({ cls: "duckmage-wizard-generator-options" }); const previewBox = genBody.createDiv({ cls: "duckmage-wizard-generator-preview" }); const canvas = previewBox.createEl("canvas", { cls: "duckmage-setup-canvas" }); @@ -721,6 +755,7 @@ export class SetupWizardView extends ItemView { paletteName: defaultPaletteFor(plugin.settings), hexOrientation: plugin.settings.hexOrientation ?? "flat", mapKinds: [...enabledKinds(plugin.settings)], + featureLevel: plugin.settings.featureLevel, generatorOptions: {}, seed: randomSeed(), }; diff --git a/src/advancedHints.ts b/src/advancedHints.ts new file mode 100644 index 00000000..a8ec2585 --- /dev/null +++ b/src/advancedHints.ts @@ -0,0 +1,127 @@ +/** + * The ways a Simple user finds Advanced features (see src/featureLevel.ts): + * a small "More" line where a hidden feature would sit, a "Turn on …?" box + * when they reach for one, and a one-time "Ready for more?" check-in. Every + * hint turns on just that feature or all of Advanced, and can be closed. + */ + +import { App } from "obsidian"; +import type HexmakerPlugin from "./HexmakerPlugin"; +import { HexmakerModal } from "./HexmakerModal"; +import { ADVANCED_FEATURES, hasFeature, type AdvancedFeature } from "./featureLevel"; + +const info = (f: AdvancedFeature) => ADVANCED_FEATURES.find((x) => x.id === f)!; + +/** + * A one-line "More: …" hint in `parent` for a feature that's off, unless + * it's on or this spot's hint was closed. `spot` names the place (one id per + * screen), so closing it there doesn't hide it elsewhere. `text` overrides + * the feature's own pitch with one that fits the spot. + */ +export function renderAdvancedHint( + parent: HTMLElement, + plugin: HexmakerPlugin, + feature: AdvancedFeature, + spot: string, + text?: string, +): HTMLElement | null { + const s = plugin.settings; + if (hasFeature(s, feature) || s.dismissedHints.includes(spot)) return null; + const f = info(feature); + const el = parent.createDiv({ cls: "duckmage-advanced-hint" }); + el.createSpan({ text: "✦", cls: "duckmage-advanced-hint-mark" }); + el.createSpan({ text: text ?? f.pitch, cls: "duckmage-advanced-hint-text" }); + const on = el.createEl("button", { text: `Turn on ${f.label.toLowerCase()}`, cls: "duckmage-advanced-hint-on" }); + on.addEventListener("click", () => void plugin.enableAdvancedFeature(feature)); + const close = el.createEl("button", { text: "✕", cls: "duckmage-advanced-hint-close", attr: { "aria-label": "Hide this hint", title: "Hide this hint (the features section of settings can show it again)" } }); + close.addEventListener("click", () => { + s.dismissedHints = [...new Set([...s.dismissedHints, spot])]; + void plugin.saveSettings(); + el.remove(); + }); + return el; +} + +/** "Turn on ?": shown when a Simple user reaches for an Advanced feature. */ +export class EnableFeatureModal extends HexmakerModal { + constructor( + app: App, + private plugin: HexmakerPlugin, + private feature: AdvancedFeature, + private onEnabled: () => void, + ) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + const f = info(this.feature); + this.titleEl.setText(`Turn on ${f.label.toLowerCase()}?`); + const { contentEl } = this; + contentEl.createEl("p", { text: f.pitch }); + contentEl.createEl("p", { + text: "It's one of the advanced features. Turn on just this, or all of them; either can be turned off again in settings, and nothing you've made is touched.", + cls: "duckmage-map-origin-desc", + }); + const row = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); + const one = row.createEl("button", { text: `Turn on ${f.label.toLowerCase()}`, cls: "mod-cta" }); + one.addEventListener("click", () => void this.enable(false)); + row.createEl("button", { text: "Turn on all advanced features" }).addEventListener("click", () => void this.enable(true)); + row.createEl("button", { text: "Not now" }).addEventListener("click", () => this.close()); + } + + private async enable(all: boolean): Promise { + if (all) await this.plugin.setFeatureLevel("advanced"); + else await this.plugin.enableAdvancedFeature(this.feature); + this.close(); + this.onEnabled(); + } + + onClose(): void { + this.contentEl.empty(); + } +} + +/** Run `then` now if the feature is on, else after the user turns it on. */ +export function withFeature(plugin: HexmakerPlugin, feature: AdvancedFeature, then: () => void): void { + if (hasFeature(plugin.settings, feature)) then(); + else new EnableFeatureModal(plugin.app, plugin, feature, then).open(); +} + +/** The one-time "Ready for more?" check-in (see shouldNudge). */ +export class AdvancedNudgeModal extends HexmakerModal { + constructor(app: App, private plugin: HexmakerPlugin) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + this.titleEl.setText("Ready for more?"); + const { contentEl } = this; + contentEl.createEl("p", { text: "You've got the hang of the basics. Advanced adds:" }); + const list = contentEl.createEl("ul"); + for (const f of ADVANCED_FEATURES) { + if (hasFeature(this.plugin.settings, f.id)) continue; + const li = list.createEl("li"); + li.createEl("strong", { text: `${f.label}: ` }); + li.appendText(f.pitch); + } + contentEl.createEl("p", { text: "You can switch back any time in settings; nothing you've made is touched.", cls: "duckmage-map-origin-desc" }); + const row = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); + const on = row.createEl("button", { text: "Turn on advanced features", cls: "mod-cta" }); + on.addEventListener("click", () => { + void this.plugin.setFeatureLevel("advanced"); + this.close(); + }); + row.createEl("button", { text: "Not now" }).addEventListener("click", () => this.close()); + row.createEl("button", { text: "Don't ask again" }).addEventListener("click", () => { + this.plugin.settings.advancedNudgeOff = true; + void this.plugin.saveSettings(); + this.close(); + }); + } + + onClose(): void { + this.contentEl.empty(); + } +} diff --git a/src/constants.ts b/src/constants.ts index 0a6e6496..827c542d 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -387,5 +387,10 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { // the setting get space too if they already have space palettes // (resolveMapKinds in src/mapKinds.ts). mapKinds: ["world"], + // Resolved at load from the raw data (resolveFeatureLevel): updates from + // before feature levels get Advanced, fresh installs start Simple. + featureLevel: "simple", + advancedFeatures: [], + dismissedHints: [], terrainTypesSeeded: false, }; diff --git a/src/featureLevel.ts b/src/featureLevel.ts new file mode 100644 index 00000000..e18b1fbe --- /dev/null +++ b/src/featureLevel.ts @@ -0,0 +1,124 @@ +/** + * Feature level: Simple or Advanced. Simple is everything needed to run a + * hexcrawl (paint maps, write hex notes, roll on tables, export); Advanced + * adds the power tools below. Simple users can turn on any one of them from + * the screen where it would appear (see renderAdvancedHint), so they ramp up + * at their own pace; turning on all of them is the same as Advanced. + * + * Hiding a feature never touches its data: generators, workflows, palettes + * and linked regions all stay on disk and come back when it's turned on. + * Space (src/mapKinds.ts) is a separate switch and brings all its content, + * generators included, at either level. + */ + +export type FeatureLevel = "simple" | "advanced"; + +export type AdvancedFeature = "generators" | "workflows" | "palettes" | "regions"; + +export interface AdvancedFeatureInfo { + id: AdvancedFeature; + label: string; + /** One line on what it adds, for hints, settings and the wizard. */ + pitch: string; +} + +export const ADVANCED_FEATURES: AdvancedFeatureInfo[] = [ + { + id: "generators", + label: "Terrain generators", + pitch: "Generate terrain for you: learned from maps you've painted, or from biome presets, blended between biomes.", + }, + { + id: "workflows", + label: "Workflows", + pitch: "Chain several table rolls into one filled-in note (a settlement, an NPC, a dungeon room).", + }, + { + id: "palettes", + label: "Custom palettes", + pitch: "Design your own palettes: terrains, colours, icons, path types and submap defaults.", + }, + { + id: "regions", + label: "Neighbouring regions", + pitch: "Join maps edge to edge into one big world and walk from one into the next.", + }, +]; + +export const ALL_ADVANCED_FEATURES: AdvancedFeature[] = ADVANCED_FEATURES.map((f) => f.id); + +export interface FeatureSettings { + featureLevel?: FeatureLevel; + /** Advanced features turned on one by one while in Simple. */ + advancedFeatures?: string[]; +} + +export const isAdvanced = (s: FeatureSettings): boolean => s.featureLevel !== "simple"; + +/** Is this Advanced feature on: Advanced level, or turned on by itself. */ +export function hasFeature(s: FeatureSettings, f: AdvancedFeature): boolean { + return isAdvanced(s) || (s.advancedFeatures ?? []).includes(f); +} + +/** + * Turn one feature on (in place). Once every feature is on, the level + * becomes Advanced, so features added later come on too. + */ +export function enableFeature(s: FeatureSettings, f: AdvancedFeature): void { + const on = new Set(s.advancedFeatures ?? []); + on.add(f); + s.advancedFeatures = [...on]; + if (ALL_ADVANCED_FEATURES.every((x) => on.has(x))) s.featureLevel = "advanced"; +} + +/** + * The level for settings as loaded. A saved level always wins. Without one, + * an install that already has data (any saved settings: an update from a + * version before feature levels) gets Advanced so nothing it used + * disappears; a fresh install starts Simple until the setup wizard asks. + */ +export function resolveFeatureLevel(raw: Record | null | undefined): FeatureLevel { + const saved = raw?.["featureLevel"]; + if (saved === "simple" || saved === "advanced") return saved; + return raw && Object.keys(raw).length > 0 ? "advanced" : "simple"; +} + +/** Settings for the one-time "ready for more?" check-in. */ +export interface NudgeSettings extends FeatureSettings { + /** When the plugin first ran (ISO date). */ + installedAt?: string; + /** Last time the check-in was shown (ISO date). */ + advancedNudgeAt?: string; + /** "Don't ask again". */ + advancedNudgeOff?: boolean; +} + +/** Days after install, or maps made, before the check-in; and days between asks. */ +export const NUDGE = { afterDays: 14, afterMaps: 2, againDays: 14 }; + +const days = (from: string | undefined, now: Date): number => + from ? (now.getTime() - new Date(from).getTime()) / 86_400_000 : 0; + +/** + * Time to ask a Simple user whether they want Advanced: they've been at it a + * while (two weeks, or a couple of maps made) and weren't asked recently. + */ +export function shouldNudge(s: NudgeSettings, mapCount: number, now = new Date()): boolean { + if (isAdvanced(s) || s.advancedNudgeOff) return false; + if (s.advancedNudgeAt && days(s.advancedNudgeAt, now) < NUDGE.againDays) return false; + return mapCount >= NUDGE.afterMaps || days(s.installedAt, now) >= NUDGE.afterDays; +} + +/** The setup wizard's "How much do you want to start with?" choices. */ +export const FEATURE_LEVEL_CHOICES: { id: FeatureLevel; label: string; description: string }[] = [ + { + id: "simple", + label: "Simple", + description: "Paint maps, write hex notes, roll on encounter tables: everything you need to run a hexcrawl. You can turn on more later from any screen.", + }, + { + id: "advanced", + label: "Advanced", + description: "Also generates terrain for you (learned from your own maps, or from presets), chains tables into workflows, lets you design your own palettes, and joins maps into one big world.", + }, +]; diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 7ba6d728..850c7280 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -31,6 +31,8 @@ import { VIEW_TYPE_HEX_MAP, VIEW_TYPE_RANDOM_TABLES } from "../constants"; import { resolveHex, type Side } from "../worldgen/world"; import { neighbourSpec } from "../worldgen/neighbours"; import { WalkRegionModal } from "../worldgen/WalkRegionModal"; +import { hasFeature } from "../featureLevel"; +import { withFeature } from "../advancedHints"; import type { MapData } from "../types"; import { RegionNavigateModal } from "./RegionNavigateModal"; @@ -395,15 +397,21 @@ export class HexEditorModal extends HexmakerModal { const side = offMapSide(here, nx, ny); tile.addClass("duckmage-neighbor-tile-new"); tile.removeClass("duckmage-neighbor-tile-offmap"); - tile.title = `New land to the ${side}…`; + tile.title = hasFeature(this.plugin.settings, "regions") + ? `New land to the ${side}…` + : `Join a new map to the ${side} (neighbouring regions)…`; tile.addEventListener("click", () => { - new WalkRegionModal(this.app, this.plugin, this.mapName, side, () => { - const now = this.plugin.getMap(this.mapName); - const arrived = now ? resolveHex(this.plugin.settings.maps, now, nx, ny) : null; - if (!arrived || arrived.map.name === this.mapName) return; - this.close(); - this.options.onCrossToRegion?.(arrived.map.name, arrived.x, arrived.y); - }).open(); + // Needs neighbouring regions, and generators to pick a biome; + // in Simple each asks to be turned on first. + withFeature(this.plugin, "regions", () => withFeature(this.plugin, "generators", () => { + new WalkRegionModal(this.app, this.plugin, this.mapName, side, () => { + const now = this.plugin.getMap(this.mapName); + const arrived = now ? resolveHex(this.plugin.settings.maps, now, nx, ny) : null; + if (!arrived || arrived.map.name === this.mapName) return; + this.close(); + this.options.onCrossToRegion?.(arrived.map.name, arrived.x, arrived.y); + }).open(); + })); }); } else { tile.title = "Off map"; diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 73344d50..b8f3bedb 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -36,6 +36,8 @@ import { import { randomSeed } from "../../packages/hex-wfc/src"; import { fillPaletteSelect } from "../palettes/paletteOptions"; import { generatorMapKind, isGeneratorShown, isSpacePalette } from "../mapKinds"; +import { hasFeature } from "../featureLevel"; +import { renderAdvancedHint, withFeature } from "../advancedHints"; import { NewMapSetupModal } from "../worldgen/NewMapSetupModal"; const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "svg", "bmp"]; @@ -533,6 +535,12 @@ export class MapModal extends HexmakerModal { * lining up, slot free) are offered; an empty side can get a new region. */ private renderNeighbourBlock(el: HTMLElement, map: MapData): void { + // An Advanced feature; a map that's already linked keeps showing its links. + if (!hasFeature(this.plugin.settings, "regions") && !map.world) { + renderAdvancedHint(el, this.plugin, "regions", "map-properties", + "Join this map edge to edge with others into one big world, and walk from one into the next: neighbouring regions."); + return; + } el.createEl("h4", { text: "Neighbouring regions" }); el.createEl("p", { text: "Regions next to each other share one grid: walking off this map's edge (or the hex flower) leads into them. They must be the same size and use the same palette.", @@ -675,18 +683,25 @@ export class MapModal extends HexmakerModal { // Place next to an existing map: it becomes a neighbouring region on the // same grid, so size, palette, stagger and coordinates follow from it. - el.createEl("label", { text: "Place next to", cls: "duckmage-map-field-label" }); - el.createEl("p", { + // Neighbouring regions are an Advanced feature (hidden, with a hint, in Simple). + const placeBox = el.createDiv(); + if (!hasFeature(this.plugin.settings, "regions")) { + placeBox.hide(); + renderAdvancedHint(el, this.plugin, "regions", "new-map-place", + "Place a new map next to an existing one, so they join into one world: neighbouring regions."); + } + placeBox.createEl("label", { text: "Place next to", cls: "duckmage-map-field-label" }); + placeBox.createEl("p", { text: "Make this map a neighbouring region of another: it's the same size and palette, and lines up with it hex for hex.", cls: "duckmage-map-origin-desc", }); - const placeRow = el.createDiv({ cls: "duckmage-region-row" }); + const placeRow = placeBox.createDiv({ cls: "duckmage-region-row" }); const anchorSelect = placeRow.createEl("select"); anchorSelect.createEl("option", { value: "", text: "Nowhere (a separate map)" }); for (const m of this.plugin.settings.maps) anchorSelect.createEl("option", { value: m.name, text: m.name }); const sideSelect = placeRow.createEl("select"); for (const s of SIDES) sideSelect.createEl("option", { value: s, text: `${s} of it` }); - const placeNote = el.createEl("p", { cls: "duckmage-map-origin-desc" }); + const placeNote = placeBox.createEl("p", { cls: "duckmage-map-origin-desc" }); if (this.newMapPlacement) { anchorSelect.value = this.newMapPlacement.anchor; sideSelect.value = this.newMapPlacement.side; @@ -730,15 +745,21 @@ export class MapModal extends HexmakerModal { const paletteRow = el.createDiv({ cls: "duckmage-region-row" }); const paletteSelect = paletteRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); fillPaletteSelect(this.plugin, paletteSelect); + renderAdvancedHint(el, this.plugin, "palettes", "new-map-palette", + "Design your own palette: its terrains, colours and icons, and the paths you can draw."); // Generator (optional). Only generators whose terrains all exist in the // chosen palette are offered. - el.createEl("label", { text: "Generator", cls: "duckmage-map-field-label" }); - el.createEl("p", { + const generatorBox = el.createDiv(); + const generatorHint = el.createDiv(); + renderAdvancedHint(generatorHint, this.plugin, "generators", "new-map-generator", + "Fill a new map with generated terrain instead of painting it all by hand: terrain generators."); + generatorBox.createEl("label", { text: "Generator", cls: "duckmage-map-field-label" }); + generatorBox.createEl("p", { text: "Fill the new map with generated terrain, or leave it blank. Make generators and change their settings in the terrain generator.", cls: "duckmage-map-origin-desc", }); - const generatorRow = el.createDiv({ cls: "duckmage-region-row" }); + const generatorRow = generatorBox.createDiv({ cls: "duckmage-region-row" }); const generatorSelect = generatorRow.createEl("select", { cls: "duckmage-map-new-palette-select" }); let generators: GeneratorFile[] = []; const fillGenerators = () => { @@ -754,10 +775,16 @@ export class MapModal extends HexmakerModal { spaceContext, selected: g.file.path === current, }); - if (shown && generatorFitsPalette(g.model, names)) + // Generators are Advanced; Space brings its own at either level. + const allowed = hasFeature(this.plugin.settings, "generators") || generatorMapKind(g.model.meta) === "space"; + if (shown && allowed && generatorFitsPalette(g.model, names)) generatorSelect.createEl("option", { value: g.file.path, text: g.model.name }); } generatorSelect.value = Array.from(generatorSelect.options).some((o) => o.value === current) ? current : ""; + // Nothing but Blank to offer (Simple, no space generators): a hint instead. + const none = generatorSelect.options.length <= 1 && !hasFeature(this.plugin.settings, "generators"); + generatorBox.toggle(!none); + generatorHint.toggle(none); }; fillGenerators(); paletteSelect.addEventListener("change", fillGenerators); @@ -965,6 +992,11 @@ export class MapModal extends HexmakerModal { /** Learn a generator from a region and open it in the terrain generator. */ private async createGeneratorFrom(mapName: string): Promise { + // An Advanced feature: in Simple, offer to turn it on first. + if (!hasFeature(this.plugin.settings, "generators")) { + withFeature(this.plugin, "generators", () => void this.createGeneratorFrom(mapName)); + return; + } const result = await saveGeneratorFromMap(this.plugin, mapName, mapName); if ("error" in result) { new Notice(result.error); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 773977b5..e0e1c49c 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -77,3 +77,9 @@ Create a note-backed token (icon, shape, size, colors, description) and place it | **⊞** | Open the Hex Table — a spreadsheet view of all hex notes with filters and sorting | | **🎲** | Open the Random Tables browser — roll on any table, view odds, edit entries | | **⌖** | Go to a specific hex by entering X, Y coordinates | + +## Simple and Advanced + +**Simple** has everything you need to run a hexcrawl: paint maps, write hex notes, roll on encounter tables, export. **Advanced** adds terrain generators, workflows (chained table rolls), custom palettes and neighbouring regions (maps joined into one world). + +Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. diff --git a/src/random-tables/RandomTableView.ts b/src/random-tables/RandomTableView.ts index 47133e48..70aa4e17 100644 --- a/src/random-tables/RandomTableView.ts +++ b/src/random-tables/RandomTableView.ts @@ -10,6 +10,8 @@ import { } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import { VIEW_TYPE_RANDOM_TABLES } from "../constants"; +import { hasFeature } from "../featureLevel"; +import { renderAdvancedHint } from "../advancedHints"; import { normalizeFolder, makeTableTemplate } from "../utils"; import { RandomTableEditorModal } from "./RandomTableEditorModal"; import { WorkflowEditorModal } from "./WorkflowEditorModal"; @@ -62,6 +64,19 @@ export class RandomTableView extends ItemView { private viewMode: "tables" | "workflows" = "tables"; private tablesBtn: HTMLButtonElement | null = null; private workflowsBtn: HTMLButtonElement | null = null; + /** Holds the "workflows" hint while that Advanced feature is off. */ + private workflowHintBox: HTMLElement | null = null; + + /** Show or hide workflows to match the feature level (see src/featureLevel.ts). */ + refreshFeatures(): void { + const on = hasFeature(this.plugin.settings, "workflows"); + this.workflowsBtn?.toggle(on); + this.workflowHintBox?.empty(); + if (!on && this.workflowHintBox) + renderAdvancedHint(this.workflowHintBox, this.plugin, "workflows", "random-tables", + "Chain several of these tables into one filled-in note (a settlement, an NPC): workflows."); + if (!on && this.viewMode === "workflows") this.setViewMode("tables"); + } private tableFooterEl: HTMLElement | null = null; private workflowFooterEl: HTMLElement | null = null; @@ -144,6 +159,9 @@ export class RandomTableView extends ItemView { this.workflowsBtn.addEventListener("click", () => this.setViewMode("workflows"), ); + // Workflows are an Advanced feature: in Simple, a hint sits here instead. + this.workflowHintBox = leftCol.createDiv(); + this.refreshFeatures(); // Middle-click mode tabs → open view in new tab at that mode this.tablesBtn.addEventListener("auxclick", (e: MouseEvent) => { @@ -1656,7 +1674,7 @@ export class RandomTableView extends ItemView { // ── Used by workflows ─────────────────────────────────────────────── const tableKey = file.path.slice(0, -3); // remove .md const usingWorkflows = this.workflowMap.get(tableKey) ?? []; - if (usingWorkflows.length > 0 || this.plugin.settings.workflowsFolder) { + if (hasFeature(this.plugin.settings, "workflows") && (usingWorkflows.length > 0 || this.plugin.settings.workflowsFolder)) { const usedBySection = this.detailEl.createDiv({ cls: "duckmage-rt-used-by", }); diff --git a/src/types.ts b/src/types.ts index 982b39b3..5373031d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -48,12 +48,12 @@ export interface MapBackgroundImage { opacity?: number; } -/** See MapData.biome. */ -export interface RegionBiome { - generator: string; - from?: string[]; -} - +/** See MapData.biome. */ +export interface RegionBiome { + generator: string; + from?: string[]; +} + export interface MapData { name: string; /** Plugin version that created the map (see src/compat.ts). */ @@ -82,10 +82,10 @@ export interface MapData { staggerOffset?: "odd" | "even"; // undefined = inherit global setting /** Slot on a shared grid of neighbouring regions (see src/worldgen/world.ts). */ world?: { id: string; cx: number; cy: number }; - /** The generator (biome) a region was made from, so later neighbours can - * blend with it. `from` lists the neighbouring biomes it was blended with: - * a transition region between them and `generator`. */ - biome?: RegionBiome; + /** The generator (biome) a region was made from, so later neighbours can + * blend with it. `from` lists the neighbouring biomes it was blended with: + * a transition region between them and `generator`. */ + biome?: RegionBiome; backgroundImage?: MapBackgroundImage; /** Optional independent transform applied to the hex grid container, * used during background-image calibration so the user can resize/shift @@ -198,6 +198,18 @@ export interface HexmakerPluginSettings { palettesMigrated: boolean; /** Enabled map types (see src/mapKinds.ts). Unset = all. */ mapKinds: string[]; + /** Simple or Advanced (see src/featureLevel.ts). */ + featureLevel: "simple" | "advanced"; + /** Advanced features turned on one by one while in Simple. */ + advancedFeatures: string[]; + /** Advanced hints the user closed, by spot id. */ + dismissedHints: string[]; + /** When the plugin first ran (ISO date), for the "ready for more?" check-in. */ + installedAt?: string; + /** Last time the check-in was shown (ISO date). */ + advancedNudgeAt?: string; + /** "Don't ask again" on the check-in. */ + advancedNudgeOff?: boolean; /** True once existing palettes got terrain types (one-time seeding). */ terrainTypesSeeded: boolean; } diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 9d7a9a0a..72af533a 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -36,6 +36,8 @@ import { suggestImpassable } from "./impassableHint"; import { SIDES, type Side } from "./world"; import { blendFromNeighbours, regionBiome, generateConnected, neighbourSpec, NEIGHBOUR_SHARE, occupiedSides, placeNewRegion, regionNameAt, regionNeighbourNames, type NewRegion } from "./neighbours"; import { GeneratorLibrary } from "./GeneratorLibrary"; +import { hasFeature } from "../featureLevel"; +import { renderAdvancedHint } from "../advancedHints"; import { generatorMapKind, isGeneratorShown, isSpacePalette } from "../mapKinds"; import { sizePresets } from "./sizePresets"; import { listSaves, writeSave, readSave, applySave, renameGenerator } from "./saves"; @@ -572,6 +574,13 @@ export class GeneratorPanel { anchorSelect.value = GeneratorPanel.connect?.anchor ?? ""; sideSelect.value = GeneratorPanel.connect?.side ?? "east"; sideSelect.disabled = !anchorSelect.value; + // Neighbouring regions are an Advanced feature: a hint instead in Simple. + if (!hasFeature(this.plugin.settings, "regions")) { + connectRow.hide(); + GeneratorPanel.connect = null; + renderAdvancedHint(el, this.plugin, "regions", "generator-connect", + "Make the new map a neighbour of an existing one, its terrain carrying on across the border: neighbouring regions."); + } const connectNote = el.createEl("p", { cls: "duckmage-map-origin-desc" }); let connected: NewRegion | null = null; if (GeneratorPanel.connect) { diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index a0b8ffab..cfba7924 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -6,6 +6,8 @@ import { getTerrainFromFile } from "../frontmatter"; import { buildSubmapContext } from "./submapContext"; import { buildRegionContext } from "./regionContext"; import { neighbourSpec, occupiedSides, placeNewRegion, regionNameAt, type NewRegion } from "./neighbours"; +import { hasFeature } from "../featureLevel"; +import { renderAdvancedHint } from "../advancedHints"; import type { Side as WorldSide } from "./world"; import { routeContextPaths } from "./procedural/contextPaths"; import type { GenerationContext, Side } from "./procedural/common"; @@ -183,7 +185,12 @@ export class NewMapSetupModal extends HexmakerModal { // ── Next to (new top-level maps): join a world of neighbouring regions. // Size, palette, offset and stagger then follow the neighbour; terrain // and roads continue across the borders. - if (!this.origin && this.plugin.settings.maps.length > 0) { + // An Advanced feature: a hint stands in for it in Simple. + if (!this.origin && this.plugin.settings.maps.length > 0 && !hasFeature(this.plugin.settings, "regions")) { + renderAdvancedHint(form, this.plugin, "regions", "new-map-setup-next", + "Place this map next to an existing one so they join into one world: neighbouring regions."); + } + if (!this.origin && this.plugin.settings.maps.length > 0 && hasFeature(this.plugin.settings, "regions")) { const nextRow = this.row(form, "Next to"); const anchorSel = nextRow.createEl("select", { attr: { "aria-label": "Neighbouring map" } }); anchorSel.createEl("option", { value: "", text: "— none (stand-alone) —" }); @@ -237,6 +244,9 @@ export class NewMapSetupModal extends HexmakerModal { const genRow = this.row(form, "Generator"); this.rememberBox(genRow, "generator", "Generator and its options"); const genList = genRow.createDiv({ cls: "duckmage-setup-generators" }); + // Simple shows Blank (and Space generators); a hint says there is more. + renderAdvancedHint(form, this.plugin, "generators", "new-map-setup-generators", + "Generate this map's terrain for you: learned from maps you've painted, or from biome presets."); const optsBox = form.createDiv({ cls: "duckmage-setup-options" }); // ── Base terrain ── @@ -278,6 +288,7 @@ export class NewMapSetupModal extends HexmakerModal { const actions = contentEl.createDiv({ cls: "duckmage-setup-actions" }); const goBtn = actions.createEl("button", { cls: "mod-cta" }); const genBtn = actions.createEl("button", { text: "Open in generator", attr: { title: "Create the map blank and open the generator view on it to tune generation by hand" } }); + if (!hasFeature(this.plugin.settings, "generators")) genBtn.hide(); actions.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); const renderGenerators = () => { diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index 4ed8fece..2ad5cbec 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -21,6 +21,7 @@ import { planetSurfaceFits, } from "./procedural/planetSurface"; import { generatorMapKind, isGeneratorShown, type MapKind } from "../mapKinds"; +import { hasFeature, type FeatureSettings } from "../featureLevel"; import { generateConnected, type NewRegion } from "./neighbours"; /** @@ -224,11 +225,17 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise isGeneratorShown(settings, k.mapKind, { spaceContext, selected: k.id === selectedId })); + return kinds.filter( + (k) => + isGeneratorShown(settings, k.mapKind, { spaceContext, selected: k.id === selectedId }) + // Generators are an Advanced feature; Blank always shows, and Space + // brings its own generators at either level (isGeneratorShown). + && (k.id === BLANK_ID || k.id === selectedId || k.mapKind === "space" || hasFeature(settings, "generators")), + ); } /** diff --git a/styles.css b/styles.css index beddd6b7..3a00eaf9 100644 --- a/styles.css +++ b/styles.css @@ -6454,3 +6454,37 @@ button.duckmage-wfc-library-tab.is-active { width: 100%; min-width: 0; } + +/* Advanced-feature hint (src/advancedHints.ts): a quiet one-liner where a + hidden Advanced feature would sit, with "Turn on" and close buttons. */ +.duckmage-advanced-hint { + display: flex; + align-items: center; + gap: 0.5em; + margin: 0.5em 0; + padding: 0.35em 0.6em; + border: 1px dashed var(--background-modifier-border); + border-radius: var(--radius-s); + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +.duckmage-advanced-hint-mark { + color: var(--interactive-accent); +} + +.duckmage-advanced-hint-text { + flex: 1; +} + +.duckmage-advanced-hint button { + font-size: var(--font-ui-smaller); + padding: 0.15em 0.6em; + height: auto; +} + +.duckmage-advanced-hint-close { + box-shadow: none; + background: transparent; + color: var(--text-faint); +} diff --git a/tests/featureLevel.test.ts b/tests/featureLevel.test.ts new file mode 100644 index 00000000..91675108 --- /dev/null +++ b/tests/featureLevel.test.ts @@ -0,0 +1,63 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + ALL_ADVANCED_FEATURES, + enableFeature, + hasFeature, + isAdvanced, + NUDGE, + resolveFeatureLevel, + shouldNudge, + type FeatureSettings, +} from "../src/featureLevel"; + +describe("feature level", () => { + it("keeps a saved level", () => { + expect(resolveFeatureLevel({ featureLevel: "simple", maps: [] })).toBe("simple"); + expect(resolveFeatureLevel({ featureLevel: "advanced" })).toBe("advanced"); + }); + + it("gives an update from before feature levels Advanced, so nothing disappears", () => { + expect(resolveFeatureLevel({ maps: [{ name: "the-coast" }], setupComplete: true })).toBe("advanced"); + expect(resolveFeatureLevel({ hexOrientation: "flat" })).toBe("advanced"); + }); + + it("starts a fresh install Simple", () => { + expect(resolveFeatureLevel(null)).toBe("simple"); + expect(resolveFeatureLevel({})).toBe("simple"); + }); + + it("turns features on one at a time, and all of them means Advanced", () => { + const s: FeatureSettings = { featureLevel: "simple", advancedFeatures: [] }; + expect(hasFeature(s, "workflows")).toBe(false); + enableFeature(s, "workflows"); + expect(hasFeature(s, "workflows")).toBe(true); + expect(hasFeature(s, "generators")).toBe(false); + expect(isAdvanced(s)).toBe(false); + for (const f of ALL_ADVANCED_FEATURES) enableFeature(s, f); + expect(isAdvanced(s)).toBe(true); + }); + + it("has everything on in Advanced", () => { + for (const f of ALL_ADVANCED_FEATURES) expect(hasFeature({ featureLevel: "advanced" }, f)).toBe(true); + }); +}); + +describe("the ready-for-more check-in", () => { + const now = new Date("2026-11-01"); + const daysAgo = (n: number) => new Date(now.getTime() - n * 86_400_000).toISOString().slice(0, 10); + const simple = { featureLevel: "simple" as const, installedAt: daysAgo(1) }; + + it("waits until a couple of maps or a couple of weeks", () => { + expect(shouldNudge(simple, 1, now)).toBe(false); + expect(shouldNudge(simple, NUDGE.afterMaps, now)).toBe(true); + expect(shouldNudge({ ...simple, installedAt: daysAgo(NUDGE.afterDays) }, 1, now)).toBe(true); + }); + + it("doesn't ask again soon, ever after Don't ask again, or in Advanced", () => { + expect(shouldNudge({ ...simple, advancedNudgeAt: daysAgo(3) }, 5, now)).toBe(false); + expect(shouldNudge({ ...simple, advancedNudgeAt: daysAgo(NUDGE.againDays + 1) }, 5, now)).toBe(true); + expect(shouldNudge({ ...simple, advancedNudgeOff: true }, 5, now)).toBe(false); + expect(shouldNudge({ featureLevel: "advanced" }, 5, now)).toBe(false); + }); +}); From 699f761cd0ed957671fc1e764829ce4218117e8e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 19:49:25 -0400 Subject: [PATCH 081/558] fix(css): close the wizard preview rule the merge left open; guard it The feat/wfc-worldgen-research merge (1ca75a0) dropped the closing brace of .duckmage-wizard-generator-preview, so the browser swallowed every rule after it: the Near field, and any new styles appended at the end. tests/stylesBalanced.test.ts fails on unbalanced braces in styles.css. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 ++-- styles.css | 2 ++ tests/stylesBalanced.test.ts | 27 +++++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 tests/stylesBalanced.test.ts diff --git a/package.json b/package.json index 464960e4..91a5fba2 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/featureLevel.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/featureLevel.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/featureLevel.test.ts tests/stylesBalanced.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/featureLevel.test.ts tests/stylesBalanced.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/styles.css b/styles.css index 3a00eaf9..6693c0d6 100644 --- a/styles.css +++ b/styles.css @@ -6449,6 +6449,8 @@ button.duckmage-wfc-library-tab.is-active { align-items: center; gap: 0.4em; width: 240px; +} + /* Terrain mix: the Near rule field ("volcano 3"). */ .duckmage-wfc-near { width: 100%; diff --git a/tests/stylesBalanced.test.ts b/tests/stylesBalanced.test.ts new file mode 100644 index 00000000..ecc8d05e --- /dev/null +++ b/tests/stylesBalanced.test.ts @@ -0,0 +1,27 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; + +/** + * A rule left unclosed (easy to do when resolving a merge in styles.css) + * makes the browser swallow every rule after it, silently: 2026-10-09 a + * merge dropped one "}" and all later styles stopped applying. + */ +describe("styles.css", () => { + it("has every { closed, and no stray }", () => { + const css = readFileSync("styles.css", "utf8").replace(/\/\*[\s\S]*?\*\//g, ""); + let depth = 0; + let line = 1; + const problems: string[] = []; + for (const ch of css) { + if (ch === "\n") line++; + else if (ch === "{") depth++; + else if (ch === "}" && --depth < 0) { + problems.push(`stray } at line ${line}`); + depth = 0; + } + } + expect(problems).toEqual([]); + expect(depth).toBe(0); + }); +}); From 0136043379607c146aa0c347237777111bd61181 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 19:49:25 -0400 Subject: [PATCH 082/558] fix(css): close the wizard preview rule the merge left open; guard it The feat/wfc-worldgen-research merge (1ca75a0) dropped the closing brace of .duckmage-wizard-generator-preview, so the browser swallowed every rule after it: the Near field, and any new styles appended at the end. tests/stylesBalanced.test.ts fails on unbalanced braces in styles.css. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 ++-- styles.css | 2 ++ tests/stylesBalanced.test.ts | 27 +++++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 tests/stylesBalanced.test.ts diff --git a/package.json b/package.json index d730c875..3caacbfa 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/styles.css b/styles.css index beddd6b7..12d8928d 100644 --- a/styles.css +++ b/styles.css @@ -6449,6 +6449,8 @@ button.duckmage-wfc-library-tab.is-active { align-items: center; gap: 0.4em; width: 240px; +} + /* Terrain mix: the Near rule field ("volcano 3"). */ .duckmage-wfc-near { width: 100%; diff --git a/tests/stylesBalanced.test.ts b/tests/stylesBalanced.test.ts new file mode 100644 index 00000000..ecc8d05e --- /dev/null +++ b/tests/stylesBalanced.test.ts @@ -0,0 +1,27 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; + +/** + * A rule left unclosed (easy to do when resolving a merge in styles.css) + * makes the browser swallow every rule after it, silently: 2026-10-09 a + * merge dropped one "}" and all later styles stopped applying. + */ +describe("styles.css", () => { + it("has every { closed, and no stray }", () => { + const css = readFileSync("styles.css", "utf8").replace(/\/\*[\s\S]*?\*\//g, ""); + let depth = 0; + let line = 1; + const problems: string[] = []; + for (const ch of css) { + if (ch === "\n") line++; + else if (ch === "{") depth++; + else if (ch === "}" && --depth < 0) { + problems.push(`stray } at line ${line}`); + depth = 0; + } + } + expect(problems).toEqual([]); + expect(depth).toBe(0); + }); +}); From 9ed96184bbb8a597ee34a1d2f90e2cbc47db8335 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 20:58:25 -0400 Subject: [PATCH 083/558] docs(readme): left-click opens the editor; setup wizard; generators MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes T1/G2 (#40): the README said right-click opens the hex editor (it's left-click; right-click is the hex menu), listed Weather and Hooks & Rumors as editor sections (they aren't — pending E2), described a manual-only setup, and never mentioned generators. Adds the setup wizard and a Generators section. Co-Authored-By: Claude Opus 5.5 --- README.md | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 03b68391..1ed71e9a 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Hexmaker gives you an interactive hex grid that lives inside Obsidian. Paint ter ### Hex editor -Right-click any hex to open the editor: set terrain, override the icon, link Towns, Dungeons, Features, Quests, Factions, and Encounters Tables, and write freeform notes (Description, Landmark, Hidden, Secret, Weather, Hooks & Rumors). A 🎲 button on each section lets you roll any random table and append the result inline. Link a submap to the hex and click the center dot in the hex flower to dive into it. +Click any hex to open the editor: set terrain, override the icon, link Towns, Dungeons, Features, Quests, Factions, and Encounters Tables, and write freeform notes (Description, Landmark, Hidden, Secret). A 🎲 button on each section lets you roll any random table and append the result inline. Link a submap to the hex and click the center dot in the hex flower to dive into it. ![The hex editor showing terrain, links, and notes for a single hex](docs/Editor.PNG) @@ -61,7 +61,9 @@ Toggle the GM layer from the overlay panel to switch between player-facing and G ## Getting started -After enabling the plugin, do this once before you start mapping: +After enabling the plugin, a **setup wizard** opens. It asks what you'll map (a fantasy world, space, or both), where your world folder lives, and makes your first map. That last step can **generate the terrain** for you (Overland for a world map, Star scatter for a star sector), with a preview and a re-roll button, or start blank for painting by hand. It also creates the terrain description and encounter tables. That's all you need to start. + +To set things up by hand instead (or later): ### 1. Set your world folder Open **Settings → Hexmap World Creator** and enter a root folder name in **World folder** (e.g. `RPG/world`). This is the base for all other folders. @@ -84,8 +86,8 @@ You're ready to start mapping. ### Hex Map view An interactive hex grid rendered as an Obsidian panel. -- **Left-click** a hex to open (or create) its note. -- **Right-click** a hex to open the hex editor. +- **Left-click** a hex to open the hex editor. +- **Right-click** a hex for its menu: centre on it, open its note, enter / create / link a submap, link a table, swap hexes, create a token here, clear terrain. - **Pan** by clicking and dragging with the left or middle mouse button. - **Zoom** with the scroll wheel. - **Expand** the grid with the `+`/`−` buttons at the map edges. @@ -102,7 +104,17 @@ Organise your world into multiple named hex maps, each stored as a subfolder und - **Terrain theme** — assign a terrain type to a map. The swatch appears next to the map name in the switch list and sets the colour of the submap center dot when this map is linked as a submap from a parent map. - **Back** (`← Back` button) — returns to the previously active map after following a submap link. -### Hex editor (right-click menu) +### Generators +Maps can be generated instead of painted hex by hex. When you create a map (**Maps → New map → Guided setup…**, or the setup wizard's first map) or a submap (right-click a hex → **New submap…**), pick a generator and preview it before creating: + +- **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. +- **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge. +- **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. +- **Learned generators** — made in the **Terrain generator** view (command palette: *Open terrain generator*) by learning from maps you've already painted, or by blending several. + +Generators only change hexes when a map is created or regenerated; you can always repaint by hand afterwards. + +### Hex editor (click a hex) A modal for editing a hex note without leaving the map. - **Terrain picker** — select the terrain type for the hex from the map's palette. @@ -110,7 +122,7 @@ A modal for editing a hex note without leaving the map. - **Submap link** — link another map to this hex. The hex flower widget shows a center dot coloured by the linked map's terrain theme. Click the dot to navigate directly to that map. - **Towns / Dungeons / Features / Quests / Factions** — link existing notes from their configured folders, or create a new note by name. Linked items are clickable and open in a new tab. Each entry has a remove button. - **Encounters Table** — link random table files to a hex. Clicking a linked table opens the Random Tables view with that table pre-selected. -- **Notes sections** — Description, Landmark, Hidden, Secret, Weather, Hooks & Rumors — inline text areas with a 🎲 roll button to append a result from any random table. +- **Notes sections** — Description, Landmark, Hidden, Secret — inline text areas with a 🎲 roll button to append a result from any random table. - **Open note** link next to the hex coordinates opens the full note in a new tab. ### Random Tables view @@ -308,7 +320,7 @@ src/ hex-map/ HexMapView.ts ← interactive hex grid (ItemView) HexSidePanel.ts ← collapsible side panels (drawing tools, overlays) - HexEditorModal.ts ← right-click hex editor (Modal) + HexEditorModal.ts ← hex editor, opened by clicking a hex (Modal) MapModal.ts ← map management (switch, create, rename, delete, terrain theme) SubmapPickerModal.ts ← link submap to a hex (picker + create) TerrainPickerModal.ts ← terrain palette picker From 9169d462f989ad36f458d54c128ef9016fc5930e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:06:15 -0400 Subject: [PATCH 084/558] fix(hex-editor): show the hex's terrain, stay open on pick, clearer link fields MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes #38: - E1: the editor read terrain/icon from hex-note frontmatter, which map notes no longer hold, so the current terrain was never highlighted. Read them through the map store (works before the hex note exists too). The Terrain header names the terrain ("grass (base)" for base terrain). Picking a swatch (or Clear) no longer closes the editor: the selection and header update in place and the map repaints. - E5: the Terrain/Notes/link group collapse state is now remembered (the hexEditor*Collapsed settings existed but clicks never saved them). - E5: the link group is "Linked notes" (not "Features", which is also one of its fields); each link field is a boxed card whose input says what it links ("Search or create a quest…"). Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexEditorModal.ts | 210 +++++++++++++++++++++------------- styles.css | 18 +++ tests/hexEditorModal.test.ts | 70 +++++++++++- 3 files changed, 217 insertions(+), 81 deletions(-) diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 7ba6d728..ab3a2051 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -10,6 +10,7 @@ import { } from "../utils"; import { getTerrainFromFile, + getIconOverrideFromFile, setTerrainInFile, setIconOverrideInFile, setGmIconsInFile, @@ -34,6 +35,16 @@ import { WalkRegionModal } from "../worldgen/WalkRegionModal"; import type { MapData } from "../types"; import { RegionNavigateModal } from "./RegionNavigateModal"; +/** What each link field links, for its placeholder ("Search or create a town…"). */ +const LINK_FIELD_NOUN: Record = { + "Encounters Table": "an encounter table", + Towns: "a town", + Dungeons: "a dungeon", + Features: "a feature", + Quests: "a quest", + Factions: "a faction", +}; + /** Which side of the map an off-map hex lies past (east/west first at corners). */ function offMapSide(map: MapData, x: number, y: number): Side { const { x: ox, y: oy } = map.gridOffset; @@ -81,6 +92,13 @@ export class HexEditorModal extends HexmakerModal { this.directGmIcons = []; const path = this.plugin.hexPath(this.x, this.y, this.mapName); + // Terrain, icon and GM icons live in the map note (the map store), not in + // the hex note — and a hex can have them before its note exists. Reading + // only hex frontmatter left the current terrain never highlighted (E1). + this.directTerrain = getTerrainFromFile(this.app, path); + this.directIcon = getIconOverrideFromFile(this.app, path); + this.directGmIcons = getGmIconsFromFile(this.app, path); + this.directGmIcon = this.directGmIcons[0] ?? null; const file = this.app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return; this.hexExists = true; @@ -88,22 +106,16 @@ export class HexEditorModal extends HexmakerModal { // Single read — reused for both frontmatter and section parsing const rawContent = await this.app.vault.read(file); + // Fallback for notes the store doesn't serve yet (startup, or a note + // written moments ago that isn't indexed): read the raw frontmatter. const fmMatch = rawContent.match(/^---\r?\n([\s\S]*?)\r?\n---/); if (fmMatch) { const tm = fmMatch[1].match(/^\s*terrain:\s*(.+)$/m); - if (tm) this.directTerrain = tm[1].trim(); + if (tm && this.directTerrain === null) this.directTerrain = tm[1].trim(); const im = fmMatch[1].match(/^\s*icon:\s*(.+)$/m); - if (im) this.directIcon = im[1].trim(); + if (im && this.directIcon === null) this.directIcon = im[1].trim(); const gm = fmMatch[1].match(/^\s*gm-icon:\s*(.+)$/m); - if (gm) this.directGmIcon = gm[1].trim(); - } - // Authoritative multi-icon read via the helper (handles the new - // `gm-icons` array AND the legacy `gm-icon` singular). Done after - // the regex-based directGmIcon read so the modal stays compatible - // with existing single-icon notes. - this.directGmIcons = getGmIconsFromFile(this.app, path); - if (this.directGmIcon === null && this.directGmIcons.length > 0) { - this.directGmIcon = this.directGmIcons[0]; + if (gm && this.directGmIcon === null) this.directGmIcon = gm[1].trim(); } ({ text: this.allText, links: this.allLinks } = await getAllSectionData( @@ -188,42 +200,27 @@ export class HexEditorModal extends HexmakerModal { const { body: terrainBody, header: terrainHeader } = this.makeCollapsible( bodyEl, "Terrain", - s.hexEditorTerrainCollapsed ?? false, + "hexEditorTerrainCollapsed", + ); + const headerPreview = terrainHeader.createSpan({ + cls: "duckmage-terrain-header-preview", + }); + this.renderTerrainHeader(headerPreview, directTerrain, directIcon); + this.renderTerrainSection( + terrainBody, + path, + directTerrain, + directIcon, + this.directGmIcons, + (terrain) => this.renderTerrainHeader(headerPreview, terrain, this.directIcon), ); - const paletteEntry = directTerrain - ? this.plugin - .getMapPalette(this.mapName) - .find((p) => p.name === directTerrain) - : undefined; - const iconToShow = directIcon ?? paletteEntry?.icon; - if (paletteEntry || iconToShow) { - const preview = terrainHeader.createSpan({ - cls: "duckmage-terrain-header-preview", - }); - const swatch = preview.createSpan({ - cls: "duckmage-terrain-header-swatch", - }); - if (paletteEntry) - swatch.setCssProps({ "--duckmage-bg": paletteEntry.color }); - if (iconToShow) { - const img = swatch.createEl("img"); - img.src = getIconUrl(this.plugin, iconToShow); - } - if (paletteEntry) { - preview.createSpan({ - text: paletteEntry.name, - cls: "duckmage-terrain-header-name", - }); - } - } - this.renderTerrainSection(terrainBody, path, directTerrain, directIcon, this.directGmIcons); bodyEl.createEl("hr", { cls: "duckmage-editor-divider" }); const { body: notesBody } = this.makeCollapsible( bodyEl, "Notes", - s.hexEditorNotesCollapsed ?? false, + "hexEditorNotesCollapsed", ); for (const { key, label } of TEXT_SECTIONS) { if (!this.options.gmLayerActive && (key === "hidden" || key === "secret")) continue; @@ -238,11 +235,15 @@ export class HexEditorModal extends HexmakerModal { bodyEl.createEl("hr", { cls: "duckmage-editor-divider" }); + // The group of link fields. Not called "Features": that's one of the + // fields, and a group heading with a field's name read as that field's + // label (E5). The settings flag keeps its old name. const { body: featuresBody } = this.makeCollapsible( bodyEl, - "Features", - s.hexEditorFeaturesCollapsed ?? false, + "Linked notes", + "hexEditorFeaturesCollapsed", ); + featuresBody.addClass("duckmage-editor-link-group"); this.renderDropdownSection( featuresBody, path, @@ -433,11 +434,48 @@ export class HexEditorModal extends HexmakerModal { } } + /** Terrain header summary: swatch + current terrain name ("(base)" when + * the hex only shows the map's base terrain). Re-rendered on each pick. */ + private renderTerrainHeader( + preview: HTMLElement, + terrain: string | null, + icon: string | null, + ): void { + preview.empty(); + const palette = this.plugin.getMapPalette(this.mapName); + const base = this.plugin.getMap(this.mapName)?.baseTerrain; + const name = terrain ?? base ?? null; + const entry = name ? palette.find((p) => p.name === name) : undefined; + const iconToShow = icon ?? entry?.icon; + if (!entry && !iconToShow) { + preview.createSpan({ text: "none", cls: "duckmage-terrain-header-name" }); + return; + } + const swatch = preview.createSpan({ cls: "duckmage-terrain-header-swatch" }); + if (entry) swatch.setCssProps({ "--duckmage-bg": entry.color }); + if (iconToShow) { + const img = swatch.createEl("img"); + img.src = getIconUrl(this.plugin, iconToShow); + } + if (entry) { + preview.createSpan({ + text: terrain === null ? `${entry.name} (base)` : entry.name, + cls: "duckmage-terrain-header-name", + }); + } + } + + /** + * Collapsible group whose open/closed state is remembered in the given + * settings flag (so collapsing Terrain once keeps it collapsed on every + * hex, E5). The same flags are exposed in the settings tab. + */ private makeCollapsible( container: HTMLElement, label: string, - startCollapsed: boolean, + flag: "hexEditorTerrainCollapsed" | "hexEditorNotesCollapsed" | "hexEditorFeaturesCollapsed", ): { body: HTMLElement; header: HTMLElement } { + const startCollapsed = this.plugin.settings[flag] ?? false; const wrapper = container.createDiv({ cls: "duckmage-editor-collapsible" }); const header = wrapper.createDiv({ cls: "duckmage-editor-collapsible-header", @@ -460,6 +498,8 @@ export class HexEditorModal extends HexmakerModal { body.hide(); } arrow.textContent = collapsed ? "▼" : "▶"; + this.plugin.settings[flag] = !collapsed; + void this.plugin.saveSettings(); }); return { body, header }; } @@ -470,6 +510,7 @@ export class HexEditorModal extends HexmakerModal { currentTerrain: string | null, currentIcon: string | null, currentGmIcons: string[], + onTerrainChange: (terrain: string | null) => void, ): void { const palette = this.plugin.getMapPalette(this.mapName); @@ -477,31 +518,44 @@ export class HexEditorModal extends HexmakerModal { const grid = section.createDiv({ cls: "duckmage-terrain-picker" }); - // Clear terrain — always first in the grid - if (currentTerrain) { - const clearBtn = grid.createDiv({ - cls: "duckmage-terrain-option duckmage-terrain-option-clear", - }); - clearBtn.createDiv({ - cls: "duckmage-terrain-preview duckmage-terrain-preview-clear", - }); - clearBtn.createSpan({ - text: "Clear", - cls: "duckmage-terrain-option-name", - }); - clearBtn.addEventListener("click", () => { - void (async () => { - await setTerrainInFile(this.app, path, null); - void this.plugin.syncHexEncounterTableLink(path, null); - this.onChanged(new Map([[path, null]])); - this.close(); - })(); - }); - } + // Picking a terrain keeps the editor open (E1): the map repaints via + // onChanged, and the selection/header update in place here. + let selectedTerrain = currentTerrain; + const terrainOverrides = (): Map | undefined => + selectedTerrain ? new Map([[path, selectedTerrain]]) : undefined; + const applyTerrain = async (terrain: string | null): Promise => { + if (terrain !== null) await this.ensureHexNote(); + await setTerrainInFile(this.app, path, terrain); + void this.plugin.syncHexEncounterTableLink(path, terrain); + selectedTerrain = terrain; + this.directTerrain = terrain; + grid.querySelectorAll(".duckmage-terrain-option[data-terrain]").forEach((el) => + el.toggleClass("is-selected", el.dataset["terrain"] === terrain), + ); + clearBtn.toggle(terrain !== null); + onTerrainChange(terrain); + this.onChanged(new Map([[path, terrain]])); + }; + + // Clear terrain — always first in the grid (hidden while there's none) + const clearBtn = grid.createDiv({ + cls: "duckmage-terrain-option duckmage-terrain-option-clear", + attr: { title: "Clear this hex's terrain" }, + }); + clearBtn.createDiv({ + cls: "duckmage-terrain-preview duckmage-terrain-preview-clear", + }); + clearBtn.createSpan({ + text: "Clear", + cls: "duckmage-terrain-option-name", + }); + clearBtn.toggle(currentTerrain !== null); + clearBtn.addEventListener("click", () => void applyTerrain(null)); for (const entry of palette) { const btn = grid.createDiv({ cls: `duckmage-terrain-option${entry.name === currentTerrain ? " is-selected" : ""}`, + attr: { title: entry.name, "data-terrain": entry.name }, }); const preview = btn.createDiv({ cls: "duckmage-terrain-preview" }); @@ -520,20 +574,14 @@ export class HexEditorModal extends HexmakerModal { btn.createSpan({ text: entry.name, cls: "duckmage-terrain-option-name" }); btn.addEventListener("click", () => { - void (async () => { - await this.ensureHexNote(); - await setTerrainInFile(this.app, path, entry.name); - void this.plugin.syncHexEncounterTableLink(path, entry.name); - this.onChanged(new Map([[path, entry.name]])); - this.close(); - })(); + if (entry.name === selectedTerrain) return; + void applyTerrain(entry.name); }); } - // Keep terrain in the overrides map so renderGrid doesn't lose it during - // the brief window when Obsidian clears the metadata cache on file modify. - const terrainOverrides: Map | undefined = - currentTerrain ? new Map([[path, currentTerrain]]) : undefined; + // Keep terrain in the overrides map (see terrainOverrides above) so + // renderGrid doesn't lose it during the brief window when Obsidian + // clears the metadata cache on file modify. // Icon override palette const hidden = new Set(this.plugin.settings.hiddenIcons ?? []); @@ -548,7 +596,9 @@ export class HexEditorModal extends HexmakerModal { async (picked) => { await this.ensureHexNote(); await setIconOverrideInFile(this.app, path, picked); - this.onChanged(terrainOverrides, new Map([[path, picked]])); + this.directIcon = picked; + onTerrainChange(selectedTerrain); // header shows the icon override + this.onChanged(terrainOverrides(), new Map([[path, picked]])); }, ); @@ -742,8 +792,11 @@ export class HexEditorModal extends HexmakerModal { sourceFolder: string, initialLinks: string[], ): void { + // Each link field is its own boxed card, and its input names what it + // links, so a field can't be read as belonging to the label above or + // below it (a tester linked a dungeon as a Quest, E5). const sectionEl = container.createDiv({ - cls: "duckmage-editor-link-section", + cls: "duckmage-editor-link-section duckmage-editor-link-card", }); sectionEl.createEl("h4", { text: section, @@ -755,8 +808,9 @@ export class HexEditorModal extends HexmakerModal { const input = comboWrap.createEl("input", { type: "text", cls: "duckmage-link-combo-input", + attr: { "aria-label": `Link ${section.toLowerCase()}` }, }); - input.placeholder = `Search or create…`; + input.placeholder = `Search or create ${LINK_FIELD_NOUN[section]}…`; const arrowBtn = comboWrap.createEl("button", { text: "▾", diff --git a/styles.css b/styles.css index 12d8928d..fe5f8c29 100644 --- a/styles.css +++ b/styles.css @@ -6456,3 +6456,21 @@ button.duckmage-wfc-library-tab.is-active { width: 100%; min-width: 0; } + +/* ── Fresh-eyes fixes: hex editor (#38), path tool & navigation (#39) ───── */ + +/* Hex editor: the link fields sit in a "Linked notes" group, each in its own + boxed card so a label can't be read as belonging to the next field (E5). */ +.duckmage-editor-link-group { + padding-left: 0.6em; + border-left: 2px solid var(--background-modifier-border); +} +.duckmage-editor-link-card { + padding: 0.45em 0.6em 0.5em; + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + background: var(--background-primary-alt); +} +.duckmage-editor-link-card .duckmage-link-section-title { + color: var(--text-normal); +} diff --git a/tests/hexEditorModal.test.ts b/tests/hexEditorModal.test.ts index 6f73bd09..7f70ca7b 100644 --- a/tests/hexEditorModal.test.ts +++ b/tests/hexEditorModal.test.ts @@ -195,10 +195,11 @@ describe("HexEditorModal section start-collapsed settings", () => { makeApp({}), plugin, 1, 1, "default", () => {}, { gmLayerActive }, ) as any; const states = new Map(); - modal.makeCollapsible = (_c: unknown, label: string, startCollapsed: boolean) => { - states.set(label, startCollapsed); - return { body: {}, header: {} }; + modal.makeCollapsible = (_c: unknown, label: string, flag: string) => { + states.set(label, (plugin.settings as any)[flag] ?? false); + return { body: { addClass: () => {} }, header: { createSpan: () => ({}) } }; }; + modal.renderTerrainHeader = () => {}; modal.renderTerrainSection = () => {}; modal.renderTextSection = () => {}; modal.renderDropdownSection = () => {}; @@ -274,3 +275,66 @@ describe("HexEditorModal navigation reload", () => { expect((modal as any).directIcon).toBe("oasis.png"); }); }); + +// ── Fresh-eyes #38 (E1, E5) ───────────────────────────────────────────────── + +describe("HexEditorModal reads terrain from the map note (E1)", () => { + it("loads terrain and icon from the map store even when the hex note doesn't exist", async () => { + const { setHexDataSource } = await import("../src/frontmatter"); + setHexDataSource({ + isReady: () => true, + resolve: (p: string) => (p === "hex/3_3.md" ? { map: "m", key: "3_3" } : null), + get: (_m: string, k: string) => (k === "3_3" ? { terrain: "hill", icon: "tower.png", gmIcons: ["skull.png"] } : undefined), + set: () => {}, + } as any); + try { + const plugin = makePlugin(() => "hex/3_3.md"); + const modal = new HexEditorModal(makeApp({}), plugin, 3, 3, "m", () => {}) as any; + await modal.loadData(); + expect(modal.hexExists).toBe(false); + expect(modal.directTerrain).toBe("hill"); + expect(modal.directIcon).toBe("tower.png"); + expect(modal.directGmIcons).toEqual(["skull.png"]); + } finally { + setHexDataSource(null); + } + }); +}); + +describe("HexEditorModal remembers collapsed groups (E5)", () => { + /** Just enough of an HTMLElement for makeCollapsible. */ + function fakeEl(): any { + let shown = true; + const listeners: Record void> = {}; + return { + textContent: "", + createDiv: () => fakeEl(), + createSpan: () => fakeEl(), + createEl: () => fakeEl(), + hide: () => { shown = false; }, + show: () => { shown = true; }, + isShown: () => shown, + addEventListener: (t: string, fn: () => void) => { listeners[t] = fn; }, + fire: (t: string) => listeners[t]?.(), + }; + } + + it("collapsing a group saves its flag, so the next hex opens the same way", () => { + const plugin = makePlugin(() => "hex/1_1.md"); + const saveSettings = mock.fn(async () => {}); + (plugin as any).saveSettings = saveSettings; + const modal = new HexEditorModal(makeApp({}), plugin, 1, 1, "default", () => {}) as any; + const { body, header } = modal.makeCollapsible(fakeEl(), "Terrain", "hexEditorTerrainCollapsed"); + expect(body.isShown()).toBe(true); + header.fire("click"); + expect(body.isShown()).toBe(false); + expect(plugin.settings.hexEditorTerrainCollapsed).toBe(true); + expect(saveSettings.mock.callCount()).toBe(1); + + const next = new HexEditorModal(makeApp({}), plugin, 2, 2, "default", () => {}) as any; + const reopened = next.makeCollapsible(fakeEl(), "Terrain", "hexEditorTerrainCollapsed"); + expect(reopened.body.isShown()).toBe(false); + reopened.header.fire("click"); + expect(plugin.settings.hexEditorTerrainCollapsed).toBe(false); + }); +}); From 2e0ab181d431db52509229bf10522c6425ee2f80 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:07:08 -0400 Subject: [PATCH 085/558] fix(hex-editor): nested terrain/icon grids no longer trap the mouse wheel Fresh-eyes #38 E3: scrolling the long hex editor got caught by the inner terrain and icon grids (Chromium latches a wheel gesture to the inner area, so the modal didn't move even at the grid's end). New HexmakerModal.chainWheelToModal(grid): the wheel scrolls the modal when the grid is at its end in that direction, can't scroll, or the modal was being scrolled in the last 400 ms (a grid sliding under the pointer mid-scroll doesn't steal it). The decision is pure (src/wheelChain.ts) and tested. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +-- src/HexmakerModal.ts | 55 +++++++++++++++++++++++++++++++++++ src/hex-map/HexEditorModal.ts | 3 ++ src/wheelChain.ts | 47 ++++++++++++++++++++++++++++++ tests/wheelChain.test.ts | 44 ++++++++++++++++++++++++++++ 5 files changed, 151 insertions(+), 2 deletions(-) create mode 100644 src/wheelChain.ts create mode 100644 tests/wheelChain.test.ts diff --git a/package.json b/package.json index 3caacbfa..00dfe51d 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerModal.ts b/src/HexmakerModal.ts index 26e650f9..789acb71 100644 --- a/src/HexmakerModal.ts +++ b/src/HexmakerModal.ts @@ -1,5 +1,6 @@ import { App, Modal } from "obsidian"; import { ICON_PACK_LABELS, iconLabel, iconPack, type IconPack } from "./utils"; +import { wheelDeltaPx, wheelGoesToOuter } from "./wheelChain"; /** Last pack tab picked in any icon filter — remembered for the session. */ let lastIconPack: IconPack | "all" = "all"; @@ -96,6 +97,60 @@ export class HexmakerModal extends Modal { }; } + /** When the modal's own scroll pane last scrolled (see chainWheelToModal). */ + private lastOuterScroll = -Infinity; + private outerScrollWatched = false; + + /** + * Stop a nested scroll area (an icon or terrain grid inside a long, + * scrolling modal) from trapping the mouse wheel: the wheel scrolls the + * modal when the area is at its end, can't scroll, or the user is in the + * middle of scrolling the modal (see wheelGoesToOuter). Inside the area, + * away from its ends, the wheel still scrolls the area itself. + */ + protected chainWheelToModal(inner: HTMLElement): void { + inner.dataset["wheelChain"] = "1"; + if (!this.outerScrollWatched) { + this.outerScrollWatched = true; + // `scroll` doesn't bubble: capture it on the modal and ignore the + // chained areas' own scrolling. + this.modalEl.addEventListener( + "scroll", + (e) => { + const t = e.target as HTMLElement | null; + if (t && !t.dataset?.["wheelChain"]) this.lastOuterScroll = performance.now(); + }, + { capture: true, passive: true }, + ); + } + inner.addEventListener( + "wheel", + (e: WheelEvent) => { + if (e.ctrlKey || e.deltaY === 0) return; + const pane = this.scrollParentOf(inner); + if (!pane) return; + const box = { scrollTop: inner.scrollTop, scrollHeight: inner.scrollHeight, clientHeight: inner.clientHeight }; + if (!wheelGoesToOuter(box, e.deltaY, performance.now() - this.lastOuterScroll)) return; + e.preventDefault(); + pane.scrollTop += wheelDeltaPx(e.deltaY, e.deltaMode, pane.clientHeight); + }, + { passive: false }, + ); + } + + /** Nearest ancestor of `el` (inside this modal) that scrolls vertically. */ + private scrollParentOf(el: HTMLElement): HTMLElement | null { + const win = el.ownerDocument.defaultView ?? window; + for (let p = el.parentElement; p; p = p.parentElement) { + if (p.scrollHeight > p.clientHeight + 1) { + const oy = win.getComputedStyle(p).overflowY; + if (oy === "auto" || oy === "scroll") return p; + } + if (p === this.modalEl) break; + } + return null; + } + /** Make this modal draggable by its title-bar area. Safe to call multiple times. */ protected makeDraggable(): void { const modalEl = this.modalEl; diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index ab3a2051..0b4eb4ab 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -517,6 +517,7 @@ export class HexEditorModal extends HexmakerModal { const section = container.createDiv({ cls: "duckmage-editor-section" }); const grid = section.createDiv({ cls: "duckmage-terrain-picker" }); + this.chainWheelToModal(grid); // Picking a terrain keeps the editor open (E1): the map repaints via // onChanged, and the selection/header update in place here. @@ -628,6 +629,7 @@ export class HexEditorModal extends HexmakerModal { // Working copy of the list (with duplicates) the user is editing. const list: string[] = [...initialList]; const grid = container.createDiv({ cls: "duckmage-icon-picker duckmage-icon-picker-inline" }); + this.chainWheelToModal(grid); const countOf = (icon: string): number => list.filter((i) => i === icon).length; @@ -729,6 +731,7 @@ export class HexEditorModal extends HexmakerModal { ): void { let selected = current; const grid = container.createDiv({ cls: "duckmage-icon-picker duckmage-icon-picker-inline" }); + this.chainWheelToModal(grid); const makeTile = (icon: string | null) => { const label = icon diff --git a/src/wheelChain.ts b/src/wheelChain.ts new file mode 100644 index 00000000..914c8618 --- /dev/null +++ b/src/wheelChain.ts @@ -0,0 +1,47 @@ +/** + * Pure decision logic for nested scroll areas inside a scrolling modal + * (the hex editor's terrain and icon grids). Kept free of Obsidian imports + * so it's unit-testable; HexmakerModal.chainWheelToModal wires it up. + */ + +export interface ScrollBox { + scrollTop: number; + scrollHeight: number; + clientHeight: number; +} + +/** How long after the outer pane last scrolled a wheel step still counts as + * the same scroll gesture (so a grid sliding under the pointer mid-scroll + * doesn't steal it). */ +export const WHEEL_CONTINUE_MS = 400; + +/** + * Should a wheel step of `deltaY` over the inner scroll area `inner` scroll + * the outer pane instead? + * + * Yes when the user is mid-way through scrolling the outer pane + * (`msSinceOuterScroll` < `continueMs`), when the inner area can't scroll at + * all, or when it is already at its end in the wheel's direction (Chromium + * "latches" a wheel gesture to the inner area, so without this the modal + * wouldn't move until the user paused and started a new gesture). + */ +export function wheelGoesToOuter( + inner: ScrollBox, + deltaY: number, + msSinceOuterScroll: number, + continueMs = WHEEL_CONTINUE_MS, +): boolean { + if (deltaY === 0) return false; + if (msSinceOuterScroll < continueMs) return true; + const max = inner.scrollHeight - inner.clientHeight; + if (max <= 1) return true; + if (deltaY > 0) return inner.scrollTop >= max - 1; + return inner.scrollTop <= 0; +} + +/** Wheel delta in pixels (WheelEvent.deltaMode: 0 px, 1 lines, 2 pages). */ +export function wheelDeltaPx(deltaY: number, deltaMode: number, pageHeight: number): number { + if (deltaMode === 1) return deltaY * 16; + if (deltaMode === 2) return deltaY * pageHeight; + return deltaY; +} diff --git a/tests/wheelChain.test.ts b/tests/wheelChain.test.ts new file mode 100644 index 00000000..c7371346 --- /dev/null +++ b/tests/wheelChain.test.ts @@ -0,0 +1,44 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { wheelDeltaPx, wheelGoesToOuter, WHEEL_CONTINUE_MS } from "../src/wheelChain"; + +/** A 132px-tall icon grid holding 400px of tiles, scrolled to `top`. */ +const grid = (top: number) => ({ scrollTop: top, scrollHeight: 400, clientHeight: 132 }); +const LONG_AGO = Infinity; + +describe("wheelGoesToOuter (fresh-eyes E3: nested grids trap the wheel)", () => { + it("scrolls the grid itself while it has room in the wheel's direction", () => { + expect(wheelGoesToOuter(grid(0), 100, LONG_AGO)).toBe(false); + expect(wheelGoesToOuter(grid(100), -100, LONG_AGO)).toBe(false); + }); + + it("passes the wheel to the modal at the grid's bottom (scrolling down)", () => { + expect(wheelGoesToOuter(grid(268), 100, LONG_AGO)).toBe(true); + expect(wheelGoesToOuter(grid(267.5), 100, LONG_AGO)).toBe(true); // sub-pixel + }); + + it("passes the wheel to the modal at the grid's top (scrolling up)", () => { + expect(wheelGoesToOuter(grid(0), -100, LONG_AGO)).toBe(true); + }); + + it("passes it on when the grid can't scroll at all", () => { + expect(wheelGoesToOuter({ scrollTop: 0, scrollHeight: 120, clientHeight: 132 }, 100, LONG_AGO)).toBe(true); + }); + + it("keeps an ongoing modal scroll going when a grid slides under the pointer", () => { + expect(wheelGoesToOuter(grid(50), 100, 50)).toBe(true); + expect(wheelGoesToOuter(grid(50), 100, WHEEL_CONTINUE_MS + 1)).toBe(false); + }); + + it("ignores zero-delta (horizontal-only) wheel events", () => { + expect(wheelGoesToOuter(grid(268), 0, 0)).toBe(false); + }); +}); + +describe("wheelDeltaPx", () => { + it("converts line and page deltas to pixels", () => { + expect(wheelDeltaPx(100, 0, 500)).toBe(100); + expect(wheelDeltaPx(3, 1, 500)).toBe(48); + expect(wheelDeltaPx(1, 2, 500)).toBe(500); + }); +}); From 66f51c086761d99fa2c145dd3b2e036a692c6f78 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:07:37 -0400 Subject: [PATCH 086/558] fix(terrain-picker): show full terrain names instead of truncating them Fresh-eyes #38 E4 (part): long names in the paint palette ("forested hills", "mixed forest", "evergreen forest") were cut to "forested ..." so swatches were indistinguishable. Terrain tiles are a little wider and wrap the name onto two lines; every tile also carries the full name as its tooltip. No options removed; the hex editor's two-row strip grows to fit. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/TerrainPickerModal.ts | 3 ++- styles.css | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/hex-map/TerrainPickerModal.ts b/src/hex-map/TerrainPickerModal.ts index ea20d48b..ae4fafc9 100644 --- a/src/hex-map/TerrainPickerModal.ts +++ b/src/hex-map/TerrainPickerModal.ts @@ -130,7 +130,7 @@ export class TerrainPickerModal extends HexmakerModal { }); for (const entry of this.palette) { - const btn = grid.createDiv({ cls: "duckmage-terrain-option" }); + const btn = grid.createDiv({ cls: "duckmage-terrain-option", attr: { title: entry.name } }); const preview = btn.createDiv({ cls: "duckmage-terrain-preview" }); preview.setCssProps({ '--duckmage-bg': entry.color }); if (entry.icon) { @@ -161,6 +161,7 @@ export class TerrainPickerModal extends HexmakerModal { const entry = palette[i]; const tile = grid.createDiv({ cls: "duckmage-terrain-option duckmage-terrain-option-editable", + attr: { title: `${entry.name} (click to edit, drag to reorder)` }, }); tile.draggable = true; diff --git a/styles.css b/styles.css index fe5f8c29..c6cb8e8d 100644 --- a/styles.css +++ b/styles.css @@ -6474,3 +6474,24 @@ button.duckmage-wfc-library-tab.is-active { .duckmage-editor-link-card .duckmage-link-section-title { color: var(--text-normal); } + +/* Terrain swatches show the full name on up to two lines instead of + "forested ..." (E4); a tile's title holds the name if it's longer still. */ +.duckmage-terrain-picker .duckmage-terrain-option { + width: 72px; + min-width: 0; +} +.duckmage-terrain-picker .duckmage-terrain-option-name { + max-width: 100%; + min-height: 2.3em; + white-space: normal; + overflow-wrap: anywhere; + line-height: 1.15; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; +} +/* Two rows of the taller tiles in the hex editor's terrain strip. */ +.duckmage-hex-editor .duckmage-terrain-picker { + max-height: 164px; +} From 0ce1b52c5113a1a47121ea688ca55f4f8849daf4 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:10:19 -0400 Subject: [PATCH 087/558] fix(random-tables): friendly empty-table state with a way to add entries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes #38 E6: terrain encounter/description tables made by setup are empty shells, so rolling said "No entries found. Check the table format." — which reads as if the user broke something. Now the roller view and the inline roll modal say "This table has no entries yet. Add some results to roll on it." with an "Add entries" button (opens the table editor; the modal re-renders after saving), and Roll is disabled until there are entries. The duckmage-roller block shows the same message with "Open table" instead of silently doing nothing. No table content is invented. Co-Authored-By: Claude Opus 5.5 --- src/random-tables/RandomTableModal.ts | 25 +++++++++++++++++++++---- src/random-tables/RandomTableView.ts | 19 ++++++++++++++++--- src/random-tables/RollerBlock.ts | 20 ++++++++++++++++++-- src/random-tables/randomTable.ts | 12 ++++++++++++ styles.css | 9 +++++++++ tests/randomTable.test.ts | 22 ++++++++++++++++++++++ 6 files changed, 98 insertions(+), 9 deletions(-) diff --git a/src/random-tables/RandomTableModal.ts b/src/random-tables/RandomTableModal.ts index c6166cbf..6cebebd9 100644 --- a/src/random-tables/RandomTableModal.ts +++ b/src/random-tables/RandomTableModal.ts @@ -2,7 +2,7 @@ import { App, TFile } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { normalizeFolder } from "../utils"; -import { parseRandomTable, rollOnTable, getDieRanges } from "./randomTable"; +import { parseRandomTable, rollOnTable, getDieRanges, emptyTableMessage } from "./randomTable"; import { VIEW_TYPE_RANDOM_TABLES } from "../constants"; import { RandomTableEditorModal } from "./RandomTableEditorModal"; @@ -232,12 +232,29 @@ export class RandomTableModal extends HexmakerModal { const ranges = table.dice > 0 ? getDieRanges(table) : null; if (table.entries.length === 0) { - tableContainer.createSpan({ - text: "No entries found.", - cls: "duckmage-rt-empty", + const empty = tableContainer.createDiv({ cls: "duckmage-rt-empty-state" }); + empty.createDiv({ text: emptyTableMessage(content), cls: "duckmage-rt-empty" }); + const addBtn = empty.createEl("button", { text: "Add entries", cls: "mod-cta" }); + addBtn.addEventListener("click", () => { + new RandomTableEditorModal( + this.app, + this.plugin, + file, + () => { + void (async () => { + tableContainer.empty(); + resultBox.el.hide(); + rollBtn.disabled = true; + await this.renderOddsTable(tableContainer, resultBox, rollBtn, file); + })(); + }, + content, + ).open(); }); + rollBtn.title = "Add entries to roll on this table"; return; } + rollBtn.removeAttribute("title"); const tableEl = tableContainer.createEl("table", { cls: "duckmage-random-table", diff --git a/src/random-tables/RandomTableView.ts b/src/random-tables/RandomTableView.ts index 47133e48..01669188 100644 --- a/src/random-tables/RandomTableView.ts +++ b/src/random-tables/RandomTableView.ts @@ -16,6 +16,7 @@ import { WorkflowEditorModal } from "./WorkflowEditorModal"; import { WorkflowWizardModal } from "./WorkflowWizardModal"; import { parseRandomTable, + emptyTableMessage, rollOnTable, getDieRanges, setDiceInFrontmatter, @@ -1525,9 +1526,17 @@ export class RandomTableView extends ItemView { }); if (table.entries.length === 0) { - tableBody.createDiv({ - cls: "duckmage-rt-empty", - text: "No entries found. Check the table format.", + const empty = tableBody.createDiv({ cls: "duckmage-rt-empty-state" }); + empty.createDiv({ cls: "duckmage-rt-empty", text: emptyTableMessage(content) }); + const addBtn = empty.createEl("button", { text: "Add entries", cls: "mod-cta" }); + addBtn.addEventListener("click", () => { + new RandomTableEditorModal( + this.app, + this.plugin, + file, + () => void this.renderDetail(), + content, + ).open(); }); } else { const tableEl = tableBody.createEl("table", { @@ -1621,6 +1630,10 @@ export class RandomTableView extends ItemView { text: "Roll", cls: "duckmage-rt-roll-btn mod-cta", }); + if (table.entries.length === 0) { + rollBtn.disabled = true; + rollBtn.title = "Add entries to roll on this table"; + } const resultBox = this.detailEl.createDiv({ cls: "duckmage-roll-result" }); resultBox.hide(); diff --git a/src/random-tables/RollerBlock.ts b/src/random-tables/RollerBlock.ts index bfd6919a..ce05b708 100644 --- a/src/random-tables/RollerBlock.ts +++ b/src/random-tables/RollerBlock.ts @@ -1,6 +1,6 @@ import { TFile } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; -import { parseRandomTable, rollOnTable } from "./randomTable"; +import { emptyTableMessage, parseRandomTable, rollOnTable } from "./randomTable"; import { DIE_OPTIONS } from "./RandomTableView"; /** @@ -64,6 +64,16 @@ export function registerRollerBlock(plugin: HexmakerPlugin): void { cls: "duckmage-roller-btn mod-cta", }); + // Shown instead of a result when the table has nothing to roll yet + // (e.g. a terrain table setup created empty), with a way to fill it. + const emptyEl = block.createDiv({ cls: "duckmage-rt-empty-state" }); + emptyEl.hide(); + const emptyText = emptyEl.createDiv({ cls: "duckmage-rt-empty" }); + const openTableBtn = emptyEl.createEl("button", { text: "Open table" }); + openTableBtn.addEventListener("click", () => { + void plugin.app.workspace.getLeaf("tab").openFile(file); + }); + // Result area — hidden until first roll (reuses modal CSS classes) const resultBox = block.createDiv({ cls: "duckmage-roll-result" }); resultBox.hide(); @@ -110,7 +120,13 @@ export function registerRollerBlock(plugin: HexmakerPlugin): void { const content = await plugin.app.vault.read(file); const table = parseRandomTable(content); const rolled = rollOnTable(table); - if (!rolled) return; + if (!rolled) { + emptyText.setText(emptyTableMessage(content)); + emptyEl.show(); + resultBox.hide(); + return; + } + emptyEl.hide(); // For linked-folder / isLink entries strip the path prefix let display = rolled.result; diff --git a/src/random-tables/randomTable.ts b/src/random-tables/randomTable.ts index e6e26229..a204a12a 100644 --- a/src/random-tables/randomTable.ts +++ b/src/random-tables/randomTable.ts @@ -134,6 +134,18 @@ export function parseMarkdownListItems(content: string): string[] { return results; } +/** + * What to tell the user when a table has nothing to roll (parseRandomTable + * found no entries). Setup creates terrain tables with an empty row, so the + * usual case is "not filled in yet", not a broken format (fresh-eyes E6: the + * old "Check the table format." read as if the user had broken something). + */ +export function emptyTableMessage(content: string): string { + return /^[ \t]*\|/m.test(content) + ? "This table has no entries yet. Add some results to roll on it." + : "This note has no table to roll on yet. Add some entries to start one."; +} + /** Weighted random selection. Returns a random entry. */ export function rollOnTable(table: RandomTable): RandomTableEntry | null { if (table.entries.length === 0) return null; diff --git a/styles.css b/styles.css index c6cb8e8d..44a99640 100644 --- a/styles.css +++ b/styles.css @@ -6495,3 +6495,12 @@ button.duckmage-wfc-library-tab.is-active { .duckmage-hex-editor .duckmage-terrain-picker { max-height: 164px; } + +/* Random tables with nothing to roll yet: message + a way to fill them (E6). */ +.duckmage-rt-empty-state { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.5em; + margin: 0.5em 0; +} diff --git a/tests/randomTable.test.ts b/tests/randomTable.test.ts index 1fe4ab24..e35904fe 100644 --- a/tests/randomTable.test.ts +++ b/tests/randomTable.test.ts @@ -7,6 +7,7 @@ import { getDieRanges, setDiceInFrontmatter, extractPostTableContent, + emptyTableMessage, } from "../src/random-tables/randomTable"; // ── parseRandomTable ────────────────────────────────────────────────────────── @@ -339,3 +340,24 @@ describe("extractPostTableContent", () => { expect(extractPostTableContent("No table here.")).toBe(""); }); }); + +// ── emptyTableMessage (fresh-eyes E6) ───────────────────────────────────────── + +describe("emptyTableMessage", () => { + it("calls a setup-made table with only an empty row 'no entries yet', not a format error", () => { + const content = makeTableTemplateLike(); + expect(parseRandomTable(content).entries).toHaveLength(0); + const msg = emptyTableMessage(content); + expect(msg).toMatch(/no entries yet/); + expect(msg).not.toMatch(/format/i); + }); + + it("says there's no table yet when the note has no table at all", () => { + expect(emptyTableMessage("---\ndice: 6\n---\nJust some notes.\n")).toMatch(/no table to roll on yet/); + }); +}); + +/** Same shape as utils.makeTableTemplate (what setup writes for terrain tables). */ +function makeTableTemplateLike(): string { + return "---\ndice: 20\n---\n\n| Result | Weight |\n|--------|--------|\n| | 1 |\n"; +} From 69fe8bfbb566be2ad5596c87c92a88e32780d5fd Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:12:36 -0400 Subject: [PATCH 088/558] fix(path-tool): Path button reopens its picker; hint when a click restarts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes #39 T7: - Clicking the active Path button turned the tool off (Terrain reopens its picker), so testers lost their mode. It now always opens the path-type picker; leaving the tool is right-click → Exit tool. Re-picking the type being drawn keeps the current chain going. - Paths go hex by hex; a click on a non-adjacent hex silently started a new one-hex chain (a lone dot). It still starts one, but a Notice now says to click a hex next to the end. Clicking the end hex itself no longer stacks a second one-hex chain there. - Click outcome logic is pure (src/hex-map/toolMode.ts) and tested. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 ++-- src/hex-map/HexMapView.ts | 42 ++++++++++++++++++++++------------ src/hex-map/toolMode.ts | 34 +++++++++++++++++++++++++++ tests/toolMode.test.ts | 48 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 111 insertions(+), 17 deletions(-) create mode 100644 src/hex-map/toolMode.ts create mode 100644 tests/toolMode.test.ts diff --git a/package.json b/package.json index 00dfe51d..3dcbbd3e 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 505719b1..0e858886 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -28,6 +28,7 @@ import { } from "../constants"; import { MapModal } from "./MapModal"; import { mapAncestors } from "./submapNav"; +import { pathClickOutcome } from "./toolMode"; import { PathPickerModal } from "./PathPickerModal"; import type { MapData, PathChain, TokenEntry } from "../types"; import { @@ -1511,7 +1512,7 @@ export class HexMapView extends ItemView { switchLabel = "Switch region"; extra.push({ label: erasing ? "Link mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "path") { - onSwitch = () => this.handlePathButton(true); + onSwitch = () => this.handlePathButton(); switchLabel = "Switch path type"; extra.push({ label: erasing ? "Draw mode" : "Erase mode", onClick: toggleEraseMode }); } else if (mode === "placeToken") { @@ -4764,22 +4765,21 @@ export class HexMapView extends ItemView { } } - private handlePathButton(keep = false): void { - if (!keep && this.drawingMode === "path") { - this.exitPathMode(); - this.drawingMode = null; - this.updateToolbarButtonStates(); - this.updatePathOverlay(); - return; - } + /** + * Open the path-type picker. Clicking the Path button while drawing reopens + * it (like Terrain) instead of silently turning the tool off (fresh-eyes + * T7); leave the tool with right-click → Exit tool, Esc, or the mode bar. + */ + private handlePathButton(): void { new PathPickerModal( this.app, this.plugin, this.activePathTypeName, (typeName) => { this.leaveOtherToolFor("path"); - // A new type starts a new chain rather than continuing the old one. - this.exitPathMode(); + // A new type starts a new chain rather than continuing the old one; + // re-picking the type being drawn keeps the chain going. + if (this.drawingMode !== "path" || typeName !== this.activePathTypeName) this.exitPathMode(); this.activePathTypeName = typeName; this.drawingMode = "path"; this.isErasingMode = false; @@ -4823,16 +4823,28 @@ export class HexMapView extends ItemView { ); const before = this.cloneChains(region.pathChains); - // ── If adjacent to active end, extend that chain ───────────────────── + let neighbourKeys: string[] = []; if (this.activePathEnd !== null) { const [ax, ay] = this.activePathEnd.split("_").map(Number); - const isAdjacent = hexNeighbors( + neighbourKeys = hexNeighbors( ax, ay, this.plugin.settings.hexOrientation, this.getActiveStagger(), - ).some(([nx, ny]) => nx === x && ny === y); - if (isAdjacent) { + ).map(([nx, ny]) => `${nx}_${ny}`); + } + const outcome = pathClickOutcome(this.activePathEnd, key, neighbourKeys); + // Clicking the end again would stack a second one-hex chain on it. + if (outcome === "same") return; + if (outcome === "restart") { + // Paths don't auto-route between distant hexes; say so instead of + // silently leaving a lone dot (fresh-eyes T7). + new Notice("Paths go hex by hex: click a hex next to the end of the path. Started a new path here."); + } + + // ── If adjacent to active end, extend that chain ───────────────────── + if (this.activePathEnd !== null) { + if (outcome === "extend") { let target: PathChain | undefined; if ( this.activePathChain !== null && diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts new file mode 100644 index 00000000..0e70db1f --- /dev/null +++ b/src/hex-map/toolMode.ts @@ -0,0 +1,34 @@ +/** + * Pure helpers for the map's drawing tools (path clicks, the on-map mode + * indicator). Kept free of Obsidian imports so they're unit-testable. + */ + +export type DrawingMode = + | "path" + | "terrain" + | "icon" + | "tableLink" + | "submapLink" + | "factionLink" + | "regionLink" + | "swap" + | "placeToken"; + +/** + * What a left-click on hex `key` does while drawing a path: + * - "start": no path in progress, so start one here; + * - "extend": `key` neighbours the end of the path in progress; + * - "same": `key` IS the end of the path (ignore — don't stack a dot); + * - "restart": `key` isn't next to the end, so a new path starts there. + * Paths go hex by hex, so the caller should say so (fresh-eyes T7: two + * distant clicks silently gave a single dot). + */ +export function pathClickOutcome( + activeEnd: string | null, + key: string, + neighbourKeysOfEnd: readonly string[], +): "start" | "extend" | "same" | "restart" { + if (activeEnd === null) return "start"; + if (key === activeEnd) return "same"; + return neighbourKeysOfEnd.includes(key) ? "extend" : "restart"; +} diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts new file mode 100644 index 00000000..ee5e53d6 --- /dev/null +++ b/tests/toolMode.test.ts @@ -0,0 +1,48 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { pathClickOutcome } from "../src/hex-map/toolMode"; + +const viewSrc = readFileSync(path.join(process.cwd(), "src", "hex-map", "HexMapView.ts"), "utf8").replace(/\r\n/g, "\n"); + +/** Source of the HexMapView method `name` (up to its closing brace at two-space indent). */ +function method(name: string): string { + const m = new RegExp(`\\n private (?:async )?${name}\\(`).exec(viewSrc); + const start = m ? m.index + 1 : -1; + expect(start).toBeGreaterThan(-1); + return viewSrc.slice(start, viewSrc.indexOf("\n }\n", start)); +} + +describe("pathClickOutcome (fresh-eyes T7)", () => { + const around = ["2_1", "3_2", "3_3", "2_3", "1_3", "1_2"]; // neighbours of 2_2 + + it("starts a path when none is in progress", () => { + expect(pathClickOutcome(null, "5_5", [])).toBe("start"); + }); + + it("extends the path on a neighbour of its end", () => { + expect(pathClickOutcome("2_2", "3_2", around)).toBe("extend"); + }); + + it("ignores a click on the end itself (no stacked dot)", () => { + expect(pathClickOutcome("2_2", "2_2", around)).toBe("same"); + }); + + it("reports a restart for a distant hex so the caller can explain it", () => { + expect(pathClickOutcome("2_2", "6_6", around)).toBe("restart"); + }); +}); + +describe("Path tool button (fresh-eyes T7)", () => { + it("clicking Path while drawing reopens the picker instead of exiting", () => { + const body = method("handlePathButton"); + expect(body).toMatch(/new PathPickerModal\(/); + expect(body).not.toMatch(/exitPathMode\(\);\s*this\.drawingMode = null/); + }); + + it("a restart on a non-adjacent hex shows a hint", () => { + const body = method("onHexPathDrawClick"); + expect(body).toMatch(/outcome === "restart"[\s\S]*new Notice\(/); + }); +}); From 02cbd449dcd31d430461ccd356245a6c29376423 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:14:14 -0400 Subject: [PATCH 089/558] fix(path-tool): right-click removes a path hex; tokens don't swallow clicks Fresh-eyes #39 T2 (verified in code): - The help says "right-click a hex already in the chain to remove it", but with any tool active right-click always opened the tool menu. Now a right-click on a hex of the path type being drawn removes it from its chain (splitting it if needed, undoable); elsewhere it still opens the menu. - A token sits in a layer above the hexes, so a click on a token's hex hit the token (not a .duckmage-hex) and was dropped while drawing. Tokens are click-through (pointer-events: none) while a drawing tool is active. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 23 ++++++++++++++++++++++- styles.css | 6 ++++++ tests/toolMode.test.ts | 17 +++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 0e858886..f4f1477c 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -853,6 +853,17 @@ export class HexMapView extends ItemView { this.removeOneGmIconFromHex(hexEl, hexX, hexY, this.paintIconName); return; } + // Path tool: right-click a hex of the path type being drawn removes + // it from its chain, as the help says (fresh-eyes T2). Anywhere else + // still opens the tool menu. + if ( + this.drawingMode === "path" && + hexX !== null && hexY !== null && + this.pathChainWithHex(`${hexX}_${hexY}`, this.activePathTypeName) + ) { + void this.onHexPathDeleteClick(hexX, hexY, this.activePathTypeName); + return; + } this.showPainterContextMenu(e.clientX, e.clientY, hexX, hexY); }, { capture: true }, @@ -4886,13 +4897,23 @@ export class HexMapView extends ItemView { this.updatePathOverlay(); } - private async onHexPathDeleteClick(x: number, y: number): Promise { + /** First path chain (of `typeName`, or any type when null) through hex `key`. */ + private pathChainWithHex(key: string, typeName: string | null): PathChain | undefined { + return this.getActiveMap().pathChains.find( + (c) => (typeName === null || c.typeName === typeName) && c.hexes.includes(key), + ); + } + + /** Remove hex (x, y) from the first chain through it — only chains of + * `typeName` when given (right-click while drawing that type). */ + private async onHexPathDeleteClick(x: number, y: number, typeName: string | null = null): Promise { const key = `${x}_${y}`; const region = this.getActiveMap(); const chains = region.pathChains; const before = this.cloneChains(region.pathChains); for (let ci = 0; ci < chains.length; ci++) { + if (typeName !== null && chains[ci].typeName !== typeName) continue; const pos = chains[ci].hexes.indexOf(key); if (pos === -1) continue; diff --git a/styles.css b/styles.css index 44a99640..85a419a8 100644 --- a/styles.css +++ b/styles.css @@ -6504,3 +6504,9 @@ button.duckmage-wfc-library-tab.is-active { gap: 0.5em; margin: 0.5em 0; } + +/* While a drawing tool is active, clicks on a token fall through to the hex + under it (a token used to swallow path/paint clicks on its hex, T2). */ +.duckmage-hex-map-viewport.duckmage-draw-mode .duckmage-token { + pointer-events: none; +} diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index ee5e53d6..1bdbc81d 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -46,3 +46,20 @@ describe("Path tool button (fresh-eyes T7)", () => { expect(body).toMatch(/outcome === "restart"[\s\S]*new Notice\(/); }); }); + +describe("Path tool right-click and tokens (fresh-eyes T2)", () => { + it("right-click on a hex of the path being drawn removes it instead of opening the menu", () => { + const start = viewSrc.indexOf('"contextmenu",'); + const handler = viewSrc.slice(start, viewSrc.indexOf("{ capture: true }", start)); + expect(handler).toMatch(/this\.drawingMode === "path"[\s\S]*pathChainWithHex\([\s\S]*onHexPathDeleteClick\(hexX, hexY, this\.activePathTypeName\)[\s\S]*return;[\s\S]*showPainterContextMenu/); + }); + + it("the delete only touches chains of the given path type", () => { + expect(method("onHexPathDeleteClick")).toMatch(/typeName !== null && chains\[ci\]\.typeName !== typeName\) continue/); + }); + + it("tokens let clicks through while a drawing tool is active", () => { + const css = readFileSync(path.join(process.cwd(), "styles.css"), "utf8").replace(/\s+/g, " "); + expect(css).toContain(".duckmage-hex-map-viewport.duckmage-draw-mode .duckmage-token { pointer-events: none; }"); + }); +}); From 8aae43172b5b1f87fb4c245491f587d0d61f2c94 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:17:44 -0400 Subject: [PATCH 090/558] feat(map): on-map mode bar for drawing tools; Esc and double-right-click exit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes #39 T3: paint/draw modes are sticky and the only sign was the toolbar button's text, so testers didn't know whether the next click would paint (one stayed in Region paint mode for a whole scenario). A small bar over the map now names the active tool ("Painting terrain: forest", "Drawing Road: click neighbouring hexes", "Painting region: Kerrigan", …) with "Right-click: options · Esc: stop" and a ✕ stop button; it hides when no tool is on. Same for every drawing mode (terrain, icon, path, table / submap link, factions, regions, swap, token). Esc now leaves the active tool (view scope, so modals and menus keep their own Esc), and double-right-click exits as the help already documents (it wasn't wired). Labels are pure (toolModeLabel) and tested. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 65 ++++++++++++++++++++++++++++++++++++++- src/hex-map/toolMode.ts | 57 ++++++++++++++++++++++++++++++++++ styles.css | 35 +++++++++++++++++++++ tests/toolMode.test.ts | 29 ++++++++++++++++- 4 files changed, 184 insertions(+), 2 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index f4f1477c..e59667c6 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -28,7 +28,7 @@ import { } from "../constants"; import { MapModal } from "./MapModal"; import { mapAncestors } from "./submapNav"; -import { pathClickOutcome } from "./toolMode"; +import { pathClickOutcome, toolModeLabel } from "./toolMode"; import { PathPickerModal } from "./PathPickerModal"; import type { MapData, PathChain, TokenEntry } from "../types"; import { @@ -212,6 +212,11 @@ export class HexMapView extends ItemView { | "placeToken" | null = null; private isErasingMode = false; + /** On-map "which tool is on" bar (fresh-eyes T3); text set in updateModeBar. */ + private modeBarEl: HTMLElement | null = null; + private modeBarTextEl: HTMLElement | null = null; + /** Time of the last right-click while a tool was active (double-right-click exits). */ + private lastToolContextMenuAt = 0; private pathToolbarBtn: HTMLButtonElement | null = null; private pathBtnSwatch: HTMLElement | null = null; private terrainToolbarBtn: HTMLButtonElement | null = null; @@ -585,6 +590,32 @@ export class HexMapView extends ItemView { this.viewportEl = clipEl.createDiv({ cls: "duckmage-hex-map-viewport" }); this.applyTransform(); + // Mode bar: paint/draw tools are sticky, so say which one is on and how + // to stop it (fresh-eyes T3). Hidden while no tool is active. + this.modeBarEl = controlsEl.createDiv({ + cls: "duckmage-mode-bar", + attr: { role: "status", "aria-live": "polite" }, + }); + this.modeBarTextEl = this.modeBarEl.createSpan({ cls: "duckmage-mode-bar-text" }); + this.modeBarEl.createSpan({ + cls: "duckmage-mode-bar-hint", + text: "Right-click: options · Esc: stop", + }); + const modeBarStop = this.modeBarEl.createEl("button", { + cls: "duckmage-mode-bar-stop", + text: "✕", + attr: { title: "Stop this tool", "aria-label": "Stop this tool" }, + }); + modeBarStop.addEventListener("click", () => this.exitCurrentMode()); + this.modeBarEl.hide(); + + // Esc leaves the active tool (modals and menus handle their own Esc first). + this.scope.register([], "Escape", () => { + if (this.drawingMode === null) return true; + this.exitCurrentMode(); + return false; + }); + this.factionTooltipEl = contentEl.createDiv({ cls: "duckmage-faction-tooltip" }); this.factionTooltipEl.hide(); @@ -840,6 +871,15 @@ export class HexMapView extends ItemView { if (this.drawingMode === null) return; e.preventDefault(); e.stopPropagation(); + // Double-right-click anywhere exits the tool (as the help says). + const now = performance.now(); + const isDouble = now - this.lastToolContextMenuAt < 400; + this.lastToolContextMenuAt = isDouble ? 0 : now; + if (isDouble) { + activeDocument.querySelectorAll(".duckmage-painter-ctx-menu").forEach((m) => m.remove()); + this.exitCurrentMode(); + return; + } const hexEl = (e.target as HTMLElement).closest(".duckmage-hex"); const hexX = hexEl ? Number(hexEl.dataset.x) : null; const hexY = hexEl ? Number(hexEl.dataset.y) : null; @@ -2216,7 +2256,30 @@ export class HexMapView extends ItemView { // Terrain / icon erase visual feedback this.terrainToolbarBtn?.toggleClass("is-erase", erasing && this.drawingMode === "terrain"); this.iconToolbarBtn?.toggleClass("is-erase", erasing && this.drawingMode === "icon"); + + this.updateModeBar(); + } + + /** Show which tool is on (and how to stop it) on the map itself. */ + private updateModeBar(): void { + if (!this.modeBarEl || !this.modeBarTextEl) return; + const label = toolModeLabel({ + mode: this.drawingMode, + erasing: this.isErasingMode, + terrainName: this.paintTerrainName, + terrainPick: this.terrainPickMode, + iconName: this.paintIconName, + iconGmOnly: this.paintIconGmOnly, + pathTypeName: this.activePathTypeName, + tablePath: this.paintTablePath, + submapName: this.paintSubmapName, + factionPath: this.paintFactionPath, + regionPath: this.paintRegionPath, + }); + this.modeBarTextEl.setText(label ?? ""); + this.modeBarEl.toggle(label !== null); } + private applyTransform(): void { if (this.viewportEl) { this.viewportEl.setCssProps({ diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts index 0e70db1f..db54ec52 100644 --- a/src/hex-map/toolMode.ts +++ b/src/hex-map/toolMode.ts @@ -32,3 +32,60 @@ export function pathClickOutcome( if (key === activeEnd) return "same"; return neighbourKeysOfEnd.includes(key) ? "extend" : "restart"; } + +export interface ToolModeState { + mode: DrawingMode | null; + erasing: boolean; + terrainName?: string | null; + terrainPick?: boolean; + iconName?: string | null; + iconGmOnly?: boolean; + pathTypeName?: string | null; + tablePath?: string | null; + submapName?: string | null; + factionPath?: string | null; + regionPath?: string | null; +} + +/** "world/factions/Red Hand.md" → "Red Hand"; icon file → its name. */ +function baseName(p: string | null | undefined): string { + if (!p) return ""; + return (p.split("/").pop() ?? p).replace(/\.(md|png|svg|jpe?g|webp)$/i, ""); +} + +/** + * Text for the on-map mode indicator ("Painting terrain: forest"), or null + * when no tool is active. Paint modes are sticky, so the map says which one + * is on (fresh-eyes T3). + */ +export function toolModeLabel(s: ToolModeState): string | null { + const { mode, erasing } = s; + switch (mode) { + case null: + return null; + case "terrain": + if (s.terrainPick) return "Picking terrain: click a hex to copy its terrain"; + if (erasing || !s.terrainName) return "Clearing terrain"; + return `Painting terrain: ${s.terrainName}`; + case "icon": { + const what = s.iconGmOnly ? "GM icon" : "icon"; + if (erasing || !s.iconName) return `Erasing ${what}s`; + return `Painting ${what}: ${baseName(s.iconName)}`; + } + case "path": + if (erasing) return "Erasing paths: click a path hex to remove it"; + return `Drawing ${s.pathTypeName ?? "path"}: click neighbouring hexes`; + case "tableLink": + return erasing ? "Unlinking tables" : `Linking table: ${baseName(s.tablePath) || "…"}`; + case "submapLink": + return erasing ? "Unlinking submaps" : `Linking submap: ${s.submapName ?? "…"}`; + case "factionLink": + return erasing ? "Erasing factions" : `Painting faction: ${baseName(s.factionPath) || "…"}`; + case "regionLink": + return erasing ? "Erasing regions" : `Painting region: ${baseName(s.regionPath) || "…"}`; + case "swap": + return "Swapping hexes: click two hexes"; + case "placeToken": + return "Placing token: click a hex"; + } +} diff --git a/styles.css b/styles.css index 85a419a8..5f79127f 100644 --- a/styles.css +++ b/styles.css @@ -6510,3 +6510,38 @@ button.duckmage-wfc-library-tab.is-active { .duckmage-hex-map-viewport.duckmage-draw-mode .duckmage-token { pointer-events: none; } + +/* Mode bar: which drawing tool is on and how to stop it (T3). Sits above + the bottom expand button, centred over the map. */ +.duckmage-mode-bar { + position: absolute; + bottom: 40px; + left: 50%; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 0.6em; + max-width: calc(100% - 2em); + padding: 0.3em 0.4em 0.3em 0.8em; + border-radius: 999px; + border: 1px solid var(--interactive-accent); + background: var(--background-primary); + box-shadow: var(--shadow-s); + font-size: var(--font-ui-small); + white-space: nowrap; +} +.duckmage-mode-bar-text { + font-weight: 600; + color: var(--text-normal); + overflow: hidden; + text-overflow: ellipsis; +} +.duckmage-mode-bar-hint { + color: var(--text-muted); +} +.duckmage-mode-bar-stop { + padding: 0 0.5em; + height: 1.7em; + border-radius: 999px; + box-shadow: none; +} diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 1bdbc81d..873798b9 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -2,7 +2,7 @@ import { describe, it } from "node:test"; import expect from "expect"; import { readFileSync } from "node:fs"; import * as path from "node:path"; -import { pathClickOutcome } from "../src/hex-map/toolMode"; +import { pathClickOutcome, toolModeLabel } from "../src/hex-map/toolMode"; const viewSrc = readFileSync(path.join(process.cwd(), "src", "hex-map", "HexMapView.ts"), "utf8").replace(/\r\n/g, "\n"); @@ -63,3 +63,30 @@ describe("Path tool right-click and tokens (fresh-eyes T2)", () => { expect(css).toContain(".duckmage-hex-map-viewport.duckmage-draw-mode .duckmage-token { pointer-events: none; }"); }); }); + +describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => { + it("is null when no tool is active", () => { + expect(toolModeLabel({ mode: null, erasing: false })).toBeNull(); + }); + + it("names what each tool is doing", () => { + expect(toolModeLabel({ mode: "terrain", erasing: false, terrainName: "forest" })).toBe("Painting terrain: forest"); + expect(toolModeLabel({ mode: "terrain", erasing: false, terrainName: null })).toBe("Clearing terrain"); + expect(toolModeLabel({ mode: "terrain", erasing: false, terrainPick: true })).toMatch(/^Picking terrain/); + expect(toolModeLabel({ mode: "icon", erasing: false, iconName: "bw-castle.svg" })).toBe("Painting icon: bw-castle"); + expect(toolModeLabel({ mode: "icon", erasing: false, iconName: "x.png", iconGmOnly: true })).toBe("Painting GM icon: x"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road" })).toBe("Drawing Road: click neighbouring hexes"); + expect(toolModeLabel({ mode: "path", erasing: true })).toMatch(/^Erasing paths/); + expect(toolModeLabel({ mode: "regionLink", erasing: false, regionPath: "world/regions/Kerrigan.md" })).toBe("Painting region: Kerrigan"); + expect(toolModeLabel({ mode: "factionLink", erasing: true })).toBe("Erasing factions"); + expect(toolModeLabel({ mode: "tableLink", erasing: false, tablePath: "world/tables/ocean.md" })).toBe("Linking table: ocean"); + expect(toolModeLabel({ mode: "submapLink", erasing: false, submapName: "deep" })).toBe("Linking submap: deep"); + expect(toolModeLabel({ mode: "swap", erasing: false })).toMatch(/^Swapping hexes/); + expect(toolModeLabel({ mode: "placeToken", erasing: false })).toMatch(/^Placing token/); + }); + + it("the map view refreshes the bar with the toolbar and Esc exits the tool", () => { + expect(method("updateToolbarButtonStates")).toMatch(/this\.updateModeBar\(\);/); + expect(viewSrc).toMatch(/this\.scope\.register\(\[\], "Escape"[\s\S]{0,200}this\.exitCurrentMode\(\)/); + }); +}); From e07fc77326d78877da94a91c863dd185b1fc1199 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:20:31 -0400 Subject: [PATCH 091/558] =?UTF-8?q?fix(map-nav):=20"=E2=86=91=20parent=20m?= =?UTF-8?q?ap"=20/=20"=E2=86=90=20previous=20map",=20each=20naming=20its?= =?UTF-8?q?=20target?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes #39 T4: "↑ up" vs "← back" weren't self-explanatory. The buttons now read "↑ parent map" and "← previous map", and their tooltip and aria-label name the destination ("Up to the parent map: thornwood-vale, hex 4, 2 (Alt+↑)", "Back to the previous map: ashby-vale (Alt+←)"). canNavigateBack and the tooltip share previousMapName(). Note: src/hex-map/help.md still says "↑ up" / "← back" (owned by another session; left untouched). Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 36 +++++++++++++++++++++++++++++------- tests/toolMode.test.ts | 12 ++++++++++++ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index e59667c6..7d19652a 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -484,7 +484,16 @@ export class HexMapView extends ItemView { } canNavigateBack(): boolean { - return this.mapHistory.some((m) => m !== this.activeMapName && this.plugin.getMap(m)); + return this.previousMapName() !== undefined; + } + + /** The map Back would go to (skips maps deleted since and the current one). */ + private previousMapName(): string | undefined { + for (let i = this.mapHistory.length - 1; i >= 0; i--) { + const m = this.mapHistory[i]; + if (m !== this.activeMapName && this.plugin.getMap(m)) return m; + } + return undefined; } canNavigateUp(): boolean { @@ -501,14 +510,28 @@ export class HexMapView extends ItemView { /** Breadcrumb (ancestors), Up and Back buttons for the active map. */ private refreshMapNav(): void { - if (this.canNavigateBack()) this.backBtn?.show(); - else this.backBtn?.hide(); + // Both buttons name the map they go to (fresh-eyes T4: "↑ up" vs + // "← back" wasn't self-explanatory): Parent = the map this one is a + // submap of; Previous = the map viewed before this one (like a browser). + const prev = this.previousMapName(); + if (this.backBtn) { + if (prev) { + this.backBtn.show(); + const label = `Back to the previous map: ${prev} (Alt+←)`; + this.backBtn.title = label; + this.backBtn.setAttr("aria-label", label); + } else { + this.backBtn.hide(); + } + } const parent = this.plugin.parentOf(this.activeMapName); if (this.upBtn) { if (parent) { this.upBtn.show(); - this.upBtn.title = `Up to ${parent.map} (hex ${parent.hex.replace("_", ", ")})`; + const label = `Up to the parent map: ${parent.map}, hex ${parent.hex.replace("_", ", ")} (Alt+↑)`; + this.upBtn.title = label; + this.upBtn.setAttr("aria-label", label); } else { this.upBtn.hide(); } @@ -1001,15 +1024,14 @@ export class HexMapView extends ItemView { this.upBtn = mapNavGroup.createEl("button", { cls: "duckmage-map-up-btn", - text: "↑ up", + text: "↑ parent map", }); this.upBtn.hide(); this.upBtn.addEventListener("click", () => this.navigateUp()); this.backBtn = mapNavGroup.createEl("button", { cls: "duckmage-map-back-btn", - text: "← back", - title: "Back to previous map", + text: "← previous map", }); this.backBtn.hide(); this.backBtn.addEventListener("click", () => this.navigateBack()); diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 873798b9..36c2b2b1 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -90,3 +90,15 @@ describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => expect(viewSrc).toMatch(/this\.scope\.register\(\[\], "Escape"[\s\S]{0,200}this\.exitCurrentMode\(\)/); }); }); + +describe("Map navigation buttons say where they go (fresh-eyes T4)", () => { + it("labels Up/Back as parent/previous map and names the target map", () => { + expect(viewSrc).toContain('text: "↑ parent map"'); + expect(viewSrc).toContain('text: "← previous map"'); + const nav = method("refreshMapNav"); + expect(nav).toMatch(/backBtn\.setAttr\("aria-label", label\)/); + expect(nav).toMatch(/upBtn\.setAttr\("aria-label", label\)/); + expect(nav).toMatch(/previous map: \$\{prev\}/); + expect(nav).toMatch(/parent map: \$\{parent\.map\}/); + }); +}); From 6c224827681d87daca60ccbdc025f77f4f561503 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:21:56 -0400 Subject: [PATCH 092/558] fix(map): "Enter submap" in the hex right-click menu for every submap hex MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes N3 (rest): the menu read the hex's submap, terrain and icon only when a hex note existed, but those live in the map note now and a hex can have a submap without a note (generated maps, "New submap…"), so the entry never appeared there. Read them through the map store unconditionally and call the item "Enter submap: " (matching the ring's tooltip). "Clear terrain" / "Remove icon override" show up on such hexes for the same reason. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 15 +++++++++------ tests/toolMode.test.ts | 9 +++++++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 7d19652a..63d2dde4 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -3791,10 +3791,13 @@ export class HexMapView extends ItemView { if (this.drawingMode !== null) return; const hexPath = this.plugin.hexPath(x, y, this.activeMapName); - const hexExists = this.app.vault.getAbstractFileByPath(hexPath) instanceof TFile; - const terrain = hexExists ? getTerrainFromFile(this.app, hexPath) : null; - const iconOverride = hexExists ? getIconOverrideFromFile(this.app, hexPath) : null; - const submap = hexExists ? getSubmapFromFile(this.app, hexPath) : undefined; + // Terrain, icon and submap live in the map note, and a hex can have them + // before its hex note exists (a generated map, a submap made from this + // menu) — gating these on the note hid "Enter submap" and "Clear + // terrain" on such hexes (fresh-eyes N3). + const terrain = getTerrainFromFile(this.app, hexPath); + const iconOverride = getIconOverrideFromFile(this.app, hexPath); + const submap = getSubmapFromFile(this.app, hexPath); const menu = new Menu(); @@ -3824,8 +3827,8 @@ export class HexMapView extends ItemView { if (submap) { menu.addItem((item) => item - .setTitle(`Open submap: ${submap}`) - .setIcon("map") + .setTitle(`Enter submap: ${submap}`) + .setIcon("log-in") .onClick(() => this.navigateToMap(submap)), ); } diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 36c2b2b1..92c21f2a 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -102,3 +102,12 @@ describe("Map navigation buttons say where they go (fresh-eyes T4)", () => { expect(nav).toMatch(/parent map: \$\{parent\.map\}/); }); }); + +describe("Hex right-click menu offers Enter submap (fresh-eyes N3)", () => { + it("reads the submap from the map note, not only when a hex note exists", () => { + const menu = method("onHexContextMenu"); + expect(menu).toMatch(/const submap = getSubmapFromFile\(this\.app, hexPath\);/); + expect(menu).not.toMatch(/hexExists \?/); + expect(menu).toContain("Enter submap: ${submap}"); + }); +}); From 397635f0471c08e3ec4cef9ecdc0061e1b102890 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:33:32 -0400 Subject: [PATCH 093/558] fix(hex-editor): scroll the current terrain into view in the terrain strip Follow-up to E1 (#38), found in the sandbox check: the strip shows two rows, so on a large palette (Expanded) the highlighted current terrain was often scrolled out of sight. Scroll it into view on open. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexEditorModal.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 0b4eb4ab..1e5773a0 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -580,6 +580,16 @@ export class HexEditorModal extends HexmakerModal { }); } + // The strip shows two rows; scroll the current terrain into view so the + // highlight is visible on open, not hidden further down the palette. + const current = grid.querySelector(".duckmage-terrain-option.is-selected"); + if (current) { + window.requestAnimationFrame(() => { + const offset = current.getBoundingClientRect().top - grid.getBoundingClientRect().top; + grid.scrollTop += offset - 4; + }); + } + // Keep terrain in the overrides map (see terrainOverrides above) so // renderGrid doesn't lose it during the brief window when Obsidian // clears the metadata cache on file modify. From 0d73cee3370f36ab3e77681f53687e45b28225e6 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:33:32 -0400 Subject: [PATCH 094/558] fix(random-tables): show the Roll button as disabled on an empty table Follow-up to E6 (#38): Roll is disabled until a table has entries, but mod-cta styling made it look clickable. Dim it with a not-allowed cursor. Co-Authored-By: Claude Opus 5.5 --- styles.css | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/styles.css b/styles.css index 5f79127f..d0615cb5 100644 --- a/styles.css +++ b/styles.css @@ -6545,3 +6545,7 @@ button.duckmage-wfc-library-tab.is-active { border-radius: 999px; box-shadow: none; } +.duckmage-rt-roll-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} From 29c7a09519f0068dca9944e16994752dadff9e9e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:33:57 -0400 Subject: [PATCH 095/558] fix(path-tool): drop an abandoned one-hex start; removing the end steps back MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-ups to T7/T2 (#39), found in the sandbox check: - When a non-adjacent click restarts the path, the previous one-click start was left behind as a one-hex chain. Those are never drawn (a line needs two hexes), so it lingered invisibly in the map data — the "earlier part was gone" the tester saw. It is dropped (undoable). - Right-click (or erase) on the end of the path being drawn now steps the end back one hex so drawing carries on, instead of ending the path. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 15 +++++++++++++-- tests/toolMode.test.ts | 12 +++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 63d2dde4..15ed9b92 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -4939,6 +4939,14 @@ export class HexMapView extends ItemView { // Paths don't auto-route between distant hexes; say so instead of // silently leaving a lone dot (fresh-eyes T7). new Notice("Paths go hex by hex: click a hex next to the end of the path. Started a new path here."); + // A one-hex chain is never drawn (a line needs two hexes), so the + // abandoned start would linger invisibly in the map data: drop it. + const abandoned = this.activePathChain; + if (abandoned && abandoned.hexes.length === 1) { + const i = region.pathChains.indexOf(abandoned); + if (i !== -1) region.pathChains.splice(i, 1); + this.activePathChain = null; + } } // ── If adjacent to active end, extend that chain ───────────────────── @@ -5033,8 +5041,11 @@ export class HexMapView extends ItemView { } if (this.activePathEnd === key) { - this.activePathEnd = null; - this.activePathChain = null; + // Removing the end of the path being drawn steps it back one hex, + // so drawing carries on from there. + const stepBack = pos === chain.hexes.length && chain.hexes.length > 0; + this.activePathEnd = stepBack ? chain.hexes[chain.hexes.length - 1] : null; + this.activePathChain = stepBack ? chain : null; } this.pushPathUndo( diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 92c21f2a..2af31711 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -87,7 +87,7 @@ describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => it("the map view refreshes the bar with the toolbar and Esc exits the tool", () => { expect(method("updateToolbarButtonStates")).toMatch(/this\.updateModeBar\(\);/); - expect(viewSrc).toMatch(/this\.scope\.register\(\[\], "Escape"[\s\S]{0,200}this\.exitCurrentMode\(\)/); + expect(viewSrc).toMatch(/this\.scope\.register\(\[\], "Escape"[\s\S]{0,600}this\.exitCurrentMode\(\)/); }); }); @@ -111,3 +111,13 @@ describe("Hex right-click menu offers Enter submap (fresh-eyes N3)", () => { expect(menu).toContain("Enter submap: ${submap}"); }); }); + +describe("Path chain upkeep (fresh-eyes T7/T2 follow-up)", () => { + it("a restart drops the abandoned one-hex start (never drawn, would linger in the data)", () => { + expect(method("onHexPathDrawClick")).toMatch(/abandoned && abandoned\.hexes\.length === 1[\s\S]*pathChains\.splice\(i, 1\)/); + }); + + it("removing the end of the path being drawn steps the end back one hex", () => { + expect(method("onHexPathDeleteClick")).toMatch(/const stepBack = pos === chain\.hexes\.length && chain\.hexes\.length > 0;/); + }); +}); From 6f29776c3034463707426d92583ef0eb8238af66 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:33:57 -0400 Subject: [PATCH 096/558] fix(map): Esc closes an open tool menu before it exits the tool Follow-up to T3 (#39), found in the sandbox check: with the right-click tool menu open, Esc exited the tool and left the menu on screen (Obsidian's keymap sees Esc before the menu's own listener). The view keeps the open PainterContextMenu (new isOpen()); the first Esc closes it and keeps the tool, the next one exits. Double-right-click uses the same handle to close the menu. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 14 ++++++++++++-- src/hex-map/PainterContextMenu.ts | 4 ++++ tests/toolMode.test.ts | 6 ++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 15ed9b92..e4588f5e 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -217,6 +217,8 @@ export class HexMapView extends ItemView { private modeBarTextEl: HTMLElement | null = null; /** Time of the last right-click while a tool was active (double-right-click exits). */ private lastToolContextMenuAt = 0; + /** The open (or last) right-click tool menu, so Esc can close it first. */ + private painterMenu: PainterContextMenu | null = null; private pathToolbarBtn: HTMLButtonElement | null = null; private pathBtnSwatch: HTMLElement | null = null; private terrainToolbarBtn: HTMLButtonElement | null = null; @@ -634,6 +636,12 @@ export class HexMapView extends ItemView { // Esc leaves the active tool (modals and menus handle their own Esc first). this.scope.register([], "Escape", () => { + // An open tool menu takes the first Esc (Obsidian's keymap sees the + // key before the menu's own listener would). + if (this.painterMenu?.isOpen()) { + this.painterMenu.close(); + return false; + } if (this.drawingMode === null) return true; this.exitCurrentMode(); return false; @@ -899,7 +907,7 @@ export class HexMapView extends ItemView { const isDouble = now - this.lastToolContextMenuAt < 400; this.lastToolContextMenuAt = isDouble ? 0 : now; if (isDouble) { - activeDocument.querySelectorAll(".duckmage-painter-ctx-menu").forEach((m) => m.remove()); + this.painterMenu?.close(); this.exitCurrentMode(); return; } @@ -1594,7 +1602,9 @@ export class HexMapView extends ItemView { } // swap: no picker → onSwitch stays null, menu shows only "Exit tool" - new PainterContextMenu(onSwitch, () => this.exitCurrentMode(), switchLabel, extra).open(clientX, clientY); + this.painterMenu?.close(); + this.painterMenu = new PainterContextMenu(onSwitch, () => this.exitCurrentMode(), switchLabel, extra); + this.painterMenu.open(clientX, clientY); } /** diff --git a/src/hex-map/PainterContextMenu.ts b/src/hex-map/PainterContextMenu.ts index 9544c751..7f76c8dc 100644 --- a/src/hex-map/PainterContextMenu.ts +++ b/src/hex-map/PainterContextMenu.ts @@ -82,6 +82,10 @@ export class PainterContextMenu { this.cleanupFns.push(() => window.clearTimeout(timeoutId)); } + isOpen(): boolean { + return this.el !== null; + } + close(): void { this.el?.remove(); this.el = null; diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 2af31711..faab9788 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -121,3 +121,9 @@ describe("Path chain upkeep (fresh-eyes T7/T2 follow-up)", () => { expect(method("onHexPathDeleteClick")).toMatch(/const stepBack = pos === chain\.hexes\.length && chain\.hexes\.length > 0;/); }); }); + +describe("Esc with the tool menu open (fresh-eyes T3 follow-up)", () => { + it("closes the menu first and keeps the tool", () => { + expect(viewSrc).toMatch(/"Escape", \(\) => \{[\s\S]{0,300}this\.painterMenu\?\.isOpen\(\)[\s\S]{0,80}this\.painterMenu\.close\(\);\s*return false;/); + }); +}); From 806159efe3423eed8c81b0421c8388a11cdebdd8 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 21:40:14 -0400 Subject: [PATCH 097/558] fix(map-notes): exports read terrain/icon/region for noteless hexes Same root cause as the editor's current-terrain bug: the PNG/PDF map renderer only read terrain, icon override and region for hexes with a note, so a generated map (most hexes noteless) exported as base terrain; the hexcrawl manual's terrain/region counts skipped the same hexes. Map data now comes from the map note for every hex; faction links (in the hex note's body) still need a note. Co-Authored-By: Claude Opus 5.5 --- src/export/exporters/hexcrawlManual.ts | 8 +++++--- src/export/mapPngRenderer.ts | 25 +++++++++++-------------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/export/exporters/hexcrawlManual.ts b/src/export/exporters/hexcrawlManual.ts index 1850bb22..db822061 100644 --- a/src/export/exporters/hexcrawlManual.ts +++ b/src/export/exporters/hexcrawlManual.ts @@ -131,13 +131,15 @@ export async function collectManualData( for (let col = 0; col < cols; col++) { const x = col + ox, y = row + oy; const path = plugin.hexPath(x, y, mapName); - const file = app.vault.getAbstractFileByPath(path); - if (!(file instanceof TFile)) continue; - hexCount++; + // Terrain and region are map data: count every hex, noted or not + // (most painted hexes have no note). Only noted hexes have content. const terrain = getTerrainFromFile(app, path) ?? ""; const region = getHexRegionFromFile(app, path) ?? ""; if (terrain) terrainCounts.set(terrain, (terrainCounts.get(terrain) ?? 0) + 1); if (region) regionCounts.set(region, (regionCounts.get(region) ?? 0) + 1); + const file = app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) continue; + hexCount++; const content = await app.vault.cachedRead(file); const { text, links } = await getAllSectionData(app, path, content); diff --git a/src/export/mapPngRenderer.ts b/src/export/mapPngRenderer.ts index 3379115f..68821eae 100644 --- a/src/export/mapPngRenderer.ts +++ b/src/export/mapPngRenderer.ts @@ -211,16 +211,17 @@ export async function renderMapToPngBlob( let iconOverride: string | undefined; const factions: { color: string; style: OverlayStyle }[] = []; let region: { color: string; style: OverlayStyle } | undefined; - if (file instanceof TFile) { - const terrainName = getTerrainFromFile(plugin.app, file.path); - if (terrainName) terrain = terrainByName.get(terrainName); - } - // Unpainted hexes (often noteless) draw as the map's base terrain, - // matching the on-screen map. + // Terrain, icon and region are map data (map note): read them for + // every hex, noted or not — most painted hexes have no note. + const terrainName = getTerrainFromFile(plugin.app, notePath); + if (terrainName) terrain = terrainByName.get(terrainName); + // Unpainted hexes draw as the map's base terrain, matching the + // on-screen map. if (!terrain && map?.baseTerrain) terrain = terrainByName.get(map.baseTerrain); - if (file instanceof TFile) { - iconOverride = getIconOverrideFromFile(plugin.app, file.path) ?? undefined; - if (showFactionOverlay) { + iconOverride = getIconOverrideFromFile(plugin.app, notePath) ?? undefined; + { + // Faction links live in the hex note's body. + if (showFactionOverlay && file instanceof TFile) { for (const fName of getHexFactionLinks(plugin.app, file)) { const c = factionColorMap.get(fName); const s = factionStyleMap.get(fName); @@ -231,7 +232,7 @@ export async function renderMapToPngBlob( } } if (showRegionOverlay) { - const regionName = getHexRegionName(plugin.app, file); + const regionName = getHexRegionFromFile(plugin.app, notePath); if (regionName) { const c = regionColorMap.get(regionName); const s = regionStyleMap.get(regionName); @@ -788,10 +789,6 @@ function getHexFactionLinks(app: App, file: TFile): string[] { }); } -/** Read the `region:` frontmatter of a hex note via metadata cache. */ -function getHexRegionName(app: App, file: TFile): string | null { - return getHexRegionFromFile(app, file.path); -} function dashFor(style: "solid" | "dashed" | "dotted"): number[] { switch (style) { From 1fa2209ee23ce03ed3346e75ccc8892dc07e423e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 22:08:38 -0400 Subject: [PATCH 098/558] fix(overland): keep the sea on its side; no desert in temperate regions Fresh-eyes round 3: with Sea = West, water streaked through the interior (inlets to two-thirds of the way across, detached inland seas of 30+ hexes), and a Temperate map grew a large desert in the middle. - Sea on a side / all around: the water is decided by a steeper-tilted field (noise only makes the coast ragged), then sideSeaMask keeps the one body touching the sea edge plus small lakes (maxLakeSize), turns bigger detached water into land and grows the sea from its coast, lowest first, back to the water share. Land relief keeps the gentler tilt. Scattered / none are unchanged. - Overland deserts only for Arid / Volcanic climates; dry ground in a temperate or lush region is plains. Planet surface (a whole world) keeps its desert belts. Tests: one sea per side over 30 seeds on Limited and Expanded, lakes <= maxLakeSize, <2% water in the far half, water share within 2%, no temperate/lush desert, arid still has desert, sideSeaMask units. Co-Authored-By: Claude Opus 5.5 --- src/worldgen/procedural/planetSurface.ts | 133 ++++++++++++++++++-- tests/worldgenFirstMap.test.ts | 150 +++++++++++++++++++++++ 2 files changed, 273 insertions(+), 10 deletions(-) diff --git a/src/worldgen/procedural/planetSurface.ts b/src/worldgen/procedural/planetSurface.ts index 4c69a8e4..ea6b96cc 100644 --- a/src/worldgen/procedural/planetSurface.ts +++ b/src/worldgen/procedural/planetSurface.ts @@ -130,6 +130,94 @@ function inland(side: SeaSide, u: number, v: number): number { /** How strongly the sea side tilts the land (elevation units; noise spans ~0.3). */ const SEA_TILT = 0.6; +/** + * Tilt of the field that decides where the sea is (Overland, sea on a side + * or all around). Steeper than SEA_TILT so the noise only makes the coast + * ragged (bays, headlands) instead of running inlets across the map; the + * land's relief keeps the gentler SEA_TILT. + */ +const SEA_MASK_TILT = 1.6; + +/** Largest inland lake kept on an Overland map with a sea side (hexes, at least 3). */ +export function maxLakeSize(hexCount: number): number { + return Math.max(3, Math.round(hexCount * 0.012)); +} + +/** + * The sea of an Overland map with a sea side: one body of water touching + * that side (or every side, "around"), plus small lakes. Water the noise + * puts elsewhere — streaks and big inland seas — becomes land, and the sea + * then grows out from its coast, lowest ground first, until it covers the + * water share again. Pure; `field` is lower where the sea should be. + */ +export function sideSeaMask( + keys: [number, number][], + field: number[], + target: number, + onSeaEdge: (x: number, y: number) => boolean, + neighbours: (x: number, y: number) => [number, number][], +): boolean[] { + const n = keys.length; + const index = new Map(keys.map(([x, y], i) => [cellKey(x, y), i])); + const near = (i: number) => + neighbours(keys[i][0], keys[i][1]).map(([x, y]) => index.get(cellKey(x, y))).filter((j): j is number => j !== undefined); + const want = Math.max(0, Math.min(n, Math.round(target))); + const sea = new Array(n).fill(false); + if (want === 0) return sea; + + // Candidate water: the lowest `want` cells of the field. + const order = [...field.keys()].sort((a, b) => field[a] - field[b] || a - b); + const wet = new Array(n).fill(false); + for (let k = 0; k < want; k++) wet[order[k]] = true; + + // The sea: candidate water connected to the sea edge. + const stack: number[] = []; + for (let i = 0; i < n; i++) if (wet[i] && onSeaEdge(keys[i][0], keys[i][1])) { sea[i] = true; stack.push(i); } + while (stack.length) { + const i = stack.pop()!; + for (const j of near(i)) if (wet[j] && !sea[j]) { sea[j] = true; stack.push(j); } + } + // No water reached the edge: start from the lowest edge cell. + if (!sea.some(Boolean)) { + const edge = order.find((i) => onSeaEdge(keys[i][0], keys[i][1])); + if (edge !== undefined) sea[edge] = true; + } + + // Lakes: other water bodies, kept only while small. + const lakeMax = maxLakeSize(n); + const seen = new Array(n).fill(false); + const water = [...sea]; + for (let i = 0; i < n; i++) { + if (!wet[i] || sea[i] || seen[i]) continue; + const body = [i]; + seen[i] = true; + for (let b = 0; b < body.length; b++) + for (const j of near(body[b])) if (wet[j] && !sea[j] && !seen[j]) { seen[j] = true; body.push(j); } + if (body.length <= lakeMax) for (const j of body) water[j] = true; + } + + // The edge fallback can put one cell over: drain the highest lake cells. + let count = water.filter(Boolean).length; + for (const i of [...order].reverse()) { + if (count <= want) break; + if (water[i] && !sea[i]) { water[i] = false; count--; } + } + + // Grow the sea from its coast, lowest field first, back up to the target. + const frontier = new Set(); + for (let i = 0; i < n; i++) if (sea[i]) for (const j of near(i)) if (!water[j]) frontier.add(j); + while (count < want && frontier.size) { + let best = -1; + for (const j of frontier) if (best < 0 || field[j] < field[best] || (field[j] === field[best] && j < best)) best = j; + frontier.delete(best); + if (water[best]) continue; + water[best] = true; + count++; + for (const j of near(best)) if (!water[j]) frontier.add(j); + } + return water; +} + export interface PlanetRoles { deep?: string; sea: string; @@ -379,6 +467,8 @@ export function planetSurface( const noiseM = centers.map(([px, py]) => moistNoise(oy + px * scale * 1.3, ox + py * scale * 1.3)); let elev: number[], moistArr: number[], tempArr: number[], lv: Levels; + /** Overland with a sea side: which hexes are water (else elevation decides). */ + let seaMask: boolean[] | undefined; if (context) { ({ elev, moist: moistArr, temp: tempArr } = regionField(grid, hexes, centers, noiseE, noiseM, context, options)); lv = { sea: 0.33, deep: 0.08, shelf: 0.27, hill: 0.64, mountain: 0.79, peak: 0.92 }; @@ -387,17 +477,35 @@ export function planetSurface( const relief = options.relief ?? "normal"; const overland = flavor === "overland"; const sea: SeaSide = overland ? resolveSeaSide(options.sea, seed) : "scattered"; - // Tilt the land down toward the sea side; the water % quantile below - // then floods that side first, with the noise giving a ragged coast. + // Tilt the land down toward the sea side, so high ground lies inland. const spanX = Math.max(maxX - minX, 1e-6), spanY = Math.max(maxY - minY, 1e-6); - elev = sea === "scattered" || sea === "none" - ? noiseE - : noiseE.map((n, i) => n + SEA_TILT * (inland(sea, (xs[i] - minX) / spanX, (ys[i] - minY) / spanY) - 0.5)); - const seaLevel = water <= 0 || sea === "none" ? -Infinity : quantile(elev, water); + const inlandAt = (i: number) => inland(sea, (xs[i] - minX) / spanX, (ys[i] - minY) / spanY) - 0.5; + const sided = sea !== "scattered" && sea !== "none"; + elev = sided ? noiseE.map((n, i) => n + SEA_TILT * inlandAt(i)) : noiseE; + let seaLevel: number; + if (sided && water > 0) { + // The sea hugs its side: one body touching that edge (plus small + // lakes), from a steeper-tilted field so the coast is ragged but + // the sea doesn't streak across the map (sideSeaMask). + const field = noiseE.map((n, i) => n + SEA_MASK_TILT * inlandAt(i)); + const onEdge = (x: number, y: number) => { + const w = x === grid.offset.x, e = x === grid.offset.x + grid.cols - 1; + const nn = y === grid.offset.y, s = y === grid.offset.y + grid.rows - 1; + return sea === "west" ? w : sea === "east" ? e : sea === "north" ? nn : sea === "south" ? s : w || e || nn || s; + }; + seaMask = sideSeaMask(hexes, field, water * hexes.length, onEdge, + (x, y) => hexNeighbors(x, y, grid.orientation, grid.stagger)); + // Sea level for coasts and the lapse rate: the low end of the land. + const land = elev.filter((_, i) => !seaMask![i]); + seaLevel = land.length ? quantile(land, 0.05) : Infinity; + } else { + seaLevel = water <= 0 || sea === "none" ? -Infinity : quantile(elev, water); + } + const wetAt = (e: number, i: number) => (seaMask ? seaMask[i] : e <= seaLevel); // Lowland reference for the lapse rate: sea level, or (no sea) the low ground. const lowLevel = Number.isFinite(seaLevel) ? seaLevel : quantile(elev, 0.1); - const landElev = elev.filter((e) => e > seaLevel); - const seaElev = elev.filter((e) => e <= seaLevel); + const landElev = elev.filter((e, i) => !wetAt(e, i)); + const seaElev = elev.filter((e, i) => wetAt(e, i)); lv = { sea: seaLevel, hill: quantile(landElev.length ? landElev : [1], relief === "flat" ? 0.88 : relief === "rugged" ? 0.5 : 0.7), @@ -444,8 +552,13 @@ export function planetSurface( return undefined; }; + // Deserts belong to dry or hot climates. A whole planet has its desert + // belts whatever the climate; an Overland region is one climate, so a + // temperate (or lush, frozen) region has no desert: dry ground is plains. + const desertOk = flavor !== "overland" || climate === "arid" || climate === "volcanic"; + const cells = new Map(); - const isSea: boolean[] = elev.map((e) => e <= seaLevel); + const isSea: boolean[] = seaMask ?? elev.map((e) => e <= seaLevel); const index = new Map(hexes.map(([x, y], i) => [cellKey(x, y), i])); hexes.forEach(([x, y], i) => { @@ -472,7 +585,7 @@ export function planetSurface( if (frozen) t = roles.snow ?? roles.badlands ?? roles.desert; else if (temp < 0.22) t = roles.snow; else if (climate === "volcanic" && m < 0.45) t = roles.badlands ?? roles.desert; - else if (m < 0.32 && temp > 0.45) t = roles.desert ?? roles.badlands; + else if (desertOk && m < 0.32 && temp > 0.45) t = roles.desert ?? roles.badlands; else if (m > 0.72 && temp > 0.75) t = (m > 0.85 ? v.denseJungle : undefined) ?? roles.jungle ?? forestAt(temp, m); else if (m > 0.68 && e - lowAt < 0.05) t = roles.swamp ?? forestAt(temp, m); else if (m > 0.5) t = forestAt(temp, m); diff --git a/tests/worldgenFirstMap.test.ts b/tests/worldgenFirstMap.test.ts index 21f0aa40..6da5d248 100644 --- a/tests/worldgenFirstMap.test.ts +++ b/tests/worldgenFirstMap.test.ts @@ -4,7 +4,9 @@ import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constan import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; import { OVERLAND_OPTIONS, + maxLakeSize, planetRoles, + sideSeaMask, planetSurface, resolveSeaSide, OVERLAND_ID, @@ -14,6 +16,7 @@ import { BLANK_ID, firstMapGenerator } from "../src/worldgen/registry"; import { defaultPaletteFor } from "../src/palettes/paletteOptions"; import { isUnusedPlaceholderMap } from "../src/setupPlaceholder"; import type { ProcGrid } from "../src/worldgen/procedural/common"; +import { hexNeighbors } from "../packages/hex-wfc/src"; import type { TerrainColor } from "../src/types"; /** Fresh-eyes 2026-10-09 (#36): first-run wizard, Overland, Frozen, palette defaults. */ @@ -116,6 +119,153 @@ describe("Overland: a region, not a planet", () => { }); }); +/** Fresh-eyes round 3 (2026-10-09): Sea = West streaked water inland; a Temperate map grew a big desert. */ +describe("Overland round 3: the sea stays on its side, temperate has no desert", () => { + const big: ProcGrid = { cols: 20, rows: 16, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; + const MANY = Array.from({ length: 30 }, (_, i) => i + 1); + const run = (seed: number, options: Record, terrains: TerrainColor[] = LIMITED_TERRAIN_PALETTE) => + planetSurface(terrains, big, seed, options, undefined, "overland").cells; + + /** Water bodies (hex-connected), each with whether it touches `edge`. */ + function waterBodies(cells: Map, wet: (t: string | undefined) => boolean, edge: (x: number, y: number) => boolean) { + const seen = new Set(); + const bodies: { size: number; onEdge: boolean }[] = []; + for (const [k, t] of cells) { + if (!wet(t) || seen.has(k)) continue; + const stack = [k.split("_").map(Number) as [number, number]]; + seen.add(k); + let size = 0, onEdge = false; + while (stack.length) { + const [x, y] = stack.pop()!; + size++; + if (edge(x, y)) onEdge = true; + for (const [nx, ny] of hexNeighbors(x, y, big.orientation, big.stagger)) { + const nk = `${nx}_${ny}`; + if (cells.has(nk) && !seen.has(nk) && wet(cells.get(nk))) { seen.add(nk); stack.push([nx, ny]); } + } + } + bodies.push({ size, onEdge }); + } + return bodies; + } + + const SIDE_EDGE: Record boolean> = { + west: (x) => x === 0, + east: (x) => x === big.cols - 1, + north: (_x, y) => y === 0, + south: (_x, y) => y === big.rows - 1, + }; + /** The half of the map away from the sea. */ + const FAR_HALF: Record boolean> = { + west: (x) => x >= big.cols / 2, + east: (x) => x < big.cols / 2, + north: (_x, y) => y >= big.rows / 2, + south: (_x, y) => y < big.rows / 2, + }; + + for (const [label, terrains] of [["Limited", LIMITED_TERRAIN_PALETTE], ["Expanded", DEFAULT_TERRAIN_PALETTE]] as const) { + it(`${label}: one sea on the chosen side; other water is only small lakes`, () => { + const wet = isWet(typeOf(terrains)); + const lakeMax = maxLakeSize(big.cols * big.rows); + for (const side of Object.keys(SIDE_EDGE)) { + for (const seed of MANY) { + const cells = run(seed, { water: "30", climate: "temperate", sea: side }, terrains); + const bodies = waterBodies(cells, wet, SIDE_EDGE[side]); + const seas = bodies.filter((b) => b.onEdge); + expect(seas.length).toBe(1); + for (const lake of bodies.filter((b) => !b.onEdge)) expect(lake.size).toBeLessThanOrEqual(lakeMax); + } + } + }); + } + + it("no water streaks into the far half (30% water)", () => { + const wet = isWet(typeOf(LIMITED_TERRAIN_PALETTE)); + for (const side of Object.keys(SIDE_EDGE)) { + let far = 0, n = 0; + for (const seed of MANY) { + const cells = run(seed, { water: "30", sea: side }); + for (const [k, t] of cells) { + const [x, y] = k.split("_").map(Number); + if (!FAR_HALF[side](x, y)) continue; + n++; + if (wet(t)) far++; + } + } + expect(far / n).toBeLessThan(0.02); + } + }); + + it("keeps the water share with the sea on a side", () => { + const wet = isWet(typeOf(LIMITED_TERRAIN_PALETTE)); + for (const water of ["10", "30", "65"]) { + for (const seed of MANY.slice(0, 8)) { + const cells = run(seed, { water, sea: "west" }); + const frac = [...cells.values()].filter(wet).length / cells.size; + expect(Math.abs(frac - Number(water) / 100)).toBeLessThan(0.02); + } + } + }); + + for (const [label, terrains] of [["Limited", LIMITED_TERRAIN_PALETTE], ["Expanded", DEFAULT_TERRAIN_PALETTE]] as const) { + it(`${label}: Temperate and Lush regions grow no desert; Arid still does`, () => { + const deserts = new Set(terrains.filter((t) => t.type === "desert").map((t) => t.name)); + const desertShare = (climate: string) => { + let d = 0, n = 0; + for (const seed of MANY) { + for (const sea of ["west", "random", "scattered", "none"]) { + for (const t of run(seed, { water: "30", climate, sea }, terrains).values()) { n++; if (deserts.has(t)) d++; } + } + } + return d / n; + }; + expect(desertShare("temperate")).toBe(0); + expect(desertShare("lush")).toBe(0); + expect(desertShare("arid")).toBeGreaterThan(0.15); + }); + } + + it("Planet surface (a whole world) keeps its desert belts", () => { + let d = 0; + for (const seed of MANY) { + for (const t of planetSurface(LIMITED_TERRAIN_PALETTE, big, seed, { water: "30", climate: "temperate" }).cells.values()) if (t === "desert") d++; + } + expect(d).toBeGreaterThan(0); + }); +}); + +describe("sideSeaMask", () => { + // A 6×1 strip: neighbours are left/right. + const keys: [number, number][] = [0, 1, 2, 3, 4, 5].map((x) => [x, 0]); + const strip = (x: number, _y: number): [number, number][] => [[x - 1, 0], [x + 1, 0]]; + const west = (x: number) => x === 0; + + it("keeps a small inland lake", () => { + // Lowest four: 0 (on the sea edge) and 3,4,5, a 3-hex body (maxLakeSize = 3). + const water = sideSeaMask(keys, [0, 0.9, 0.95, 0.1, 0.1, 0.1], 4, west, strip); + expect(water).toEqual([true, false, false, true, true, true]); + }); + + it("drops a big inland body and grows the sea from the coast instead", () => { + const long: [number, number][] = Array.from({ length: 10 }, (_, x) => [x, 0]); + // Lowest six: 0 (edge) and 5..9, a 5-hex body: too big for a lake. + const field = [0, 0.6, 0.7, 0.8, 0.9, 0.1, 0.1, 0.1, 0.1, 0.1]; + const water = sideSeaMask(long, field, 6, west, strip); + expect(water).toEqual([true, true, true, true, true, true, false, false, false, false]); + }); + + it("hits the target exactly and always touches the sea edge", () => { + const field = [0.5, 0.4, 0.3, 0.2, 0.1, 0.0]; + const water = sideSeaMask(keys, field, 2, west, strip); + expect(water.filter(Boolean).length).toBe(2); + expect(water[0]).toBe(true); + }); + + it("zero target → no water", () => { + expect(sideSeaMask(keys, [0, 0, 0, 0, 0, 0], 0, west, strip).some(Boolean)).toBe(false); + }); +}); + describe("Frozen climate: no temperate belt", () => { const GREEN = new Set(["forest", "jungle", "grassland", "wetland"]); for (const [label, terrains] of [["Expanded", DEFAULT_TERRAIN_PALETTE], ["Limited", LIMITED_TERRAIN_PALETTE]] as const) { From d6b49dba473d5dade7d42eae7f1d016dd23a2df9 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 22:10:41 -0400 Subject: [PATCH 099/558] fix(hex-editor): Notes under Terrain, icon grids last; keep the editor on screen Round-3 fresh-eyes testers found Description below the fold under two long icon grids, and the editor sometimes opened with its bottom off the window (it opens short while the body loads, then grows downward), so a click on the hidden half landed on the map and closed it. - Body order is now Terrain, Notes, Linked notes, Icons (icon override + GM icons in their own collapsible group, remembered like the others). - The editor reuses HexmakerModal.keepInViewport() so growing never pushes its bottom off screen. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexEditorModal.ts | 62 ++++++++++++++++++++++++----------- src/types.ts | 2 ++ tests/hexEditorModal.test.ts | 5 +++ 3 files changed, 50 insertions(+), 19 deletions(-) diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 1e5773a0..f6128e6b 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -64,6 +64,8 @@ export class HexEditorModal extends HexmakerModal { * read sites; `directGmIcon` is the first entry of this list. */ private directGmIcons: string[] = []; private dataPreloaded = false; + /** Stops keepInViewport's observer (set on first open). */ + private stopKeepInViewport: (() => void) | null = null; constructor( app: App, @@ -176,6 +178,10 @@ export class HexEditorModal extends HexmakerModal { this.renderNeighborWidget(titleRow, this.x, this.y); this.makeDraggable(); + // The body renders after an async read, so the modal opens short and + // then grows: keep its bottom on screen (it ran off the window, and a + // click on the hidden half closed the editor — fresh-eyes round 3). + this.stopKeepInViewport ??= this.keepInViewport(); // ── Body — populated after the single async read ────────────────────── const bodyEl = contentEl.createDiv({ cls: "duckmage-editor-body" }); @@ -206,14 +212,8 @@ export class HexEditorModal extends HexmakerModal { cls: "duckmage-terrain-header-preview", }); this.renderTerrainHeader(headerPreview, directTerrain, directIcon); - this.renderTerrainSection( - terrainBody, - path, - directTerrain, - directIcon, - this.directGmIcons, - (terrain) => this.renderTerrainHeader(headerPreview, terrain, this.directIcon), - ); + const refreshHeader = () => this.renderTerrainHeader(headerPreview, this.directTerrain, this.directIcon); + this.renderTerrainSection(terrainBody, path, directTerrain, refreshHeader); bodyEl.createEl("hr", { cls: "duckmage-editor-divider" }); @@ -292,9 +292,21 @@ export class HexEditorModal extends HexmakerModal { s.featuresFolder, allLinks.get("features") ?? [], ); + + // Icon pickers last: they are long grids, and above Notes they pushed + // Description below the fold (fresh-eyes round 3). + bodyEl.createEl("hr", { cls: "duckmage-editor-divider" }); + const { body: iconsBody } = this.makeCollapsible( + bodyEl, + "Icons", + "hexEditorIconsCollapsed", + ); + this.renderIconSections(iconsBody, path, directIcon, this.directGmIcons, refreshHeader); } onClose() { + this.stopKeepInViewport?.(); + this.stopKeepInViewport = null; this.options.onModalClose?.(); this.contentEl.empty(); } @@ -473,7 +485,11 @@ export class HexEditorModal extends HexmakerModal { private makeCollapsible( container: HTMLElement, label: string, - flag: "hexEditorTerrainCollapsed" | "hexEditorNotesCollapsed" | "hexEditorFeaturesCollapsed", + flag: + | "hexEditorTerrainCollapsed" + | "hexEditorNotesCollapsed" + | "hexEditorFeaturesCollapsed" + | "hexEditorIconsCollapsed", ): { body: HTMLElement; header: HTMLElement } { const startCollapsed = this.plugin.settings[flag] ?? false; const wrapper = container.createDiv({ cls: "duckmage-editor-collapsible" }); @@ -508,9 +524,7 @@ export class HexEditorModal extends HexmakerModal { container: HTMLElement, path: string, currentTerrain: string | null, - currentIcon: string | null, - currentGmIcons: string[], - onTerrainChange: (terrain: string | null) => void, + onTerrainChange: () => void, ): void { const palette = this.plugin.getMapPalette(this.mapName); @@ -522,8 +536,6 @@ export class HexEditorModal extends HexmakerModal { // Picking a terrain keeps the editor open (E1): the map repaints via // onChanged, and the selection/header update in place here. let selectedTerrain = currentTerrain; - const terrainOverrides = (): Map | undefined => - selectedTerrain ? new Map([[path, selectedTerrain]]) : undefined; const applyTerrain = async (terrain: string | null): Promise => { if (terrain !== null) await this.ensureHexNote(); await setTerrainInFile(this.app, path, terrain); @@ -534,7 +546,7 @@ export class HexEditorModal extends HexmakerModal { el.toggleClass("is-selected", el.dataset["terrain"] === terrain), ); clearBtn.toggle(terrain !== null); - onTerrainChange(terrain); + onTerrainChange(); this.onChanged(new Map([[path, terrain]])); }; @@ -590,9 +602,21 @@ export class HexEditorModal extends HexmakerModal { }); } - // Keep terrain in the overrides map (see terrainOverrides above) so - // renderGrid doesn't lose it during the brief window when Obsidian - // clears the metadata cache on file modify. + } + + /** Icon override + (GM layer) game master icon pickers. */ + private renderIconSections( + container: HTMLElement, + path: string, + currentIcon: string | null, + currentGmIcons: string[], + onIconChange: () => void, + ): void { + const section = container.createDiv({ cls: "duckmage-editor-section" }); + // Keep terrain in the overrides map so renderGrid doesn't lose it during + // the brief window when Obsidian clears the metadata cache on file modify. + const terrainOverrides = (): Map | undefined => + this.directTerrain ? new Map([[path, this.directTerrain]]) : undefined; // Icon override palette const hidden = new Set(this.plugin.settings.hiddenIcons ?? []); @@ -608,7 +632,7 @@ export class HexEditorModal extends HexmakerModal { await this.ensureHexNote(); await setIconOverrideInFile(this.app, path, picked); this.directIcon = picked; - onTerrainChange(selectedTerrain); // header shows the icon override + onIconChange(); // header shows the icon override this.onChanged(terrainOverrides(), new Map([[path, picked]])); }, ); diff --git a/src/types.ts b/src/types.ts index 982b39b3..2e759500 100644 --- a/src/types.ts +++ b/src/types.ts @@ -172,6 +172,8 @@ export interface HexmakerPluginSettings { hexEditorTerrainCollapsed: boolean; hexEditorFeaturesCollapsed: boolean; hexEditorNotesCollapsed: boolean; + /** Hex editor "Icons" group collapsed. Unset = open. */ + hexEditorIconsCollapsed?: boolean; rollTableExcludedFolders: string[]; encounterTableExcludedFolders: string[]; defaultMap: string; diff --git a/tests/hexEditorModal.test.ts b/tests/hexEditorModal.test.ts index 7f70ca7b..e6b00d80 100644 --- a/tests/hexEditorModal.test.ts +++ b/tests/hexEditorModal.test.ts @@ -201,6 +201,7 @@ describe("HexEditorModal section start-collapsed settings", () => { }; modal.renderTerrainHeader = () => {}; modal.renderTerrainSection = () => {}; + modal.renderIconSections = () => {}; modal.renderTextSection = () => {}; modal.renderDropdownSection = () => {}; modal.renderBody({ createEl: () => ({}) }, "hex/1_1.md"); @@ -218,6 +219,10 @@ describe("HexEditorModal section start-collapsed settings", () => { it("starts Notes expanded when the setting is off", () => { expect(collapsedStates(false, true).get("Notes")).toBe(false); }); + + it("puts Notes right under Terrain and the long icon grids last (fresh-eyes round 3)", () => { + expect([...collapsedStates(false, true).keys()]).toEqual(["Terrain", "Notes", "Linked notes", "Icons"]); + }); }); // ── Navigation: reload on hex change ───────────────────────────────────────── From 459fa13385afc5db9844516eb63b0299cee7f050 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 22:10:42 -0400 Subject: [PATCH 100/558] fix(modal): the wheel scrolls the modal before a nested icon grid src/wheelChain.ts let a grid take the wheel until it hit its own end, so with the pointer parked over the hex editor's icon grids (most of the modal) the first wheel scrolled the grid and the modal never moved (round-3 journals: "scrolling the editor only works if the pointer is outside them"). The rule is now outer-first (wheelTarget): the modal scrolls unless it is already at its end, the user clicked into the grid, or a gesture that started on the grid is still going. The token editor's icon grid is chained too. Co-Authored-By: Claude Opus 5.5 --- src/HexmakerModal.ts | 39 +++++++++++++++++----- src/hex-map/TokenModal.ts | 1 + src/wheelChain.ts | 69 ++++++++++++++++++++++++++------------- tests/wheelChain.test.ts | 66 +++++++++++++++++++++++++++---------- 4 files changed, 127 insertions(+), 48 deletions(-) diff --git a/src/HexmakerModal.ts b/src/HexmakerModal.ts index 789acb71..912d1907 100644 --- a/src/HexmakerModal.ts +++ b/src/HexmakerModal.ts @@ -1,6 +1,6 @@ import { App, Modal } from "obsidian"; import { ICON_PACK_LABELS, iconLabel, iconPack, type IconPack } from "./utils"; -import { wheelDeltaPx, wheelGoesToOuter } from "./wheelChain"; +import { wheelDeltaPx, wheelTarget } from "./wheelChain"; /** Last pack tab picked in any icon filter — remembered for the session. */ let lastIconPack: IconPack | "all" = "all"; @@ -103,10 +103,10 @@ export class HexmakerModal extends Modal { /** * Stop a nested scroll area (an icon or terrain grid inside a long, - * scrolling modal) from trapping the mouse wheel: the wheel scrolls the - * modal when the area is at its end, can't scroll, or the user is in the - * middle of scrolling the modal (see wheelGoesToOuter). Inside the area, - * away from its ends, the wheel still scrolls the area itself. + * scrolling modal) from trapping the mouse wheel. The modal scrolls + * first; the area only takes the wheel once the modal is at its end, the + * user has clicked into the area, or a gesture that started on the area + * is still going (see wheelTarget for the full rule). */ protected chainWheelToModal(inner: HTMLElement): void { inner.dataset["wheelChain"] = "1"; @@ -123,16 +123,37 @@ export class HexmakerModal extends Modal { { capture: true, passive: true }, ); } + // When the wheel last scrolled this area (programmatic scrolls, like + // bringing the current terrain into view, don't count). + let lastInnerWheel = -Infinity; + // Clicked into the area and still over it: the user is browsing it. + let engaged = false; + inner.addEventListener("pointerdown", () => { engaged = true; }); + inner.addEventListener("pointerleave", () => { engaged = false; }); inner.addEventListener( "wheel", (e: WheelEvent) => { if (e.ctrlKey || e.deltaY === 0) return; const pane = this.scrollParentOf(inner); - if (!pane) return; - const box = { scrollTop: inner.scrollTop, scrollHeight: inner.scrollHeight, clientHeight: inner.clientHeight }; - if (!wheelGoesToOuter(box, e.deltaY, performance.now() - this.lastOuterScroll)) return; + const now = performance.now(); + const box = (el: HTMLElement) => ({ scrollTop: el.scrollTop, scrollHeight: el.scrollHeight, clientHeight: el.clientHeight }); + const target = pane + ? wheelTarget({ + inner: box(inner), + outer: box(pane), + deltaY: e.deltaY, + msSinceOuterScroll: now - this.lastOuterScroll, + msSinceInnerScroll: now - lastInnerWheel, + innerEngaged: engaged, + }) + : "inner"; + if (target === "inner") { + // Let the browser scroll the area natively. + lastInnerWheel = now; + return; + } e.preventDefault(); - pane.scrollTop += wheelDeltaPx(e.deltaY, e.deltaMode, pane.clientHeight); + if (target === "outer" && pane) pane.scrollTop += wheelDeltaPx(e.deltaY, e.deltaMode, pane.clientHeight); }, { passive: false }, ); diff --git a/src/hex-map/TokenModal.ts b/src/hex-map/TokenModal.ts index 8ed8110b..f5a4d4fb 100644 --- a/src/hex-map/TokenModal.ts +++ b/src/hex-map/TokenModal.ts @@ -133,6 +133,7 @@ export class TokenModal extends HexmakerModal { const visibleIcons = this.plugin.availableIcons.filter((i) => !hidden.has(i)); contentEl.createEl("p", { text: "Icon", cls: "duckmage-icon-inline-label" }); const iconGrid = contentEl.createDiv({ cls: "duckmage-icon-picker duckmage-icon-picker-inline" }); + this.chainWheelToModal(iconGrid); const makeIconTile = (icon: string | null) => { const label = icon diff --git a/src/wheelChain.ts b/src/wheelChain.ts index 914c8618..114b759b 100644 --- a/src/wheelChain.ts +++ b/src/wheelChain.ts @@ -10,33 +10,58 @@ export interface ScrollBox { clientHeight: number; } -/** How long after the outer pane last scrolled a wheel step still counts as - * the same scroll gesture (so a grid sliding under the pointer mid-scroll - * doesn't steal it). */ +/** How long after a pane last scrolled a wheel step still counts as the + * same scroll gesture (so a grid sliding under the pointer mid-scroll + * doesn't steal it, and a grid being scrolled keeps the wheel). */ export const WHEEL_CONTINUE_MS = 400; +/** Can `box` scroll any further in the direction of `deltaY`? */ +export function canScroll(box: ScrollBox, deltaY: number): boolean { + const max = box.scrollHeight - box.clientHeight; + if (max <= 1 || deltaY === 0) return false; + return deltaY > 0 ? box.scrollTop < max - 1 : box.scrollTop > 0; +} + +export interface WheelChainState { + /** The nested grid under the pointer. */ + inner: ScrollBox; + /** The modal's own scroll pane. */ + outer: ScrollBox; + deltaY: number; + msSinceOuterScroll: number; + msSinceInnerScroll: number; + /** The user clicked into the grid (or its filter) and hasn't left it: + * they are browsing it, so it owns the wheel. */ + innerEngaged: boolean; +} + /** - * Should a wheel step of `deltaY` over the inner scroll area `inner` scroll - * the outer pane instead? + * Which pane a wheel step over a nested grid should scroll. + * + * Outer first: round-3 testers parked the pointer over the big icon grids + * (they fill most of the editor) and the first wheel scrolled the grid, + * never the modal, so Notes/Linked notes stayed out of reach. The old rule + * ("the grid scrolls until it hits its end") made every grid a wheel trap. + * Now the modal scrolls unless the grid is clearly what the user means: * - * Yes when the user is mid-way through scrolling the outer pane - * (`msSinceOuterScroll` < `continueMs`), when the inner area can't scroll at - * all, or when it is already at its end in the wheel's direction (Chromium - * "latches" a wheel gesture to the inner area, so without this the modal - * wouldn't move until the user paused and started a new gesture). + * - the grid can't move that way → modal; + * - the modal can't move that way (scrolled to its end) → grid; + * - a gesture already in progress keeps its pane (whichever scrolled + * within `continueMs`, the most recent winning); + * - the user engaged the grid (clicked it) → grid; + * - otherwise → modal. */ -export function wheelGoesToOuter( - inner: ScrollBox, - deltaY: number, - msSinceOuterScroll: number, - continueMs = WHEEL_CONTINUE_MS, -): boolean { - if (deltaY === 0) return false; - if (msSinceOuterScroll < continueMs) return true; - const max = inner.scrollHeight - inner.clientHeight; - if (max <= 1) return true; - if (deltaY > 0) return inner.scrollTop >= max - 1; - return inner.scrollTop <= 0; +export function wheelTarget(s: WheelChainState, continueMs = WHEEL_CONTINUE_MS): "inner" | "outer" | "none" { + if (s.deltaY === 0) return "none"; + const innerCan = canScroll(s.inner, s.deltaY); + const outerCan = canScroll(s.outer, s.deltaY); + if (!innerCan) return outerCan ? "outer" : "none"; + if (!outerCan) return "inner"; + const innerRecent = s.msSinceInnerScroll < continueMs; + const outerRecent = s.msSinceOuterScroll < continueMs; + if (innerRecent && (!outerRecent || s.msSinceInnerScroll <= s.msSinceOuterScroll)) return "inner"; + if (outerRecent) return "outer"; + return s.innerEngaged ? "inner" : "outer"; } /** Wheel delta in pixels (WheelEvent.deltaMode: 0 px, 1 lines, 2 pages). */ diff --git a/tests/wheelChain.test.ts b/tests/wheelChain.test.ts index c7371346..ad6b60c2 100644 --- a/tests/wheelChain.test.ts +++ b/tests/wheelChain.test.ts @@ -1,37 +1,69 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { wheelDeltaPx, wheelGoesToOuter, WHEEL_CONTINUE_MS } from "../src/wheelChain"; +import { canScroll, wheelDeltaPx, wheelTarget, WHEEL_CONTINUE_MS, type WheelChainState } from "../src/wheelChain"; /** A 132px-tall icon grid holding 400px of tiles, scrolled to `top`. */ const grid = (top: number) => ({ scrollTop: top, scrollHeight: 400, clientHeight: 132 }); +/** The editor's scroll pane: 700px tall, 1600px of content. */ +const modal = (top: number) => ({ scrollTop: top, scrollHeight: 1600, clientHeight: 700 }); const LONG_AGO = Infinity; -describe("wheelGoesToOuter (fresh-eyes E3: nested grids trap the wheel)", () => { - it("scrolls the grid itself while it has room in the wheel's direction", () => { - expect(wheelGoesToOuter(grid(0), 100, LONG_AGO)).toBe(false); - expect(wheelGoesToOuter(grid(100), -100, LONG_AGO)).toBe(false); +const state = (over: Partial): WheelChainState => ({ + inner: grid(0), + outer: modal(0), + deltaY: 100, + msSinceOuterScroll: LONG_AGO, + msSinceInnerScroll: LONG_AGO, + innerEngaged: false, + ...over, +}); + +describe("canScroll", () => { + it("knows when a box has room in the wheel's direction", () => { + expect(canScroll(grid(0), 100)).toBe(true); + expect(canScroll(grid(0), -100)).toBe(false); + expect(canScroll(grid(268), 100)).toBe(false); + expect(canScroll(grid(267.5), 100)).toBe(false); // sub-pixel end + expect(canScroll({ scrollTop: 0, scrollHeight: 120, clientHeight: 132 }, 100)).toBe(false); + }); +}); + +describe("wheelTarget (fresh-eyes round 3: icon grids still ate the wheel)", () => { + it("scrolls the modal, not the grid, when the pointer just sits over a grid", () => { + // The round-3 trap: grid at its top, modal at its top, first wheel. + expect(wheelTarget(state({}))).toBe("outer"); + expect(wheelTarget(state({ inner: grid(100), outer: modal(300), deltaY: -100 }))).toBe("outer"); }); - it("passes the wheel to the modal at the grid's bottom (scrolling down)", () => { - expect(wheelGoesToOuter(grid(268), 100, LONG_AGO)).toBe(true); - expect(wheelGoesToOuter(grid(267.5), 100, LONG_AGO)).toBe(true); // sub-pixel + it("hands the wheel to the grid once the modal is at its end", () => { + expect(wheelTarget(state({ outer: modal(900) }))).toBe("inner"); + expect(wheelTarget(state({ inner: grid(100), outer: modal(0), deltaY: -100 }))).toBe("inner"); }); - it("passes the wheel to the modal at the grid's top (scrolling up)", () => { - expect(wheelGoesToOuter(grid(0), -100, LONG_AGO)).toBe(true); + it("passes it to the modal when the grid can't move that way", () => { + expect(wheelTarget(state({ inner: grid(268), innerEngaged: true }))).toBe("outer"); + expect(wheelTarget(state({ inner: { scrollTop: 0, scrollHeight: 120, clientHeight: 132 } }))).toBe("outer"); }); - it("passes it on when the grid can't scroll at all", () => { - expect(wheelGoesToOuter({ scrollTop: 0, scrollHeight: 120, clientHeight: 132 }, 100, LONG_AGO)).toBe(true); + it("lets a grid the user clicked into own the wheel", () => { + expect(wheelTarget(state({ innerEngaged: true }))).toBe("inner"); }); - it("keeps an ongoing modal scroll going when a grid slides under the pointer", () => { - expect(wheelGoesToOuter(grid(50), 100, 50)).toBe(true); - expect(wheelGoesToOuter(grid(50), 100, WHEEL_CONTINUE_MS + 1)).toBe(false); + it("keeps a gesture on the pane it started on", () => { + // Scrolling the grid (modal at its end, then the modal moved a hair): + expect(wheelTarget(state({ inner: grid(50), msSinceInnerScroll: 20 }))).toBe("inner"); + // Scrolling the modal while an engaged grid slides under the pointer: + expect(wheelTarget(state({ innerEngaged: true, msSinceOuterScroll: 20 }))).toBe("outer"); + // The most recent pane wins when both moved lately. + expect(wheelTarget(state({ msSinceInnerScroll: 10, msSinceOuterScroll: 200 }))).toBe("inner"); + expect(wheelTarget(state({ msSinceInnerScroll: 200, msSinceOuterScroll: 10 }))).toBe("outer"); + // A gesture older than the window no longer counts. + expect(wheelTarget(state({ msSinceInnerScroll: WHEEL_CONTINUE_MS + 1 }))).toBe("outer"); }); - it("ignores zero-delta (horizontal-only) wheel events", () => { - expect(wheelGoesToOuter(grid(268), 0, 0)).toBe(false); + it("does nothing for horizontal-only wheels or when neither pane can move", () => { + expect(wheelTarget(state({ deltaY: 0 }))).toBe("none"); + expect(wheelTarget(state({ inner: grid(268), outer: modal(900) }))).toBe("none"); }); }); From 06ff11512f24500cdfad75eb280bc250fa80a146 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 22:11:38 -0400 Subject: [PATCH 101/558] fix(setup-wizard): create exactly the previewed map; clear orientation choice; correct click tip Fresh-eyes round 3 (region run, scenario 1): - Next now creates the outcome the preview drew when nothing changed since (generationKey over generator, options, seed, size, orientation, stagger, palette) instead of a second run; only large maps with no preview are generated at Next. A caption under the preview says so, and Overland's "One side (random)" names the side the seed picked, so choosing that side no longer looks like a no-op. - Orientation cards are a radio group: the chosen one is filled, ticked "Selected" and aria-checked; hover only lightens a card (it used the accent border, so both cards looked chosen). Arrow keys / Enter work. - The end tip said right-click opens the editor; it is left-click (right-click is the hex menu). The tools tip points at the pencil. - The name field says when the name will be saved as a slug. CSS: one self-contained block appended at the end of styles.css. Co-Authored-By: Claude Opus 5.5 --- src/SetupWizardView.ts | 111 +++++++++++++++++++++++++++++---- src/worldgen/registry.ts | 21 +++++++ styles.css | 36 +++++++++++ tests/worldgenFirstMap.test.ts | 27 +++++++- 4 files changed, 181 insertions(+), 14 deletions(-) diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index b2839190..0dbbe233 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -12,6 +12,7 @@ import { pathColors } from "./worldgen/generators"; import { BLANK_ID, firstMapGenerator, + generationKey, kindsForPalette, listGeneratorKinds, suggestBaseTerrain, @@ -20,6 +21,7 @@ import { type TerrainGeneratorKind, } from "./worldgen/registry"; import { PLACEHOLDER_MAP_NAME, isUnusedPlaceholderMap } from "./setupPlaceholder"; +import { OVERLAND_ID, resolveSeaSide } from "./worldgen/procedural/planetSurface"; // ─── Types ──────────────────────────────────────────────────────────────────── @@ -51,6 +53,9 @@ interface WizardContext { generatorId?: string; generatorOptions: Record; seed: number; + /** The last previewed run and its generationKey: Next creates exactly + * this map when nothing changed since (no second run). */ + preview?: { key: string; outcome: GenerateOutcome }; /** Label of the generator the map was made with (summary); undefined = blank. */ generatedWith?: string; } @@ -114,6 +119,21 @@ function resolvedOptions(kind: TerrainGeneratorKind, ctx: WizardContext): Record return out; } +/** generationKey of the wizard's current choices (see WizardContext.preview). */ +function wizardRunKey(plugin: HexmakerPlugin, ctx: WizardContext, kind: TerrainGeneratorKind): string { + const grid = wizardGrid(plugin, ctx); + return generationKey({ + generatorId: kind.id, + options: resolvedOptions(kind, ctx), + seed: ctx.seed, + cols: grid.cols, + rows: grid.rows, + orientation: ctx.hexOrientation, + stagger: grid.stagger, + palette: ctx.paletteName, + }); +} + /** * Run the chosen generator for the wizard's map. Generators read the hex * orientation from settings, which the wizard only saves on Next, so the @@ -386,8 +406,17 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { cls: "duckmage-wizard-input", }); nameInput.value = ctx.mapName; + // Map names are slugs (folder + note names): say so before Next. + const slugNote = nameRow.createEl("p", { cls: "duckmage-wizard-note-count" }); + const syncSlug = () => { + const slug = slugify(ctx.mapName); + slugNote.setText(slug && slug !== ctx.mapName ? `Saved as "${slug}" (map names are lower-case, with dashes).` : ""); + slugNote.toggle(!!slugNote.getText()); + }; + syncSlug(); nameInput.addEventListener("input", () => { ctx.mapName = nameInput.value.trim(); + syncSlug(); cb.onUpdate(); }); @@ -437,26 +466,55 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { // Hex orientation const orientRow = container.createDiv({ cls: "duckmage-wizard-field" }); orientRow.createEl("label", { text: "Hex orientation", cls: "duckmage-wizard-label" }); - const orientBtns = orientRow.createDiv({ cls: "duckmage-wizard-orient-row" }); + // A radio group: the chosen card is ticked and filled; hover only + // lightens a card, so it never looks chosen. + const orientBtns = orientRow.createDiv({ + cls: "duckmage-wizard-orient-row", + attr: { role: "radiogroup", "aria-label": "Hex orientation" }, + }); + const orientCards: { value: "flat" | "pointy"; el: HTMLElement; mark: HTMLElement }[] = []; + const syncOrient = () => { + for (const c of orientCards) { + const on = ctx.hexOrientation === c.value; + c.el.toggleClass("is-active", on); + c.el.setAttr("aria-checked", on ? "true" : "false"); + c.el.setAttr("tabindex", on ? "0" : "-1"); + c.mark.setText(on ? "✓ Selected" : ""); + } + }; for (const { value, label, desc } of [ { value: "flat" as const, label: "Flat-top", desc: "Flat sides face north and south — wider hexes" }, { value: "pointy" as const, label: "Pointy-top", desc: "Points face north and south — taller hexes" }, ]) { const btn = orientBtns.createDiv({ - cls: "duckmage-wizard-orient-btn" + (ctx.hexOrientation === value ? " is-active" : ""), + cls: "duckmage-wizard-orient-btn", + attr: { role: "radio" }, }); - btn.createSpan({ text: label, cls: "duckmage-wizard-orient-label" }); + const head = btn.createDiv({ cls: "duckmage-wizard-orient-head" }); + head.createSpan({ text: label, cls: "duckmage-wizard-orient-label" }); + const mark = head.createSpan({ cls: "duckmage-wizard-orient-mark" }); btn.createSpan({ text: desc, cls: "duckmage-wizard-orient-desc" }); - btn.addEventListener("click", () => { + orientCards.push({ value, el: btn, mark }); + const choose = () => { + if (ctx.hexOrientation === value) return; ctx.hexOrientation = value; - orientBtns - .querySelectorAll(".duckmage-wizard-orient-btn") - .forEach(el => el.removeClass("is-active")); - btn.addClass("is-active"); + syncOrient(); refresh(); + }; + btn.addEventListener("click", choose); + btn.addEventListener("keydown", (e) => { + if (e.key === "Enter" || e.key === " ") { e.preventDefault(); choose(); } + if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown") { + e.preventDefault(); + ctx.hexOrientation = ctx.hexOrientation === "flat" ? "pointy" : "flat"; + syncOrient(); + refresh(); + orientCards.find((c) => c.value === ctx.hexOrientation)?.el.focus(); + } }); } + syncOrient(); // Terrain palette const paletteRow = container.createDiv({ cls: "duckmage-wizard-field" }); @@ -481,7 +539,18 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { const canvas = previewBox.createEl("canvas", { cls: "duckmage-setup-canvas" }); const rerollBtn = previewBox.createEl("button", { text: "🎲 Re-roll", attr: { title: "Generate again with a new random seed" } }); const status = previewBox.createDiv({ cls: "duckmage-setup-status" }); + const exactNote = previewBox.createDiv({ + cls: "duckmage-wizard-preview-exact", + text: "Next creates exactly this map. Re-roll for another.", + }); rerollBtn.addEventListener("click", () => { ctx.seed = randomSeed(); refresh(); }); + /** Overland's "One side (random)": say which side this seed picked. */ + let seaRandomOption: HTMLOptionElement | undefined; + const syncSeaLabel = () => { + if (!seaRandomOption) return; + const side = resolveSeaSide("random", ctx.seed); + seaRandomOption.text = `One side (random: ${side})`; + }; let kinds: TerrainGeneratorKind[] = []; const terrains = () => plugin.getPaletteOrPresetTerrains(ctx.paletteName); @@ -506,15 +575,20 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { }); } optsBox.empty(); + seaRandomOption = undefined; const kind = kinds.find((k) => k.id === ctx.generatorId); for (const opt of kind?.options ?? []) { const row = optsBox.createEl("label", { cls: "duckmage-wizard-generator-option" }); row.createSpan({ text: opt.label }); const sel = row.createEl("select"); - for (const c of opt.choices) sel.createEl("option", { value: c.value, text: c.label }); + for (const c of opt.choices) { + const o = sel.createEl("option", { value: c.value, text: c.label }); + if (kind?.id === OVERLAND_ID && opt.key === "sea" && c.value === "random") seaRandomOption = o; + } sel.value = ctx.generatorOptions[opt.key] ?? opt.default; sel.addEventListener("change", () => { ctx.generatorOptions[opt.key] = sel.value; refresh(); }); } + syncSeaLabel(); }; const refresh = () => { @@ -526,11 +600,15 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { let cells = new Map(); let paths: { type: string; route?: string; hexes: string[] }[] = []; let featureCells: Set | undefined; + syncSeaLabel(); + exactNote.hide(); if (kind && kind.id !== BLANK_ID) { if (ctx.mapCols * ctx.mapRows > PREVIEW_AUTO_LIMIT) { status.setText("Large map — no preview; terrain is generated when you continue."); } else { const outcome = runGenerator(plugin, ctx, kind, pal); + ctx.preview = { key: wizardRunKey(plugin, ctx, kind), outcome }; + if (outcome.ok) exactNote.show(); if (!outcome.ok) { status.setText(outcome.message); status.addClass("mod-warning"); @@ -586,8 +664,15 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { const kind = kinds.find((k) => k.id === selected); let outcome: GenerateOutcome | undefined; if (kind && kind.id !== BLANK_ID) { - onProgress(`Generating terrain (${kind.label})…`); - outcome = runGenerator(plugin, ctx, kind, terrains); + // The map the preview showed, as is, when nothing changed since; + // otherwise (large map, no preview) run it now. + const key = wizardRunKey(plugin, ctx, kind); + if (ctx.preview?.key === key) { + outcome = ctx.preview.outcome; + } else { + onProgress(`Generating terrain (${kind.label})…`); + outcome = runGenerator(plugin, ctx, kind, terrains); + } if (!outcome.ok) throw new Error(outcome.message); } @@ -670,9 +755,9 @@ function makeDoneStep(): WizardStep { ctx.generatedWith ? "Repaint anything you like: open Terrain in the drawing tools, pick a type and click hexes." : "Paint terrain — the terrain picker opens automatically when you hit \"Open hex map\". Pick a type and click hexes to paint.", - "Right-click any hex to open its full editor: add towns, dungeons, notes, and more.", + "Click any hex to open its editor: terrain, notes, towns, dungeons and more. Right-click a hex for its menu (open note, new submap, tokens).", "Open the 🎲 tab to browse and roll your random tables.", - "Use the toolbar to paint icons, draw roads or rivers, and link factions.", + "The pencil button (top right of the map) opens the drawing tools: paint icons, draw roads or rivers, link factions.", ]) { tips.createEl("li", { text: tip, cls: "duckmage-wizard-tip-item" }); } diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index 4ed8fece..01b51f92 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -242,6 +242,27 @@ export function firstMapGenerator(fitting: { id: string }[], mapKinds: Iterable< return prefs.find((id) => fitting.some((k) => k.id === id)) ?? BLANK_ID; } +/** + * Everything a generator run depends on, as one string: when a preview's + * key matches the create-time key, the previewed outcome is what gets + * created (no second run that could differ). Option order doesn't matter. + */ +export function generationKey(req: { + generatorId: string; + options: Record; + seed: number; + cols: number; + rows: number; + orientation: string; + stagger: string; + palette: string; + /** Anything else the run reads (neighbour, parent hex…). */ + extra?: string; +}): string { + const opts = Object.keys(req.options).sort().map((k) => [k, req.options[k]]); + return JSON.stringify([req.generatorId, opts, req.seed, req.cols, req.rows, req.orientation, req.stagger, req.palette, req.extra ?? ""]); +} + /** Generators usable with a palette, Blank first. Context-only ones need `hasContext`. */ export function kindsForPalette( kinds: TerrainGeneratorKind[], diff --git a/styles.css b/styles.css index d0615cb5..c590c5f9 100644 --- a/styles.css +++ b/styles.css @@ -6549,3 +6549,39 @@ button.duckmage-wfc-library-tab.is-active { opacity: 0.5; cursor: not-allowed; } + +/* ── Fresh-eyes r3 (setup, new map, export) — fix/fresh-eyes-r3-setup ── + Self-contained block; keep it together at the end of the file. */ + +/* Setup wizard: the chosen orientation card is ticked and filled; hover + only lightens a card so it never reads as chosen. */ +.duckmage-wizard-orient-btn:hover:not(.is-active) { + border-color: var(--background-modifier-border-hover); + background: var(--background-modifier-hover); +} +.duckmage-wizard-orient-btn.is-active { + border-color: var(--interactive-accent); + background: hsla(var(--interactive-accent-hsl), 0.18); + box-shadow: 0 0 0 1px var(--interactive-accent); +} +.duckmage-wizard-orient-btn:focus-visible { + outline: 2px solid var(--interactive-accent); + outline-offset: 2px; +} +.duckmage-wizard-orient-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.5em; +} +.duckmage-wizard-orient-mark { + font-size: 0.78em; + font-weight: 600; + color: var(--interactive-accent); +} +.duckmage-wizard-preview-exact { + font-size: var(--font-ui-smaller); + color: var(--text-muted); + text-align: center; + max-width: 240px; +} diff --git a/tests/worldgenFirstMap.test.ts b/tests/worldgenFirstMap.test.ts index 6da5d248..9ff0eda2 100644 --- a/tests/worldgenFirstMap.test.ts +++ b/tests/worldgenFirstMap.test.ts @@ -12,7 +12,7 @@ import { OVERLAND_ID, } from "../src/worldgen/procedural/planetSurface"; import { STAR_SCATTER_ID } from "../src/worldgen/procedural/starScatter"; -import { BLANK_ID, firstMapGenerator } from "../src/worldgen/registry"; +import { BLANK_ID, firstMapGenerator, generationKey } from "../src/worldgen/registry"; import { defaultPaletteFor } from "../src/palettes/paletteOptions"; import { isUnusedPlaceholderMap } from "../src/setupPlaceholder"; import type { ProcGrid } from "../src/worldgen/procedural/common"; @@ -334,6 +334,31 @@ describe("firstMapGenerator (setup wizard default)", () => { }); }); +describe("generationKey (create exactly the previewed map)", () => { + const base = { + generatorId: OVERLAND_ID, options: { water: "30", sea: "west" }, seed: 42, + cols: 20, rows: 16, orientation: "flat", stagger: "odd", palette: "Limited", + }; + + it("is the same for the same run, whatever the option order", () => { + expect(generationKey(base)).toBe(generationKey({ ...base, options: { sea: "west", water: "30" } })); + }); + + it("changes with anything the run reads", () => { + const k = generationKey(base); + for (const change of [ + { seed: 43 }, { options: { water: "30", sea: "east" } }, { cols: 21 }, { rows: 15 }, + { orientation: "pointy" }, { stagger: "even" }, { palette: "Expanded" }, { generatorId: BLANK_ID }, + { extra: "next to thornwood (east)" }, + ]) expect(generationKey({ ...base, ...change })).not.toBe(k); + }); + + it("a preview run and a create run with the same key give the same map", () => { + const run = () => planetSurface(LIMITED_TERRAIN_PALETTE, { ...grid, cols: 20, rows: 16 }, base.seed, base.options, undefined, "overland").cells; + expect([...run()]).toEqual([...run()]); + }); +}); + describe("isUnusedPlaceholderMap (the shipped 'default' map)", () => { const map = { name: "default", pathChains: [] }; const unused = { hexCount: 0, folderEntries: ["_default.md"], referenced: false }; From 7aa4ad7c4b54b5b960d9d7e59499cbe2f286e44b Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 22:16:12 -0400 Subject: [PATCH 102/558] fix(map): finer wheel zoom; the wheel never zooms the map from a modal or panel Round-3 testers found zoom steps coarse ("one notch jumps from tiny to large") and hit scroll-to-zoom when they meant to scroll something else. - Wheel zoom per notch drops from ~1.32x to ~1.16x, and one event counts at most 100px of travel, so a multi-notch flick can't jump 5x. Trackpad deltas stay small and smooth (src/hex-map/wheelZoom.ts, unit-tested). - The view's wheel handler only zooms when the wheel is over the map itself: over the drawing-tool / overlay panels and menus it lets them scroll, and while a modal is open it does nothing. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 ++-- src/hex-map/HexMapView.ts | 32 ++++++++++++++++---------------- src/hex-map/wheelZoom.ts | 32 ++++++++++++++++++++++++++++++++ tests/wheelZoom.test.ts | 39 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 89 insertions(+), 18 deletions(-) create mode 100644 src/hex-map/wheelZoom.ts create mode 100644 tests/wheelZoom.test.ts diff --git a/package.json b/package.json index 3dcbbd3e..e6dcd952 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index e4588f5e..544f5d7a 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -29,6 +29,7 @@ import { import { MapModal } from "./MapModal"; import { mapAncestors } from "./submapNav"; import { pathClickOutcome, toolModeLabel } from "./toolMode"; +import { wheelZoomLog, wheelZoomsMap } from "./wheelZoom"; import { PathPickerModal } from "./PathPickerModal"; import type { MapData, PathChain, TokenEntry } from "../types"; import { @@ -655,32 +656,31 @@ export class HexMapView extends ItemView { }); // ── Zoom (scroll wheel, no modifier required) ────────────────────────── - // Delta-aware + rAF-batched. Mouse notch (deltaY=100) → ~1.33× per event. - // Trackpads (deltaY≈2-10) → tiny per-event factors that look smooth - // because many events fire per frame and the rAF tick applies them as - // one update. NO easing tail — the visual lands exactly at the - // cumulative wheel delta and stops the frame after the last event. - const ZOOM_SENSITIVITY = 0.0028; + // Delta-aware + rAF-batched (see wheelZoom.ts). Mouse notch (deltaY=100) + // → ~1.16× per event. Trackpads (deltaY≈2-10) → tiny per-event factors + // that look smooth because many events fire per frame and the rAF tick + // applies them as one update. NO easing tail — the visual lands exactly + // at the cumulative wheel delta and stops the frame after the last event. this.registerDomEvent( contentEl, "wheel", (e: WheelEvent) => { + // Over the toolbar panels/menus the wheel scrolls them; with a modal + // open it belongs to the modal (fresh-eyes round 3: "scroll-to-zoom + // when I meant to scroll the modal"). + const overMap = e.target instanceof Node && clipEl.contains(e.target); + const modalOpen = !!contentEl.ownerDocument.body.querySelector(":scope > .modal-container"); + if (!wheelZoomsMap(overMap, modalOpen)) { + if (modalOpen) e.preventDefault(); + return; + } // Calibration mode: image/grid wheel handlers own plain-wheel scaling // (they stopPropagation), so this only fires for Ctrl/Cmd+wheel // (which the layer handlers explicitly let through) or wheels outside // both layers. Treat both as a viewport zoom. e.preventDefault(); const rect = contentEl.getBoundingClientRect(); - // Normalize deltaY across deltaMode (LINE: ~33px/line, PAGE: ~400px). - const PX_PER_LINE = 33; - const PX_PER_PAGE = 400; - const dyPx = - e.deltaMode === WheelEvent.DOM_DELTA_LINE - ? e.deltaY * PX_PER_LINE - : e.deltaMode === WheelEvent.DOM_DELTA_PAGE - ? e.deltaY * PX_PER_PAGE - : e.deltaY; - this.pendingZoomLog += -dyPx * ZOOM_SENSITIVITY; + this.pendingZoomLog += wheelZoomLog(e.deltaY, e.deltaMode); this.pendingZoomPivot = { cx: e.clientX - rect.left, cy: e.clientY - rect.top, diff --git a/src/hex-map/wheelZoom.ts b/src/hex-map/wheelZoom.ts new file mode 100644 index 00000000..9dad7cef --- /dev/null +++ b/src/hex-map/wheelZoom.ts @@ -0,0 +1,32 @@ +/** + * Wheel → map zoom maths, kept free of Obsidian imports for unit tests. + * HexMapView sums these log-zoom steps per animation frame. + */ + +/** Log-zoom per pixel of wheel travel. A mouse notch (~100px) zooms + * ~1.16×; it was 0.0028 (~1.32× a notch), which round-3 testers found + * jumped "from tiny to large" in a notch or two. */ +export const ZOOM_PER_PX = 0.0015; + +/** Most wheel travel one event may count. Fast flicks and some drivers send + * a single event worth several notches; uncapped, one event could zoom 5×. */ +export const MAX_ZOOM_PX_PER_EVENT = 100; + +const PX_PER_LINE = 33; +const PX_PER_PAGE = 400; + +/** Log-zoom change for one wheel event (positive = zoom in). */ +export function wheelZoomLog(deltaY: number, deltaMode: number): number { + const px = deltaMode === 1 ? deltaY * PX_PER_LINE : deltaMode === 2 ? deltaY * PX_PER_PAGE : deltaY; + const capped = Math.max(-MAX_ZOOM_PX_PER_EVENT, Math.min(MAX_ZOOM_PX_PER_EVENT, px)); + return capped === 0 ? 0 : -capped * ZOOM_PER_PX; +} + +/** + * Should a wheel event that reached the map view zoom the map? Only when it + * is over the map itself: never while a modal is open (the wheel belongs to + * the modal), and not over the view's own panels and menus (they scroll). + */ +export function wheelZoomsMap(overMap: boolean, modalOpen: boolean): boolean { + return overMap && !modalOpen; +} diff --git a/tests/wheelZoom.test.ts b/tests/wheelZoom.test.ts new file mode 100644 index 00000000..f2284e82 --- /dev/null +++ b/tests/wheelZoom.test.ts @@ -0,0 +1,39 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { MAX_ZOOM_PX_PER_EVENT, wheelZoomLog, wheelZoomsMap, ZOOM_PER_PX } from "../src/hex-map/wheelZoom"; + +describe("wheelZoomLog (fresh-eyes round 3: zoom steps too coarse)", () => { + it("zooms in on wheel up and out on wheel down", () => { + expect(wheelZoomLog(-100, 0)).toBeGreaterThan(0); + expect(wheelZoomLog(100, 0)).toBeLessThan(0); + expect(wheelZoomLog(0, 0)).toBe(0); + }); + + it("zooms a mouse notch by well under 1.25×", () => { + const factor = Math.exp(wheelZoomLog(-100, 0)); + expect(factor).toBeGreaterThan(1.1); + expect(factor).toBeLessThan(1.25); + }); + + it("keeps trackpad steps tiny so they look smooth", () => { + expect(Math.exp(wheelZoomLog(-4, 0))).toBeLessThan(1.01); + }); + + it("caps one event, so a multi-notch flick can't jump several sizes", () => { + expect(wheelZoomLog(-600, 0)).toBeCloseTo(MAX_ZOOM_PX_PER_EVENT * ZOOM_PER_PX); + expect(wheelZoomLog(600, 0)).toBeCloseTo(-MAX_ZOOM_PX_PER_EVENT * ZOOM_PER_PX); + }); + + it("converts line and page deltas before capping", () => { + expect(wheelZoomLog(-1, 1)).toBeCloseTo(33 * ZOOM_PER_PX); + expect(wheelZoomLog(-1, 2)).toBeCloseTo(MAX_ZOOM_PX_PER_EVENT * ZOOM_PER_PX); + }); +}); + +describe("wheelZoomsMap", () => { + it("zooms only over the map with no modal open", () => { + expect(wheelZoomsMap(true, false)).toBe(true); + expect(wheelZoomsMap(true, true)).toBe(false); + expect(wheelZoomsMap(false, false)).toBe(false); + }); +}); From 024514bd579e31d1bea42664a48052d85d0c3b57 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 22:16:30 -0400 Subject: [PATCH 103/558] =?UTF-8?q?feat(hex-editor):=20"Saving=E2=80=A6=20?= =?UTF-8?q?/=20=E2=9C=93=20Saved"=20cue=20for=20autosave;=20text=20saves?= =?UTF-8?q?=20while=20typing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Testers reopened hexes to check their text had stuck: the editor saved silently (and only on blur). Now: - A small status in the title row shows "Saving…" while any write from the editor is in flight (text, terrain, icons, GM icons, links) and "✓ Saved" for two seconds after, or "Couldn't save" if one failed (SaveTracker in src/hex-map/saveStatus.ts, unit-tested). - Text sections autosave 0.8s after typing stops, on blur, and on close or hex navigation; the target hex is captured when the box renders. Unchanged text is no longer written, so merely focusing a box doesn't create the hex note. - Section labels are tied to their boxes (label for=), so clicking "Description" focuses it. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/hex-map/HexEditorModal.ts | 111 ++++++++++++++++++++++++++-------- src/hex-map/saveStatus.ts | 64 ++++++++++++++++++++ styles.css | 14 +++++ tests/saveStatus.test.ts | 79 ++++++++++++++++++++++++ 5 files changed, 245 insertions(+), 27 deletions(-) create mode 100644 src/hex-map/saveStatus.ts create mode 100644 tests/saveStatus.test.ts diff --git a/package.json b/package.json index e6dcd952..6f20cde9 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index f6128e6b..c4af3524 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -34,6 +34,7 @@ import { neighbourSpec } from "../worldgen/neighbours"; import { WalkRegionModal } from "../worldgen/WalkRegionModal"; import type { MapData } from "../types"; import { RegionNavigateModal } from "./RegionNavigateModal"; +import { SAVE_STATUS_TEXT, SaveTracker, type SaveState } from "./saveStatus"; /** What each link field links, for its placeholder ("Search or create a town…"). */ const LINK_FIELD_NOUN: Record = { @@ -45,6 +46,11 @@ const LINK_FIELD_NOUN: Record = { Factions: "a faction", }; +/** Typing pause after which a text section autosaves. */ +const TEXT_AUTOSAVE_MS = 800; +/** Unique ids for label for= ↔ textarea pairs. */ +let textFieldSeq = 0; + /** Which side of the map an off-map hex lies past (east/west first at corners). */ function offMapSide(map: MapData, x: number, y: number): Side { const { x: ox, y: oy } = map.gridOffset; @@ -66,6 +72,15 @@ export class HexEditorModal extends HexmakerModal { private dataPreloaded = false; /** Stops keepInViewport's observer (set on first open). */ private stopKeepInViewport: (() => void) | null = null; + /** "Saving…" / "✓ Saved" cue in the title row (fresh-eyes round 3). */ + private saveStatusEl: HTMLElement | null = null; + private saves = new SaveTracker( + (state) => this.renderSaveStatus(state), + (fn, ms) => window.setTimeout(fn, ms), + (id) => window.clearTimeout(id), + ); + /** Text sections with typed-but-unsaved changes: flush on close/navigate. */ + private pendingTextSaves = new Set<() => void>(); constructor( app: App, @@ -129,6 +144,8 @@ export class HexEditorModal extends HexmakerModal { onOpen() { const { contentEl } = this; + // Re-render on navigation: save what was typed into the previous hex. + this.flushTextSaves(); contentEl.empty(); contentEl.addClass("duckmage-hex-editor"); @@ -175,6 +192,10 @@ export class HexEditorModal extends HexmakerModal { new HexExportModal(this.app, this.plugin, fileNow).open(); }); } + this.saveStatusEl = titleLeft.createSpan({ + cls: "duckmage-editor-save-status", + attr: { "aria-live": "polite" }, + }); this.renderNeighborWidget(titleRow, this.x, this.y); this.makeDraggable(); @@ -305,12 +326,27 @@ export class HexEditorModal extends HexmakerModal { } onClose() { + this.flushTextSaves(); + this.saves.dispose(); + this.saveStatusEl = null; this.stopKeepInViewport?.(); this.stopKeepInViewport = null; this.options.onModalClose?.(); this.contentEl.empty(); } + private flushTextSaves(): void { + for (const save of [...this.pendingTextSaves]) save(); + this.pendingTextSaves.clear(); + } + + private renderSaveStatus(state: SaveState): void { + const el = this.saveStatusEl; + if (!el) return; + el.setText(SAVE_STATUS_TEXT[state]); + el.dataset["state"] = state; + } + private isOnMap(nx: number, ny: number): boolean { const region = this.plugin.getOrCreateMap(this.mapName); const { gridOffset, gridSize } = region; @@ -563,7 +599,7 @@ export class HexEditorModal extends HexmakerModal { cls: "duckmage-terrain-option-name", }); clearBtn.toggle(currentTerrain !== null); - clearBtn.addEventListener("click", () => void applyTerrain(null)); + clearBtn.addEventListener("click", () => void this.saves.track(applyTerrain(null))); for (const entry of palette) { const btn = grid.createDiv({ @@ -588,7 +624,7 @@ export class HexEditorModal extends HexmakerModal { btn.addEventListener("click", () => { if (entry.name === selectedTerrain) return; - void applyTerrain(entry.name); + void this.saves.track(applyTerrain(entry.name)); }); } @@ -733,7 +769,7 @@ export class HexEditorModal extends HexmakerModal { t.removeClass("is-selected"); } }); - await persist(); + await this.saves.track(persist()); })(); }); @@ -745,7 +781,7 @@ export class HexEditorModal extends HexmakerModal { if (idx === -1) return; list.splice(idx, 1); refreshBadge(); - void persist(); + void this.saves.track(persist()); }); return tile; @@ -789,7 +825,7 @@ export class HexEditorModal extends HexmakerModal { grid.querySelectorAll(".duckmage-icon-option").forEach((el) => el.toggleClass("is-selected", (el as HTMLElement).dataset["icon"] === (icon ?? "")), ); - await onPick(icon); + await this.saves.track(onPick(icon)); })(); }); tile.dataset["icon"] = icon ?? ""; @@ -907,8 +943,8 @@ export class HexEditorModal extends HexmakerModal { const onRemove = (link: string) => { currentLinks = currentLinks.filter((l) => l !== link); refresh(); - void removeLinkFromSection(this.app, path, section, link).then(() => - this.onChanged(), + void this.saves.track( + removeLinkFromSection(this.app, path, section, link).then(() => this.onChanged()), ); }; @@ -990,7 +1026,11 @@ export class HexEditorModal extends HexmakerModal { anchor = null; }; - const selectFile = async (file: TFile) => { + // Tracked so the title row shows "Saving…" → "✓ Saved". + const selectFile = (file: TFile) => this.saves.track(selectFileNow(file)); + const createAndLink = (name: string) => this.saves.track(createAndLinkNow(name)); + + const selectFileNow = async (file: TFile) => { closeDropdown(); input.value = ""; const hexFile = await this.ensureHexNote(); @@ -1001,12 +1041,12 @@ export class HexEditorModal extends HexmakerModal { const linkPath = this.app.metadataCache.fileToLinktext(file, path); currentLinks = [...currentLinks, linkPath]; refresh(); - void addLinkToSection(this.app, path, section, `[[${linkPath}]]`); + await addLinkToSection(this.app, path, section, `[[${linkPath}]]`); void addBacklinkToFile(this.app, file.path, path); this.onChanged(); }; - const createAndLink = async (name: string) => { + const createAndLinkNow = async (name: string) => { closeDropdown(); input.value = ""; const folder = normalizeFolder(sourceFolder); @@ -1037,7 +1077,7 @@ export class HexEditorModal extends HexmakerModal { const linkPath = this.app.metadataCache.fileToLinktext(file, path); currentLinks = [...currentLinks, linkPath]; refresh(); - void addLinkToSection(this.app, path, section, `[[${linkPath}]]`); + await addLinkToSection(this.app, path, section, `[[${linkPath}]]`); void addBacklinkToFile(this.app, file.path, path); this.onChanged(); }; @@ -1146,9 +1186,11 @@ export class HexEditorModal extends HexmakerModal { const labelRow = sectionEl.createDiv({ cls: "duckmage-text-section-label-row", }); - labelRow.createEl("label", { + // label for= → clicking the label focuses the box. + const labelEl = labelRow.createEl("label", { text: label, cls: "duckmage-text-section-label", + attr: { for: `duckmage-hex-text-${section}-${++textFieldSeq}` }, }); // 📖 button: terrain description table (description section) or section-specific table @@ -1185,6 +1227,7 @@ export class HexEditorModal extends HexmakerModal { const textarea = sectionEl.createEl("textarea", { cls: "duckmage-text-section-textarea", + attr: { id: labelEl.htmlFor }, }); if (previewTablePath) { @@ -1205,11 +1248,7 @@ export class HexEditorModal extends HexmakerModal { if (textarea.value && !textarea.value.endsWith("\n")) textarea.value += "\n"; textarea.value += result; - void (async () => { - const file = await this.ensureHexNote(); - if (!file) return; - await setSectionContent(this.app, path, section, textarea.value); - })(); + save(); this.onChanged(); }, capturedPath, @@ -1220,17 +1259,39 @@ export class HexEditorModal extends HexmakerModal { textarea.placeholder = `${label}…`; textarea.value = initialContent; - textarea.addEventListener("blur", () => { - void (async () => { - const file = await this.ensureHexNote(); - if (!file) return; - await setSectionContent(this.app, path, section, textarea.value); - })(); + // Autosave: a moment after typing stops, on blur, and on close or + // navigation (flushTextSaves). The hex is captured now, so a save that + // lands after navigating still goes to this hex. Unchanged text isn't + // written (just focusing a box no longer creates the hex note). + const hx = this.x; + const hy = this.y; + let lastSaved = initialContent; + let timer: number | null = null; + const save = (): void => { + if (timer !== null) window.clearTimeout(timer); + timer = null; + this.pendingTextSaves.delete(save); + const value = textarea.value; + if (value === lastSaved) return; + lastSaved = value; + void this.saves.track( + (async () => { + const file = await this.ensureHexNote(hx, hy); + if (!file) throw new Error(`Could not create the note for hex ${hx}, ${hy}`); + await setSectionContent(this.app, path, section, value); + })(), + ); + }; + textarea.addEventListener("input", () => { + if (timer !== null) window.clearTimeout(timer); + timer = window.setTimeout(save, TEXT_AUTOSAVE_MS); + this.pendingTextSaves.add(save); }); + textarea.addEventListener("blur", save); } - private async ensureHexNote(): Promise { - const path = this.plugin.hexPath(this.x, this.y, this.mapName); + private async ensureHexNote(x = this.x, y = this.y): Promise { + const path = this.plugin.hexPath(x, y, this.mapName); const existing = this.app.vault.getAbstractFileByPath(path); if (existing instanceof TFile) return existing; return this.plugin.createHexNote(this.x, this.y, this.mapName); diff --git a/src/hex-map/saveStatus.ts b/src/hex-map/saveStatus.ts new file mode 100644 index 00000000..f823f439 --- /dev/null +++ b/src/hex-map/saveStatus.ts @@ -0,0 +1,64 @@ +/** + * The hex editor's small autosave cue ("Saving…" → "✓ Saved"). Round-3 + * testers reopened hexes to check their text had stuck, because nothing said + * it had. DOM-free so it can be unit-tested; HexEditorModal renders it. + */ + +export type SaveState = "idle" | "saving" | "saved" | "error"; + +export const SAVE_STATUS_TEXT: Record = { + idle: "", + saving: "Saving…", + saved: "✓ Saved", + error: "Couldn't save", +}; + +/** How long "✓ Saved" stays up. */ +export const SAVED_SHOWN_MS = 2000; + +export class SaveTracker { + private pending = 0; + private failed = false; + private timer: number | null = null; + + constructor( + private render: (state: SaveState) => void, + private setTimer: (fn: () => void, ms: number) => number, + private clearTimer: (id: number) => void, + ) {} + + /** Show "Saving…" until `work` (and any other tracked save) settles, then + * "✓ Saved" for a moment — or "Couldn't save" if any of them failed. */ + async track(work: Promise): Promise { + this.pending++; + this.show("saving"); + try { + await work; + } catch (err) { + this.failed = true; + console.error("Hexmaker: save failed", err); + } finally { + this.pending--; + if (this.pending === 0) { + this.show(this.failed ? "error" : "saved"); + this.failed = false; + } + } + } + + dispose(): void { + if (this.timer !== null) this.clearTimer(this.timer); + this.timer = null; + } + + private show(state: SaveState): void { + this.dispose(); + this.render(state); + if (state === "saved") { + this.timer = this.setTimer(() => { + this.timer = null; + this.render("idle"); + }, SAVED_SHOWN_MS); + } + } +} diff --git a/styles.css b/styles.css index d0615cb5..d1292136 100644 --- a/styles.css +++ b/styles.css @@ -6549,3 +6549,17 @@ button.duckmage-wfc-library-tab.is-active { opacity: 0.5; cursor: not-allowed; } + +/* Hex editor autosave cue ("Saving…" → "✓ Saved"), fresh-eyes round 3. */ +.duckmage-editor-save-status { + font-size: var(--font-ui-smaller); + color: var(--text-muted); + margin-left: 0.5em; + white-space: nowrap; +} +.duckmage-editor-save-status[data-state="saved"] { + color: var(--text-success); +} +.duckmage-editor-save-status[data-state="error"] { + color: var(--text-error); +} diff --git a/tests/saveStatus.test.ts b/tests/saveStatus.test.ts new file mode 100644 index 00000000..ee7c791e --- /dev/null +++ b/tests/saveStatus.test.ts @@ -0,0 +1,79 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { SAVE_STATUS_TEXT, SAVED_SHOWN_MS, SaveTracker, type SaveState } from "../src/hex-map/saveStatus"; + +/** A tracker wired to a log of rendered states and a manual clock. */ +function harness() { + const shown: SaveState[] = []; + const timers = new Map void; ms: number }>(); + let next = 1; + const tracker = new SaveTracker( + (s) => shown.push(s), + (fn, ms) => { timers.set(next, { fn, ms }); return next++; }, + (id) => { timers.delete(id); }, + ); + const fire = () => { for (const [id, t] of [...timers]) { timers.delete(id); t.fn(); } }; + return { shown, timers, tracker, fire }; +} + +const deferred = () => { + let resolve!: () => void; + let reject!: (e: unknown) => void; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + return { promise, resolve, reject }; +}; + +describe("SaveTracker (fresh-eyes round 3: no 'saved' cue)", () => { + it("shows Saving… then ✓ Saved, then clears after a moment", async () => { + const h = harness(); + await h.tracker.track(Promise.resolve()); + expect(h.shown).toEqual(["saving", "saved"]); + expect([...h.timers.values()][0].ms).toBe(SAVED_SHOWN_MS); + h.fire(); + expect(h.shown.at(-1)).toBe("idle"); + expect(SAVE_STATUS_TEXT.saved).toContain("Saved"); + }); + + it("waits for every overlapping save before saying Saved", async () => { + const h = harness(); + const a = deferred(); + const b = deferred(); + const ta = h.tracker.track(a.promise); + const tb = h.tracker.track(b.promise); + a.resolve(); + await ta; + expect(h.shown.at(-1)).toBe("saving"); + b.resolve(); + await tb; + expect(h.shown.at(-1)).toBe("saved"); + }); + + it("reports a failed save instead of Saved, and doesn't throw", async () => { + const h = harness(); + const origError = console.error; + console.error = () => {}; + try { + await h.tracker.track(Promise.reject(new Error("disk full"))); + } finally { + console.error = origError; + } + expect(h.shown.at(-1)).toBe("error"); + expect(h.timers.size).toBe(0); // the error stays up + await h.tracker.track(Promise.resolve()); + expect(h.shown.at(-1)).toBe("saved"); + }); + + it("a new save cancels the pending clear", async () => { + const h = harness(); + await h.tracker.track(Promise.resolve()); + expect(h.timers.size).toBe(1); + const d = deferred(); + const t = h.tracker.track(d.promise); + expect(h.timers.size).toBe(0); + d.resolve(); + await t; + expect(h.timers.size).toBe(1); + h.tracker.dispose(); + expect(h.timers.size).toBe(0); + }); +}); From 992fae7f4a0f88cbda03e6d0a0ecf5697cee8fd8 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Fri, 9 Oct 2026 22:19:42 -0400 Subject: [PATCH 104/558] fix(new-map): neighbour maps get edge-continuing generators; labelled setup form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fresh-eyes round 3, G10 (the subregions persona's #1 confusion, two rounds running) and the submap dialog findings: Neighbour maps - Maps -> New map: "Guided setup…" (and a new "Overland and more…" button next to the learned-only Generator dropdown) carries the typed name and the "Place next to" map + side into Guided setup instead of starting over. - Guided setup hides parent-hex-only generators (Region detail, "zoom into the parent hex") unless there is a parent hex: kindsForPalette now keys on a parent hex, not on any context. - Next to a neighbour, generators that continue the shared edge come first (neighbourFirst), each card says "Continues 's edge" or "Ignores 's edge", and an unpicked generator starts on one that continues it (defaultGeneratorFor): Overland, else a learned one (generateConnected). - Overland now reads a neighbouring region's border (context edgeCells, edgePulls): elevation and moisture near the seam are pulled toward the neighbour's terrain in the map's own levels, a neighbour's sea across the seam counts as open sea for the sea mask, and a land border keeps the sea off the seam. No edge cells -> output unchanged. - The preview draws the neighbour's edge faded around the map (the seam) with a caption saying whether the chosen generator follows it. Submap / setup form labels - Every row label is a
`); if (h.landmark && stripTags(h.landmark).replace(/[.]$/, "") !== stripTags(title)) parts.push(runIn("Landmark", h.landmark)); for (const [key, label] of LINK_LABELS) { - if (h.links[key].length) parts.push(runIn(label, esc(h.links[key].join(", ")))); + if (h.links[key].length) parts.push(runIn(labels[key] ?? label, esc(h.links[key].join(", ")))); } if (h.weather) parts.push(runIn("Weather", h.weather)); if (h.hooks) parts.push(runIn("Hooks and rumors", h.hooks)); @@ -166,14 +166,14 @@ function hexEntry(h: ManualHex, player: boolean): string { `; } -function section(s: ManualSection, player: boolean, single: boolean): string { +function section(s: ManualSection, player: boolean, single: boolean, labels?: ManualData["linkLabels"]): string { const heading = single ? "Hex key" : `Section ${esc(s.label)}`; return `

${heading} hexes ${esc(s.range)}

${heading} map ${s.hexes.length - ? `
${s.hexes.map((h) => hexEntry(h, player)).join("\n")}
` + ? `
${s.hexes.map((h) => hexEntry(h, player, labels)).join("\n")}
` : `

No keyed hexes in this section.

`}
`; } @@ -201,7 +201,7 @@ ${contents(d)} ${includes(d, "legend") ? legend(d) : ""} ${includes(d, "tables") ? tables(d) : ""} ${includes(d, "factions") ? factionsAndRegions(d) : ""} -${d.sections.map((s) => section(s, d.player, d.sections.length === 1)).join("\n")} +${d.sections.map((s) => section(s, d.player, d.sections.length === 1, d.linkLabels)).join("\n")} ${includes(d, "index") ? index(d) : ""}
`; } diff --git a/src/export/manual/manualModel.ts b/src/export/manual/manualModel.ts index 181ddf40..aa69452e 100644 --- a/src/export/manual/manualModel.ts +++ b/src/export/manual/manualModel.ts @@ -100,6 +100,9 @@ export interface ManualData { index: { category: string; entries: ManualIndexEntry[] }[]; /** Front/back matter the user left out of this handout. */ omit?: ManualPart[]; + /** Link section names in the map type's words (G4b: Settlements on a + * space map). Missing = the usual names. */ + linkLabels?: Partial>; } /** Optional parts of the manual (the title page and hex key always print). */ diff --git a/src/export/mapPngRenderer.ts b/src/export/mapPngRenderer.ts index 324abc25..e6d772fb 100644 --- a/src/export/mapPngRenderer.ts +++ b/src/export/mapPngRenderer.ts @@ -50,6 +50,7 @@ import { import { BADGE_INFO, BADGE_SECTIONS, badgeSize, hiddenBadges as hiddenBadgeKinds, linkSectionsFromCache, type BadgeSection } from "../hex-map/linkBadges"; import { usedTerrainEntries } from "../hex-map/terrainLegend"; import { hexNameTone } from "../hex-map/hexNameLayer"; +import { MIN_NAME_SCREEN_PX, nameFontShorthand, resolveNameFont } from "../hex-map/hexNameFont"; import { DEFAULT_TOKEN_FILL, groupSize, tokenGroupOffsets, tokenNamePlacement } from "../hex-map/tokenDefaults"; import { getIconUrl, normalizeFolder } from "../utils"; import { UNKNOWN_PATH_TYPE } from "../constants"; @@ -128,6 +129,8 @@ export async function renderMapToPngBlob( ): Promise { const map = plugin.settings.maps.find((m) => m.name === mapName); if (!map) throw new Error(`Map "${mapName}" not found`); + // Link badge kinds in the legend use the map type's words (G4b). + const sectionWords = plugin.sectionWordsFor(mapName); const R = opts.hexRadius ?? 50; const padding = opts.padding ?? 40; @@ -340,7 +343,7 @@ export async function renderMapToPngBlob( const legendFont = Math.max(12, Math.round(R * 0.26)); const legendRows: TerrainLegendRow[] = [ ...legendTerrains.map((t): TerrainLegendRow => ({ name: t.name, color: t.color, icon: showIcons ? t.icon : undefined, iconColor: t.iconColor })), - ...(showLegend ? badgeKinds : []).map((s): TerrainLegendRow => ({ name: BADGE_INFO[s].label, color: BADGE_INFO[s].color, badge: s })), + ...(showLegend ? badgeKinds : []).map((s): TerrainLegendRow => ({ name: sectionWords(s).label, color: BADGE_INFO[s].color, badge: s })), ]; const legendSize = showLegend && legendRows.length ? drawTerrainLegend(measureContext(), 0, 0, legendRows, legendFont, orientation, true) @@ -544,8 +547,13 @@ export async function renderMapToPngBlob( // Hex names, over paths, on the side of the hex away from its coordinates. if (showHexNames) { - const px = pngHexNamePx(R); - ctx.font = `700 ${px}px sans-serif`; + // The map's name font, as on screen (NM3); the theme font is the + // document's, which the map inherits. + const nameFont = resolveNameFont(map, plugin.settings); + const themeFamily = getComputedStyle(activeDocument.body).fontFamily || "sans-serif"; + const fontAt = (size: number) => nameFontShorthand(nameFont, size, themeFamily); + const px = pngHexNamePx(R, nameFont.scale); + ctx.font = fontAt(px); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.lineJoin = "round"; @@ -555,12 +563,12 @@ export async function renderMapToPngBlob( if (!hex.name) continue; const y = pngHexNameY(coordPlacement, showCoords && !!opts.coordLabel, hex.cy, R); // Within about the hex's width: two smaller lines for long names. - ctx.font = `700 ${px}px sans-serif`; + ctx.font = fontAt(px); let lines = wrapHexName(hex.name, R * 1.8, (s) => ctx.measureText(s).width); let linePx = px; if (lines.length > 1) { - linePx = Math.max(10, Math.round(px * 0.85)); - ctx.font = `700 ${linePx}px sans-serif`; + linePx = Math.max(MIN_NAME_SCREEN_PX, Math.round(px * 0.85)); + ctx.font = fontAt(linePx); lines = wrapHexName(hex.name, R * 1.8, (s) => ctx.measureText(s).width); } const lineH = linePx * 1.1; diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 302253a3..96fe3a6f 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -59,16 +59,6 @@ import { DebouncedSave, SAVE_STATUS_TEXT, SAVE_STATUS_TITLE, SaveTracker, type S import { openNoteFocused } from "../openNote"; import { TERRAIN_FILTER_MIN, terrainMatches, terrainStartsCollapsed } from "./terrainSection"; -/** What each link field links, for its placeholder ("Search or create a town…"). */ -const LINK_FIELD_NOUN: Record = { - "Encounters Table": "an encounter table", - Towns: "a town", - Dungeons: "a dungeon", - Features: "a feature", - Quests: "a quest", - Factions: "a faction", -}; - /** Typing pause after which a text section autosaves. */ const TEXT_AUTOSAVE_MS = 800; /** Unique ids for label for= ↔ textarea pairs. */ @@ -1104,8 +1094,11 @@ export class HexEditorModal extends HexmakerModal { const sectionEl = container.createDiv({ cls: "duckmage-editor-link-section duckmage-editor-link-card", }); + // Display words follow the map type (G4b: Settlements on a space map); + // the note keeps its heading. + const words = this.plugin.sectionWordsFor(this.mapName)(section); sectionEl.createEl("h4", { - text: section, + text: words.label, cls: "duckmage-link-section-title", }); @@ -1114,9 +1107,9 @@ export class HexEditorModal extends HexmakerModal { const input = comboWrap.createEl("input", { type: "text", cls: "duckmage-link-combo-input", - attr: { "aria-label": `Link ${section.toLowerCase()}` }, + attr: { "aria-label": `Link ${words.label.toLowerCase()}` }, }); - input.placeholder = `Search or create ${LINK_FIELD_NOUN[section]}…`; + input.placeholder = `Search or create ${words.noun}…`; const arrowBtn = comboWrap.createEl("button", { text: "▾", diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 08b7902a..748f3cae 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -39,6 +39,7 @@ import { wheelZoomLog, wheelZoomsMap } from "./wheelZoom"; import { groupSize, pickTokenFill, tokenGroupOffsets, tokenNamePlacement } from "./tokenDefaults"; import { hexHoverLabel, hexKeyCoords, overlayClosed, pointerMovedFrom } from "./hexHover"; import { renderHexNameLayer } from "./hexNameLayer"; +import { resolveNameFont } from "./hexNameFont"; import { whenSized } from "./whenSized"; import { getHexNameFromFile } from "../frontmatter"; import { nearestHex } from "./hitTest"; @@ -208,6 +209,8 @@ export class HexMapView extends ItemView { private namesTimer: number | null = null; /** Names the hex-name layer was last drawn with ("x_y=name" lines), to skip no-op redraws. */ private drawnHexNames = ""; + /** Zoom at the last transform: a change redraws the names (readable size, NM3). */ + private namesZoom = 1; private controlsEl: HTMLElement | null = null; private settleTimer: number | null = null; // Wheel-zoom rAF coalescing. Wheel events fire faster than the browser @@ -1292,6 +1295,11 @@ export class HexMapView extends ItemView { } this.refreshTerrainLegend(); }, + // Name font changed (NM3): redraw the names. + onHexNameFontChange: () => { + const grid = this.viewportEl?.querySelector(".duckmage-hex-map-grid"); + if (grid && !this.cancelMeasuredLayers) this.drawHexNames(grid, true); + }, }, ); toolsPanel.onBeforeOpen = () => this.overlayPanel?.close(); @@ -2561,6 +2569,11 @@ export class HexMapView extends ItemView { "--duckmage-vp-scale": String(this.zoom), }); } + // Names keep a readable size on screen (NM3): redraw once the zoom settles. + if (this.zoom !== this.namesZoom) { + this.namesZoom = this.zoom; + this.scheduleHexNames(); + } this.updateCalHandleScale(); this.onViewportMoved(); } @@ -4884,7 +4897,7 @@ export class HexMapView extends ItemView { const own = terrain !== undefined ? terrain : pending ? pending.terrain : getTerrainFromFile(this.app, hexPath); // The notes it links (towns, dungeons…), from the metadata cache (S3). const note = this.app.vault.getAbstractFileByPath(hexPath); - const linked = note instanceof TFile ? linkedNotesText(linksBySection(this.app.metadataCache.getFileCache(note))) : ""; + const linked = note instanceof TFile ? linkedNotesText(linksBySection(this.app.metadataCache.getFileCache(note)), this.plugin.sectionWordsFor(this.activeMapName)) : ""; const label = hexHoverLabel(x, y, own, this.getActiveMap().baseTerrain ?? null, getHexNameFromFile(hexPath), linked); if (hexEl.title !== label) { hexEl.title = label; @@ -6142,7 +6155,7 @@ export class HexMapView extends ItemView { } this.badgeSectionsByHex = sections; const map = this.getActiveMap(); - renderLinkBadgeLayer(gridContainer, this.coordPlacements, this.coordGridSize, sections, badgeSize(map.linkBadgeSize)); + renderLinkBadgeLayer(gridContainer, this.coordPlacements, this.coordGridSize, sections, badgeSize(map.linkBadgeSize), this.plugin.sectionWordsFor(this.activeMapName)); // The legend lists the kinds on the map: redraw it when they change. const kinds = [...new Set([...sections.values()].flat())]; if (kinds.sort().join() !== [...this.badgeKindsOnMap].sort().join()) { @@ -6182,10 +6195,15 @@ export class HexMapView extends ItemView { // The fill is in the signature: repainting a named hex can flip its name's tone. // Badges in the signature too: names make room for them (R8). const limits = this.nameBadgeLimits(names); - const sig = [...names].map(([k, n]) => `${k}=${n}|${fills.get(k) ?? ""}|${limits.get(k) ?? ""}`).sort().join("\n"); + // The font and the grid's on-screen size too: a name's size has a + // readable floor (NM3), so zooming can change its layout. + const font = resolveNameFont(this.getActiveMap(), this.plugin.settings); + const screenEm = names.size ? (parseFloat(getComputedStyle(gridContainer).fontSize) || 16) * this.zoom : 0; + const sig = [...names].map(([k, n]) => `${k}=${n}|${fills.get(k) ?? ""}|${limits.get(k) ?? ""}`).sort().join("\n") + + `\nfont=${font.family}|${font.scale}|${font.bold}|${font.italic}|${screenEm.toFixed(1)}`; if (onlyIfChanged && sig === this.drawnHexNames) return; this.drawnHexNames = sig; - renderHexNameLayer(gridContainer, names, fills, this.plugin.settings.coordPlacement ?? "bottom", limits); + renderHexNameLayer(gridContainer, names, fills, this.plugin.settings.coordPlacement ?? "bottom", limits, font, this.zoom); } /** How far right each named hex's name may reach: clear of its shown badges (R8). */ @@ -6249,9 +6267,11 @@ export class HexMapView extends ItemView { } if (map.baseTerrain && painted < cols * rows) used.push(map.baseTerrain); const entries = usedTerrainEntries(this.plugin.getMapPalette(this.activeMapName), used); - // The link badge kinds on the map, as on the PNG legend (round 7 R8). + // The link badge kinds on the map, as on the PNG legend (round 7 R8), + // named for the map type (G4b). + const words = this.plugin.sectionWordsFor(this.activeMapName); const badges = legendBadgeKinds(this.badgeKindsOnMap, map.showLinkBadges ?? true, hiddenBadges(map)) - .map((s) => ({ label: BADGE_INFO[s].label, icon: BADGE_INFO[s].icon, cls: BADGE_INFO[s].cls })); + .map((s) => ({ label: words(s).label, icon: BADGE_INFO[s].icon, cls: BADGE_INFO[s].cls })); // Pinned to the view's bottom-left, small, names cut short; folds to // a "Legend" chip (MK2). renderTerrainLegend(parent, entries, { diff --git a/src/hex-map/HexSidePanel.ts b/src/hex-map/HexSidePanel.ts index 8ef44ddb..4b908eee 100644 --- a/src/hex-map/HexSidePanel.ts +++ b/src/hex-map/HexSidePanel.ts @@ -2,6 +2,7 @@ import { setIcon } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { MapData } from "../types"; import { BADGE_INFO, BADGE_SECTIONS, BADGE_SIZES, badgeHideClass, badgeSize, hiddenBadges, toggleHiddenBadge } from "./linkBadges"; +import { NAME_FAMILIES, NAME_SIZES, nameStyleId, resolveNameFont, type HexNameSize, type ResolvedNameFont } from "./hexNameFont"; // ── Abstract base ──────────────────────────────────────────────────────────── @@ -116,6 +117,8 @@ export interface OverlayPanelExtras { onLegendChange?: (show: boolean) => void; /** Badge size or the badge kinds shown changed (redraw badges + legend). */ onBadgesChange?: () => void; + /** The map's hex-name font changed (redraw the names). */ + onHexNameFontChange?: () => void; } export class OverlayPanel extends HexSidePanel { @@ -135,6 +138,10 @@ export class OverlayPanel extends HexSidePanel { private badgeChips = new Map(); private badgeSizeBtns = new Map(); private legendCb: HTMLInputElement | null = null; + private nameFamilySelect: HTMLSelectElement | null = null; + private nameSizeBtns = new Map(); + private nameBoldBtn: HTMLButtonElement | null = null; + private nameItalicBtn: HTMLButtonElement | null = null; private extras: OverlayPanelExtras; constructor( @@ -163,8 +170,10 @@ export class OverlayPanel extends HexSidePanel { protected buildPanel(panel: HTMLDivElement): void { // The Labels group comes first: one heading, its toggles side by side. const labelGroup = panel.createDiv({ cls: "duckmage-overlay-group" }); - labelGroup.createDiv({ cls: "duckmage-overlay-group-title", text: "Labels" }); + const labelTitle = labelGroup.createDiv({ cls: "duckmage-overlay-group-title" }); + labelTitle.createSpan({ text: "Labels" }); const labelRow = labelGroup.createDiv({ cls: "duckmage-overlay-group-row" }); + this.buildNameFontRow(labelTitle, labelGroup); for (const opt of OVERLAY_OPTIONS) { const row = opt.inLabels ? labelRow.createDiv({ cls: "duckmage-overlay-row duckmage-overlay-label-toggle" }) @@ -307,6 +316,97 @@ export class OverlayPanel extends HexSidePanel { } + /** + * Hex-name font (NM3): an "Aa" button in the Labels heading unfolds one + * compact row (font, size S–XL, bold, italic, back to the default), so + * the menu doesn't grow. Saved per map; unset parts follow the default + * in the plugin settings. + */ + private buildNameFontRow(title: HTMLElement, group: HTMLElement): void { + const btn = title.createEl("button", { + cls: "duckmage-overlay-font-btn", + text: "Aa", + attr: { "aria-label": "Hex name font", "aria-expanded": "false" }, + }); + const row = group.createDiv({ cls: "duckmage-overlay-subrow duckmage-overlay-font-row" }); + row.hide(); + btn.addEventListener("click", () => { + const open = !row.isShown(); + row.toggle(open); + btn.toggleClass("is-open", open); + btn.setAttr("aria-expanded", String(open)); + }); + + const changed = () => { + void this.plugin.saveSettings(); + this.syncNameFont(); + this.extras.onHexNameFontChange?.(); + }; + + const family = row.createEl("select", { cls: "dropdown duckmage-overlay-font-family", attr: { "aria-label": "Font" } }); + for (const f of NAME_FAMILIES) family.createEl("option", { value: f.id, text: f.label }); + family.addEventListener("change", () => { + this.getActiveMap().hexNameFont = family.value; + changed(); + }); + this.nameFamilySelect = family; + + const sizes = row.createDiv({ cls: "duckmage-overlay-sizes", attr: { role: "group", "aria-label": "Name size" } }); + for (const s of NAME_SIZES) { + const b = sizes.createEl("button", { + cls: "duckmage-overlay-size", + text: s.label, + attr: { "aria-label": `Name size ${s.label}` }, + }); + this.nameSizeBtns.set(s.id, b); + b.addEventListener("click", () => { + this.getActiveMap().hexNameSize = s.id; + changed(); + }); + } + + const styles = row.createDiv({ cls: "duckmage-overlay-sizes", attr: { role: "group", "aria-label": "Name style" } }); + const styleBtn = (text: string, label: string, cls: string, flip: (f: ResolvedNameFont) => ResolvedNameFont) => { + const b = styles.createEl("button", { cls: `duckmage-overlay-size ${cls}`, text, attr: { "aria-label": label } }); + b.addEventListener("click", () => { + const map = this.getActiveMap(); + const next = flip(resolveNameFont(map, this.plugin.settings)); + map.hexNameStyle = nameStyleId(next.bold, next.italic); + changed(); + }); + return b; + }; + this.nameBoldBtn = styleBtn("B", "Bold", "duckmage-overlay-font-bold", (f) => ({ ...f, bold: !f.bold })); + this.nameItalicBtn = styleBtn("I", "Italic", "duckmage-overlay-font-italic", (f) => ({ ...f, italic: !f.italic })); + + const reset = row.createEl("button", { + cls: "clickable-icon duckmage-overlay-font-reset", + attr: { "aria-label": "Use the default name font (settings)" }, + }); + setIcon(reset, "rotate-ccw"); + reset.addEventListener("click", () => { + const map = this.getActiveMap(); + delete map.hexNameFont; + delete map.hexNameSize; + delete map.hexNameStyle; + changed(); + }); + } + + /** Name-font controls ← the current map's font. */ + private syncNameFont(): void { + const font = resolveNameFont(this.getActiveMap(), this.plugin.settings); + if (this.nameFamilySelect) this.nameFamilySelect.value = font.family; + for (const [id, b] of this.nameSizeBtns) { + b.toggleClass("is-active", id === font.size); + b.setAttr("aria-pressed", String(id === font.size)); + } + this.nameBoldBtn?.toggleClass("is-active", font.bold); + this.nameBoldBtn?.setAttr("aria-pressed", String(font.bold)); + this.nameItalicBtn?.toggleClass("is-active", font.italic); + this.nameItalicBtn?.setAttr("aria-pressed", String(font.italic)); + } + /** * Link badges: one row (master toggle + a ▸ that unfolds a compact strip * of per-type chips) so the menu doesn't grow a row per link type. @@ -389,7 +489,10 @@ export class OverlayPanel extends HexSidePanel { b.toggleClass("is-active", s === size); b.setAttr("aria-pressed", String(s === size)); } + // Chip names in the map type's words (G4b). + const words = this.plugin.sectionWordsFor(map.name); for (const [s, chip] of this.badgeChips) { + chip.setAttr("aria-label", `${words(s).label} badges`); chip.toggleClass("is-off", hidden.has(s)); chip.setAttr("aria-pressed", String(!hidden.has(s))); } @@ -435,6 +538,7 @@ export class OverlayPanel extends HexSidePanel { this.onTokensChange(show); } this.applyBadgeClasses(map); + this.syncNameFont(); this.syncLegendToggle(); } diff --git a/src/hex-map/TerrainEntryEditorModal.ts b/src/hex-map/TerrainEntryEditorModal.ts index d815d69f..26fe61df 100644 --- a/src/hex-map/TerrainEntryEditorModal.ts +++ b/src/hex-map/TerrainEntryEditorModal.ts @@ -227,11 +227,12 @@ export class TerrainEntryEditorModal extends HexmakerModal { else delete this.entry.type; setImpassable(this.entry, this.pendingImpassable); if (this.isNew) { - // Brand-new entry — no hex can have this terrain yet and no table files exist - // to rename. Just commit the name and create fresh table files. - this.entry.name = this.pendingName; - await this.plugin.saveSettings(); - await this.plugin.ensureTerrainTables(); + // Brand-new entry: it was saved under its placeholder name ("New"), + // which already gave it empty tables (HG5). Naming it moves those + // tables to the real name; then make sure they exist. + if (nameChanged) await this.plugin.renameTerrain(this.entry, this.pendingName); + else await this.plugin.saveSettings(); + await this.plugin.ensureTablesForNewTerrains(); this.plugin.refreshHexMap(); } else if (nameChanged) { await this.plugin.renameTerrain(this.entry, this.pendingName); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index be98fe87..adc13e7e 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -107,7 +107,7 @@ Opening the layers panel or the drawing tools never moves the map. Name a hex in the **Name** box at the top of the hex editor. The name shows on the map, in the hover text and in the hex table. If the hex has a note, the name is added to the note's aliases, so the quick switcher finds it. Hex notes also get their map name and coordinates as an alias ("Gloomwood 3, 4"), so you can find a hex by typing them. -Tokens show their name underneath. The layers panel's **Labels** group turns coordinates, hex names and token names on and off; a hidden token name still shows on hover. Long hex names shrink and wrap at spaces (never mid-word) inside the hex, clear of its badges, in a colour that reads on the terrain; zoom in to read small ones. **Export** can include hex names, tokens, link badges and a legend, and lets you pick the PDF table's columns and the manual's parts for a handout. It starts from what the map shows and remembers your choices per map. +Tokens show their name underneath. The layers panel's **Labels** group turns coordinates, hex names and token names on and off; a hidden token name still shows on hover. Hex names never get smaller than readable on screen: a long name shrinks and wraps at spaces (never mid-word) to fit inside the hex, clear of its badges, and spills past the hex when it can't fit at a readable size. **Aa** beside the Labels heading picks this map's hex-name font, size, bold and italic (the default is in settings); the PNG export uses it too. **Export** can include hex names, tokens, link badges and a legend, and lets you pick the PDF table's columns and the manual's parts for a handout. It starts from what the map shows and remembers your choices per map. --- @@ -127,6 +127,10 @@ With generators on, new maps can also use the built-in **biomes and presets** (G Pickers that link notes (to hexes, tokens, sections) never offer template notes (the hex template, workflow templates, a Templates folder); pickers for choosing a template do. Notes starting with `_` are never offered. +On **space maps** (a palette with space terrain types, or a map under one), the hex editor, hex table, badge legend and exports call the link sections **Settlements**, **Sites**, **Points of Interest** and **Missions** instead of Towns, Dungeons, Features and Quests. Only the labels change: notes keep their usual headings, so links keep working. + +Every new terrain (from the terrain tool, the palette editor, a new palette or a palette note) gets its description and encounter tables right away, empty. Renaming a terrain renames its tables. + **Templates**: the plugin keeps its note templates in one folder (**Settings → Templates folder**, `templates` in the world folder by default): `hex.md` for hex notes and `town.md` for new towns made from the hex editor. Edit them there and new notes follow. ## Palettes diff --git a/src/hex-map/hexNameFont.ts b/src/hex-map/hexNameFont.ts new file mode 100644 index 00000000..edb7c166 --- /dev/null +++ b/src/hex-map/hexNameFont.ts @@ -0,0 +1,149 @@ +/** + * Font options for hex names on the map and in the PNG export (NM3): font + * family, size and style, per map (map note keys `name-font`, `name-size`, + * `name-style`) with a plugin-wide default. Values are plain words so the + * map note stays readable; reading is forgiving (`Serif`, `120%`, `1.2`, + * `bold italic`, `script` …), and anything unreadable falls back to the + * default rather than breaking the map. + * + * No fonts are bundled: each family is a stack of fonts most systems have. + */ + +export type HexNameFamily = "theme" | "serif" | "sans" | "handwritten"; +export type HexNameSize = "small" | "medium" | "large" | "huge"; +export type HexNameStyle = "bold" | "bold italic" | "regular" | "italic"; + +export const NAME_FAMILIES: { id: HexNameFamily; label: string }[] = [ + { id: "theme", label: "Theme" }, + { id: "serif", label: "Serif" }, + { id: "sans", label: "Sans" }, + { id: "handwritten", label: "Handwritten" }, +]; + +export const NAME_SIZES: { id: HexNameSize; label: string; scale: number }[] = [ + { id: "small", label: "S", scale: 0.85 }, + { id: "medium", label: "M", scale: 1 }, + { id: "large", label: "L", scale: 1.25 }, + { id: "huge", label: "XL", scale: 1.5 }, +]; + +export const NAME_STYLES: { id: HexNameStyle; label: string }[] = [ + { id: "bold", label: "Bold" }, + { id: "bold italic", label: "Bold italic" }, + { id: "regular", label: "Regular" }, + { id: "italic", label: "Italic" }, +]; + +/** Font stacks; "theme" uses the theme's interface font. */ +export const NAME_FONT_STACKS: Record, string> = { + serif: `"Palatino Linotype", Palatino, "Book Antiqua", Georgia, "Times New Roman", serif`, + sans: `"Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif`, + handwritten: `"Segoe Print", "Bradley Hand", "Comic Sans MS", "Chalkboard SE", cursive`, +}; + +/** + * Smallest on-screen size of a hex name, px (NM3: names are map locales and + * stay readable at any zoom; a long one may spill past its hex). + */ +export const MIN_NAME_SCREEN_PX = 11; + +export const DEFAULT_NAME_FONT: ResolvedNameFont = { family: "theme", size: "medium", scale: 1, bold: true, italic: false }; + +export interface ResolvedNameFont { + family: HexNameFamily; + size: HexNameSize | null; + /** Size multiplier (1 = the usual size). */ + scale: number; + bold: boolean; + italic: boolean; +} + +/** Name-font settings as stored (map data or plugin settings). */ +export interface NameFontSettings { + hexNameFont?: string; + hexNameSize?: string; + hexNameStyle?: string; +} + +/** A family from what's written; undefined when it can't be read. */ +export function parseNameFamily(raw: unknown): HexNameFamily | undefined { + if (typeof raw !== "string") return undefined; + const t = raw.trim().toLowerCase(); + if (!t) return undefined; + if (/^(theme|default|interface|auto)/.test(t)) return "theme"; + if (/hand|script|cursive|written/.test(t)) return "handwritten"; + if (/sans/.test(t)) return "sans"; + if (/serif/.test(t)) return "serif"; + return undefined; +} + +/** A size multiplier from what's written ("large", "XL", "120%", "1.2"). */ +export function parseNameSize(raw: unknown): number | undefined { + if (typeof raw === "number") return Number.isFinite(raw) && raw > 0 ? clampScale(raw) : undefined; + if (typeof raw !== "string") return undefined; + const t = raw.trim().toLowerCase(); + if (!t) return undefined; + const byWord = NAME_SIZES.find((s) => s.id === t || s.label.toLowerCase() === t); + if (byWord) return byWord.scale; + if (/^(x-?large|extra large)$/.test(t)) return 1.5; + if (t === "normal" || t === "default") return 1; + const m = /^(\d+(?:\.\d+)?|\.\d+)\s*(%)?$/.exec(t); + if (!m) return undefined; + const n = Number(m[1]) / (m[2] ? 100 : 1); + return n > 0 ? clampScale(n) : undefined; +} + +const clampScale = (n: number) => Math.min(3, Math.max(0.5, n)); + +/** Bold / italic from what's written ("bold italic", "regular", "italic"). */ +export function parseNameStyle(raw: unknown): { bold: boolean; italic: boolean } | undefined { + if (typeof raw !== "string") return undefined; + const t = raw.trim().toLowerCase(); + if (!t) return undefined; + const italic = /italic|oblique/.test(t); + const bold = /bold|heavy|black/.test(t); + const plain = /regular|normal|plain|light/.test(t); + if (!italic && !bold && !plain) return undefined; + return { bold, italic }; +} + +/** The size word for a multiplier, or null for one between the steps. */ +export function nameSizeId(scale: number): HexNameSize | null { + return NAME_SIZES.find((s) => Math.abs(s.scale - scale) < 1e-6)?.id ?? null; +} + +/** The style word for bold / italic. */ +export function nameStyleId(bold: boolean, italic: boolean): HexNameStyle { + return bold ? (italic ? "bold italic" : "bold") : italic ? "italic" : "regular"; +} + +/** + * The font a map's hex names use: each of the map's own settings when it + * has a readable one, else the plugin-wide default's, else the built-in + * default (bold, theme font, usual size). + */ +export function resolveNameFont(map: NameFontSettings | undefined, global: NameFontSettings | undefined): ResolvedNameFont { + const family = parseNameFamily(map?.hexNameFont) ?? parseNameFamily(global?.hexNameFont) ?? DEFAULT_NAME_FONT.family; + const scale = parseNameSize(map?.hexNameSize) ?? parseNameSize(global?.hexNameSize) ?? DEFAULT_NAME_FONT.scale; + const style = parseNameStyle(map?.hexNameStyle) ?? parseNameStyle(global?.hexNameStyle) ?? DEFAULT_NAME_FONT; + return { family, size: nameSizeId(scale), scale, bold: style.bold, italic: style.italic }; +} + +/** The CSS font-family for a family; "theme" → `themeFamily` (the map's own font). */ +export function nameFontFamily(family: HexNameFamily, themeFamily: string): string { + return family === "theme" ? themeFamily || "sans-serif" : NAME_FONT_STACKS[family]; +} + +/** A canvas / CSS `font` shorthand for a name at `px`. */ +export function nameFontShorthand(font: ResolvedNameFont, px: number, themeFamily: string): string { + return `${font.italic ? "italic " : ""}${font.bold ? 700 : 400} ${px}px ${nameFontFamily(font.family, themeFamily)}`; +} + +/** + * The smallest font (grid em) at which a name still reads: MIN_NAME_SCREEN_PX + * over the on-screen size of one grid em (its font px × the view's zoom). + */ +export function readableFloorEm(gridFontPx: number, zoom: number, minPx = MIN_NAME_SCREEN_PX): number { + const screen = gridFontPx * zoom; + return screen > 0 ? minPx / screen : 0; +} diff --git a/src/hex-map/hexNameLayer.ts b/src/hex-map/hexNameLayer.ts index e727afcd..7604cde9 100644 --- a/src/hex-map/hexNameLayer.ts +++ b/src/hex-map/hexNameLayer.ts @@ -8,11 +8,16 @@ * * Line breaks are worked out here, not by CSS (round 7 R7: CSS wrapping in a * box sized from a guessed character width broke words mid-letter, "The / - * Drowne"). `layoutHexName` wraps only at spaces, shrinks the font until the - * name fits inside the hex, and ellipsizes only when the smallest size still - * doesn't fit. Everything is in em, so the labels scale with the map's zoom. + * Drowne"). `layoutHexName` wraps only at spaces and shrinks the font until + * the name fits inside the hex, but never below a readable size on screen + * (NM3: names are map locales, always legible). A name that doesn't fit at + * that size spills past its hex, still broken only at spaces, never cut. + * Everything is in em, so the labels scale with the map's zoom; the view + * redraws them when the zoom settles, to keep the readable floor. */ +import { nameFontFamily, readableFloorEm, type ResolvedNameFont, DEFAULT_NAME_FONT } from "./hexNameFont"; + import { parseColor, relativeLuminance } from "../coordStyle"; export const HEX_NAMES_LAYER_CLASS = "duckmage-hex-names-layer"; @@ -29,7 +34,6 @@ export const NAME_WIDTH_SHARE = 0.96; const NAME_CROSS_EM = 0.35; /** With the coordinates in the middle, the gap (grid em) kept clear of the centre. */ const NAME_MIDDLE_CLEAR_EM = 0.5; -const ELLIPSIS = "…"; /** * Text tone for a name on a hex of fill colour `fill` (round 6 S4: a white @@ -55,6 +59,11 @@ export interface HexNameLayoutOptions { /** How far right of the centre (grid em) the name may reach: the left * edge of the hex's link badges (badgeNameLimit). Default: no limit. */ rightLimit?: number; + /** Font size multiplier from the map's name font (NM3). Default 1. */ + scale?: number; + /** Smallest font (grid em) that still reads on screen (readableFloorEm). + * The name never goes below it, even if that means spilling out. */ + floorEm?: number; } export interface HexNameLayout { @@ -68,8 +77,8 @@ export interface HexNameLayout { /** Horizontal offset of the label's centre, grid em (negative = left, * clear of the badges). */ dxEm: number; - /** True when an ellipsis cut the name (the hover shows it whole). */ - cut: boolean; + /** True when the name is wider or taller than its hex (it spills past). */ + overflow: boolean; } /** Half the hex's width at `dy` (grid em) from its centre. */ @@ -80,14 +89,6 @@ export function hexHalfWidthAt(dy: number, hexW: number, hexH: number, flat: boo return Math.max(0, (hexW / 2) * ((hexH / 2 - d) / (hexH / 4))); } -/** Cut `text` to fit `room` (em at 1em), ending in an ellipsis. */ -export function ellipsize(text: string, room: number, measure: (t: string) => number): string { - if (measure(text) <= room) return text; - let t = text; - while (t.length > 1 && measure(t.trimEnd() + ELLIPSIS) > room) t = t.slice(0, -1); - return t.trimEnd() + ELLIPSIS; -} - /** * The split of `words` into `lines` lines (at spaces) whose widest line is * narrowest. Names are a few words, so every split is tried. @@ -105,18 +106,19 @@ export function balancedLines(words: readonly string[], lines: number, measure: return best; } -/** At most this many lines; a longer name is cut with an ellipsis. */ +/** At most this many lines; a longer name puts more words on each. */ export const NAME_MAX_LINES = 3; /** - * Lay a name out inside its hex: the biggest font (from NAME_MAX_FONT_EM - * down to NAME_MIN_FONT_EM) at which it fits on one line, or on two or - * three lines broken at spaces. Words are never broken; a word too wide - * even at the smallest size is cut with an ellipsis, and so is a name that - * needs more lines. The label sits on the side of the hex away from the - * coordinates, clear of the hex's link badges, and its width is checked - * against the hex's real outline at the label's height, so it stays inside - * the hex. + * Lay a name out in its hex: the biggest font (from NAME_MAX_FONT_EM times + * the map's size scale, down to `floorEm`, the smallest size that reads on + * screen; NAME_MIN_FONT_EM without one) at which it fits on one line, or on + * two or three lines broken at spaces. Words are never broken and nothing is + * cut: a name that doesn't fit at the smallest allowed size keeps that size + * and spills past the hex, on the split that spills least. The label sits + * on the side of the hex away from the coordinates (and grows away from + * them), clear of the hex's link badges, and its width is checked against + * the hex's real outline at the label's height. */ export function layoutHexName(name: string, opts: HexNameLayoutOptions): HexNameLayout { const { measure, hexW, hexH, flat } = opts; @@ -125,6 +127,12 @@ export function layoutHexName(name: string, opts: HexNameLayoutOptions): HexName const dir = coords === "bottom" ? -1 : 1; const nearMin = coords === "middle" ? NAME_MIDDLE_CLEAR_EM : -NAME_CROSS_EM; const limit = opts.rightLimit ?? Infinity; + const scale = opts.scale && opts.scale > 0 ? opts.scale : 1; + const maxF = NAME_MAX_FONT_EM * scale; + // With a readable floor, that's the smallest size (zoomed in, a long name + // may shrink below NAME_MIN_FONT_EM to stay in its hex, clear of the + // badges, and still read); without one, NAME_MIN_FONT_EM. + const minF = opts.floorEm !== undefined ? Math.max(opts.floorEm, 1e-3) : NAME_MIN_FONT_EM * scale; const place = (lines: number, f: number) => { const h = lines * NAME_LINE_HEIGHT * f; const centre = Math.max(0, h / 2 + nearMin); @@ -136,55 +144,55 @@ export function layoutHexName(name: string, opts: HexNameLayoutOptions): HexName // Room in the label's own em (what `measure` returns). return { centre, room: (half + right) / f, dx: (right - half) / 2 }; }; - const done = (lines: string[], f: number, cut = false): HexNameLayout => { + const done = (lines: string[], f: number, overflow = false): HexNameLayout => { const p = place(lines.length, f); return { lines, fontEm: Number(f.toFixed(3)), dyEm: Number((dir * p.centre).toFixed(3)) || 0, dxEm: Number(p.dx.toFixed(3)) || 0, - cut, + overflow, }; }; const words = name.trim().split(/\s+/).filter(Boolean); - if (!words.length) return { lines: [], fontEm: NAME_MAX_FONT_EM, dyEm: 0, dxEm: 0, cut: false }; + if (!words.length) return { lines: [], fontEm: Number(maxF.toFixed(3)), dyEm: 0, dxEm: 0, overflow: false }; const maxLines = Math.min(NAME_MAX_LINES, words.length); const splits: string[][] = []; for (let n = 1; n <= maxLines; n++) splits.push(balancedLines(words, n, measure)); const widest = (lines: readonly string[]) => Math.max(...lines.map(measure)); + const fits = (lines: readonly string[], f: number) => widest(lines) <= place(lines.length, f).room + 1e-9; - const steps = Math.round((NAME_MAX_FONT_EM - NAME_MIN_FONT_EM) / NAME_FONT_STEP); - for (let i = 0; i <= steps; i++) { - const f = NAME_MAX_FONT_EM - i * NAME_FONT_STEP; - for (const lines of splits) if (widest(lines) <= place(lines.length, f).room) return done(lines, f); + if (minF <= maxF) { + const step = NAME_FONT_STEP * scale; + for (let f = maxF; f > minF + 1e-9; f -= step) { + for (const lines of splits) if (fits(lines, f)) return done(lines, f); + } + for (const lines of splits) if (fits(lines, minF)) return done(lines, minF); } - // Too long even at the smallest size: fill the lines with whole words and - // cut the last with an ellipsis (a word wider than the room is cut too). - const f = NAME_MIN_FONT_EM; - const room = place(maxLines, f).room; - const out: string[] = []; - let w = 0; - while (w < words.length && out.length < maxLines - 1) { - let n = 1; - while (w + n < words.length && measure(words.slice(w, w + n + 1).join(" ")) <= room) n++; - out.push(ellipsize(words.slice(w, w + n).join(" "), room, measure)); - w += n; + // Too long for the hex at the smallest readable size (or the readable + // size is bigger than the hex allows): keep that size and spill past the + // hex on the split that spills least: the larger of its width over the + // hex's and its height over the hex's (fewer lines on a tie). + const f = minF; + let best = splits[0]; + let bestOver = Infinity; + for (const lines of splits) { + const over = Math.max((widest(lines) * f) / (hexW * NAME_WIDTH_SHARE), (lines.length * NAME_LINE_HEIGHT * f) / hexH); + if (over < bestOver - 1e-9) { bestOver = over; best = lines; } } - if (w < words.length) out.push(ellipsize(words.slice(w).join(" "), room, measure)); - const cut = out.join(" ") !== words.join(" "); - return done(out, f, cut); + return done(best, f, !fits(best, f)); } /** * A text measurer for the label font: canvas measureText (no DOM layout), * in em at 1em, cached per string. */ -export function canvasMeasure(fontFamily: string, weight = 700): (text: string) => number { +export function canvasMeasure(fontFamily: string, weight = 700, italic = false): (text: string) => number { const ctx = typeof OffscreenCanvas === "undefined" ? null : new OffscreenCanvas(1, 1).getContext("2d"); const cache = new Map(); - if (ctx) ctx.font = `${weight} 100px ${fontFamily || "sans-serif"}`; + if (ctx) ctx.font = `${italic ? "italic " : ""}${weight} 100px ${fontFamily || "sans-serif"}`; return (text: string) => { let w = cache.get(text); if (w === undefined) { @@ -208,6 +216,10 @@ export function renderHexNameLayer( coords: "top" | "middle" | "bottom" = "bottom", /** Per hex ("x_y"): how far right its name may reach (badgeNameLimit). */ rightLimits: ReadonlyMap = new Map(), + /** The map's name font (NM3). */ + font: ResolvedNameFont = DEFAULT_NAME_FONT, + /** The view's pending CSS zoom (1 once baked into the font size). */ + zoom = 1, ): void { gridContainer.querySelector(`.${HEX_NAMES_LAYER_CLASS}`)?.remove(); if (names.size === 0) return; @@ -240,10 +252,18 @@ export function renderHexNameLayer( placements.push({ name, ox, oy, key }); } if (!placements.length) return; - const measure = canvasMeasure(style.fontFamily); + const family = nameFontFamily(font.family, style.fontFamily); + const measure = canvasMeasure(family, font.bold ? 700 : 400, font.italic); + const floorEm = readableFloorEm(gridFont, zoom); // ── writes ── const layer = gridContainer.createDiv({ cls: HEX_NAMES_LAYER_CLASS }); + // One font for the layer; the labels inherit it. + layer.setCssProps({ + "--duckmage-name-family": family, + "--duckmage-name-weight": font.bold ? "700" : "400", + "--duckmage-name-style": font.italic ? "italic" : "normal", + }); for (const p of placements) { const fit = layoutHexName(p.name, { measure, @@ -252,11 +272,13 @@ export function renderHexNameLayer( flat, coords, rightLimit: rightLimits.get(p.key), + scale: font.scale, + floorEm, }); const tone = hexNameTone(fills.get(p.key)); const label = layer.createDiv({ cls: "duckmage-hex-name-label" - + (fit.cut ? " is-cut" : "") + + (fit.overflow ? " is-overflow" : "") + (tone ? ` is-on-${tone === "dark" ? "light" : "dark"}` : ""), text: fit.lines.join("\n"), }); diff --git a/src/hex-map/linkBadges.ts b/src/hex-map/linkBadges.ts index 81f101a2..70b84340 100644 --- a/src/hex-map/linkBadges.ts +++ b/src/hex-map/linkBadges.ts @@ -1,4 +1,5 @@ import { setIcon } from "obsidian"; +import type { SectionWordsFn } from "../mapKinds"; /** * Link badges: a small marker per link type (town, dungeon, feature, quest, @@ -142,12 +143,17 @@ function linkLabel(l: { link?: string; displayText?: string }): string { * Hover text for a hex's links (S3): "Town: Gullmouth", "Dungeons: A, B". * Empty when the hex links nothing. */ -export function linkedNotesText(bySection: ReadonlyMap): string { +export function linkedNotesText( + bySection: ReadonlyMap, + /** Display words for the map's type (G4b). */ + words?: SectionWordsFn, +): string { const parts: string[] = []; for (const [s, names] of bySection) { const shown = names.filter(Boolean); if (!shown.length) continue; - parts.push(`${shown.length === 1 ? BADGE_INFO[s].one : BADGE_INFO[s].label}: ${shown.join(", ")}`); + const w = words?.(s) ?? BADGE_INFO[s]; + parts.push(`${shown.length === 1 ? w.one : w.label}: ${shown.join(", ")}`); } return parts.join(" · "); } @@ -199,6 +205,8 @@ export function renderLinkBadgeLayer( gridSize: { w: number; h: number }, sectionsByHex: ReadonlyMap, size: BadgeSize = DEFAULT_BADGE_SIZE, + /** Display words for the map's type (G4b). */ + words?: SectionWordsFn, ): void { grid.querySelector(".duckmage-link-badges-layer")?.remove(); if (sectionsByHex.size === 0) return; @@ -222,7 +230,7 @@ export function renderLinkBadgeLayer( const info = BADGE_INFO[s]; const b = group.createSpan({ cls: `duckmage-link-badge duckmage-link-badge-${info.cls}`, - attr: { "aria-label": info.label }, + attr: { "aria-label": words?.(s).label ?? info.label }, }); setIcon(b, info.icon); } diff --git a/src/hex-table/HexTableView.ts b/src/hex-table/HexTableView.ts index 840caa06..506e4b7e 100644 --- a/src/hex-table/HexTableView.ts +++ b/src/hex-table/HexTableView.ts @@ -5,7 +5,8 @@ import { VIEW_TYPE_HEX_TABLE, VIEW_TYPE_RANDOM_TABLES, } from "../constants"; -import type { TerrainColor } from "../types"; +import { LINK_SECTIONS, type TerrainColor } from "../types"; +import type { SectionWordsFn } from "../mapKinds"; import { getAllSectionData } from "../sections"; import { displayedEncounterLinks } from "../encounterLinks"; import { getTerrainFromFile, getHexNameFromFile } from "../frontmatter"; @@ -82,6 +83,8 @@ export class HexTableView extends ItemView { private filterHasQuest = false; private filterHasFaction = false; private mapFilter = "all"; + /** Column names for link sections, per the shown maps' type (G4b). */ + private words: SectionWordsFn | null = null; private mapSelectEl: HTMLSelectElement | null = null; // Filter UI elements (created once in onOpen) @@ -106,6 +109,24 @@ export class HexTableView extends ItemView { getViewType(): string { return VIEW_TYPE_HEX_TABLE; } + + /** + * Section words for the shown hexes (G4b): the filtered map's type; with + * all maps shown, their shared type's words, or the usual ones if mixed. + */ + private sectionWords(): SectionWordsFn { + if (this.mapFilter !== "all") return this.plugin.sectionWordsFor(this.mapFilter); + const all = this.plugin.settings.maps.map((m) => this.plugin.sectionWordsFor(m.name)); + const sig = (w: SectionWordsFn) => LINK_SECTIONS.map((s) => w(s).label).join("|"); + if (all.length && all.every((w) => sig(w) === sig(all[0]))) return all[0]; + return this.plugin.sectionWordsFor(undefined); + } + + /** A column's header: link sections in the map type's words. */ + private colLabel(col: { key: string; label: string; isLink: boolean }): string { + if (!col.isLink || col.key === "encounters table") return col.label; + return (this.words ?? this.sectionWords())(col.key).label; + } getDisplayText(): string { return this.mapFilter && this.mapFilter !== "all" ? `Hex table — ${this.mapFilter}` @@ -218,7 +239,7 @@ export class HexTableView extends ItemView { }); this.townCb = townLabel.createEl("input"); this.townCb.type = "checkbox"; - townLabel.appendText("Town"); + townLabel.createSpan({ text: "Town", attr: { "data-duckmage-section": "Towns" } }); this.townCb.addEventListener("change", () => { this.filterHasTown = this.townCb!.checked; this.applyFilters(); @@ -230,7 +251,7 @@ export class HexTableView extends ItemView { }); this.dungeonCb = dungeonLabel.createEl("input"); this.dungeonCb.type = "checkbox"; - dungeonLabel.appendText("Dungeon"); + dungeonLabel.createSpan({ text: "Dungeon", attr: { "data-duckmage-section": "Dungeons" } }); this.dungeonCb.addEventListener("change", () => { this.filterHasDungeon = this.dungeonCb!.checked; this.applyFilters(); @@ -242,7 +263,7 @@ export class HexTableView extends ItemView { }); this.featureCb = featureLabel.createEl("input"); this.featureCb.type = "checkbox"; - featureLabel.appendText("Feature"); + featureLabel.createSpan({ text: "Feature", attr: { "data-duckmage-section": "Features" } }); this.featureCb.addEventListener("change", () => { this.filterHasFeature = this.featureCb!.checked; this.applyFilters(); @@ -254,7 +275,7 @@ export class HexTableView extends ItemView { }); this.questCb = questLabel.createEl("input"); this.questCb.type = "checkbox"; - questLabel.appendText("Quest"); + questLabel.createSpan({ text: "Quest", attr: { "data-duckmage-section": "Quests" } }); this.questCb.addEventListener("change", () => { this.filterHasQuest = this.questCb!.checked; this.applyFilters(); @@ -266,7 +287,7 @@ export class HexTableView extends ItemView { }); this.factionCb = factionLabel.createEl("input"); this.factionCb.type = "checkbox"; - factionLabel.appendText("Faction"); + factionLabel.createSpan({ text: "Faction", attr: { "data-duckmage-section": "Factions" } }); this.factionCb.addEventListener("change", () => { this.filterHasFaction = this.factionCb!.checked; this.applyFilters(); @@ -542,8 +563,14 @@ export class HexTableView extends ItemView { headerRow.createEl("th", { text: "Hex" }); headerRow.createEl("th", { text: "Terrain" }); headerRow.createEl("th", { text: "Type" }); + const words = this.sectionWords(); + this.words = words; + // The "has a …" filters follow too. + this.contentEl.querySelectorAll("[data-duckmage-section]").forEach((el) => { + el.setText(words(el.dataset.duckmageSection ?? "").one); + }); for (const col of COLUMNS) { - headerRow.createEl("th", { text: col.label }); + headerRow.createEl("th", { text: this.colLabel(col) }); } const tbody = table.createEl("tbody"); @@ -1005,7 +1032,7 @@ export class HexTableView extends ItemView { const current = td.dataset.fullContent ?? ""; new HexCellModal( this.app, - `${x}, ${y} — ${col.label}`, + `${x}, ${y} — ${this.colLabel(col)}`, current, true, ).open(); @@ -1028,7 +1055,7 @@ export class HexTableView extends ItemView { const current = td.dataset.fullContent ?? ""; new HexCellModal( this.app, - `${x}, ${y} — ${col.label}`, + `${x}, ${y} — ${this.colLabel(col)}`, current, false, path, diff --git a/src/mapKinds.ts b/src/mapKinds.ts index 963fcdf3..2cb0bf4f 100644 --- a/src/mapKinds.ts +++ b/src/mapKinds.ts @@ -9,12 +9,30 @@ import { terrainTypeInfo } from "./terrainTypes"; export type MapKind = "world" | "space"; +/** + * What a link section is called on screen: the plural (headings, columns, + * legend), one item ("Town: Gullmouth") and the noun for "Search or create + * a town…". + */ +export interface SectionWords { + label: string; + one: string; + noun: string; +} + export interface MapKindInfo { id: MapKind; label: string; description: string; /** Bundled icon prefix this kind owns (hidden from pickers when off). */ iconPrefix?: string; + /** + * Display names for link sections on maps of this kind (G4b), keyed by + * the section's heading ("Towns"). Display only: the note keeps its + * headings, so links and older notes still read. Sections not listed + * keep their usual words. + */ + sectionWords?: Partial>; } export const MAP_KINDS: MapKindInfo[] = [ @@ -28,9 +46,60 @@ export const MAP_KINDS: MapKindInfo[] = [ label: "Space", description: "Sector charts, star systems and planets: Space - Sector / Space - System palettes, Star scatter, Orbits and Planet surface generators, planet generators, the space icon pack.", iconPrefix: "space-", + sectionWords: { + Towns: { label: "Settlements", one: "Settlement", noun: "a settlement" }, + Dungeons: { label: "Sites", one: "Site", noun: "a site" }, + Features: { label: "Points of Interest", one: "Point of interest", noun: "a point of interest" }, + Quests: { label: "Missions", one: "Mission", noun: "a mission" }, + }, }, ]; +/** The usual words for each link section (any map without its own). */ +export const DEFAULT_SECTION_WORDS: Record = { + Towns: { label: "Towns", one: "Town", noun: "a town" }, + Dungeons: { label: "Dungeons", one: "Dungeon", noun: "a dungeon" }, + Features: { label: "Features", one: "Feature", noun: "a feature" }, + Quests: { label: "Quests", one: "Quest", noun: "a quest" }, + Factions: { label: "Factions", one: "Faction", noun: "a faction" }, + "Encounters Table": { label: "Encounters Table", one: "Encounter table", noun: "an encounter table" }, +}; + +/** Looks up a link section's display words; `section` is the heading ("Towns"), any case. */ +export type SectionWordsFn = (section: string) => SectionWords; + +/** Words for `section` under `kind` (undefined = the usual words). */ +export function sectionWords(section: string, kind?: MapKindInfo): SectionWords { + const key = Object.keys(DEFAULT_SECTION_WORDS).find((k) => k.toLowerCase() === section.toLowerCase()) ?? section; + return kind?.sectionWords?.[key] + ?? DEFAULT_SECTION_WORDS[key] + ?? { label: section, one: section, noun: section.toLowerCase() }; +} + +/** A lookup bound to one map type. */ +export function sectionWordsFor(kind?: MapKindInfo): SectionWordsFn { + return (section) => sectionWords(section, kind); +} + +/** + * The map type whose section words a map uses (G4b). `chain` is the + * terrain lists of the map's palette, then its parent's, and so on up: the + * first one using terrain types of a map type that names its sections + * decides (a planet submap of a star system keeps the system's words). + * Driven by the types' data, so any map type with `sectionWords` works. + */ +export function sectionKindFor( + chain: readonly (readonly { type?: string }[])[], + kinds: readonly MapKindInfo[] = MAP_KINDS, +): MapKindInfo | undefined { + for (const terrains of chain) { + const used = new Set(terrains.map((t) => terrainTypeInfo(t.type)?.kind).filter(Boolean)); + const hit = kinds.find((k) => k.sectionWords && used.has(k.id)); + if (hit) return hit; + } + return undefined; +} + export const ALL_MAP_KINDS: MapKind[] = MAP_KINDS.map((k) => k.id); /** Kinds enabled in settings; unset (older data.json) = all. */ @@ -73,14 +142,17 @@ export function isSpacePalette(terrains: readonly { type?: string }[] | undefine * by name, in palette order. */ export function terrainsForTables( - palettes: readonly { terrains: readonly T[] }[], + palettes: readonly { name?: string; terrains: readonly T[] }[], kinds: Iterable, + /** Palettes a map uses: their terrains always get tables (HG5). */ + inUse: Iterable = [], ): T[] { const spaceOnly = !new Set(kinds).has("world"); + const used = new Set(inUse); const seen = new Set(); const out: T[] = []; for (const p of palettes) { - if (spaceOnly && !isSpacePalette(p.terrains)) continue; + if (spaceOnly && !isSpacePalette(p.terrains) && !(p.name !== undefined && used.has(p.name))) continue; for (const t of p.terrains) { if (seen.has(t.name)) continue; seen.add(t.name); @@ -90,6 +162,19 @@ export function terrainsForTables( return out; } +/** + * Terrains in `terrains` that weren't in `known` (by name): the ones that + * still need their tables (HG5). Deduplicated, in order. + */ +export function newTerrains(known: ReadonlySet, terrains: readonly T[]): T[] { + const seen = new Set(); + return terrains.filter((t) => { + if (known.has(t.name) || seen.has(t.name)) return false; + seen.add(t.name); + return true; + }); +} + export interface GeneratorShowContext { /** The map being made is in space: its palette, or a parent map's, is a * space palette (planet submaps of a system still get planet generators). */ diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index 5de18d38..b78762b9 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -1,4 +1,5 @@ import type { MapData, PathChain, RegionSettings } from "../types"; +import { parseNameFamily, parseNameSize, parseNameStyle } from "../hex-map/hexNameFont"; /** * Map notes: one note per map ("hexes//_.md") holding the map's @@ -321,6 +322,10 @@ const SIMPLE_KEYS: [keyof MapSettings, string, Kind, string[]?][] = [ ["linkBadgeSize", "link-badge-size", "str"], ["showHexNames", "show-hex-names", "bool"], ["showTokenNames", "show-token-names", "bool"], + // Hex-name font (NM3): plain words, read forgivingly (hexNameFont.ts). + ["hexNameFont", "name-font", "str"], + ["hexNameSize", "name-size", "str"], + ["hexNameStyle", "name-style", "str"], ["gridDisplayScale", "grid-display-scale", "num"], ["gridDisplayScaleX", "grid-display-scale-x", "num"], ["gridDisplayScaleY", "grid-display-scale-y", "num"], @@ -607,6 +612,12 @@ function readFrontmatter(src: string, opts: MapNoteReadOptions): FmRead { else if (field === "staggerOffset") { if (/^(odd|even)$/i.test(t)) out[field] = t.toLowerCase(); else bad(k, field, "should be odd or even"); + } else if (field === "hexNameFont" && !parseNameFamily(t)) { + bad(k, field, "should be theme, serif, sans or handwritten"); + } else if (field === "hexNameSize" && parseNameSize(t) === undefined) { + bad(k, field, "should be small, medium, large, huge or a size like 120%"); + } else if (field === "hexNameStyle" && !parseNameStyle(t)) { + bad(k, field, "should be bold, bold italic, regular or italic"); } else if (field === "submapKind") { if (/^(region|location)$/i.test(t)) out[field] = t.toLowerCase(); else bad(k, field, "should be region or location"); diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index f5a5355d..4ec8143d 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -331,6 +331,8 @@ export class PaletteStore { private async persist(): Promise { await this.plugin.saveData(this.plugin.settings); + // A terrain added in a palette note gets its tables (HG5). + void this.plugin.ensureTablesForNewTerrains(); this.plugin.refreshHexMap(); this.plugin.refreshPaletteEditors(); } diff --git a/src/types.ts b/src/types.ts index b032f7fb..f224987f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -136,6 +136,12 @@ export interface MapData { linkBadgeSize?: string; showHexNames?: boolean; // undefined = true: hex name labels on the map showTokenNames?: boolean; // undefined = true: name under each token + /** Hex-name font (NM3): "theme" | "serif" | "sans" | "handwritten"; unset = the plugin default. */ + hexNameFont?: string; + /** Hex-name size: "small" | "medium" | "large" | "huge" (or a multiplier); unset = the plugin default. */ + hexNameSize?: string; + /** Hex-name style: "bold" | "bold italic" | "regular" | "italic"; unset = the plugin default. */ + hexNameStyle?: string; staggerOffset?: "odd" | "even"; // undefined = inherit global setting /** Slot on a shared grid of neighbouring regions (see src/worldgen/world.ts). */ world?: { id: string; cx: number; cy: number }; @@ -283,6 +289,10 @@ export interface HexmakerPluginSettings { advancedNudgeOff?: boolean; /** True once existing palettes got terrain types (one-time seeding). */ terrainTypesSeeded: boolean; + /** Default hex-name font for maps without their own (NM3; see hexNameFont.ts). Unset = theme font, medium, bold. */ + hexNameFont?: string; + hexNameSize?: string; + hexNameStyle?: string; /** Terrain legend on the map and generator previews. Unset = shown. */ showTerrainLegend?: boolean; /** The map export form's last choices, per map name (round 6 S9). */ diff --git a/styles.css b/styles.css index 0f35d061..efedda1b 100644 --- a/styles.css +++ b/styles.css @@ -7493,7 +7493,37 @@ button.duckmage-terrain-legend-chip { .duckmage-overlay-group-title { font-size: 0.8em; color: var(--text-muted); + display: flex; + align-items: center; +} +/* "Aa": unfolds the hex-name font row (NM3) */ +.duckmage-overlay-group-title button.duckmage-overlay-font-btn { + margin-left: auto; + font-size: 1em; + padding: 0 5px; + height: 1.6em; + box-shadow: none; } +.duckmage-overlay-group-title button.duckmage-overlay-font-btn.is-open { + background: var(--interactive-accent); + color: var(--text-on-accent); +} +.duckmage-overlay-font-row { + flex-wrap: wrap; + align-items: center; + padding: 4px 0 2px 0; + max-width: 15em; +} +.duckmage-overlay-font-row .duckmage-overlay-sizes { margin-left: 0; } +.duckmage-overlay-font-row select.duckmage-overlay-font-family { + font-size: 0.8em; + height: 1.8em; + padding-top: 0; + padding-bottom: 0; +} +.duckmage-overlay-font-row .duckmage-overlay-font-bold { font-weight: 700; } +.duckmage-overlay-font-row .duckmage-overlay-font-italic { font-style: italic; } +.duckmage-overlay-font-row .duckmage-overlay-font-reset { padding: 0 2px; height: auto; } .duckmage-overlay-group-row { display: flex; flex-wrap: wrap; @@ -7522,7 +7552,10 @@ button.duckmage-terrain-legend-chip { scales with the zoom. Lines break only at spaces (round 7 R7). */ transform: translate(calc(-50% + var(--duckmage-name-dx, 0em)), calc(-50% + var(--duckmage-name-dy, 0em))); font-size: var(--duckmage-name-font, 0.95em); - font-weight: 700; + /* The map's name font (NM3), set on the layer by renderHexNameLayer. */ + font-family: var(--duckmage-name-family, inherit); + font-weight: var(--duckmage-name-weight, 700); + font-style: var(--duckmage-name-style, normal); line-height: 1.1; --duckmage-name-ink: var(--text-normal); --duckmage-name-halo: var(--background-primary); diff --git a/tests/freshEyesR7b.test.ts b/tests/freshEyesR7b.test.ts index 8d0113da..43e06b24 100644 --- a/tests/freshEyesR7b.test.ts +++ b/tests/freshEyesR7b.test.ts @@ -66,7 +66,8 @@ describe("S13: installing a palette gives its terrains their tables", () => { it("installPalettePreset creates terrain tables when the vault uses them", () => { const src = read("src", "HexmakerPlugin.ts"); const m = /async installPalettePreset[\s\S]*?\n {2}\}/.exec(src); - expect(m![0]).toMatch(/await this\.ensureTerrainTables\(palette\.terrains\)/); + // HG5: the save gives new terrains their tables; the install waits for them. + expect(m![0]).toMatch(/await this\.ensureTablesForNewTerrains\(\)/); }); }); diff --git a/tests/helpers/simVault.ts b/tests/helpers/simVault.ts index 7c1a1388..3ba2ac21 100644 --- a/tests/helpers/simVault.ts +++ b/tests/helpers/simVault.ts @@ -274,6 +274,7 @@ export class MockApp { // ─── Plugin ──────────────────────────────────────────────────────────────── import { DEFAULT_SETTINGS } from "../../src/constants"; +import { sectionKindFor, sectionWordsFor } from "../../src/mapKinds"; import type { HexmakerPluginSettings } from "../../src/types"; export class MockHexmakerPlugin { @@ -306,6 +307,11 @@ export class MockHexmakerPlugin { ?.terrains ?? this.settings.terrainPalettes[0]?.terrains ?? [] ); } + + /** Section display words by map type (G4b), from the map's own palette. */ + sectionWordsFor(mapName: string | undefined) { + return sectionWordsFor(sectionKindFor(mapName ? [this.getMapPalette(mapName)] : [])); + } } function makeSimSettings(): HexmakerPluginSettings { diff --git a/tests/hexNames.test.ts b/tests/hexNames.test.ts index 42fb831c..97038d6a 100644 --- a/tests/hexNames.test.ts +++ b/tests/hexNames.test.ts @@ -174,7 +174,7 @@ describe("X1: handout options", () => { }); // ── Round 6: readable names (S4, U5), token names (S8), PNG labels (S5) ──── -import { balancedLines, ellipsize, hexHalfWidthAt, hexNameTone, layoutHexName, NAME_MAX_FONT_EM, NAME_MIN_FONT_EM, NAME_LINE_HEIGHT } from "../src/hex-map/hexNameLayer"; +import { balancedLines, hexHalfWidthAt, hexNameTone, layoutHexName, NAME_MAX_FONT_EM, NAME_MIN_FONT_EM, NAME_LINE_HEIGHT } from "../src/hex-map/hexNameLayer"; import { clampLabelTop, clampLabelX, pngBadgeCircles, wrapHexName } from "../src/export/handoutLabels"; import { readFileSync as readCss } from "node:fs"; @@ -214,14 +214,14 @@ describe("hex names stay inside their hex (round 6 U5, round 7 R7)", () => { const l = layoutHexName("Hut", flat); expect(l.lines).toEqual(["Hut"]); expect(l.fontEm).toBe(NAME_MAX_FONT_EM); - expect(l.cut).toBe(false); + expect(l.overflow).toBe(false); }); it("never breaks inside a word (the tester saw 'The / Drowne', 'Gullmout / h')", () => { for (const o of [flat, pointy]) { for (const name of ["The Drowned Abbey", "Gullmouth", "Saltmere Keep", "Hermit's Hut"]) { const l = layoutHexName(name, o); - expect(l.cut).toBe(false); + expect(l.overflow).toBe(false); // Joined back with spaces, the lines are exactly the name. expect(l.lines.join(" ")).toBe(name); expect(l.lines.length).toBeLessThanOrEqual(3); @@ -247,29 +247,25 @@ describe("hex names stay inside their hex (round 6 U5, round 7 R7)", () => { it("uses a third line rather than cutting a name beside the badges", () => { // Flat hex, one M badge at the right: the tester's dungeon. const l = layoutHexName("The Drowned Abbey", { ...flat, rightLimit: 2.55 - 1.2 - 0.08 }); - expect(l.cut).toBe(false); + expect(l.overflow).toBe(false); expect(l.lines.join(" ")).toBe("The Drowned Abbey"); expect(l.dxEm).toBeLessThan(0); // shifted left, clear of the badge }); - it("ellipsizes a word too wide even at the smallest size", () => { + it("lets a word too wide even at the smallest size spill past the hex, whole (NM3)", () => { const l = layoutHexName("Supercalifragilisticexpialidocious", flat); - expect(l.lines).toHaveLength(1); - expect(l.lines[0].endsWith("…")).toBe(true); - expect(l.cut).toBe(true); + expect(l.lines).toEqual(["Supercalifragilisticexpialidocious"]); + expect(l.overflow).toBe(true); expect(l.fontEm).toBe(NAME_MIN_FONT_EM); - expect(fitsInHex(l, flat)).toBe(true); }); - it("cuts a name that needs more than three lines after whole words", () => { + it("puts a very long name on three lines of whole words, never cut (NM3)", () => { const name = "Old Mill of the Fens by the Long Grey Lake of Kings"; const l = layoutHexName(name, flat); expect(l.lines.length).toBeLessThanOrEqual(3); - expect(l.cut).toBe(true); - expect(l.lines[l.lines.length - 1].endsWith("…")).toBe(true); - // The lines before the last hold whole words only. - expect(name.startsWith(l.lines.slice(0, -1).join(" ") + " ")).toBe(true); - expect(fitsInHex(l, flat)).toBe(true); + expect(l.lines.join(" ")).toBe(name); + expect(l.lines.join("")).not.toContain("…"); + expect(l.overflow).toBe(true); }); it("sits on the side away from the coordinates", () => { @@ -280,13 +276,6 @@ describe("hex names stay inside their hex (round 6 U5, round 7 R7)", () => { expect(mid.dyEm - (NAME_LINE_HEIGHT * mid.fontEm) / 2).toBeGreaterThanOrEqual(0.5 - 1e-3); }); - it("ellipsize keeps what fits and adds an ellipsis", () => { - expect(ellipsize("Abbey", 10, measure)).toBe("Abbey"); - const cut = ellipsize("Abbeyfield", 3, measure); - expect(cut.endsWith("…")).toBe(true); - expect(measure(cut)).toBeLessThanOrEqual(3); - }); - it("lets CSS show the computed lines as they are (no CSS word breaking)", () => { const css = readCss("styles.css", "utf8"); const at = css.indexOf(".duckmage-hex-name-label {"); diff --git a/tests/mapMarkers.test.ts b/tests/mapMarkers.test.ts index 8896968c..340ca2f8 100644 --- a/tests/mapMarkers.test.ts +++ b/tests/mapMarkers.test.ts @@ -262,7 +262,8 @@ describe("badge size (round 7 R8)", () => { const limit = badgeNameLimit(s, flat, n); expect(limit).toBeLessThan(chipsLeft); for (const name of ["Gullmouth", "The Drowned Abbey", "Hut"]) { - const l = layoutHexName(name, { measure, hexW: flat ? 4.4 : 3.81, hexH: flat ? 3.81 : 4.4, flat, rightLimit: limit }); + // Zoomed in enough that the readable floor (NM3) leaves room to shrink. + const l = layoutHexName(name, { measure, hexW: flat ? 4.4 : 3.81, hexH: flat ? 3.81 : 4.4, flat, rightLimit: limit, floorEm: 0.1 }); const widest = Math.max(...l.lines.map(measure)) * l.fontEm; expect(l.dxEm + widest / 2).toBeLessThanOrEqual(limit + 1e-6); } diff --git a/tests/r3Labels.test.ts b/tests/r3Labels.test.ts new file mode 100644 index 00000000..5ead45e2 --- /dev/null +++ b/tests/r3Labels.test.ts @@ -0,0 +1,311 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import { layoutHexName, NAME_LINE_HEIGHT, NAME_MAX_FONT_EM, NAME_MIN_FONT_EM } from "../src/hex-map/hexNameLayer"; +import { + DEFAULT_NAME_FONT, + MIN_NAME_SCREEN_PX, + NAME_FONT_STACKS, + nameFontShorthand, + nameSizeId, + nameStyleId, + parseNameFamily, + parseNameSize, + parseNameStyle, + readableFloorEm, + resolveNameFont, +} from "../src/hex-map/hexNameFont"; +import { pngHexNamePx } from "../src/export/handoutLabels"; +import { buildMapNote, parseMapNote, readMapNote, type MapNoteData } from "../src/maps/mapNote"; +import { + DEFAULT_SECTION_WORDS, + MAP_KINDS, + newTerrains, + sectionKindFor, + sectionWords, + sectionWordsFor, + terrainsForTables, + type MapKindInfo, +} from "../src/mapKinds"; +import { linkedNotesText } from "../src/hex-map/linkBadges"; +import { hexTableLines, type HexRow } from "../src/export/exporters/mapWithTable"; +import { buildManualHtml } from "../src/export/manual/manualHtml"; +import type { ManualData, ManualHex } from "../src/export/manual/manualModel"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; + +const read = (...p: string[]) => readFileSync(p.join("/"), "utf8"); + +// ── NM3: hex names always legible, overflow allowed, font options ────────── + +// A bold sans font: about 0.6em a character, narrower for i/l/space. +const measure = (t: string) => [...t].reduce((w, c) => w + (c === " " ? 0.28 : /[il.']/.test(c) ? 0.3 : /[mwMW]/.test(c) ? 0.9 : 0.6), 0); +const flat = { measure, hexW: 4.4, hexH: 3.81, flat: true }; +const pointy = { measure, hexW: 3.81, hexH: 4.4, flat: false }; +const NAMES = ["Hut", "Gullmouth", "The Drowned Abbey", "Old Mill of the Fens by the Long Grey Lake", "Supercalifragilisticexpialidocious"]; + +describe("NM3: hex names keep a readable size on screen", () => { + it("works out the floor from the grid's font and the zoom", () => { + expect(readableFloorEm(16, 1)).toBeCloseTo(MIN_NAME_SCREEN_PX / 16); + expect(readableFloorEm(16, 0.5)).toBeCloseTo(MIN_NAME_SCREEN_PX / 8); + expect(readableFloorEm(40, 1)).toBeCloseTo(MIN_NAME_SCREEN_PX / 40); + expect(MIN_NAME_SCREEN_PX).toBeGreaterThanOrEqual(10); + expect(MIN_NAME_SCREEN_PX).toBeLessThanOrEqual(11); + }); + + it("never sets a name smaller than the floor, at any zoom", () => { + for (const o of [flat, pointy]) { + for (const gridPx of [4, 6, 9, 16, 30, 60]) { + const floorEm = readableFloorEm(gridPx, 1); + for (const name of NAMES) { + const l = layoutHexName(name, { ...o, floorEm }); + // On screen: font em × grid px ≥ the minimum. + expect(l.fontEm * gridPx).toBeGreaterThanOrEqual(MIN_NAME_SCREEN_PX - 0.01); + } + } + } + }); + + it("on a fitted 20×16 map (tiny hexes) long names spill past the hex at the readable size", () => { + // About 6px per grid em when a 20×16 map fits a laptop view. + const floorEm = readableFloorEm(6, 1); + expect(floorEm).toBeGreaterThan(NAME_MAX_FONT_EM); + const l = layoutHexName("The Drowned Abbey", { ...flat, floorEm }); + expect(l.fontEm).toBeCloseTo(floorEm, 2); + expect(l.overflow).toBe(true); + expect(l.lines.join(" ")).toBe("The Drowned Abbey"); + }); + + it("wraps only at spaces and never cuts, even when spilling", () => { + for (const o of [flat, pointy]) { + for (const floorEm of [undefined, 0.2, 0.7, 1.5, 3]) { + for (const name of NAMES) { + const l = layoutHexName(name, { ...o, floorEm }); + expect(l.lines.join(" ")).toBe(name); + expect(l.lines.join("")).not.toContain("…"); + expect(l.lines.length).toBeLessThanOrEqual(3); + } + } + } + }); + + it("spills away from the coordinates, not over them", () => { + const floorEm = 2; // far bigger than the hex allows + const name = "Old Mill of the Fens"; + // Coordinates at the bottom: the label's lower edge stays near the centre. + const up = layoutHexName(name, { ...flat, floorEm, coords: "bottom" }); + const h = up.lines.length * NAME_LINE_HEIGHT * up.fontEm; + expect(up.dyEm + h / 2).toBeLessThanOrEqual(0.35 + 1e-3); + // Coordinates at the top: its upper edge does. + const down = layoutHexName(name, { ...flat, floorEm, coords: "top" }); + const h2 = down.lines.length * NAME_LINE_HEIGHT * down.fontEm; + expect(down.dyEm - h2 / 2).toBeGreaterThanOrEqual(-0.35 - 1e-3); + }); + + it("zoomed in, a long name shrinks to stay inside its hex rather than spill", () => { + const l = layoutHexName("Old Mill of the Fens by the Long Grey Lake", { ...flat, floorEm: 0.1 }); + expect(l.overflow).toBe(false); + expect(l.fontEm).toBeLessThan(NAME_MIN_FONT_EM); + }); + + it("scales the size with the map's name size", () => { + expect(layoutHexName("Hut", { ...flat, scale: 1.5 }).fontEm).toBeCloseTo(NAME_MAX_FONT_EM * 1.5, 3); + expect(layoutHexName("Hut", { ...flat, scale: 0.85 }).fontEm).toBeCloseTo(NAME_MAX_FONT_EM * 0.85, 3); + // A bigger size can't push a name below the readable floor either. + const l = layoutHexName("The Drowned Abbey", { ...flat, scale: 1.5, floorEm: 0.9 }); + expect(l.fontEm).toBeGreaterThanOrEqual(0.9); + }); + + it("keeps the labels' CSS in step: font from the layer, lines as computed", () => { + const css = read("styles.css"); + const at = css.indexOf(".duckmage-hex-name-label {"); + const rule = css.slice(at, css.indexOf("}", at)); + expect(rule).toMatch(/font-family:\s*var\(--duckmage-name-family/); + expect(rule).toMatch(/font-weight:\s*var\(--duckmage-name-weight/); + expect(rule).toMatch(/font-style:\s*var\(--duckmage-name-style/); + expect(rule).toMatch(/white-space:\s*pre/); + }); + + it("redraws names when the zoom settles (the floor depends on it)", () => { + const src = read("src", "hex-map", "HexMapView.ts"); + expect(src).toMatch(/if \(this\.zoom !== this\.namesZoom\)/); + expect(src).toMatch(/renderHexNameLayer\([^)]*font, this\.zoom\)/); + }); +}); + +describe("NM3: hex-name font options", () => { + it("reads font, size and style forgivingly", () => { + expect(parseNameFamily("Serif")).toBe("serif"); + expect(parseNameFamily("sans-serif")).toBe("sans"); + expect(parseNameFamily("Handwritten")).toBe("handwritten"); + expect(parseNameFamily("script")).toBe("handwritten"); + expect(parseNameFamily("theme")).toBe("theme"); + expect(parseNameFamily("comic")).toBeUndefined(); + expect(parseNameSize("large")).toBe(1.25); + expect(parseNameSize("XL")).toBe(1.5); + expect(parseNameSize("120%")).toBeCloseTo(1.2); + expect(parseNameSize("1.1")).toBeCloseTo(1.1); + expect(parseNameSize(9)).toBe(3); // clamped + expect(parseNameSize("big")).toBeUndefined(); + expect(parseNameStyle("Bold Italic")).toEqual({ bold: true, italic: true }); + expect(parseNameStyle("regular")).toEqual({ bold: false, italic: false }); + expect(parseNameStyle("italic")).toEqual({ bold: false, italic: true }); + expect(parseNameStyle("fancy")).toBeUndefined(); + }); + + it("uses the map's choice, then the plugin default, then bold theme medium", () => { + expect(resolveNameFont(undefined, undefined)).toEqual(DEFAULT_NAME_FONT); + const global = { hexNameFont: "serif", hexNameSize: "large", hexNameStyle: "italic" }; + expect(resolveNameFont({}, global)).toMatchObject({ family: "serif", size: "large", bold: false, italic: true }); + // Per key: the map overrides only what it sets; junk falls through. + expect(resolveNameFont({ hexNameFont: "handwritten", hexNameSize: "junk" }, global)) + .toMatchObject({ family: "handwritten", size: "large", italic: true }); + expect(nameSizeId(1.1)).toBeNull(); + expect(nameStyleId(true, true)).toBe("bold italic"); + expect(nameStyleId(false, false)).toBe("regular"); + }); + + it("builds the same font for the canvas (PNG) as on screen", () => { + const f = resolveNameFont({ hexNameFont: "serif", hexNameStyle: "bold italic" }, undefined); + expect(nameFontShorthand(f, 14, "Inter")).toBe(`italic 700 14px ${NAME_FONT_STACKS.serif}`); + expect(nameFontShorthand(DEFAULT_NAME_FONT, 12, "Inter")).toBe("700 12px Inter"); + }); + + it("bundles no fonts: every stack ends in a generic family", () => { + for (const stack of Object.values(NAME_FONT_STACKS)) expect(stack).toMatch(/(serif|sans-serif|cursive)$/); + }); + + it("sizes PNG names by the map's size, never below the readable minimum", () => { + expect(pngHexNamePx(100)).toBe(27); + expect(pngHexNamePx(100, 1.5)).toBe(41); + expect(pngHexNamePx(10, 0.85)).toBe(MIN_NAME_SCREEN_PX); + const src = read("src", "export", "mapPngRenderer.ts"); + expect(src).toMatch(/resolveNameFont\(map, plugin\.settings\)/); + expect(src).toMatch(/pngHexNamePx\(R, nameFont\.scale\)/); + }); + + it("stores the font in the map note as plain keys, and flags unreadable ones", () => { + const data: MapNoteData = { + settings: { paletteName: "Default", gridSize: { cols: 3, rows: 2 }, gridOffset: { x: 0, y: 0 }, hexNameFont: "serif", hexNameSize: "large", hexNameStyle: "bold italic" }, + hexes: new Map(), + paths: [], + }; + const note = buildMapNote("m", data); + expect(note).toContain("name-font: serif"); + expect(note).toContain("name-size: large"); + expect(note).toContain("name-style: bold italic"); + const back = parseMapNote(note)!; + expect(back.settings).toMatchObject({ hexNameFont: "serif", hexNameSize: "large", hexNameStyle: "bold italic" }); + // Typed by hand: read as written, a typo is listed (and kept), not fatal. + const typo = readMapNote(note.replace("name-font: serif", "name-font: Gothic").replace("name-size: large", "name-size: 130%")); + expect(typo?.ok).toBe(true); + if (!typo?.ok) return; + expect(typo.data.settings.hexNameSize).toBe("130%"); + expect(typo.data.problems?.some((p) => p.key === "name-font")).toBe(true); + }); + + it("has the font row in the layers menu Labels group, and the default in settings (both paths)", () => { + const panel = read("src", "hex-map", "HexSidePanel.ts"); + expect(panel).toMatch(/buildNameFontRow\(labelTitle, labelGroup\)/); + const tab = read("src", "HexmakerSettingTab.ts"); + expect(tab).toMatch(/key: "hexNameFont"/); + expect(tab).toMatch(/\.setName\("Hex name font"\)/); + }); +}); + +// ── G4b: space-flavoured section names, by map type ──────────────────────── + +const space = MAP_KINDS.find((k) => k.id === "space")!; + +describe("G4b: link section words follow the map type", () => { + it("uses the usual words with no map type", () => { + for (const [s, w] of Object.entries(DEFAULT_SECTION_WORDS)) expect(sectionWords(s)).toEqual(w); + expect(sectionWords("towns").label).toBe("Towns"); // any case + }); + + it("space maps say Settlements, Sites, Points of Interest, Missions", () => { + const w = sectionWordsFor(space); + expect(w("Towns")).toEqual({ label: "Settlements", one: "Settlement", noun: "a settlement" }); + expect(w("dungeons").label).toBe("Sites"); + expect(w("Features").label).toBe("Points of Interest"); + expect(w("Quests").label).toBe("Missions"); + // Not listed: the usual words. + expect(w("Factions").label).toBe("Factions"); + expect(w("Encounters Table").label).toBe("Encounters Table"); + }); + + it("finds the type from the palette's terrain types, then the parents' (not from names)", () => { + expect(sectionKindFor([SPACE_SECTOR_TERRAINS])).toBe(space); + expect(sectionKindFor([SPACE_SYSTEM_TERRAINS])).toBe(space); + expect(sectionKindFor([DEFAULT_TERRAIN_PALETTE])).toBeUndefined(); + // A planet surface (world terrains) under a star system keeps the space words. + expect(sectionKindFor([DEFAULT_TERRAIN_PALETTE, SPACE_SYSTEM_TERRAINS])).toBe(space); + // A palette named "Space" with no space types is not space. + expect(sectionKindFor([[{ type: "forest" }]])).toBeUndefined(); + }); + + it("is data: any map type with section words gets them", () => { + const custom: MapKindInfo = { ...space, id: "space", sectionWords: { Towns: { label: "Habitats", one: "Habitat", noun: "a habitat" } } }; + expect(sectionWordsFor(sectionKindFor([[{ type: "void" }]], [custom]))("Towns").label).toBe("Habitats"); + }); + + it("names links in the hover text, the PDF table and the manual in those words", () => { + const w = sectionWordsFor(space); + expect(linkedNotesText(new Map([["Towns", ["Kerrigan IV"]], ["Dungeons", ["A", "B"]]]), w)).toBe("Settlement: Kerrigan IV · Sites: A, B"); + const row: HexRow = { hex: "1, 1", name: "", terrain: "void", towns: "Port", dungeons: "", features: "", quests: "", factions: "", encounters: "", description: "" }; + expect(hexTableLines([row], ["towns"], w)[0]).toBe("| Hex | Settlements |"); + expect(hexTableLines([row], ["towns"])[0]).toBe("| Hex | Towns |"); + const noLinks = { towns: [], dungeons: [], features: [], quests: [], factions: [] }; + const hex: ManualHex = { number: "0101", x: 0, y: 0, terrain: "void", landmark: "", description: "", hidden: "", secret: "", weather: "", hooks: "", links: { ...noLinks, towns: ["Port"] } }; + const d: ManualData = { + title: "m", version: "1", date: "2026-10-10", hexCount: 1, keyedCount: 1, player: true, numberDigits: 2, + overviewMapUri: "data:,", legend: [], paths: [], tables: [], factions: [], regions: [], + sections: [{ label: "A1", range: "0101–0101", mapUri: "data:,", hexes: [hex] }], + index: [], linkLabels: { towns: "Settlements" }, + }; + expect(buildManualHtml(d)).toContain("Settlements"); + }); + + it("is wired into the hex editor, hex table, badges legend and exports", () => { + expect(read("src", "hex-map", "HexEditorModal.ts")).toMatch(/sectionWordsFor\(this\.mapName\)\(section\)/); + expect(read("src", "hex-table", "HexTableView.ts")).toMatch(/this\.colLabel\(col\)/); + expect(read("src", "hex-map", "HexMapView.ts")).toMatch(/label: words\(s\)\.label/); + expect(read("src", "export", "mapPngRenderer.ts")).toMatch(/name: sectionWords\(s\)\.label/); + expect(read("src", "export", "exporters", "singleHex.ts")).toMatch(/sectionWordsFor\(/); + expect(read("src", "export", "exporters", "hexcrawlManual.ts")).toMatch(/linkLabels:/); + }); +}); + +// ── HG5: every terrain gets (empty) tables when it's created ─────────────── + +describe("HG5: new terrains get their tables", () => { + it("spots terrains not seen before, once each", () => { + const known = new Set(["forest", "hills"]); + const now = [{ name: "forest" }, { name: "lava" }, { name: "hills" }, { name: "lava" }, { name: "ash" }]; + expect(newTerrains(known, now).map((t) => t.name)).toEqual(["lava", "ash"]); + expect(newTerrains(new Set(["lava", "ash", "forest", "hills"]), now)).toEqual([]); + }); + + it("covers every palette a map uses, even one of a map type that's off", () => { + const world = { name: "Limited", terrains: [{ name: "forest" }] }; + const sector = { name: "Sector", terrains: SPACE_SECTOR_TERRAINS }; + // Space only: the fantasy palette is skipped (G4) … + expect(terrainsForTables([world, sector], ["space"]).some((t) => t.name === "forest")).toBe(false); + // … unless a map uses it. + expect(terrainsForTables([world, sector], ["space"], ["Limited"]).some((t) => t.name === "forest")).toBe(true); + }); + + it("runs after every save and palette-note import, creates empty tables, and moves them on rename", () => { + const src = read("src", "HexmakerPlugin.ts"); + const save = /async saveSettings\(\)[\s\S]*?\n {2}\}/.exec(src)![0]; + expect(save).toMatch(/void this\.ensureTablesForNewTerrains\(\)/); + expect(read("src", "palettes", "PaletteStore.ts")).toMatch(/ensureTablesForNewTerrains\(\)/); + const create = /private async createTerrainTableFiles[\s\S]*?\n {2}\}/.exec(src)![0]; + // The usual template with no rows: makeTableTemplate(dice, fm, link) — no 4th (rows) argument. + expect(create).toMatch(/this\.buildRollerLink\(\),\n\s*\),/); + const rename = /private async renameTerrainTables[\s\S]*?\n {2}\}/.exec(src)![0]; + expect(rename).toMatch(/fileManager\.renameFile\(oldFile, newPath\)/); + // A new terrain named in its editor moves its placeholder's tables. + expect(read("src", "hex-map", "TerrainEntryEditorModal.ts")).toMatch(/if \(nameChanged\) await this\.plugin\.renameTerrain\(this\.entry, this\.pendingName\)/); + }); +}); From 80dcb015d1149bd242709a7b93fbb28de90d671e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 18:35:22 -0400 Subject: [PATCH 223/558] feat(palettes): savanna and river delta in Expanded, added once to existing copies (OW8) - Expanded gains "savanna" (grassland type) and "river delta" (wetland); World biomes paints the savanna and river-delta biomes with them. - Existing installs: presetUpdates.ts offers terrains added to a bundled palette after it shipped to the installed copy ONCE (remembered in settings.presetTerrainsAdded), after a backup of the palette notes. A terrain of that name the user already has is never touched; a deleted one is never re-added; a palette that merely shares the name (few of the preset's terrains) is left alone. Generic: any preset can list additions. - World biomes: rare transition biomes count toward the rare cap. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/constants.ts | 12 ++++++ src/overworld/biomes.ts | 3 +- src/palettes/PaletteStore.ts | 42 ++++++++++++++++++- src/palettes/presetUpdates.ts | 77 +++++++++++++++++++++++++++++++++++ tests/overworldBiomes.test.ts | 11 +++-- tests/presetTerrains.test.ts | 66 ++++++++++++++++++++++++++++++ 7 files changed, 206 insertions(+), 9 deletions(-) create mode 100644 src/palettes/presetUpdates.ts create mode 100644 tests/presetTerrains.test.ts diff --git a/package.json b/package.json index 970bdd10..78eb9807 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/overworldRender.test.ts tests/overworldRegionWorld.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/overworldRender.test.ts tests/overworldRegionWorld.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/presetTerrains.test.ts tests/overworldRender.test.ts tests/overworldRegionWorld.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/presetTerrains.test.ts tests/overworldRender.test.ts tests/overworldRegionWorld.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/constants.ts b/src/constants.ts index 161ec1ba..4f724034 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -312,6 +312,17 @@ export const DEFAULT_TERRAIN_PALETTE: TerrainColor[] = [ icon: "bw-dunes.png", category: "coast", }, + // Added after release (OW8): the World biomes generator paints savanna and + // river delta overworld hexes with these. Existing Expanded palettes get + // them once (src/palettes/presetUpdates.ts, ADDED_PRESET_TERRAINS). + { name: "savanna", type: "grassland", color: "#c4b25c", icon: "bw-grassland.png", category: "lowlands" }, + { name: "river delta", type: "wetland", color: "#5f9a7a", icon: "bw-marsh.png", category: "bog" }, +]; + +/** Terrains added to a bundled palette after it shipped: offered once to installed copies. */ +export const ADDED_PRESET_TERRAINS: { preset: string; terrain: string }[] = [ + { preset: EXPANDED_PALETTE_NAME, terrain: "savanna" }, + { preset: EXPANDED_PALETTE_NAME, terrain: "river delta" }, ]; export const LIMITED_TERRAIN_PALETTE: TerrainColor[] = [ @@ -400,4 +411,5 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { advancedFeatures: [], dismissedHints: [], terrainTypesSeeded: false, + presetTerrainsAdded: [], }; diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index 982d805f..cb90e28e 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -127,10 +127,11 @@ const REPRESENTATIVE: Record = { "temperate-forest": ["mixed forest", "forest"], "deep-forest": ["forest heavy", "mixed forest heavy"], grassland: ["grass"], - savanna: ["cactus", "cactus heavy"], + savanna: ["savanna", "cactus", "cactus heavy"], jungle: ["jungle", "jungle heavy"], badlands: ["badlands", "desert rocky", "desert"], swamp: ["swamp", "marsh", "bog"], + "river-delta": ["river delta"], valley: ["hills", "foothills"], karst: ["jungle hills"], alpine: ["mountain", "mountains snow", "peak"], diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index cfdee4bf..46ece364 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -16,7 +16,9 @@ import { } from "./paletteNote"; import { PALETTE_PRESETS, uniquePaletteName } from "./presets"; import { clonePathTypes, parsePathTypes, pathTypesKey, setPathTypes } from "./pathTypeTable"; -import { DEFAULT_PATH_TYPES } from "../constants"; +import { ADDED_PRESET_TERRAINS, DEFAULT_PATH_TYPES } from "../constants"; +import { applyPresetTerrains, planPresetTerrains } from "./presetUpdates"; +import { writeJsonBackup } from "../backup"; import { inferTerrainType } from "../terrainTypes"; /** @@ -261,6 +263,9 @@ export class PaletteStore { } if (await this.loadAll()) dirty = true; + // Terrains added to a bundled palette since it was installed: once each. + const added = await this.addNewPresetTerrains(); + if (added) dirty = true; // Path types moved from settings into palettes: every palette without // them gets the full old list, and the notes get their table below. const filled = fillPalettePathTypes(settings.terrainPalettes, settings.pathTypes) > 0; @@ -278,7 +283,7 @@ export class PaletteStore { // Write seeded types into the notes now, in the same queued step. Queued // separately, an unload in between left notes untyped while settings // said seeding was done — and notes win on the next load. - if (seeded || filled) await this.syncNow(); + if (seeded || filled || added) await this.syncNow(); if (dirty) await this.persist(); } @@ -336,6 +341,39 @@ export class PaletteStore { }); } + /** + * Give installed copies of bundled palettes the terrains added to them + * since (OW8), once each, after backing up the palette notes. A terrain + * the palette already has is left exactly as the user made it. Returns + * true when anything changed (settings or palettes). + */ + private async addNewPresetTerrains(): Promise { + const settings = this.plugin.settings; + const done = new Set(settings.presetTerrainsAdded ?? []); + const plan = planPresetTerrains(settings.terrainPalettes, ADDED_PRESET_TERRAINS, done, (n) => PALETTE_PRESETS.find((p) => p.name === n)?.terrains); + if (!plan.done.length) return false; + if (plan.add.length) { + try { + const notes: Record = {}; + for (const { palette } of plan.add) { + const path = this.boundPath.get(palette); + if (path) notes[path] = this.lastContent.get(path) ?? ""; + } + const dir = `${this.plugin.manifest.dir}/backups/palettes-${new Date().toISOString().slice(0, 10)}`; + await writeJsonBackup(this.plugin.app.vault.adapter, dir, "palettes-before-new-terrains", JSON.stringify({ savedAt: new Date().toISOString(), notes })); + } catch (e) { + // No backup, no change: try again next start. + console.error("Hexmap World Creator: couldn't back up palette notes; new terrains not added", e); + return false; + } + applyPresetTerrains(plan); + const what = plan.add.map(({ palette, terrains }) => `${terrains.map((t) => t.name).join(", ")} to "${palette.name}"`).join("; "); + new Notice(`Hexmap World Creator: added ${what}.`); + } + settings.presetTerrainsAdded = [...done, ...plan.done]; + return true; + } + private async persist(): Promise { await this.plugin.saveData(this.plugin.settings); this.plugin.refreshHexMap(); diff --git a/src/palettes/presetUpdates.ts b/src/palettes/presetUpdates.ts new file mode 100644 index 00000000..e20ec341 --- /dev/null +++ b/src/palettes/presetUpdates.ts @@ -0,0 +1,77 @@ +/** + * Terrains added to a bundled palette after people installed it (OW8: + * "savanna" and "river delta" in Expanded). Each is offered to an installed + * copy of that palette ONCE: added when the palette doesn't have a terrain + * of that name, then remembered as done, so a user who deletes or renames + * it never gets it back, and a terrain they already have (their own colour, + * type, icon) is never touched. + * + * Generic: any preset can list new terrains here; nothing is special-cased. + * A palette counts as a copy of the preset when it has the preset's name + * and still shares most of its terrains (an unrelated palette that happens + * to have the name is left alone). + * + * Pure: no Obsidian imports. PaletteStore backs up the palette notes before + * applying the result. + */ + +import type { TerrainColor, TerrainPalette } from "../types"; + +export interface AddedPresetTerrain { + /** Preset (palette) name. */ + preset: string; + /** Terrain name in the preset's terrain list. */ + terrain: string; +} + +/** Share of the preset's (older) terrains a palette must still have to count as its copy. */ +export const COPY_OVERLAP = 0.5; + +/** The once-only key for an entry (stored in settings.presetTerrainsAdded). */ +export const addedKey = (a: AddedPresetTerrain): string => `${a.preset}/${a.terrain}`.toLowerCase(); + +export interface PresetTerrainPlan { + /** Terrains to append, per palette (the palette objects themselves). */ + add: { palette: TerrainPalette; terrains: TerrainColor[] }[]; + /** Keys to remember as done (offered, whether added or not). */ + done: string[]; +} + +/** + * Which new preset terrains go into which installed palettes. `presetTerrains` + * looks a preset's current terrains up by name. Nothing is changed here. + */ +export function planPresetTerrains( + palettes: TerrainPalette[], + entries: AddedPresetTerrain[], + alreadyDone: ReadonlySet, + presetTerrains: (preset: string) => TerrainColor[] | undefined, +): PresetTerrainPlan { + const add = new Map(); + const done: string[] = []; + for (const e of entries) { + const key = addedKey(e); + if (alreadyDone.has(key)) continue; + const preset = presetTerrains(e.preset); + const fresh = preset?.find((t) => t.name.toLowerCase() === e.terrain.toLowerCase()); + if (!preset || !fresh) continue; // not shipped (yet): try again next time + done.push(key); + const pal = palettes.find((p) => p.name === e.preset); + if (!pal) continue; // not installed: a later install copies the preset as it is now + const names = new Set(pal.terrains.map((t) => t.name.toLowerCase())); + const newNames = new Set(entries.filter((x) => x.preset === e.preset).map((x) => x.terrain.toLowerCase())); + const older = preset.filter((t) => !newNames.has(t.name.toLowerCase())); + const kept = older.filter((t) => names.has(t.name.toLowerCase())).length; + if (older.length && kept / older.length < COPY_OVERLAP) continue; + if (names.has(fresh.name.toLowerCase())) continue; + const list = add.get(pal) ?? []; + if (!list.some((t) => t.name.toLowerCase() === fresh.name.toLowerCase())) list.push({ ...fresh }); + add.set(pal, list); + } + return { add: [...add].map(([palette, terrains]) => ({ palette, terrains })), done }; +} + +/** Apply a plan: append the terrains to each palette. */ +export function applyPresetTerrains(plan: PresetTerrainPlan): void { + for (const { palette, terrains } of plan.add) palette.terrains.push(...terrains.map((t) => ({ ...t }))); +} diff --git a/tests/overworldBiomes.test.ts b/tests/overworldBiomes.test.ts index 65f59b2c..f930b449 100644 --- a/tests/overworldBiomes.test.ts +++ b/tests/overworldBiomes.test.ts @@ -90,16 +90,19 @@ describe("biomes: terrain ↔ biome", () => { } }); - it("Expanded shows every biome but the delta; Limited shows fewer and the rest fall back", () => { + it("Expanded shows every biome (savanna and river delta have their own terrains, OW8); Limited shows fewer and the rest fall back", () => { const exp = representableBiomes(EXP); - expect(exp.size).toBe(BIOMES.length - 1); - expect(exp.has("river-delta")).toBe(false); + expect(exp.size).toBe(BIOMES.length); + expect(representativeTerrain("savanna", EXP)).toBe("savanna"); + expect(representativeTerrain("river-delta", EXP)).toBe("river delta"); + expect(biomeForTerrain("savanna", EXP)).toBe("savanna"); + expect(biomeForTerrain("river delta", EXP)).toBe("river-delta"); const lim = representableBiomes(LIMITED_TERRAIN_PALETTE); expect([...lim].sort()).toEqual(["alpine", "badlands", "grassland", "open-sea", "temperate-forest", "tundra", "valley"]); expect(resolveBiome("taiga", lim)).toBe("tundra"); expect(resolveBiome("jungle", lim)).toBe("temperate-forest"); expect(resolveBiome("archipelago", lim)).toBe("open-sea"); - expect(resolveBiome("river-delta", exp)).toBe("swamp"); + expect(resolveBiome("river-delta", lim)).toBe("grassland"); }); it("ecotones: incompatible pairs and their transitions", () => { diff --git a/tests/presetTerrains.test.ts b/tests/presetTerrains.test.ts new file mode 100644 index 00000000..c9fed5b5 --- /dev/null +++ b/tests/presetTerrains.test.ts @@ -0,0 +1,66 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { ADDED_PRESET_TERRAINS, DEFAULT_TERRAIN_PALETTE, EXPANDED_PALETTE_NAME, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { PALETTE_PRESETS } from "../src/palettes/presets"; +import { addedKey, applyPresetTerrains, planPresetTerrains } from "../src/palettes/presetUpdates"; +import type { TerrainPalette } from "../src/types"; + +const presetTerrains = (n: string) => PALETTE_PRESETS.find((p) => p.name === n)?.terrains; +const NEW = new Set(ADDED_PRESET_TERRAINS.map((a) => a.terrain)); +/** An Expanded palette as installed before OW8. */ +const oldExpanded = (): TerrainPalette => ({ + name: EXPANDED_PALETTE_NAME, + terrains: DEFAULT_TERRAIN_PALETTE.filter((t) => !NEW.has(t.name)).map((t) => ({ ...t })), +}); + +describe("terrains added to a bundled palette (OW8)", () => { + it("ships savanna and river delta in Expanded, typed and coloured", () => { + const sav = DEFAULT_TERRAIN_PALETTE.find((t) => t.name === "savanna")!; + const delta = DEFAULT_TERRAIN_PALETTE.find((t) => t.name === "river delta")!; + expect(sav).toMatchObject({ type: "grassland" }); + expect(delta).toMatchObject({ type: "wetland" }); + expect(sav.color).toMatch(/^#[0-9a-f]{6}$/); + expect(delta.icon).toBeTruthy(); + }); + + it("adds them once to an installed Expanded copy, and records each as done", () => { + const pal = oldExpanded(); + const plan = planPresetTerrains([pal], ADDED_PRESET_TERRAINS, new Set(), presetTerrains); + expect(plan.add).toHaveLength(1); + expect(plan.add[0].terrains.map((t) => t.name)).toEqual(["savanna", "river delta"]); + applyPresetTerrains(plan); + expect(pal.terrains.slice(-2).map((t) => t.name)).toEqual(["savanna", "river delta"]); + expect(plan.done).toEqual(ADDED_PRESET_TERRAINS.map(addedKey)); + // Next start: already done, nothing more. + const again = planPresetTerrains([pal], ADDED_PRESET_TERRAINS, new Set(plan.done), presetTerrains); + expect(again.add).toHaveLength(0); + expect(again.done).toHaveLength(0); + }); + + it("never overwrites a terrain the user already has, and never re-adds one they deleted", () => { + const pal = oldExpanded(); + pal.terrains.push({ name: "Savanna", color: "#000000", type: "desert" }); + const plan = planPresetTerrains([pal], ADDED_PRESET_TERRAINS, new Set(), presetTerrains); + applyPresetTerrains(plan); + expect(pal.terrains.filter((t) => t.name.toLowerCase() === "savanna")).toEqual([{ name: "Savanna", color: "#000000", type: "desert" }]); + expect(pal.terrains.some((t) => t.name === "river delta")).toBe(true); + // The user deletes river delta: once done, it stays deleted. + pal.terrains = pal.terrains.filter((t) => t.name !== "river delta"); + const later = planPresetTerrains([pal], ADDED_PRESET_TERRAINS, new Set(plan.done), presetTerrains); + expect(later.add).toHaveLength(0); + }); + + it("leaves palettes that aren't a copy of the preset alone (other names, or the name on a different palette)", () => { + const limited: TerrainPalette = { name: "Limited", terrains: LIMITED_TERRAIN_PALETTE.map((t) => ({ ...t })) }; + const impostor: TerrainPalette = { name: EXPANDED_PALETTE_NAME, terrains: [{ name: "lava sea", color: "#f00" }] }; + const plan = planPresetTerrains([limited, impostor], ADDED_PRESET_TERRAINS, new Set(), presetTerrains); + expect(plan.add).toHaveLength(0); + expect(plan.done).toHaveLength(2); // offered; not installed as a copy, so never again + expect(impostor.terrains).toHaveLength(1); + }); + + it("works for an empty or custom palette list (nothing installed: nothing to add)", () => { + const plan = planPresetTerrains([], ADDED_PRESET_TERRAINS, new Set(), presetTerrains); + expect(plan.add).toHaveLength(0); + }); +}); From 14f65501b8d7d2e2cff9c371339ce7e5fa9fd256 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 18:35:24 -0400 Subject: [PATCH 224/558] docs(overworld): README/help for overworlds, regions view, biome tool; dev/demo-world.mjs sandbox demo (OW7) Co-Authored-By: Claude Opus 5.5 --- README.md | 13 ++++- dev/demo-seed/.hexmaker-sandbox | 1 + dev/demo-seed/Start here.md | 17 ++++++ dev/demo-world.mjs | 99 +++++++++++++++++++++++++++++++++ src/hex-map/help.md | 4 +- 5 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 dev/demo-seed/.hexmaker-sandbox create mode 100644 dev/demo-seed/Start here.md create mode 100644 dev/demo-world.mjs diff --git a/README.md b/README.md index 5e5ad6a3..8f9e596c 100644 --- a/README.md +++ b/README.md @@ -109,13 +109,23 @@ Organise your world into multiple named hex maps, each stored as a subfolder und ### Generators Maps can be generated instead of painted hex by hex. When you create a map (**Maps → New map…**, or the setup wizard's first map) or a submap (right-click a hex → **New map from this hex…**), pick a generator and preview it before creating. A new map starts on Overland (Star scatter for space-only setups); pick Blank to paint it all yourself. **More** under the form sets the starting coordinates, stagger and a background image (picked from the vault or dropped from your computer), and the **folder name** (made from the name; you can change it later in Map properties). A new submap is named after its hex, or the parent map's name and the hex's coordinates ("Gloomwood 3, 4") if the hex has no name; click the name once to select it all and type your own. +- **World biomes** (Advanced) — an overworld: one biome per hex, laid out by temperature, moisture and height, with transition biomes (taiga between tundra and forest, savanna between jungle and badlands) where two shouldn't touch. Its hexes open into regions that blend with each other. - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it. - **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. Orbits places moons (the *moon* terrain) beside their planets; a system with a planet always has at least one. - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. -**Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which. The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. Regions don't yet blend with their neighbours or fill the parent hex; that comes next. +**Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which. The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. + +**Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and the crumbs next to the map button name all six neighbours by direction ("North-east: Fenmarch"). A new region is made from a short form: biome (the hex's terrain is its biome), blend, how wiggly the borders are, and a seed, with a live preview of the region against its neighbours. It blends with the overworld around it, and the hexes along its edges are pinned to the regions already made, so seams line up whatever order you make them in. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. + +**Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: + +- **Regions** (the full view): every region's own hexes, drawn small and stitched together over the overworld. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Painted hexes are locked, so remaking a region keeps them. +- **Biomes**: one biome per hex, labelled, with transitions outlined. Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, after asking, since that replaces its generated terrain; **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. + +A small **minimap** of the overworld (bottom right) shows on the overworld and on each of its regions, with the region you're in outlined; click a hex on it to go there. **Neighbouring maps** (below) and overworlds both stay available: pick per map. A map can have N/E/S/W neighbours and regions at once; a region itself joins its neighbours by itself, so it doesn't offer the neighbour tools. **Neighbouring maps.** In **Maps → New map…**, **Next to** makes the new map a region beside an existing one (same size and palette, lined up hex for hex); **Properties → New region here…** opens the form already placed. The generators marked *Continues … edge* (Overland and learned generators) carry the neighbour's terrain on across the shared border, and the preview shows the neighbour's edge faded around the new map. Region detail is only offered for submaps, since it zooms into a parent hex. @@ -274,6 +284,7 @@ Every command, as it appears in the command palette: | **Hexmap World Creator: Open random tables** | Opens the random tables and workflows view. | | **Hexmap World Creator: Open terrain generator** | Opens the terrain generator (learn, blend and run generators). | | **Hexmap World Creator: Open palette editor** | Opens the terrain palette editor. | +| **Hexmap World Creator: New overworld…** | A map of biomes (World biomes) whose hexes open into regions that join up; can make every region at once. Advanced: Regions and overworlds. | | **Hexmap World Creator: Go up to parent map** | From a submap, back to the map it belongs to. | | **Hexmap World Creator: Go back to previous map** | Returns to the map you were on before. | | **Hexmap World Creator: Add map data to this map's hex notes** | Adds a Map data box (terrain, region, name, from the map) under the title of every hex note of the open map, kept up to date when you open a hex. New hex notes from the built-in template already have one. | diff --git a/dev/demo-seed/.hexmaker-sandbox b/dev/demo-seed/.hexmaker-sandbox new file mode 100644 index 00000000..a9102929 --- /dev/null +++ b/dev/demo-seed/.hexmaker-sandbox @@ -0,0 +1 @@ +This vault is a throwaway sandbox made by dev/demo-world.mjs. The Hexmap World Creator demo builders only run in vaults holding this file. diff --git a/dev/demo-seed/Start here.md b/dev/demo-seed/Start here.md new file mode 100644 index 00000000..c113f1f6 --- /dev/null +++ b/dev/demo-seed/Start here.md @@ -0,0 +1,17 @@ +# Overworld demo + +A sandbox vault. Nothing here touches your real vault. The map view opens on **Demo Bricks**: a 19-hex overworld from the World biomes generator. Every hex opens into an 8 × 8 region, and all 19 regions are already made. + +Things to try: + +- [ ] **The full view.** The overworld shows every region's hexes stitched together. Hover a hex for its region's name. Click anywhere to go into that region, at that spot. +- [ ] **The minimap** (bottom right). Click a hex on it to jump to that region. Inside a region it outlines where you are. +- [ ] **Cross a seam.** In a region, the names in the bar above the map are its neighbours ("North-east: …"). The dimmed hexes past the edge are the next region: click one to go there. +- [ ] **Find a transition.** Hexes with a white outline (Biomes view, or the minimap) are in-between biomes, like taiga between tundra and forest. +- [ ] **Paint across regions.** On the overworld, pick the terrain tool and paint a river valley or a road corridor straight over the stitched hexes. It writes into each region it crosses. Undo takes the whole stroke back. +- [ ] **Set a biome.** Switch to **Biomes** (bottom right) and click a hex. Pick another biome: the region is remade (it asks first). Your hand-painted hexes stay. +- [ ] **Reroll and tune.** In the same box, **Reroll** for a new layout, or **Settings…** for blend, wiggly borders and seed, with a live preview. +- [ ] **Locations.** The middle hex has three locations: right-click it for "Locations (3)…". +- [ ] **Go up.** From a region, the breadcrumb (or Go up) returns to the overworld and flashes the hex. + +Hex-flower regions (a hex of hexes per overworld hex) aren't in this demo yet. diff --git a/dev/demo-world.mjs b/dev/demo-world.mjs new file mode 100644 index 00000000..7ee9904d --- /dev/null +++ b/dev/demo-world.mjs @@ -0,0 +1,99 @@ +#!/usr/bin/env node +/** + * Overworld demo world for playtesting (OW7), in a THROWAWAY sandbox vault. + * + * # build first (from WSL): npm run build + * node dev/demo-world.mjs [--seed 7] [--bench] [--no-launch-check] + * + * 1. `sandbox.mjs create` a new run from this worktree's built plugin, with + * dev/demo-seed (the `.hexmaker-sandbox` marker + "Start here.md"). + * 2. `sandbox.mjs launch` (separate Obsidian profile, its own CDP port). + * 3. Connects, checks the open vault IS the run's vault and holds the marker, + * then calls plugin.devTools.buildDemoWorld() (and buildBenchWorld() with + * --bench: 100 regions × 64 hexes, with layer timings). + * 4. Writes demo.json and a screenshot into the run folder, prints the run + * folder, and LEAVES OBSIDIAN RUNNING for the owner. Stop it with + * `node stop --run `. + * + * Never touches the main vault: sandbox.mjs refuses to create runs inside a + * vault, and this script refuses unless the open vault is the run's vault + * and has the marker file. + */ +import fs from "node:fs"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, ".."); +const SB_DIR = process.env.UX_SANDBOX_DIR ?? "C:/Users/markr/work/tools/skills-share/ux-testing/fresh-eyes-tester/scripts"; +const SB = path.join(SB_DIR, "sandbox.mjs"); +const MARKER = ".hexmaker-sandbox"; +const PLUGIN_ID = JSON.parse(fs.readFileSync(path.join(ROOT, "manifest.json"), "utf8")).id; + +const args = process.argv.slice(2); +const flag = (k) => args.includes(`--${k}`); +const val = (k, d) => { const i = args.indexOf(`--${k}`); return i >= 0 && args[i + 1] ? args[i + 1] : d; }; +const seed = Number(val("seed", "7")); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const die = (m) => { console.error("ERROR: " + m); process.exit(1); }; + +if (!fs.existsSync(path.join(ROOT, "main.js"))) die("main.js missing: build first (npm run build)."); +const common = await import(pathToFileURL(path.join(SB_DIR, "lib", "common.mjs")).href); + +// 1. create +const created = JSON.parse(execFileSync(process.execPath, [SB, "create", "--plugin-dir", ROOT, "--seed", path.join(HERE, "demo-seed"), "--name", flag("bench") ? "demo-bench" : "demo-world"], { encoding: "utf8" })); +const runDir = created.runDir; +if (!fs.existsSync(path.join(created.vault, MARKER))) die(`marker ${MARKER} missing in ${created.vault}`); +// 2. launch +execFileSync(process.execPath, [SB, "launch", "--run", runDir, "--width", "1500", "--height", "950"], { stdio: "inherit" }); + +const run = common.readRun(runDir); +const { browser, page } = await common.connect(run); +try { + // 3. safety: the open vault is the sandbox vault, with the marker + const base = await common.assertSandboxVault(page, run); + if (!base || !common.samePath(base, run.vault)) die(`open vault ${base} is not the sandbox vault ${run.vault}`); + if (!fs.existsSync(path.join(base, MARKER))) die("open vault has no sandbox marker"); + + // wait for the plugin's dev tools (palettes + map store load first) + const t0 = Date.now(); + while (!(await page.evaluate((id) => !!window.app.plugins.plugins[id]?.devTools, PLUGIN_ID))) { + if (Date.now() - t0 > 30000) die("plugin devTools never appeared (is the marker in the vault root?)"); + await sleep(500); + } + const report = { runDir, vault: run.vault, seed }; + report.demo = await page.evaluate((id, s) => window.app.plugins.plugins[id].devTools.buildDemoWorld({ seed: s }), PLUGIN_ID, seed); + if (flag("bench")) report.bench = await page.evaluate((id) => window.app.plugins.plugins[id].devTools.buildBenchWorld({ side: 10 }), PLUGIN_ID); + + // open the map view on the overworld and time the region layer + const showAndTime = async (name) => { + await page.evaluate(async (id, n) => { + const p = window.app.plugins.plugins[id]; + document.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); + await p.showMap(n); + }, PLUGIN_ID, name); + await sleep(2500); + // second draw: bitmaps cached (only the composite) + const first = await page.evaluate((id) => window.app.plugins.plugins[id].devTools.overworldStats(), PLUGIN_ID); + await page.evaluate((id) => { + const leaf = window.app.workspace.getLeavesOfType("duckmage-hex-map")[0]; + leaf?.view?.redraw?.(); + }, PLUGIN_ID); + await sleep(1500); + const cached = await page.evaluate((id) => window.app.plugins.plugins[id].devTools.overworldStats(), PLUGIN_ID); + return { first, cached }; + }; + if (report.bench) { + report.benchLayer = await showAndTime(report.bench.name); + await page.screenshot({ path: path.join(runDir, "shots", "bench-overworld.png") }); + } + report.demoLayer = await showAndTime(report.demo.overworld); + await page.screenshot({ path: path.join(runDir, "shots", "demo-overworld.png") }); + fs.writeFileSync(path.join(runDir, "demo.json"), JSON.stringify(report, null, 2)); + console.log(JSON.stringify(report, null, 2)); + console.log(`\nDemo ready. Run folder: ${runDir}`); + console.log(`Obsidian is left running. Stop it with: node "${SB}" stop --run "${runDir}"`); +} finally { + browser.disconnect(); +} diff --git a/src/hex-map/help.md b/src/hex-map/help.md index f48cab14..360476c7 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -119,6 +119,8 @@ Tokens show their name underneath. The layers panel's **Labels** group turns coo Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. +**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view: **Regions** shows every region's hexes stitched together (click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (click to set one: an empty hex gets its region, a hex with one has it remade after asking). The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. + Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. A road or river that ends on the edge of a region, next to where the neighbour's road of the same type ends, is drawn on to the shared edge on both maps, so the two join up. @@ -133,7 +135,7 @@ Pickers that link notes (to hexes, tokens, sections) never offer template notes ## Palettes -**Expanded** is the default fantasy palette on new installs (if you used the plugin before, new maps keep starting on your first palette): more terrains (coasts, wetlands, forest and mountain kinds) and it matches the generators. **Limited** has fewer, simpler terrains and is quicker to paint. +**Expanded** is the default fantasy palette on new installs (if you used the plugin before, new maps keep starting on your first palette): more terrains (coasts, wetlands, forest and mountain kinds) and it matches the generators. **Limited** has fewer, simpler terrains and is quicker to paint. Expanded now has **savanna** and **river delta** too (World biomes paints those biomes with them); an Expanded palette you already have gets them once, after a backup, unless it has terrains of those names already. Delete them and they stay deleted. ## Rolling from a hex From 4450f5911720c79a3632a0acea27c871bb0001be Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 18:35:42 -0400 Subject: [PATCH 225/558] fix: no special cases for default content; behaviour comes from palette data Owner rule (2026-10-10): never treat the defaults as special by name. - Terrain type is the only source of type defaults: an untyped terrain is never guessed from its name at run time (impassable, builtin generator mapping, Region detail / Overland context, context paths). Name guesses only fill the Type column visibly (seeding, Guess button, new terrain). - Space roles get their own types (moon, comet, debris, starport, jump point, jump limit, star system); Orbits and Star scatter place by type only, no name regexes. Presets retyped; installed palettes upgraded once. - Procedural generators drop the untyped name/category fallbacks. - Orbits' Star option lists the palette's own stars. - Base terrain = first void-typed terrain, not "void"/"empty space". - Learned generators' default impassable list comes from the palette (isImpassable), not the names shallows/ocean/trench; the no-paths impassable hint uses the palette flag instead of a name regex. - New setting "Palette for new maps" (seeded Expanded on new installs) replaces the name check for Expanded / Space - Sector; renames repoint it. - Installed palettes no longer borrow child palette / submap defaults from a same-named preset at run time; copied in once instead. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- src/HexmakerPlugin.ts | 33 ++++--- src/HexmakerSettingTab.ts | 48 ++++++++-- src/SetupWizardView.ts | 4 +- src/hex-map/help.md | 4 +- src/impassable.ts | 4 +- src/palettes/PaletteEditorView.ts | 4 +- src/palettes/PaletteStore.ts | 60 +++++++++++-- src/palettes/paletteOptions.ts | 84 ++++++++++++----- src/palettes/presets.ts | 14 +-- src/terrainTypes.ts | 58 +++++++++--- src/types.ts | 12 ++- src/worldgen/GeneratorPanel.ts | 6 +- src/worldgen/NewMapSetupModal.ts | 5 +- src/worldgen/builtinGenerators.ts | 17 ++-- src/worldgen/generators.ts | 49 +++++++--- src/worldgen/impassableHint.ts | 17 ++-- src/worldgen/procedural/common.ts | 48 +++------- src/worldgen/procedural/contextPaths.ts | 6 +- src/worldgen/procedural/orbits.ts | 84 ++++++++--------- src/worldgen/procedural/planetSurface.ts | 50 +++++------ src/worldgen/procedural/starScatter.ts | 49 ++++------ src/worldgen/registry.ts | 21 +++-- tests/builtinGenerators.test.ts | 31 +++++++ tests/impassable.test.ts | 42 +++++++-- tests/proceduralGenerators.test.ts | 109 +++++++++++++++++------ tests/regionContext.test.ts | 18 ++-- tests/terrainTypes.test.ts | 77 +++++++++++++++- tests/worldgenFirstMap.test.ts | 70 ++++++++++++--- tests/worldgenGenerators.test.ts | 31 +++++-- tests/worldgenImpassableHint.test.ts | 14 +-- 31 files changed, 750 insertions(+), 324 deletions(-) diff --git a/README.md b/README.md index 38e360e8..a63fe590 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it. -- **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. Orbits places moons (the *moon* terrain) beside their planets; a system with a planet always has at least one. +- **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. @@ -201,7 +201,7 @@ Click the **pencil** icon on the right edge of the map to open the drawing tools **Auto-route:** the picker (and the bar at the top of the map while drawing) switches between **Hex by hex** and **Auto-route**: in the picker, choose how to draw (step 1), then the path type (step 2). With Auto-route, click a start hex and then an end hex: the path takes the shortest way inside the map, around impassable terrain, keeping close to the straight line between the two, and then carries on from that end, so you can route leg by leg. Rivers (and other path types that cross impassable terrain, or are named river, stream or creek) wind gently instead of running straight. A route continues an existing path only when its start is that path's end; starting anywhere else (such as the first hex of another road) makes a new path, and existing paths are never changed. The result is an ordinary path: right-click hexes to remove them, or switch back to hex by hex to extend it. -- **Impassable terrain** — set per terrain in the palette editor (Impassable column) or the terrain editor. Defaults go by terrain *type*, not name, so they work in any palette, custom ones included: every terrain of a water type (deep water, water, shallows) is impassable unless you untick it, and a terrain with no type counts as the type its name suggests ("Black Lake" is water). A palette with no impassable terrain says so in the bar. +- **Impassable terrain** — set per terrain in the palette editor (Impassable column) or the terrain editor. Defaults go by terrain *type*, never by name, so they work in any palette, custom ones included: every terrain of a water type (deep water, water, shallows) is impassable unless you untick it. A terrain with no type has no default (an untyped "Black Lake" is passable); give it a type, or use **Guess types from names** in the palette editor. A palette with no impassable terrain says so in the bar. Learned generators' **Connected land** uses the same impassable terrains until you save your own list. - **Per path type** — each path type has **Avoid impassable terrain** (in its editor). Roads avoid water; rivers don't (they're off by default for river-like names). - **Cross impassable** — tick it in the bar to let one route go through anyway. If no route exists the map tells you, and suggests this or changing which terrains are impassable. @@ -309,6 +309,7 @@ Open **Settings → Hexmap World Creator** to configure: | **Hex orientation** | `flat` (default) or `pointy` top hex style. | | **Path types** | Named path types used by the Path drawing tool. Each type has a name, colour, width, line style, and routing mode. Manage them from the Path button on the hex map toolbar. | | **Palettes folder** | Folder holding one note per terrain palette (default `{world folder}/palettes`). | +| **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | | **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 2783e3d2..6436bdc8 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -32,7 +32,7 @@ import { PaletteStore } from "./palettes/PaletteStore"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; import { enabledKinds, isIconHiddenByKind, isSpacePalette, resolveMapKinds, terrainsForTables } from "./mapKinds"; import { enableFeature, hasFeature, resolveFeatureLevel, shouldNudge, type AdvancedFeature, type FeatureLevel } from "./featureLevel"; -import { resolveExpandedDefault } from "./palettes/paletteOptions"; +import { defaultPaletteFor, resolveDefaultPalette, resolveExpandedDefault } from "./palettes/paletteOptions"; import { AdvancedNudgeModal, EnableFeatureModal } from "./advancedHints"; import { mapAncestors } from "./hex-map/submapNav"; import { @@ -644,7 +644,10 @@ export default class HexmakerPlugin extends Plugin { // once from the raw data, like the level, and saved with it. this.settings.expandedByDefault = resolveExpandedDefault(rawData); const firstExpanded = typeof rawData?.["expandedByDefault"] !== "boolean"; - if (firstLevel || firstExpanded || !rawData?.["installedAt"]) await this.saveData(this.settings); + // "Palette for new maps": seeded once from the above, then the user's. + this.settings.defaultPalette = resolveDefaultPalette(rawData); + const firstDefaultPalette = typeof rawData?.["defaultPalette"] !== "string"; + if (firstLevel || firstExpanded || firstDefaultPalette || !rawData?.["installedAt"]) await this.saveData(this.settings); } /** @@ -1987,16 +1990,20 @@ export default class HexmakerPlugin extends Plugin { /** * Palette to pre-select for a new submap of `parentMap`: the parent - * palette's `childPalette` (installed or a preset), else the parent's own - * palette, else the first palette. + * palette's `childPalette` (its note's `child-palette`; the preset's only + * while that preset isn't installed), else the parent's own palette, else + * the palette for new maps. An installed palette is never topped up from + * a same-named preset: clearing its child palette means none. */ childPaletteFor(parentMap: string): string { const parentPaletteName = this.getMap(parentMap)?.paletteName; const parentPalette = parentPaletteName ? this.getPaletteByName(parentPaletteName) : undefined; - const child = parentPalette?.childPalette ?? (parentPaletteName ? getPreset(parentPaletteName)?.childPalette : undefined); + const child = parentPalette + ? parentPalette.childPalette + : parentPaletteName ? getPreset(parentPaletteName)?.childPalette : undefined; if (child && (this.getPaletteByName(child) || getPreset(child))) return child; if (parentPalette) return parentPalette.name; - return this.settings.terrainPalettes[0]?.name ?? DEFAULT_PALETTE_NAME; + return defaultPaletteFor(this.settings); } /** @@ -2106,15 +2113,17 @@ export default class HexmakerPlugin extends Plugin { /** * Saved setup for a new submap made from a `terrain` hex on `parentMap`: * the parent palette's Submap defaults row for that terrain (from its - * note), else the matching preset's row (palettes installed before the - * preset gained defaults still get them). + * note). Only a preset that isn't installed answers from its own rows; + * palettes installed before their preset gained defaults got the rows + * copied in once (PaletteStore, `paletteDataUpgraded`), so a row the user + * deletes stays deleted. */ submapDefaultFor(parentMap: string, terrain: string | null | undefined): SubmapDefault | undefined { if (!terrain) return undefined; const paletteName = this.getMap(parentMap)?.paletteName; if (!paletteName) return undefined; - const own = this.getPaletteByName(paletteName)?.submapDefaults?.[terrain]; - if (own) return own; + const pal = this.getPaletteByName(paletteName); + if (pal) return pal.submapDefaults?.[terrain]; return getPreset(paletteName)?.submapDefaults?.[terrain]; } @@ -2132,7 +2141,7 @@ export default class HexmakerPlugin extends Plugin { const paletteName = this.getMap(parentMap)?.paletteName; const pal = paletteName ? this.getPaletteByName(paletteName) : undefined; if (!pal) return; - // Start from what the user currently sees (own row, else the preset row). + // Start from what the user currently sees (see submapDefaultFor). const current: SubmapDefault = { ...(this.submapDefaultFor(parentMap, terrain) ?? {}) }; for (const k of clear) delete current[k]; Object.assign(current, set); @@ -2191,7 +2200,7 @@ export default class HexmakerPlugin extends Plugin { if (!r) { r = { name, - paletteName: DEFAULT_PALETTE_NAME, + paletteName: defaultPaletteFor(this.settings), gridSize: { cols: 20, rows: 16 }, gridOffset: { x: 0, y: 0 }, pathChains: [], diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index af641122..4fb04544 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -2,6 +2,7 @@ import { App, Notice, PluginSettingTab, Setting } from "obsidian"; import type HexmakerPlugin from "./HexmakerPlugin"; import { normalizeFolder } from "./utils"; import { AddPaletteModal } from "./palettes/AddPaletteModal"; +import { repointPaletteName } from "./palettes/paletteOptions"; import { MAP_KINDS, enabledKinds, type MapKind } from "./mapKinds"; import { ADVANCED_FEATURES, hasFeature, isAdvanced } from "./featureLevel"; @@ -96,6 +97,10 @@ type LocalSettingDefinitionItem = const TEMPLATES_FOLDER_DESC = "Vault-relative folder for the plugin's note templates: the hex template (unless Template path points elsewhere) and the town template. Edit them there; new notes use them. Blank = \"templates\" in the world folder. Workflow templates stay with their workflows."; +/** The "Palette for new maps" setting's description (both settings paths). */ +const DEFAULT_PALETTE_DESC = + "The palette a new map starts on. First palette = the first one listed below (overland before space)."; + /** Settings keys holding vault paths that must be run through normalizeFolder. */ const FOLDER_PATH_KEYS = new Set([ "templatePath", @@ -203,10 +208,8 @@ export class HexmakerSettingTab extends PluginSettingTab { nameInput.value = pal.name; return; } - // Update any maps using this palette - for (const r of this.plugin.settings.maps) { - if (r.paletteName === pal.name) r.paletteName = trimmed; - } + // Repoint maps, the new-map default and child palettes. + repointPaletteName(this.plugin.settings, pal.name, trimmed); pal.name = trimmed; await this.plugin.saveSettings(); this.requestDeclarativeRerender(); @@ -644,6 +647,16 @@ export class HexmakerSettingTab extends PluginSettingTab { desc: "Each region uses one palette. Assign a palette when creating a region — it cannot be changed after. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note.", searchable: false, }, + { + name: "Palette for new maps", + desc: DEFAULT_PALETTE_DESC, + control: { + type: "dropdown", + key: "defaultPalette", + options: this.defaultPaletteOptions(), + defaultValue: "", + }, + }, ], }, { @@ -757,6 +770,15 @@ export class HexmakerSettingTab extends PluginSettingTab { this.plugin.onMapKindsChanged(); } + /** Choices for "Palette for new maps": first palette, then every palette (the saved one kept even if gone). */ + private defaultPaletteOptions(): Record { + const out: Record = { "": "First palette" }; + for (const p of this.plugin.settings.terrainPalettes) out[p.name] = p.name; + const saved = this.plugin.settings.defaultPalette; + if (saved && !(saved in out)) out[saved] = `${saved} (not installed)`; + return out; + } + /** "Open note" button for a palette row — opens the palette's note in a new tab. */ private addOpenNoteButton(parent: HTMLElement, paletteName: string): void { parent.createEl("button", { text: "Edit", cls: "mod-cta" }).addEventListener("click", () => { @@ -1480,6 +1502,18 @@ export class HexmakerSettingTab extends PluginSettingTab { text: "Each region uses one palette. Assign a palette when creating a region — it cannot be changed after. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note.", cls: "setting-item-description", }); + new Setting(containerEl) + .setName("Palette for new maps") + .setDesc(DEFAULT_PALETTE_DESC) + .addDropdown((d) => + d + .addOptions(this.defaultPaletteOptions()) + .setValue(this.plugin.settings.defaultPalette ?? "") + .onChange(async (v) => { + this.plugin.settings.defaultPalette = v; + await this.plugin.saveSettings(); + }), + ); const palettes = this.plugin.settings.terrainPalettes; @@ -1521,10 +1555,8 @@ export class HexmakerSettingTab extends PluginSettingTab { nameInput.value = pal.name; return; } - // Update any maps using this palette - for (const r of this.plugin.settings.maps) { - if (r.paletteName === pal.name) r.paletteName = trimmed; - } + // Repoint maps, the new-map default and child palettes. + repointPaletteName(this.plugin.settings, pal.name, trimmed); pal.name = trimmed; await this.plugin.saveSettings(); })(); diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index fd02feea..35223480 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -15,6 +15,7 @@ import { describeKind, firstMapGenerator, generationKey, + kindOptions, kindsForPalette, listGeneratorKinds, suggestBaseTerrain, @@ -640,7 +641,7 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { optsBox.empty(); seaRandomOption = undefined; const kind = kinds.find((k) => k.id === ctx.generatorId); - for (const opt of kind?.options ?? []) { + for (const opt of kind ? kindOptions(kind, terrains()) : []) { const row = optsBox.createEl("label", { cls: "duckmage-wizard-generator-option" }); row.createSpan({ text: opt.label }); const sel = row.createEl("select"); @@ -649,6 +650,7 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { if (kind?.id === OVERLAND_ID && opt.key === "sea" && c.value === "random") seaRandomOption = o; } sel.value = ctx.generatorOptions[opt.key] ?? opt.default; + if (sel.selectedIndex < 0) sel.value = opt.default; sel.addEventListener("change", () => { ctx.generatorOptions[opt.key] = sel.value; refresh(); }); } syncSeaLabel(); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index be98fe87..ec28f5b7 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -131,7 +131,9 @@ Pickers that link notes (to hexes, tokens, sections) never offer template notes ## Palettes -**Expanded** is the default fantasy palette on new installs (if you used the plugin before, new maps keep starting on your first palette): more terrains (coasts, wetlands, forest and mountain kinds) and it matches the generators. **Limited** has fewer, simpler terrains and is quicker to paint. +**Expanded** is the default fantasy palette on new installs (if you used the plugin before, new maps keep starting on your first palette): more terrains (coasts, wetlands, forest and mountain kinds) and it matches the generators. **Limited** has fewer, simpler terrains and is quicker to paint. Pick any palette as the start for new maps in **Settings → Palette for new maps**. + +No palette or terrain is special because of its name. What a terrain does comes from its **Type**: water types are impassable to auto-routes, generators place terrain by type, Orbits puts the *moon*-type terrain beside planets and the *jump point* past the last orbit. Rename anything, or build a palette from scratch, and it works the same once its terrains have types. A terrain with no type gets no defaults and generators skip it; **Guess types from names** in the palette editor fills the Type column for you to check. ## Rolling from a hex diff --git a/src/impassable.ts b/src/impassable.ts index e5e6e8a5..0e2cde60 100644 --- a/src/impassable.ts +++ b/src/impassable.ts @@ -8,8 +8,8 @@ import { effectiveTerrainType, terrainTypeGroup, TERRAIN_GROUPS, typesInGroup, t * when unset, by its terrain type's GROUP (PA4): every type in the water * group (deep water, water, shallows) is impassable by default. Defaults go * by type, never by terrain name, so any palette (custom ones too) gets - * them; an untyped terrain counts as the type its name suggests - * (effectiveTerrainType). Hex-by-hex drawing ignores all of this; only + * them; an untyped terrain has no type default (passable unless ticked), + * whatever it is called (effectiveTerrainType). Hex-by-hex drawing ignores all of this; only * auto-route asks. */ diff --git a/src/palettes/PaletteEditorView.ts b/src/palettes/PaletteEditorView.ts index 03cb9430..1ac98563 100644 --- a/src/palettes/PaletteEditorView.ts +++ b/src/palettes/PaletteEditorView.ts @@ -131,12 +131,12 @@ export class PaletteEditorView extends ItemView { contentEl.createEl("h3", { text: `Terrains (${pal.terrains.length})` }); contentEl.createDiv({ cls: "setting-item-description", - text: "Type gives a terrain its defaults, whatever its name: water types (deep water, water, shallows) are impassable to auto-routed roads. Tick or untick Impassable to override one terrain.", + text: "Type gives a terrain its defaults, whatever its name: water types (deep water, water, shallows) are impassable to auto-routed paths, and generators place terrains by type. Tick or untick Impassable to override one terrain.", }); const untyped = pal.terrains.filter((t) => !t.type).length; if (untyped) { const hint = contentEl.createDiv({ cls: "duckmage-pe-hint" }); - hint.createSpan({ text: `${untyped} terrain${untyped === 1 ? " has" : "s have"} no type. ` }); + hint.createSpan({ text: `${untyped} terrain${untyped === 1 ? " has" : "s have"} no type, so no defaults, and generators skip ${untyped === 1 ? "it" : "them"}. ` }); hint.createEl("button", { text: "Guess types from names" }).addEventListener("click", () => { let n = 0; for (const t of pal.terrains) { diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index f5a5355d..917f9100 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -14,10 +14,11 @@ import { terrainsEqual, updatePaletteNote, } from "./paletteNote"; -import { PALETTE_PRESETS, uniquePaletteName } from "./presets"; +import { PALETTE_PRESETS, cloneSubmapDefaults, getPreset, uniquePaletteName } from "./presets"; import { clonePathTypes, parsePathTypes, pathTypesKey, setPathTypes } from "./pathTypeTable"; import { DEFAULT_PATH_TYPES } from "../constants"; -import { inferTerrainType } from "../terrainTypes"; +import { inferTerrainType, refinedSpaceType } from "../terrainTypes"; +import { repointPaletteName } from "./paletteOptions"; /** * Fill in missing terrain types: a same-named terrain in a preset wins, @@ -38,6 +39,43 @@ export function seedTerrainTypes(palettes: TerrainPalette[]): number { return n; } +/** + * One-time upgrade of data that used to be worked out from names at run + * time, so from now on only what the palette note says counts: + * - space terrains typed before the space roles had their own types get + * them (a "moon" typed world becomes a moon; see refinedSpaceType); + * - an installed palette named like a built-in preset gets that preset's + * child palette and Submap defaults rows it doesn't have yet (they used + * to be borrowed from the preset by name on every lookup). + * Returns how many palettes changed. + */ +export function upgradePaletteData(palettes: TerrainPalette[]): number { + let n = 0; + for (const pal of palettes) { + let changed = false; + for (const t of pal.terrains) { + const refined = refinedSpaceType(t); + if (refined) { t.type = refined; changed = true; } + } + const preset = getPreset(pal.name); + if (preset?.childPalette && !pal.childPalette) { + pal.childPalette = preset.childPalette; + changed = true; + } + if (preset?.submapDefaults) { + const missing = Object.keys(preset.submapDefaults).filter((k) => !pal.submapDefaults?.[k]); + if (missing.length) { + const rows = cloneSubmapDefaults(preset.submapDefaults); + pal.submapDefaults = { ...(pal.submapDefaults ?? {}) }; + for (const k of missing) pal.submapDefaults[k] = rows[k]; + changed = true; + } + } + if (changed) n++; + } + return n; +} + /** * Copy a note's metadata (`child-palette`, the Submap defaults table) onto * the palette. Returns true if anything changed. @@ -187,11 +225,9 @@ export class PaletteStore { } } - /** Rename a palette in memory and repoint every map that uses it. */ + /** Rename a palette in memory and repoint everything that names it. */ private renamePalette(pal: TerrainPalette, newName: string): void { - for (const m of this.plugin.settings.maps) { - if (m.paletteName === pal.name) m.paletteName = newName; - } + repointPaletteName(this.plugin.settings, pal.name, newName); pal.name = newName; } @@ -267,11 +303,21 @@ export class PaletteStore { settings.terrainTypesSeeded = true; dirty = true; } + // One-time: write into the palettes what used to be inferred from + // names at run time (space role types, a preset's child palette and + // Submap defaults). Runs after the seeding so freshly typed terrains + // are upgraded too. + let upgraded = false; + if (!settings.paletteDataUpgraded) { + upgraded = upgradePaletteData(settings.terrainPalettes) > 0; + settings.paletteDataUpgraded = true; + dirty = true; + } this.ready = true; // Write seeded types into the notes now, in the same queued step. Queued // separately, an unload in between left notes untyped while settings // said seeding was done — and notes win on the next load. - if (seeded || filled) await this.syncNow(); + if (seeded || filled || upgraded) await this.syncNow(); if (dirty) await this.persist(); } diff --git a/src/palettes/paletteOptions.ts b/src/palettes/paletteOptions.ts index 343e0115..b12626ea 100644 --- a/src/palettes/paletteOptions.ts +++ b/src/palettes/paletteOptions.ts @@ -1,6 +1,6 @@ import type HexmakerPlugin from "../HexmakerPlugin"; -import { PALETTE_PRESETS, SPACE_SECTOR_PALETTE_NAME } from "./presets"; -import { enabledKinds, isKindEnabled, isSpacePalette } from "../mapKinds"; +import { PALETTE_PRESETS } from "./presets"; +import { ALL_MAP_KINDS, enabledKinds, isKindEnabled, isSpacePalette, type MapKind } from "../mapKinds"; import { EXPANDED_PALETTE_NAME, LIMITED_PALETTE_NAME } from "../constants"; /** @@ -46,7 +46,8 @@ export function refreshPaletteHint(select: HTMLSelectElement): void { * Whether new maps default to the Expanded palette (GEN1 = B: new installs * only). A saved value wins; without one, a fresh install (no saved data) * gets true and an update gets false, so existing users keep the default - * they had (their first overland palette). + * they had (their first overland palette). Only used to seed + * `defaultPalette` (see resolveDefaultPalette). */ export function resolveExpandedDefault(raw: Record | null | undefined): boolean { const saved = raw?.["expandedByDefault"]; @@ -55,35 +56,47 @@ export function resolveExpandedDefault(raw: Record | null | und } /** - * Palette a new top-level map starts on when the user hasn't picked one. - * World users on a fresh install get Expanded when it's installed (G7b); - * existing installs (`expandedByDefault: false`) keep their first overland - * palette, as before G7b. With no overland palette installed: the - * Expanded preset (fresh) or the first world preset (existing). Space-only - * users get Space - Sector (installed, else the preset, which createNewMap - * installs on first use) or another installed space palette. + * The "Palette for new maps" setting from data.json. A saved value wins + * ("" = first palette). Without one it is seeded once from GEN1: Expanded + * on fresh installs (and installs that already defaulted to it), blank for + * older installs. After that it is an ordinary setting the user can point + * at any palette; nothing looks for the name "Expanded" again. + */ +export function resolveDefaultPalette(raw: Record | null | undefined): string { + const saved = raw?.["defaultPalette"]; + if (typeof saved === "string") return saved; + return resolveExpandedDefault(raw) ? EXPANDED_PALETTE_NAME : ""; +} + +/** + * Palette a new top-level map starts on when the user hasn't picked one: + * the "Palette for new maps" setting (`defaultPalette`), when that palette + * is installed and its map type is on. Otherwise the first installed + * palette of an enabled map type (overland before space); with none + * installed, the setting's preset (createNewMap installs it on first use), + * else the first preset of an enabled type. + * No palette is special by name: rename or delete any of them and this + * still picks something sensible. */ export function defaultPaletteFor(settings: { mapKinds?: string[]; terrainPalettes: { name: string; terrains: readonly { type?: string }[] }[]; - /** See resolveExpandedDefault. Unset = fresh-install behaviour. */ - expandedByDefault?: boolean; + /** See resolveDefaultPalette. Unset or "" = first palette. */ + defaultPalette?: string; }): string { const kinds = enabledKinds(settings); const pals = settings.terrainPalettes; - if (kinds.has("world")) { - const world = pals.filter((p) => !isSpacePalette(p.terrains)); - const fresh = settings.expandedByDefault !== false; - if (fresh) { - const expanded = world.find((p) => p.name === EXPANDED_PALETTE_NAME); - if (expanded) return expanded.name; - } - if (world.length) return world[0].name; - if (fresh) return EXPANDED_PALETTE_NAME; - return PALETTE_PRESETS.find((p) => p.kind === "world")?.name ?? EXPANDED_PALETTE_NAME; + const kindOf = (terrains: readonly { type?: string }[]): MapKind => (isSpacePalette(terrains) ? "space" : "world"); + const want = settings.defaultPalette; + const installed = want ? pals.find((p) => p.name === want) : undefined; + if (installed && kinds.has(kindOf(installed.terrains))) return installed.name; + for (const kind of ALL_MAP_KINDS) { + if (!kinds.has(kind)) continue; + const first = pals.find((p) => kindOf(p.terrains) === kind); + if (first) return first.name; } - const space = pals.filter((p) => isSpacePalette(p.terrains)); - return space.find((p) => p.name === SPACE_SECTOR_PALETTE_NAME)?.name ?? space[0]?.name ?? SPACE_SECTOR_PALETTE_NAME; + const preset = want && !installed ? PALETTE_PRESETS.find((p) => p.name === want && kinds.has(p.kind)) : undefined; + return preset?.name ?? PALETTE_PRESETS.find((p) => kinds.has(p.kind))?.name ?? pals[0]?.name ?? ""; } /** @@ -126,3 +139,26 @@ export function fillPaletteSelect( } hintUpdaters.get(select)?.(); } + +/** + * A palette was renamed: repoint everything that names it (maps, the + * "Palette for new maps" setting, other palettes' child palette and + * Submap defaults), so a rename never silently drops a reference. + */ +export function repointPaletteName( + settings: { + maps: { paletteName: string }[]; + defaultPalette?: string; + terrainPalettes: { childPalette?: string; submapDefaults?: Record }[]; + }, + oldName: string, + newName: string, +): void { + if (oldName === newName) return; + for (const m of settings.maps) if (m.paletteName === oldName) m.paletteName = newName; + if (settings.defaultPalette === oldName) settings.defaultPalette = newName; + for (const p of settings.terrainPalettes) { + if (p.childPalette === oldName) p.childPalette = newName; + for (const row of Object.values(p.submapDefaults ?? {})) if (row.palette === oldName) row.palette = newName; + } +} diff --git a/src/palettes/presets.ts b/src/palettes/presets.ts index 1a8d4fc7..9585faab 100644 --- a/src/palettes/presets.ts +++ b/src/palettes/presets.ts @@ -49,7 +49,7 @@ export const SPACE_SECTOR_TERRAINS: TerrainColor[] = [ { name: "asteroid belt", type: "asteroids", color: "#5e554d", icon: "space-asteroid.png", iconColor: "#e7e5e4", category: "worlds" }, { name: "gas giant", type: "gas-giant", color: "#b07d45", icon: "space-ringed-planet.svg", iconColor: "#fff7ed", category: "worlds" }, // Points of interest - { name: "star system", type: "star", color: "#c9a227", icon: "space-orbit.svg", iconColor: "#fff7d6", category: "features" }, + { name: "star system", type: "star-system", color: "#c9a227", icon: "space-orbit.svg", iconColor: "#fff7d6", category: "features" }, { name: "deep-space station", type: "station", color: "#7d8794", icon: "space-orbital.svg", iconColor: "#f8fafc", category: "features" }, { name: "black hole", type: "anomaly", color: "#000000", icon: "space-target-outline.svg", iconColor: "#a78bfa", category: "features" }, { name: "anomaly", type: "anomaly", color: "#7c3aad", icon: "space-anomaly.svg", iconColor: "#f5d0fe", category: "features" }, @@ -60,7 +60,7 @@ export const SPACE_SYSTEM_TERRAINS: TerrainColor[] = [ // Space { name: "void", type: "void", color: "#05070f", category: "space" }, { name: "nebula", type: "nebula", color: "#3b2a5c", category: "space" }, - { name: "jump limit", type: "void", color: "#1d1838", icon: "space-ring-dashed.svg", iconColor: "#c4b5fd", category: "space" }, + { name: "jump limit", type: "jump-limit", color: "#1d1838", icon: "space-ring-dashed.svg", iconColor: "#c4b5fd", category: "space" }, // Stars { name: "yellow star", type: "star", color: "#f2c94c", icon: "space-sun.svg", iconColor: "#7c2d12", category: "stars" }, { name: "red dwarf", type: "star", color: "#d9573b", icon: "space-sun.svg", iconColor: "#fde68a", category: "stars" }, @@ -76,15 +76,15 @@ export const SPACE_SYSTEM_TERRAINS: TerrainColor[] = [ { name: "molten planet", type: "world", color: "#a8402a", icon: "space-planet-core.svg", iconColor: "#fde68a", category: "bodies" }, { name: "gas giant", type: "gas-giant", color: "#b07d45", icon: "space-ringed-planet.svg", iconColor: "#fff7ed", category: "bodies" }, { name: "ice giant", type: "gas-giant", color: "#5f9fb8", icon: "space-frozen-orb.svg", iconColor: "#ecfeff", category: "bodies" }, - { name: "moon", type: "world", color: "#9a9aa2", icon: "space-moon.svg", iconColor: "#111827", category: "bodies" }, + { name: "moon", type: "moon", color: "#9a9aa2", icon: "space-moon.svg", iconColor: "#111827", category: "bodies" }, { name: "asteroid belt", type: "asteroids", color: "#5e554d", icon: "space-asteroid.png", iconColor: "#e7e5e4", category: "bodies" }, - { name: "comet", type: "asteroids", color: "#8fb3c4", icon: "space-meteor.svg", iconColor: "#0f172a", category: "bodies" }, + { name: "comet", type: "comet", color: "#8fb3c4", icon: "space-meteor.svg", iconColor: "#0f172a", category: "bodies" }, // Installations { name: "space station", type: "station", color: "#7d8794", icon: "space-orbital.svg", iconColor: "#f8fafc", category: "installations" }, - { name: "starport", type: "station", color: "#c0c7cf", icon: "space-star-gate.svg", iconColor: "#111827", category: "installations" }, - { name: "jump point", type: "station", color: "#5b3fc4", icon: "space-portal.svg", iconColor: "#ede9fe", category: "installations" }, + { name: "starport", type: "starport", color: "#c0c7cf", icon: "space-star-gate.svg", iconColor: "#111827", category: "installations" }, + { name: "jump point", type: "jump-point", color: "#5b3fc4", icon: "space-portal.svg", iconColor: "#ede9fe", category: "installations" }, // Hazards - { name: "debris field", type: "asteroids", color: "#4d4640", icon: "space-dots-hex.svg", iconColor: "#e7e5e4", category: "hazards" }, + { name: "debris field", type: "debris", color: "#4d4640", icon: "space-dots-hex.svg", iconColor: "#e7e5e4", category: "hazards" }, { name: "radiation belt", type: "anomaly", color: "#7d6a1f", icon: "space-radioactive.svg", iconColor: "#fef08a", category: "hazards" }, ]; diff --git a/src/terrainTypes.ts b/src/terrainTypes.ts index cb1e700a..63701b87 100644 --- a/src/terrainTypes.ts +++ b/src/terrainTypes.ts @@ -52,15 +52,24 @@ const TYPE_DEFS: TypeDef[] = [ { id: "badlands", label: "Badlands", kind: "world", keywords: ["badland", "brokenland", "waste", "canyon", "mesa"] }, { id: "volcanic", label: "Volcanic", kind: "world", keywords: ["volcan", "lava", "ash", "magma"] }, { id: "settlement", label: "Settlement", kind: "world", keywords: ["urban", "city", "town", "village", "ruin"] }, - // Space - { id: "void", label: "Void / empty space", kind: "space", keywords: ["void", "empty space", "deep space", "jump limit"] }, + // Space. The generators place by type (Orbits puts moons beside planets + // and a jump point past the last orbit), so each of those roles has its + // own type instead of being told apart by name. + { id: "void", label: "Void / empty space", kind: "space", keywords: ["void", "empty space", "deep space"] }, + { id: "jump-limit", label: "Jump limit (ring)", kind: "space", keywords: ["jump limit"] }, { id: "nebula", label: "Nebula / cloud", kind: "space", keywords: ["nebula", "dust", "cloud"] }, { id: "rift", label: "Rift", kind: "space", keywords: ["rift"] }, { id: "star", label: "Star", kind: "space", keywords: ["star", "sun", "dwarf", "giant star"] }, - { id: "world", label: "World / planet", kind: "space", keywords: ["world", "planet", "moon"] }, + { id: "star-system", label: "Star system (sector marker)", kind: "space", keywords: ["star system"] }, + { id: "world", label: "World / planet", kind: "space", keywords: ["world", "planet"] }, + { id: "moon", label: "Moon", kind: "space", keywords: ["moon", "satellite"] }, { id: "gas-giant", label: "Gas giant", kind: "space", keywords: ["gas giant", "ice giant"] }, - { id: "asteroids", label: "Asteroids / debris", kind: "space", keywords: ["asteroid", "belt", "debris", "comet", "meteor"] }, - { id: "station", label: "Station / port", kind: "space", keywords: ["station", "starport", "port", "jump point", "gate"] }, + { id: "asteroids", label: "Asteroid belt", kind: "space", keywords: ["asteroid", "belt", "meteor"] }, + { id: "comet", label: "Comet", kind: "space", keywords: ["comet"] }, + { id: "debris", label: "Debris field", kind: "space", keywords: ["debris", "wreck"] }, + { id: "station", label: "Station", kind: "space", keywords: ["station", "outpost"] }, + { id: "starport", label: "Starport", kind: "space", keywords: ["starport", "spaceport", "port"] }, + { id: "jump-point", label: "Jump point / gate", kind: "space", keywords: ["jump point", "gate"] }, { id: "anomaly", label: "Anomaly / hazard", kind: "space", keywords: ["anomaly", "black hole", "radiation", "hazard"] }, ]; @@ -87,13 +96,16 @@ export function typesInGroup(group: TerrainGroup): string[] { } /** - * The type a terrain counts as: its own (when a known type), else the - * best guess from its name and category, so untyped terrains in custom - * palettes still get type-based defaults. + * The type a terrain counts as: its own Type when that is a known type id, + * else none. Behaviour never guesses from the name (an untyped "Black + * Lake" is not water): the Type column is the one place that says what a + * terrain is, so what the palette editor shows is what the plugin does. + * Name guesses (inferTerrainType) only fill the Type column as a visible + * suggestion: the one-time seeding of old palettes, the editor's "Guess + * types from names" button, and a new terrain's name. */ -export function effectiveTerrainType(t: { type?: string; name?: string; category?: string }): string | undefined { - if (isTerrainType(t.type)) return t.type; - return t.name ? inferTerrainType(t.name, t.category) : undefined; +export function effectiveTerrainType(t: { type?: string }): string | undefined { + return isTerrainType(t.type) ? t.type : undefined; } /** @@ -144,3 +156,27 @@ export function inferTerrainType(name: string, category?: string, kind?: MapKind }; return scan(name) ?? (category ? scan(category) : undefined); } + +/** + * One-time upgrade for palettes typed before the space roles got their own + * types (moon, comet, debris, starport, jump point, jump limit, star + * system). Back then Orbits and Star scatter told those apart by name + * inside a coarser type; this turns the same name rule into the terrain's + * Type once, so from then on the Type column alone decides (and can be + * changed). Returns the refined type, or undefined to leave it as is. + */ +export function refinedSpaceType(t: { name: string; type?: string }): string | undefined { + const n = t.name; + switch (t.type) { + case "world": return /\bmoons?\b|satellite/i.test(n) ? "moon" : undefined; + case "asteroids": + if (/comet/i.test(n)) return "comet"; + return /debris|wreck/i.test(n) ? "debris" : undefined; + case "station": + if (/jump|gate/i.test(n)) return "jump-point"; + return /port/i.test(n) ? "starport" : undefined; + case "void": return /limit/i.test(n) ? "jump-limit" : undefined; + case "star": return /system/i.test(n) ? "star-system" : undefined; + default: return undefined; + } +} diff --git a/src/types.ts b/src/types.ts index b032f7fb..3d8bab23 100644 --- a/src/types.ts +++ b/src/types.ts @@ -292,8 +292,18 @@ export interface HexmakerPluginSettings { /** On-map legend folded to a small "Legend" chip. */ terrainLegendCollapsed?: boolean; /** New maps default to the Expanded palette: true on fresh installs, - * false for installs that predate it (GEN1; see resolveExpandedDefault). */ + * false for installs that predate it (GEN1; see resolveExpandedDefault). + * Only seeds `defaultPalette` now. */ expandedByDefault?: boolean; + /** "Palette for new maps": a palette name; "" or unset = the first + * palette of an enabled map type (see defaultPaletteFor). Seeded once + * by resolveDefaultPalette. */ + defaultPalette?: string; + /** One-time upgrades of palette data that used to be inferred from + * names at run time (see PaletteStore.load): space role types (moon, + * comet, starport…) and a preset's child palette / submap defaults + * copied into same-named installed palettes. */ + paletteDataUpgraded?: boolean; /** Folder holding the plugin's note templates (hex, town). Empty = * "{worldFolder}/templates" (see src/noteTemplates.ts). */ templatesFolder: string; diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 1df33c75..888ca5e8 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -35,6 +35,7 @@ import { getIconUrl, linkLabel } from "../utils"; import { makeScrubbable, wheelValue } from "./scrub"; import { rebalance, toPercents } from "./regionWeights"; import { suggestImpassable } from "./impassableHint"; +import { isImpassable } from "../impassable"; import { SIDES, hexRangeText, type Side } from "./world"; import { blendFromNeighbours, regionBiome, generateConnected, neighbourSpec, NEIGHBOUR_SHARE, occupiedSides, placeNewRegion, regionNameAt, regionNeighbourNames, type NewRegion } from "./neighbours"; import { GeneratorLibrary } from "./GeneratorLibrary"; @@ -262,7 +263,7 @@ export class GeneratorPanel { summary.setAttr("title", [...detail, ...g.warnings].join("\n")); // Current settings, kept in sync with the file. - const s = () => generatorSettings(model); + const s = () => generatorSettings(model, this.plugin.getPaletteByName(GeneratorPanel.paletteName)?.terrains ?? []); // A just-loaded save's settings win over a possibly stale read of the file. const isThisGenerator = (sv: GeneratorSave) => (!!file && sv.generatorPath === file.path) || sv.generatorName === model.name; if (GeneratorPanel.loadedSave && isThisGenerator(GeneratorPanel.loadedSave)) model.settings = { ...GeneratorPanel.loadedSave.settings }; @@ -1005,7 +1006,8 @@ export class GeneratorPanel { // Terrain the learned paths go around, offered to add (never added for you). const drawHints = () => { hintBox.empty(); - const hints = suggestImpassable(model, colors, s().impassable); + const palette = this.plugin.getPaletteByName(GeneratorPanel.paletteName)?.terrains ?? []; + const hints = suggestImpassable(model, colors, s().impassable, new Set(palette.filter(isImpassable).map((t) => t.name))); if (!hints.length) return; const row = hintBox.createDiv({ cls: "duckmage-region-row" }); row.createSpan({ text: "Suggested", cls: "duckmage-map-origin-label" }); diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index cd62f24d..d9c549d4 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -31,6 +31,7 @@ import { kindsForPalette, listGeneratorKinds, neighbourFirst, + kindOptions, optionsWithDefaults, regionDetailDescription, runGenerator, @@ -605,11 +606,13 @@ export class NewMapSetupModal extends HexmakerModal { this.options.sea = seaHint.side; this.seaFromNeighbour = true; } - for (const opt of kind?.options ?? []) { + for (const opt of kind ? kindOptions(kind, terrains) : []) { const r = this.row(optsBox, opt.label); const sel = this.labelled(r, r.createEl("select")); for (const c of opt.choices) sel.createEl("option", { value: c.value, text: c.label }); sel.value = this.options[opt.key] ?? opt.default; + // A saved choice this palette doesn't offer (a star it hasn't got). + if (sel.selectedIndex < 0) sel.value = opt.default; const hint = opt.key === "sea" && seaHint && this.seaFromNeighbour ? r.createDiv({ cls: "setting-item-description duckmage-setup-sea-hint", text: neighbourSeaText(seaHint, anchor ?? "the neighbouring map") }) : undefined; diff --git a/src/worldgen/builtinGenerators.ts b/src/worldgen/builtinGenerators.ts index a2751e05..3aadb861 100644 --- a/src/worldgen/builtinGenerators.ts +++ b/src/worldgen/builtinGenerators.ts @@ -25,7 +25,7 @@ import { } from "../../packages/hex-wfc/src"; import type { TerrainColor } from "../types"; import { DEFAULT_TERRAIN_PALETTE } from "../constants"; -import { inferTerrainType } from "../terrainTypes"; +import { effectiveTerrainType, inferTerrainType } from "../terrainTypes"; import biomeAlpine from "./builtin/biome-alpine.md"; import biomeBadlands from "./builtin/biome-badlands.md"; @@ -139,9 +139,10 @@ export const TYPE_FALLBACKS: Record = { settlement: [], }; -/** A palette terrain's type: its own, else guessed from its name. */ +/** A palette terrain's type: its Type column only (untyped terrains are + * never matched by name; see effectiveTerrainType). */ function typeOf(t: TerrainColor): string | undefined { - return t.type ?? inferTerrainType(t.name, t.category, "world"); + return effectiveTerrainType(t); } const words = (s: string) => new Set(s.toLowerCase().split(/[^a-z]+/).filter(Boolean)); @@ -151,7 +152,7 @@ const words = (s: string) => new Set(s.toLowerCase().split(/[^a-z]+/).filter(Boo * name). Generator terrains with no match are left out. */ export function mapTerrainsByType(model: HexWfcModel, palette: TerrainColor[]): Map { - const byName = new Map(palette.map((t) => [t.name.toLowerCase(), t.name])); + const byName = new Map(palette.map((t) => [t.name.toLowerCase(), t])); const byType = new Map(); for (const t of palette) { const ty = typeOf(t); @@ -160,10 +161,14 @@ export function mapTerrainsByType(model: HexWfcModel, palette: TerrainColor[]): } const out = new Map(); for (const { name } of model.terrains) { - const exact = byName.get(name.toLowerCase()); - if (exact) { out.set(name, exact); continue; } + // The generator's own terrains are typed from the shipped reference + // list (they were written against it); the palette's go by their Type + // column only. A same-named palette terrain wins only when its type + // agrees, so an "ocean" typed desert is never used as sea. const type = REFERENCE_TYPES.get(name.toLowerCase()) ?? inferTerrainType(name, undefined, "world"); if (!type) continue; + const exact = byName.get(name.toLowerCase()); + if (exact && typeOf(exact) === type) { out.set(name, exact.name); continue; } for (const ty of [type, ...(TYPE_FALLBACKS[type] ?? [])]) { const cands = byType.get(ty); if (!cands?.length) continue; diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index 5588fef1..3161352c 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -15,6 +15,8 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import { getFrontMatter, getTerrainFromFile, setTerrainInFile } from "../frontmatter"; import { normalizeFolder, slugify } from "../utils"; import { VERSION_KEY, pluginVersion } from "../compat"; +import { isImpassable } from "../impassable"; +import type { TerrainColor } from "../types"; import { learnModel, mergeModels, @@ -369,26 +371,51 @@ export interface GridSpec { stagger: "odd" | "even"; } -/** Terrain names treated as impassable until a generator sets its own list. */ -export const DEFAULT_IMPASSABLE = ["shallows", "ocean", "trench"]; - /** * Impassable terrains for a generator that has never saved the setting: its - * terrains named like DEFAULT_IMPASSABLE (any case), so "Connected land" - * works out of the box. Once the generator saves a list (even an empty one), - * that list is used instead. + * terrains that the palette marks impassable (the palette's Impassable + * column, else the terrain type's group: water by default; see + * isImpassable), so "Connected land" works out of the box on any palette + * and agrees with the path tool. Once the generator saves a list (even an + * empty one), that list is used instead. */ -export function defaultImpassable(model: HexWfcModel): string[] | undefined { +export function defaultImpassable(model: HexWfcModel, palette: readonly TerrainColor[]): string[] | undefined { if (model.settings?.impassable !== undefined) return undefined; - return model.terrains.map((t) => t.name).filter((n) => DEFAULT_IMPASSABLE.includes(n.toLowerCase())); + const blocked = new Set(palette.filter(isImpassable).map((t) => t.name.toLowerCase())); + return model.terrains.map((t) => t.name).filter((n) => blocked.has(n.toLowerCase())); } /** Saved settings with the plugin's defaults filled in (see defaultImpassable). */ -export function generatorSettings(model: HexWfcModel): Required { - const impassable = defaultImpassable(model); +export function generatorSettings(model: HexWfcModel, palette: readonly TerrainColor[]): Required { + const impassable = defaultImpassable(model, palette); return resolveSettings(model, impassable ? { impassable } : {}); } +/** + * The palette entries for a list of terrain names: from the palette that + * has them all (the one the map or generator panel uses), else the first + * entry of each name across palettes. + */ +export function paletteEntriesFor(plugin: HexmakerPlugin, names: readonly string[]): TerrainColor[] { + const palettes = plugin.settings.terrainPalettes ?? []; + const own = palettes.find((p) => names.every((n) => p.terrains.some((t) => t.name === n))); + const want = new Set(names); + const seen = new Set(); + const out: TerrainColor[] = []; + for (const t of own ? own.terrains : palettes.flatMap((p) => p.terrains)) { + if (!want.has(t.name) || seen.has(t.name)) continue; + seen.add(t.name); + out.push(t); + } + return out; +} + +/** The solver's `impassable` option from defaultImpassable, when it applies. */ +function impassableDefault(model: HexWfcModel, palette: readonly TerrainColor[]): { impassable?: string[] } { + const list = defaultImpassable(model, palette); + return list ? { impassable: list } : {}; +} + /** * Run a generator on a grid. Terrains the palette lacks are dropped from the * generator first. Fixed hexes whose terrain the generator doesn't know are @@ -423,7 +450,7 @@ export function generateTerrain( stagger: grid.stagger, seed, fixed, - ...(defaultImpassable(model) ? { impassable: defaultImpassable(model) } : {}), + ...impassableDefault(model, paletteEntriesFor(plugin, paletteTerrains)), }); } diff --git a/src/worldgen/impassableHint.ts b/src/worldgen/impassableHint.ts index 4db93bd3..9decb2e3 100644 --- a/src/worldgen/impassableHint.ts +++ b/src/worldgen/impassableHint.ts @@ -9,7 +9,8 @@ * small terrains the paths simply weren't drawn near aren't suggested. * * Fallback, only for generators without paths: a big terrain that looks like - * water (blue, or named like it). + * water (blue) or that the palette marks impassable (its Impassable column + * or type group). Never by name. */ import type { HexWfcModel, PathFeature } from "../../packages/hex-wfc/src"; @@ -26,8 +27,6 @@ const AVOID_RATIO = 0.25; /** Suggest only if missing it this completely by chance is under this probability. */ const MAX_CHANCE = 0.001; -const WATERY = /\b(ocean|sea|lake|water|shallows|deep|trench|abyss|chasm|lava|magma|void|reef|lagoon|bay)\b/i; - /** Roughly how many hexes a route covered in the example. */ function routeHexes(p: PathFeature, exampleHexes: number): number { const side = Math.sqrt(Math.max(exampleHexes, 1)); @@ -52,6 +51,8 @@ export function suggestImpassable( model: HexWfcModel, colors: Map = new Map(), already: string[] = [], + /** Terrains the palette marks impassable (see isImpassable). */ + paletteImpassable: ReadonlySet = new Set(), ): ImpassableHint[] { const total = model.terrains.reduce((n, t) => n + Math.max(0, t.weight), 0); if (total <= 0) return []; @@ -90,17 +91,19 @@ export function suggestImpassable( return out.sort((a, b) => a.terrain.localeCompare(b.terrain)); } - // No paths to go on: only big terrain that looks like water. + // No paths to go on: only big terrain that looks like water or that the + // palette marks impassable. const out: ImpassableHint[] = []; for (const c of candidates) { if (c.share < 0.05) continue; const hs = hueSat(colors.get(c.name)); const blue = !!hs && hs.h >= 185 && hs.h <= 250 && hs.s >= 0.25; - const named = WATERY.test(c.name); - if (!blue && !named) continue; + const marked = paletteImpassable.has(c.name); + if (!blue && !marked) continue; + const why = [marked ? "the palette marks it impassable" : "", blue ? "its colour looks like water" : ""].filter(Boolean).join(" and "); out.push({ terrain: c.name, - reason: `looks like water (${[named ? "its name" : "", blue ? "its colour" : ""].filter(Boolean).join(" and ")}) and covers ${pct(c.share)}; there are no paths to tell for sure`, + reason: `${why}, and it covers ${pct(c.share)}; there are no paths to tell for sure`, }); } return out.sort((a, b) => a.terrain.localeCompare(b.terrain)); diff --git a/src/worldgen/procedural/common.ts b/src/worldgen/procedural/common.ts index 04b954e2..e2748b0d 100644 --- a/src/worldgen/procedural/common.ts +++ b/src/worldgen/procedural/common.ts @@ -121,35 +121,27 @@ export function centerHex(grid: ProcGrid): [number, number] { export { cellKey }; /** - * Find a palette terrain for a role: the first name match (case-insensitive), - * else — when `category` is given — the first terrain in that category. - * Lets the generators run on renamed or user-made palettes, not just the - * shipped presets. + * The first terrain whose name is one of `names` (case-insensitive), in the + * order of `names`. Only used to break ties among terrains already chosen + * by type (findByType's `preferNames`); never to pick a terrain by name. */ -export function findTerrain( - terrains: TerrainColor[], - names: string[], - category?: string, -): string | undefined { +export function findTerrain(terrains: TerrainColor[], names: string[]): string | undefined { const byName = new Map(terrains.map((t) => [t.name.toLowerCase(), t.name])); for (const n of names) { const hit = byName.get(n.toLowerCase()); if (hit) return hit; } - if (category) return terrains.find((t) => t.category?.toLowerCase() === category)?.name; return undefined; } -/** All terrains in a category (case-insensitive), in palette order. */ -export function inCategory(terrains: TerrainColor[], category: string): string[] { - return terrains.filter((t) => t.category?.toLowerCase() === category).map((t) => t.name); -} - /* - * Type-aware lookups. A terrain's `type` (see terrainTypes.ts) is - * authoritative: a typed terrain fills only the roles of its type, however - * it is named, so "ocean" typed desert is never used as sea. The name / - * category guesses above are the fallback for untyped terrains only. + * Type-aware lookups. A terrain's `type` (see terrainTypes.ts) is the only + * thing that gives it a role: a typed terrain fills only the roles of its + * type, however it is named ("ocean" typed desert is never used as sea), + * and an untyped terrain fills none — not even one named "ocean" or filed + * under a "sea" category. Generators work the same on any palette, the + * shipped ones included; the palette editor's "Guess types from names" + * button types a hand-made palette in one go. */ /** Terrains with a known type id. Unknown ids count as untyped. */ @@ -157,11 +149,6 @@ function typeOf(t: TerrainColor): string | undefined { return isTerrainType(t.type) ? t.type : undefined; } -/** Terrains without a (known) type: the ones name / category guesses may use. */ -export function untyped(terrains: TerrainColor[]): TerrainColor[] { - return terrains.filter((t) => !typeOf(t)); -} - /** Names of all terrains of the given types, in palette order. */ export function ofType(terrains: TerrainColor[], typeIds: string[]): string[] { return terrains.filter((t) => typeIds.includes(typeOf(t) ?? "")).map((t) => t.name); @@ -190,19 +177,6 @@ export function findByType( return undefined; } -/** - * Resolve a role: by type first, else by name / category among the - * untyped terrains (older or hand-made palettes). - */ -export function findRole( - terrains: TerrainColor[], - typeIds: string[], - names: string[], - category?: string, -): string | undefined { - return findByType(terrains, typeIds, names) ?? findTerrain(untyped(terrains), names, category); -} - /** Lower-case name → type id, for weight tables keyed by type. */ export function typeIndex(terrains: TerrainColor[]): Map { const out = new Map(); diff --git a/src/worldgen/procedural/contextPaths.ts b/src/worldgen/procedural/contextPaths.ts index 1cba2b17..16199edc 100644 --- a/src/worldgen/procedural/contextPaths.ts +++ b/src/worldgen/procedural/contextPaths.ts @@ -1,6 +1,6 @@ import { hexCenter, hexNeighbors, mulberry32 } from "../../../packages/hex-wfc/src"; import type { TerrainColor } from "../../types"; -import { inferTerrainType, isTerrainType } from "../../terrainTypes"; +import { effectiveTerrainType } from "../../terrainTypes"; import { SIDE_VECTORS, cellKey, centerHex, gridKeys, type ContextPath, type ProcGrid, type ProcPath, type Side } from "./common"; /** @@ -49,7 +49,7 @@ export function edgeHex(grid: ProcGrid, side: Side): [number, number] { /** * Route each context path over the generated cells. `terrains` gives each - * cell's type (falling back to a name guess); unpainted cells cost 1. + * cell's type (its Type column; untyped and unpainted cells cost 1). */ export function routeContextPaths( cells: Map, @@ -58,7 +58,7 @@ export function routeContextPaths( paths: ContextPath[], seed: number, ): ProcPath[] { - const typeByName = new Map(terrains.map((t) => [t.name, isTerrainType(t.type) ? t.type : inferTerrainType(t.name, t.category)])); + const typeByName = new Map(terrains.map((t) => [t.name, effectiveTerrainType(t)])); const hexes = gridKeys(grid); const inGrid = new Set(hexes.map(([x, y]) => cellKey(x, y))); const out: ProcPath[] = []; diff --git a/src/worldgen/procedural/orbits.ts b/src/worldgen/procedural/orbits.ts index 7163e157..fc91b002 100644 --- a/src/worldgen/procedural/orbits.ts +++ b/src/worldgen/procedural/orbits.ts @@ -4,13 +4,9 @@ import { cellKey, centerHex, distance, - findByType, - findTerrain, gridKeys, - inCategory, ofType, typeIndex, - untyped, weightedPick, type GenerationContext, type ProcGrid, @@ -27,10 +23,11 @@ import { * giants more often, and up to two; the mainworld may get a station or starport alongside; * a comet and a jump point sit out past the last orbit. * - * Works on any palette with a background (type void, or "void" / "empty - * space" / first `space` terrain) and at least one star and one body — by - * type (star; world / gas-giant / asteroids), else by name or the `stars` - * / `bodies` categories. + * Works on any palette with a background (type void), at least one star + * (type star) and one body (world / gas-giant / asteroids). Every other + * role has its own type too — moon, comet, station, starport, jump point, + * jump limit — so it is the Type column, never a terrain's name, that + * decides what goes where. */ export const ORBITS_ID = "procedural:orbits"; @@ -61,6 +58,20 @@ export const ORBITS_OPTIONS: ProcOption[] = [ }, ]; +/** + * Orbits' options for a palette: the Star choice lists that palette's own + * stars (star-typed terrains), so it only offers what it can place. With + * no palette given, the shipped star list. + */ +export function orbitsOptions(terrains?: TerrainColor[]): ProcOption[] { + if (!terrains) return ORBITS_OPTIONS; + const stars = ofType(terrains, ["star"]); + return ORBITS_OPTIONS.map((o) => o.key !== "star" ? o : { + ...o, + choices: [{ value: "random", label: "Random" }, ...stars.map((s) => ({ value: s.toLowerCase(), label: s.charAt(0).toUpperCase() + s.slice(1) }))], + }); +} + /** Galactic mix: red dwarfs dominate. */ const STAR_WEIGHTS: Record = { "red dwarf": 6, @@ -101,11 +112,6 @@ const ZONE_TYPE_WEIGHTS: Record> = { asteroids: { inner: 0.5, habitable: 1, outer: 1.5 }, }; -/** Typed bodies that never take an orbit of their own. */ -const MOON = /\bmoons?\b|satellite/i; -const COMET = /comet/i; -const DEBRIS = /debris|wreck/i; - export interface OrbitRoles { background: string; stars: string[]; @@ -117,56 +123,42 @@ export interface OrbitRoles { jumpPoint?: string; jumpLimit?: string; belt?: string; - /** Bodies drawn as an arc of their ring (asteroid-type bodies, belts). */ + /** Bodies drawn as an arc of their ring (asteroid-belt type). */ belts: string[]; - /** Bodies that may get a moon (gas-giant type, or "giant" in the name). */ + /** Bodies that may get two moons (gas-giant type). */ giants: string[]; /** Per-zone body weights (lower-case names) for weightedPick. */ zoneWeights: Record>; } /** - * Roles by type first — void, star, world / gas-giant / asteroids, station - * — split by name hints where the type is coarse (moon vs planet, comet vs - * belt, starport vs jump point); untyped terrains fall back to the - * category and exact-name lookups. + * Roles by terrain type only: void (background), star, world / gas-giant / + * asteroids (bodies that take an orbit), and one terrain each for moon, + * comet, station, starport, jump point and jump limit. A terrain's name + * plays no part, so a custom palette ("Luna" typed moon) works the same as + * the shipped one, and an untyped terrain is never placed. */ export function orbitRoles(terrains: TerrainColor[]): OrbitRoles | undefined { - const loose = untyped(terrains); - // "jump limit" is void-typed too, but it is a marker, not the background. - const background = findByType(terrains.filter((t) => !/limit/i.test(t.name)), ["void"], ["void", "empty space", "deep space", "space"]) - ?? findTerrain(loose, ["void", "empty space", "deep space", "space"], "space"); - // A sector's "star system" marker is star-typed but isn't a star. - let stars = [...ofType(terrains, ["star"]).filter((s) => !/system/i.test(s)), ...inCategory(loose, "stars")]; - if (stars.length === 0) { - const s = findTerrain(loose, ["yellow star", "star", "sun"]); - stars = s ? [s] : []; - } - const typedBodies = ofType(terrains, ["world", "gas-giant", "asteroids"]); - let bodies = [ - ...typedBodies.filter((b) => !MOON.test(b) && !COMET.test(b) && !DEBRIS.test(b)), - ...inCategory(loose, "bodies").filter((b) => !/^(moon|comet)$/i.test(b)), - ]; - if (bodies.length === 0) bodies = loose.map((t) => t.name).filter((n) => BODY_NAMES.includes(n.toLowerCase())); + const background = ofType(terrains, ["void"])[0]; + const stars = ofType(terrains, ["star"]); + const bodies = ofType(terrains, ["world", "gas-giant", "asteroids"]); if (!background || stars.length === 0 || bodies.length === 0) return undefined; const types = typeIndex(terrains); - const exact = (n: string) => findTerrain(loose, [n]); - const station = (want: RegExp | undefined, avoid: RegExp | undefined, prefer: string[]) => - findByType(terrains.filter((t) => (!want || want.test(t.name)) && !avoid?.test(t.name)), ["station"], prefer); - const belts = bodies.filter((b) => types.get(b.toLowerCase()) === "asteroids" || /belt/i.test(b)); + const first = (type: string) => ofType(terrains, [type])[0]; + const belts = ofType(terrains, ["asteroids"]); return { background, stars, bodies, - moon: findByType(terrains.filter((t) => MOON.test(t.name)), ["world"], ["moon"]) ?? exact("moon"), - comet: findByType(terrains.filter((t) => COMET.test(t.name)), ["asteroids"], ["comet"]) ?? exact("comet"), - station: station(undefined, /port|jump|gate/i, ["space station", "station"]) ?? exact("space station"), - starport: station(/port/i, undefined, ["starport"]) ?? exact("starport"), - jumpPoint: station(/jump|gate/i, undefined, ["jump point"]) ?? exact("jump point"), - jumpLimit: findByType(terrains.filter((t) => /limit/i.test(t.name)), ["void"], ["jump limit"]) ?? exact("jump limit"), + moon: first("moon"), + comet: first("comet"), + station: first("station"), + starport: first("starport"), + jumpPoint: first("jump-point"), + jumpLimit: first("jump-limit"), belt: belts[0], belts, - giants: bodies.filter((b) => types.get(b.toLowerCase()) === "gas-giant" || /giant/i.test(b)), + giants: ofType(terrains, ["gas-giant"]), zoneWeights: { inner: zoneWeights(bodies, types, "inner"), habitable: zoneWeights(bodies, types, "habitable"), diff --git a/src/worldgen/procedural/planetSurface.ts b/src/worldgen/procedural/planetSurface.ts index 53acffdd..a8647cd2 100644 --- a/src/worldgen/procedural/planetSurface.ts +++ b/src/worldgen/procedural/planetSurface.ts @@ -1,6 +1,6 @@ import { hexCenter, hexNeighbors, mulberry32 } from "../../../packages/hex-wfc/src"; import type { TerrainColor } from "../../types"; -import { inferTerrainType, isTerrainType } from "../../terrainTypes"; +import { isTerrainType } from "../../terrainTypes"; import { SIDES, SIDE_VECTORS, @@ -10,7 +10,6 @@ import { type GenerationContext, type Side, findByType, - findRole, gridKeys, typeIndex, ofType, @@ -27,9 +26,9 @@ import { * water % and climate let one generator cover ocean worlds, deserts and * ice balls (the space presets set these per planet type). * - * Terrain roles resolve by terrain type, then (for untyped terrains) by - * name and category, so the Limited / Expanded palettes and user palettes - * with any names all work. + * Terrain roles resolve by terrain type only, so the Limited / Expanded + * palettes and user palettes with any names work the same (untyped + * terrains get no role). */ export const PLANET_SURFACE_ID = "procedural:planet-surface"; @@ -149,7 +148,7 @@ export function seaSideFromNeighbours( const w = x < o.x, e = x > o.x + cols - 1, nn = y < o.y, s = y > o.y + rows - 1; if (Number(w) + Number(e) + Number(nn) + Number(s) !== 1) continue; // corners: ambiguous const seam: Seam = w ? "west" : e ? "east" : nn ? "north" : "south"; - const type = isTerrainType(c.type) ? c.type : c.terrain ? inferTerrainType(c.terrain) : undefined; + const type = isTerrainType(c.type) ? c.type : undefined; if (!type) continue; const at = seams.get(seam) ?? { n: 0, wet: [] }; at.n++; @@ -351,34 +350,33 @@ function planetVariants(terrains: TerrainColor[], forest: string | undefined): P /** * Roles by terrain type first (water, grassland, forest, …), so custom - * names like "Kelp sea" or "Pinewood" work; untyped palettes fall back to - * the name and category guesses. The base hills / mountain role skips + * names like "Kelp sea" or "Pinewood" work; untyped terrains get no role. The base hills / mountain role skips * wooded variants ("forested hills"), which only appear on moist ground. */ export function planetRoles(terrains: TerrainColor[]): PlanetRoles | undefined { - const sea = findRole(terrains, ["water"], ["ocean", "sea", "water"], "sea"); - const plains = findRole(terrains, ["grassland"], ["grass", "grassland", "plains", "lowland", "meadow"], "lowlands"); + const sea = findByType(terrains, ["water"], ["ocean", "sea", "water"]); + const plains = findByType(terrains, ["grassland"], ["grass", "grassland", "plains", "lowland", "meadow"]); if (!sea || !plains) return undefined; const bare = terrains.filter((t) => !WOODED.test(t.name)); - const rugged = (type: string, names: string[], category?: string) => - findByType(bare, [type], names) ?? findRole(terrains, [type], names, category); - const forest = findRole(terrains, ["forest"], ["forest", "mixed forest", "woods"], "forest"); + const rugged = (type: string, names: string[]) => + findByType(bare, [type], names) ?? findByType(terrains, [type], names); + const forest = findByType(terrains, ["forest"], ["forest", "mixed forest", "woods"]); return { sea, plains, - deep: findRole(terrains, ["deep-water"], ["trench", "deep ocean", "deep water", "abyss"]), - shallows: findRole(terrains, ["shallows"], ["shallows", "shallow water", "reef"]), - beach: findRole(terrains, ["coast"], ["beach", "coast", "shore", "sand"], "coast"), + deep: findByType(terrains, ["deep-water"], ["trench", "deep ocean", "deep water", "abyss"]), + shallows: findByType(terrains, ["shallows"], ["shallows", "shallow water", "reef"]), + beach: findByType(terrains, ["coast"], ["beach", "coast", "shore", "sand"]), forest, - jungle: findRole(terrains, ["jungle"], ["jungle", "rainforest"]), - swamp: findRole(terrains, ["wetland"], ["swamp", "marsh", "bog"], "bog"), + jungle: findByType(terrains, ["jungle"], ["jungle", "rainforest"]), + swamp: findByType(terrains, ["wetland"], ["swamp", "marsh", "bog"]), hills: rugged("hills", ["hills", "hill", "foothills"]), - mountain: rugged("mountains", ["mountain", "mountains"], "mountain"), - peak: findRole(terrains, ["peaks"], ["peak", "mountains snow", "mountain snow", "snowy peak"]), - snow: findRole(terrains, ["snow"], ["snow", "tundra", "ice", "glacier"], "snow"), - desert: findRole(terrains, ["desert"], ["desert", "dunes", "desert rocky"], "desert"), - badlands: findRole(terrains, ["badlands"], ["badlands", "brokenlands", "wasteland"]), - volcano: findRole(terrains, ["volcanic"], ["volcano", "volcanic"]), + mountain: rugged("mountains", ["mountain", "mountains"]), + peak: findByType(terrains, ["peaks"], ["peak", "mountains snow", "mountain snow", "snowy peak"]), + snow: findByType(terrains, ["snow"], ["snow", "tundra", "ice", "glacier"]), + desert: findByType(terrains, ["desert"], ["desert", "dunes", "desert rocky"]), + badlands: findByType(terrains, ["badlands"], ["badlands", "brokenlands", "wasteland"]), + volcano: findByType(terrains, ["volcanic"], ["volcano", "volcanic"]), variants: planetVariants(terrains, forest), }; } @@ -491,7 +489,7 @@ const TYPE_TARGETS: Record = { function targetOf(c: ContextTerrain | undefined): [number, number, number] | undefined { if (!c) return undefined; - const type = isTerrainType(c.type) ? c.type : c.terrain ? inferTerrainType(c.terrain) : undefined; + const type = isTerrainType(c.type) ? c.type : undefined; return type ? TYPE_TARGETS[type] : undefined; } @@ -804,7 +802,7 @@ export function edgePulls( ): (EdgePull | undefined)[] { const cells = [...edgeCells] .map(([k, c]) => { - const type = isTerrainType(c.type) ? c.type : c.terrain ? inferTerrainType(c.terrain) : undefined; + const type = isTerrainType(c.type) ? c.type : undefined; return { at: k.split("_").map(Number) as [number, number], type }; }) .filter((c): c is { at: [number, number]; type: NonNullable } => !!c.type && !!TYPE_TARGETS[c.type]); diff --git a/src/worldgen/procedural/starScatter.ts b/src/worldgen/procedural/starScatter.ts index 5771fe3a..693667a2 100644 --- a/src/worldgen/procedural/starScatter.ts +++ b/src/worldgen/procedural/starScatter.ts @@ -4,13 +4,9 @@ import type { TerrainColor } from "../../types"; import { cellKey, distance, - findRole, - findTerrain, gridKeys, - inCategory, ofType, typeIndex, - untyped, weightedPick, type ProcGrid, type ProcOption, @@ -25,10 +21,8 @@ import { * them, rare features (black hole, anomaly, deep-space station) are * sprinkled in, and nearby systems can be joined by jump routes. * - * Works on any palette with a background terrain (type void, or "empty - * space" / "void" / first `space` terrain) and at least one world (type - * world / gas-giant / asteroids, or the `worlds` category, or a "star - * system" terrain). + * Works on any palette with a background terrain (type void) and at least + * one world (type world / gas-giant / asteroids, or a star-system terrain). */ export const STAR_SCATTER_ID = "procedural:star-scatter"; @@ -96,38 +90,29 @@ export interface StarScatterRoles { /** Weights for typed terrains whose names aren't in the tables above. */ const WORLD_TYPE_WEIGHTS: Record = { world: 2.5, "gas-giant": 1, asteroids: 1.5 }; -const FEATURE_TYPE_WEIGHTS: Record = { station: 3, anomaly: 1.5 }; +const FEATURE_TYPE_WEIGHTS: Record = { station: 3, starport: 3, "jump-point": 3, anomaly: 1.5 }; -/** Typed worlds that aren't a system's mainworld: comets, debris fields. */ -const NOT_MAINWORLD = /comet|debris/i; +/** Feature types that host a system (and so a jump route). */ +const HOSTS_SYSTEM = new Set(["station", "starport", "jump-point"]); /** - * Roles by type first (void / world, gas-giant, asteroids / nebula / - * station, anomaly), then by name and category for untyped terrains. List - * roles take both, so a half-typed palette still uses everything. + * Roles by terrain type only: void (background), world / gas-giant / + * asteroids (mainworlds; comets and debris have their own types and are + * left out), nebula (clouds), station / starport / jump point / anomaly + * (features). With no worlds, a star-system (or star) terrain marks the + * systems. Names and categories play no part; untyped terrains are unused. */ export function starScatterRoles(terrains: TerrainColor[]): StarScatterRoles | undefined { - const loose = untyped(terrains); - const background = findRole(terrains, ["void"], ["empty space", "void", "deep space", "space"], "space"); - let worlds = [ - ...ofType(terrains, ["world", "gas-giant", "asteroids"]).filter((t) => !NOT_MAINWORLD.test(t)), - ...inCategory(loose, "worlds"), - ]; + const background = ofType(terrains, ["void"])[0]; + let worlds = ofType(terrains, ["world", "gas-giant", "asteroids"]); if (worlds.length === 0) { - const system = findRole(terrains, ["star"], ["star system", "system", "star"]); + const system = ofType(terrains, ["star-system"])[0] ?? ofType(terrains, ["star"])[0]; worlds = system ? [system] : []; } if (!background || worlds.length === 0) return undefined; - const clouds = [ - ...ofType(terrains, ["nebula"]), - ...inCategory(loose, "space").filter((t) => t !== background && !/rift/i.test(t)), - ]; - const cloudNames = clouds.length ? clouds : [findTerrain(loose, ["nebula", "dust cloud"])].filter((t): t is string => !!t); - const features = [ - ...ofType(terrains, ["station", "anomaly"]), - ...inCategory(loose, "features").filter((t) => !/^star system$/i.test(t)), - ]; - return { background, worlds, clouds: cloudNames, features }; + const clouds = ofType(terrains, ["nebula"]); + const features = ofType(terrains, ["station", "starport", "jump-point", "anomaly"]); + return { background, worlds, clouds, features }; } /** Name weights, else the terrain's type weight; unknowns fall through to the default. */ @@ -166,7 +151,7 @@ export function starScatter( const worldWeights = weightsFor(roles.worlds, types, WORLD_WEIGHTS, WORLD_TYPE_WEIGHTS); const featureWeights = weightsFor(roles.features, types, FEATURE_WEIGHTS, FEATURE_TYPE_WEIGHTS); // Stations host a system (and so a route); black holes and anomalies don't. - const hostsSystem = (t: string) => types.get(t.toLowerCase()) === "station" || /station/i.test(t); + const hostsSystem = (t: string) => HOSTS_SYSTEM.has(types.get(t.toLowerCase()) ?? ""); const density = DENSITY[options.density ?? "standard"] ?? 0.5; const hexes = gridKeys(grid); const cells = new Map(); diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index de0e6029..96c93f40 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -8,9 +8,9 @@ import { toPathChains, type GridSpec, } from "./generators"; -import { findTerrain, SIDES, type GenerationContext, type ProcGrid, type ProcOption, type Side } from "./procedural/common"; +import { ofType, SIDES, type GenerationContext, type ProcGrid, type ProcOption, type Side } from "./procedural/common"; import { STAR_SCATTER_ID, STAR_SCATTER_OPTIONS, starScatter, starScatterOffered } from "./procedural/starScatter"; -import { ORBITS_ID, ORBITS_OPTIONS, orbits, orbitsFits } from "./procedural/orbits"; +import { ORBITS_ID, ORBITS_OPTIONS, orbits, orbitsFits, orbitsOptions } from "./procedural/orbits"; import { PLANET_SURFACE_ID, OVERLAND_ID, @@ -83,6 +83,10 @@ export interface TerrainGeneratorKind { * via generateConnected). */ continuesNeighbours?: boolean; options: ProcOption[]; + /** The options as shown for one palette, when a choice lists that + * palette's own terrains (Orbits' Star). Same keys and defaults as + * `options`; see kindOptions. */ + optionsFor?(terrains: TerrainColor[]): ProcOption[]; /** Can this generator produce terrain for a palette with these terrains? */ fits(terrains: TerrainColor[]): boolean; generate(req: GenerateRequest): GenerateOutcome; @@ -160,11 +164,12 @@ export function describeKind(kind: TerrainGeneratorKind, terrains: TerrainColor[ } /** - * The terrain a fresh map shows where nothing has been painted: the space - * background on space palettes ("void" / "empty space"), otherwise none. + * The terrain a fresh map shows where nothing has been painted: the + * palette's first void-typed terrain (the space background), otherwise + * none. By type, so a renamed or custom background works too. */ export function suggestBaseTerrain(terrains: TerrainColor[]): string | undefined { - return findTerrain(terrains, ["void", "empty space", "deep space"]); + return ofType(terrains, ["void"])[0]; } function procGrid(plugin: HexmakerPlugin, grid: GridSpec): ProcGrid { @@ -212,6 +217,7 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise { const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitPath, req.context); @@ -372,6 +378,11 @@ export function runGenerator( return { ...outcome, paths: [...outcome.paths, ...routed] }; } +/** A generator's options as shown for a palette (see optionsFor). */ +export function kindOptions(kind: Pick, terrains: TerrainColor[]): ProcOption[] { + return kind.optionsFor?.(terrains) ?? kind.options; +} + /** A generator's options at their defaults, overridden by `chosen`. */ export function optionsWithDefaults(kind: Pick, chosen: Record = {}): Record { const out: Record = {}; diff --git a/tests/builtinGenerators.test.ts b/tests/builtinGenerators.test.ts index 968fdafc..5e036aba 100644 --- a/tests/builtinGenerators.test.ts +++ b/tests/builtinGenerators.test.ts @@ -105,6 +105,37 @@ describe("shipped biome / preset generators", () => { for (const t of used) expect(custom.some((c) => c.name === t)).toBe(true); }); + it("the Expanded palette renamed maps every generator terrain to the same palette entry", () => { + const renamed = DEFAULT_TERRAIN_PALETTE.map((t, i) => ({ ...t, name: `Terrain ${i}` })); + for (const [slug, model] of models) { + const a = mapTerrainsByType(model, DEFAULT_TERRAIN_PALETTE); + const b = mapTerrainsByType(model, renamed); + for (const t of model.terrains) { + const ia = DEFAULT_TERRAIN_PALETTE.findIndex((x) => x.name === a.get(t.name)); + const ib = renamed.findIndex((x) => x.name === b.get(t.name)); + // Same type always; same entry unless a word-match tie-break picked a sibling. + expect({ slug, t: t.name, type: renamed[ib]?.type }).toEqual({ slug, t: t.name, type: DEFAULT_TERRAIN_PALETTE[ia]?.type }); + } + } + }); + + it("a same-named palette terrain of another type is not used (an \"ocean\" typed desert is not the sea)", () => { + const pal: TerrainColor[] = [ + { name: "ocean", type: "desert", color: "#ff0" }, + { name: "Brine", type: "water", color: "#00f" }, + ]; + const mapping = mapTerrainsByType(models.get("preset-archipelago")!, pal); + expect(mapping.get("ocean")).toBe("Brine"); + }); + + it("untyped palettes (or everything deleted) fit no shipped generator", () => { + const untyped = DEFAULT_TERRAIN_PALETTE.map(({ type: _t, ...rest }) => rest); + for (const model of models.values()) { + expect(fitBuiltinModel(model, untyped)).toBeUndefined(); + expect(fitBuiltinModel(model, [])).toBeUndefined(); + } + }); + it("doesn't fit a space palette", () => { for (const model of models.values()) expect(fitBuiltinModel(model, SPACE_SYSTEM_TERRAINS)).toBeUndefined(); }); diff --git a/tests/impassable.test.ts b/tests/impassable.test.ts index 2fe66a07..7f1ee319 100644 --- a/tests/impassable.test.ts +++ b/tests/impassable.test.ts @@ -133,24 +133,50 @@ describe("impassable by type group (PA4)", () => { expect(impassableNames(custom)).toEqual(["Mirror Mere", "Kraken Deeps", "Coral Shelf"]); }); - it("an untyped custom terrain counts as the type its name suggests", () => { - expect(effectiveTerrainType({ name: "Black Lake" })).toBe("water"); - expect(effectiveTerrainType({ name: "Mirror Mere", type: "water" })).toBe("water"); - expect(effectiveTerrainType({ name: "Mirror Mere" })).toBeUndefined(); - expect(isImpassable({ name: "Black Lake" })).toBe(true); - expect(isImpassable({ name: "Old Forest" })).toBe(false); - // A known type wins over the name. + // Owner rule (2026-10-10): never special-case names. The Type column is + // the only thing that gives a terrain its defaults, so an untyped "Black + // Lake" is passable (the editor shows Type blank and Impassable unticked: + // what it shows is what it does). + it("an untyped terrain has no type, whatever its name", () => { + expect(effectiveTerrainType({ name: "Black Lake" } as { type?: string })).toBeUndefined(); + expect(effectiveTerrainType({ type: "water" })).toBe("water"); + expect(effectiveTerrainType({ type: "made-up" })).toBeUndefined(); + expect(isImpassable({ name: "Black Lake" })).toBe(false); + expect(isImpassable({ name: "ocean" })).toBe(false); + expect(impassableSourceText({ name: "Black Lake" })).toBe("Default (no type: passable)"); + // The type decides, never the name. expect(isImpassable({ name: "Lake District", type: "hills" })).toBe(false); + expect(isImpassable({ name: "Dry Gulch", type: "water" })).toBe(true); }); it("a per-terrain override still wins, and only overrides are stored", () => { expect(isImpassable({ name: "Ford", type: "shallows", impassable: false })).toBe(false); expect(isImpassable({ name: "Lava Field", type: "volcanic", impassable: true })).toBe(true); - const lake: TerrainColor = { name: "Black Lake", color: "#00f" }; + const lake: TerrainColor = { name: "Black Lake", color: "#00f", type: "water" }; setImpassable(lake, true); expect("impassable" in lake).toBe(false); setImpassable(lake, false); expect(lake.impassable).toBe(false); + const untyped: TerrainColor = { name: "Black Lake", color: "#00f" }; + setImpassable(untyped, true); + expect(untyped.impassable).toBe(true); + }); + + it("a palette with different names behaves the same as the shipped one", () => { + // Expanded's water group, renamed and reordered. + const shipped = impassableNames(DEFAULT_TERRAIN_PALETTE); + const renamed = DEFAULT_TERRAIN_PALETTE.map((t, i) => ({ ...t, name: `Terrain ${i}` })).reverse(); + expect(impassableNames(renamed).length).toBe(shipped.length); + expect(renamed.filter(isImpassable).map((t) => t.type).sort()) + .toEqual(DEFAULT_TERRAIN_PALETTE.filter(isImpassable).map((t) => t.type).sort()); + }); + + it("a palette built from scratch (everything deleted) works: nothing typed, nothing blocked", () => { + expect(impassableNames([])).toEqual([]); + const scratch: TerrainColor[] = [{ name: "ocean", color: "#00f" }, { name: "river", color: "#00f" }]; + expect(impassableNames(scratch)).toEqual([]); + scratch[0].type = "water"; + expect(impassableNames(scratch)).toEqual(["ocean"]); }); it("the palette editor says where a value comes from", () => { diff --git a/tests/proceduralGenerators.test.ts b/tests/proceduralGenerators.test.ts index ecf996c3..c64f067f 100644 --- a/tests/proceduralGenerators.test.ts +++ b/tests/proceduralGenerators.test.ts @@ -6,16 +6,14 @@ import { } from "../src/palettes/presets"; import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; import { starScatter, starScatterFits, starScatterRoles } from "../src/worldgen/procedural/starScatter"; -import { orbits, orbitsFits, orbitRoles } from "../src/worldgen/procedural/orbits"; +import { orbits, orbitsFits, orbitRoles, orbitsOptions } from "../src/worldgen/procedural/orbits"; import { planetSurface, planetSurfaceFits, planetRoles } from "../src/worldgen/procedural/planetSurface"; import { centerHex, distance, findByType, - findRole, findTerrain, ofType, - untyped, weightedPick, type ProcGrid, } from "../src/worldgen/procedural/common"; @@ -31,10 +29,9 @@ const count = (cells: Map, pred: (t: string) => boolean) => [...cells.values()].filter(pred).length; describe("procedural helpers", () => { - it("findTerrain matches names case-insensitively, then falls back to a category", () => { + it("findTerrain matches names case-insensitively (a tie-break only; categories never pick)", () => { const t = [{ name: "Void", color: "#000", category: "space" }, { name: "x", color: "#111", category: "space" }]; expect(findTerrain(t, ["void"])).toBe("Void"); - expect(findTerrain(t, ["nothing"], "space")).toBe("Void"); expect(findTerrain(t, ["nothing"])).toBeUndefined(); }); @@ -46,10 +43,13 @@ describe("procedural helpers", () => { expect(weightedPick(mulberry32(5), [], {})).toBeUndefined(); }); - it("suggests void / empty space as the base terrain", () => { + it("suggests the first void-typed terrain as the base terrain, whatever its name", () => { expect(suggestBaseTerrain(SPACE_SYSTEM_TERRAINS)).toBe("void"); expect(suggestBaseTerrain(SPACE_SECTOR_TERRAINS)).toBe("empty space"); expect(suggestBaseTerrain(DEFAULT_TERRAIN_PALETTE)).toBeUndefined(); + expect(suggestBaseTerrain([{ name: "The Black", color: "#000", type: "void" }])).toBe("The Black"); + // Named like a background but not typed as one: not a background. + expect(suggestBaseTerrain([{ name: "void", color: "#000" }])).toBeUndefined(); }); }); @@ -115,15 +115,20 @@ describe("star scatter", () => { expect(none.paths).toEqual([]); }); - it("works on a minimal custom palette (renamed terrains, categories only)", () => { + it("works on a minimal custom palette (renamed terrains, typed)", () => { const custom = [ - { name: "Black", color: "#000", category: "space" }, - { name: "Haven", color: "#0f0", category: "worlds" }, + { name: "Black", color: "#000", type: "void" }, + { name: "Haven", color: "#0f0", type: "world" }, ]; expect(starScatterFits(custom)).toBe(true); const r = starScatter(custom, grid(6, 6), 1, { density: "dense" }); expect(new Set(r.cells.values())).toEqual(new Set(["Black", "Haven"])); }); + + it("an untyped palette fits nothing, even with the shipped names and categories", () => { + const untypedSector = SPACE_SECTOR_TERRAINS.map(({ type: _t, ...rest }) => rest); + expect(starScatterFits(untypedSector)).toBe(false); + }); }); describe("orbits", () => { @@ -259,7 +264,6 @@ describe("terrain types", () => { it("ofType lists terrains of the given types in palette order; unknown types count as untyped", () => { expect(ofType(pal, ["forest"])).toEqual(["Forest heavy", "forest", "Pinewood"]); expect(ofType([t("x", "bogus")], ["bogus"])).toEqual([]); - expect(untyped([...pal, t("y", "bogus")]).map((x) => x.name)).toEqual(["sea", "y"]); }); it("findByType prefers name hints within the type, then palette order, then later types", () => { @@ -270,9 +274,9 @@ describe("terrain types", () => { expect(findByType(pal, ["water"], ["ocean"])).toBeUndefined(); }); - it("findRole falls back to names only among untyped terrains", () => { - expect(findRole(pal, ["water"], ["ocean", "sea"])).toBe("sea"); - expect(findRole([t("ocean", "desert")], ["water"], ["ocean"])).toBeUndefined(); + it("an untyped terrain fills no role, even named like one", () => { + expect(findByType(pal, ["water"], ["ocean", "sea"])).toBeUndefined(); + expect(findByType([t("ocean", "desert")], ["water"], ["ocean"])).toBeUndefined(); }); }); @@ -323,14 +327,14 @@ describe("terrain types", () => { t("Big Blue", "gas-giant"), t("Rubble ring", "asteroids"), t("Luna", "world"), - t("Pale moon", "world"), - t("Iceball comet", "asteroids"), - t("Highport", "station"), - t("Gateway", "station"), + t("Pale moon", "moon"), + t("Iceball comet", "comet"), + t("Highport", "starport"), + t("Gateway", "jump-point"), t("Outpost", "station"), ]; - it("resolves roles from types, splitting coarse types by name hints", () => { + it("resolves every role from types alone", () => { const r = orbitRoles(custom)!; expect(r.background).toBe("Abyssal Drift"); expect(r.stars).toEqual(["Embers"]); @@ -369,7 +373,36 @@ describe("terrain types", () => { }); it("does not take a sector's star-system marker for a star", () => { - expect(orbitRoles([t("void", "void"), t("star system", "star"), t("Eden", "world")])).toBeUndefined(); + expect(orbitRoles([t("void", "void"), t("star system", "star-system"), t("Eden", "world")])).toBeUndefined(); + }); + + it("names play no part: a moon named like a planet is a moon, a planet named Moonbase is a planet", () => { + const r = orbitRoles([t("Edge", "void"), t("Sol", "star"), t("Moonbase", "world"), t("Terra Minor", "moon")])!; + expect(r.bodies).toEqual(["Moonbase"]); + expect(r.moon).toBe("Terra Minor"); + }); + + it("the Star option lists the palette's own stars", () => { + const star = orbitsOptions(custom).find((o) => o.key === "star")!; + expect(star.choices).toEqual([{ value: "random", label: "Random" }, { value: "embers", label: "Embers" }]); + const shipped = orbitsOptions(SPACE_SYSTEM_TERRAINS).find((o) => o.key === "star")!; + expect(shipped.choices.map((c) => c.value)).toEqual(["random", "yellow star", "red dwarf", "blue giant", "white dwarf", "brown dwarf"]); + const r = orbits(custom, grid(13, 13), 3, { star: "embers" }); + expect([...r.cells.values()]).toContain("Embers"); + }); + + it("the shipped System palette, renamed, fills every role the same way", () => { + const renamed = SPACE_SYSTEM_TERRAINS.map((x, i) => ({ ...x, name: `Body ${i}` })); + const rename = (n: string | undefined) => (n === undefined ? undefined : renamed[SPACE_SYSTEM_TERRAINS.findIndex((x) => x.name === n)].name); + const a = orbitRoles(SPACE_SYSTEM_TERRAINS)!; + const b = orbitRoles(renamed)!; + for (const k of ["background", "moon", "comet", "station", "starport", "jumpPoint", "jumpLimit", "belt"] as const) expect(b[k]).toBe(rename(a[k])); + for (const k of ["stars", "bodies", "belts", "giants"] as const) expect(b[k]).toEqual(a[k].map(rename)); + for (let seed = 1; seed <= 5; seed++) { + const cells = orbits(renamed, grid(13, 13), seed, {}).cells; + const [cx, cy] = centerHex(grid(13, 13)); + expect(b.stars).toContain(cells.get(`${cx}_${cy}`)); + } }); }); @@ -418,11 +451,23 @@ describe("terrain types", () => { expect(planetSurfaceFits([t("ocean", "desert"), t("grass", "grassland")])).toBe(false); }); - it("untyped palettes still resolve by name and category", () => { + it("untyped palettes fit nothing, even with the shipped names and categories", () => { const pal = [t("ocean"), t("Lowland", undefined, "lowlands"), t("forest"), t("hills")]; - const r = planetRoles(pal)!; - expect(r).toMatchObject({ sea: "ocean", plains: "Lowland", forest: "forest", hills: "hills" }); - expect(r.variants).toEqual({ forest: {}, hills: {}, mountain: {} }); + expect(planetRoles(pal)).toBeUndefined(); + expect(planetSurfaceFits(DEFAULT_TERRAIN_PALETTE.map(({ type: _t, ...rest }) => rest))).toBe(false); + }); + + it("the shipped Expanded palette, renamed, fills the same roles", () => { + const renamed = DEFAULT_TERRAIN_PALETTE.map((x, i) => ({ ...x, name: `T${i}` })); + const a = planetRoles(DEFAULT_TERRAIN_PALETTE)!; + const b = planetRoles(renamed)!; + const idx = (r: typeof a) => (n: string | undefined) => n === undefined ? -1 : (r === a ? DEFAULT_TERRAIN_PALETTE : renamed).findIndex((x) => x.name === n); + // Same type for every base role (which one of several same-typed + // terrains is a tie-break; see findByType). + for (const k of ["sea", "plains", "deep", "shallows", "beach", "forest", "jungle", "swamp", "hills", "mountain", "peak", "snow", "desert", "badlands", "volcano"] as const) { + const ia = idx(a)(a[k]), ib = idx(b)(b[k]); + expect(ib >= 0 ? renamed[ib].type : undefined).toBe(ia >= 0 ? DEFAULT_TERRAIN_PALETTE[ia].type : undefined); + } }); it("spreads the Expanded palette's woodland variants by climate", () => { @@ -437,14 +482,24 @@ describe("terrain types", () => { }); }); - describe("untyped space fallback", () => { - it("orbits still resolves from categories and exact names", () => { + describe("untyped space palettes", () => { + it("orbits needs types: shipped names and categories alone don't fit", () => { const pal = [ t("void", undefined, "space"), t("Sol", undefined, "stars"), t("Terra", undefined, "bodies"), t("moon", undefined, "bodies"), t("jump point"), ]; - const r = orbitRoles(pal)!; - expect(r).toMatchObject({ background: "void", stars: ["Sol"], bodies: ["Terra"], moon: "moon", jumpPoint: "jump point" }); + expect(orbitRoles(pal)).toBeUndefined(); + expect(orbitsFits(SPACE_SYSTEM_TERRAINS.map(({ type: _t, ...rest }) => rest))).toBe(false); + }); + + it("with everything deleted, no space generator fits and nothing throws", () => { + expect(orbitRoles([])).toBeUndefined(); + expect(starScatterRoles([])).toBeUndefined(); + expect(planetRoles([])).toBeUndefined(); + expect(orbits([], grid(5, 5), 1).cells.size).toBe(0); + expect(starScatter([], grid(5, 5), 1).cells.size).toBe(0); + expect(planetSurface([], grid(5, 5), 1).cells.size).toBe(0); + expect(suggestBaseTerrain([])).toBeUndefined(); }); }); }); diff --git a/tests/regionContext.test.ts b/tests/regionContext.test.ts index 1206812f..e906ca4b 100644 --- a/tests/regionContext.test.ts +++ b/tests/regionContext.test.ts @@ -87,10 +87,14 @@ describe("Region detail (planet surface with context)", () => { expect(east).toBeLessThan(0.15); }); - it("untyped context terrains are read from their names", () => { - const ctx: GenerationContext = { parent: { terrain: "dark forest" }, sides: { S: { terrain: "salt sea" } } }; - const r = planetSurface(DEFAULT_TERRAIN_PALETTE, grid, 2, {}, ctx); + it("context terrains are read by type, never by name", () => { + const typed: GenerationContext = { parent: { terrain: "Gloomwood", type: "forest" }, sides: { S: { terrain: "Brine", type: "water" } } }; + const r = planetSurface(DEFAULT_TERRAIN_PALETTE, grid, 2, {}, typed); expect(share(r.cells, all, new Set(["forest"]))).toBeGreaterThan(0.3); + // Untyped: "dark forest" says nothing about the parent; no forest target. + const untyped: GenerationContext = { parent: { terrain: "dark forest" } }; + const u = planetSurface(DEFAULT_TERRAIN_PALETTE, grid, 2, {}, untyped); + expect(share(u.cells, all, new Set(["forest"]))).toBeLessThan(share(r.cells, all, new Set(["forest"]))); }); it("is deterministic per seed", () => { @@ -133,11 +137,11 @@ describe("Region detail keeps its card's promise (fresh-eyes round 7)", () => { // SE and mixed forest to the SW. Both neighbours are forest-type, so the // type blend alone produced no evergreen at all. const ctx: GenerationContext = { - parent: { terrain: "mixed forest heavy" }, + parent: { terrain: "mixed forest heavy", type: "forest" }, sides: { - NE: { terrain: "evergreen heavy" }, - SE: { terrain: "evergreen heavy" }, - SW: { terrain: "mixed forest" }, + NE: { terrain: "evergreen heavy", type: "forest" }, + SE: { terrain: "evergreen heavy", type: "forest" }, + SW: { terrain: "mixed forest", type: "forest" }, }, }; const g: ProcGrid = { cols: 13, rows: 13, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; diff --git a/tests/terrainTypes.test.ts b/tests/terrainTypes.test.ts index 363c410a..7ef3b117 100644 --- a/tests/terrainTypes.test.ts +++ b/tests/terrainTypes.test.ts @@ -1,8 +1,9 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { TERRAIN_TYPES, inferTerrainType, isTerrainType, terrainTypeInfo } from "../src/terrainTypes"; +import { TERRAIN_TYPES, inferTerrainType, isTerrainType, refinedSpaceType, terrainTypeInfo } from "../src/terrainTypes"; import { buildPaletteNote, parsePaletteNote, updatePaletteNote } from "../src/palettes/paletteNote"; -import { seedTerrainTypes } from "../src/palettes/PaletteStore"; +import { seedTerrainTypes, upgradePaletteData } from "../src/palettes/PaletteStore"; +import { presetToPalette, getPreset, SPACE_SECTOR_PALETTE_NAME, SPACE_SYSTEM_PALETTE_NAME } from "../src/palettes/presets"; import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; import { PALETTE_PRESETS } from "../src/palettes/presets"; import type { TerrainPalette } from "../src/types"; @@ -73,6 +74,78 @@ describe("Type column in palette notes", () => { }); }); +describe("space role types (owner rule: never special-case names)", () => { + it("each Orbits / Star scatter role has its own type in the shipped palettes", () => { + const sys = getPreset(SPACE_SYSTEM_PALETTE_NAME)!.terrains; + const typeOf = (n: string) => sys.find((t) => t.name === n)?.type; + expect(typeOf("moon")).toBe("moon"); + expect(typeOf("comet")).toBe("comet"); + expect(typeOf("debris field")).toBe("debris"); + expect(typeOf("starport")).toBe("starport"); + expect(typeOf("jump point")).toBe("jump-point"); + expect(typeOf("jump limit")).toBe("jump-limit"); + expect(getPreset(SPACE_SECTOR_PALETTE_NAME)!.terrains.find((t) => t.name === "star system")?.type).toBe("star-system"); + }); + + it("suggests the new types from names (a suggestion only)", () => { + expect(inferTerrainType("starport")).toBe("starport"); + expect(inferTerrainType("jump gate")).toBe("jump-point"); + expect(inferTerrainType("space station")).toBe("station"); + expect(inferTerrainType("Pale moon")).toBe("moon"); + expect(inferTerrainType("star system")).toBe("star-system"); + }); + + it("refinedSpaceType turns the old name rule into a type once", () => { + expect(refinedSpaceType({ name: "moon", type: "world" })).toBe("moon"); + expect(refinedSpaceType({ name: "Luna", type: "world" })).toBeUndefined(); + expect(refinedSpaceType({ name: "Halley's comet", type: "asteroids" })).toBe("comet"); + expect(refinedSpaceType({ name: "debris field", type: "asteroids" })).toBe("debris"); + expect(refinedSpaceType({ name: "asteroid belt", type: "asteroids" })).toBeUndefined(); + expect(refinedSpaceType({ name: "Highport", type: "station" })).toBe("starport"); + expect(refinedSpaceType({ name: "Gateway", type: "station" })).toBe("jump-point"); + expect(refinedSpaceType({ name: "Outpost", type: "station" })).toBeUndefined(); + expect(refinedSpaceType({ name: "jump limit", type: "void" })).toBe("jump-limit"); + expect(refinedSpaceType({ name: "star system", type: "star" })).toBe("star-system"); + // Only upgrades the old coarse type; a terrain already typed otherwise is left alone. + expect(refinedSpaceType({ name: "moon", type: "desert" })).toBeUndefined(); + expect(refinedSpaceType({ name: "moon" })).toBeUndefined(); + }); + + it("upgradePaletteData retypes old space palettes and copies a preset's child palette and submap rows once", () => { + // An old install of Space - Sector / System: coarse types, no child palette, no submap rows. + const oldSystem = presetToPalette(getPreset(SPACE_SYSTEM_PALETTE_NAME)!); + for (const t of oldSystem.terrains) { + if (t.type === "moon") t.type = "world"; + if (t.type === "comet" || t.type === "debris") t.type = "asteroids"; + if (t.type === "starport" || t.type === "jump-point") t.type = "station"; + if (t.type === "jump-limit") t.type = "void"; + } + delete oldSystem.submapDefaults; + const oldSector = presetToPalette(getPreset(SPACE_SECTOR_PALETTE_NAME)!); + delete oldSector.childPalette; + const mine: TerrainPalette = { name: "Mine", terrains: [{ name: "Moonlet", color: "#999", type: "world" }] }; + expect(upgradePaletteData([oldSystem, oldSector, mine])).toBe(2); + expect(oldSystem.terrains.map((t) => t.type)).toEqual(getPreset(SPACE_SYSTEM_PALETTE_NAME)!.terrains.map((t) => t.type)); + expect(Object.keys(oldSystem.submapDefaults ?? {}).sort()).toEqual(Object.keys(getPreset(SPACE_SYSTEM_PALETTE_NAME)!.submapDefaults!).sort()); + expect(oldSector.childPalette).toBe(SPACE_SYSTEM_PALETTE_NAME); + expect(mine.terrains[0].type).toBe("world"); + // Second run: nothing left to do. + expect(upgradePaletteData([oldSystem, oldSector, mine])).toBe(0); + }); + + it("keeps rows the user already has and never touches a renamed or custom palette's metadata", () => { + const sector = presetToPalette(getPreset(SPACE_SECTOR_PALETTE_NAME)!, "My sector"); + delete sector.childPalette; + delete sector.submapDefaults; + expect(upgradePaletteData([sector])).toBe(0); + expect(sector.childPalette).toBeUndefined(); + const system = presetToPalette(getPreset(SPACE_SYSTEM_PALETTE_NAME)!); + system.submapDefaults = { moon: { cols: 5 } }; + upgradePaletteData([system]); + expect(system.submapDefaults.moon).toEqual({ cols: 5 }); + }); +}); + describe("seedTerrainTypes", () => { it("copies preset types by name and infers the rest, leaving typed terrains alone", () => { const palettes: TerrainPalette[] = [{ diff --git a/tests/worldgenFirstMap.test.ts b/tests/worldgenFirstMap.test.ts index 9598e0fa..dc57ab0c 100644 --- a/tests/worldgenFirstMap.test.ts +++ b/tests/worldgenFirstMap.test.ts @@ -16,7 +16,7 @@ import { } from "../src/worldgen/procedural/planetSurface"; import { STAR_SCATTER_ID } from "../src/worldgen/procedural/starScatter"; import { BLANK_ID, firstMapGenerator, generationKey } from "../src/worldgen/registry"; -import { defaultPaletteFor, paletteHint, resolveExpandedDefault } from "../src/palettes/paletteOptions"; +import { defaultPaletteFor, paletteHint, repointPaletteName, resolveDefaultPalette, resolveExpandedDefault } from "../src/palettes/paletteOptions"; import { isUnusedPlaceholderMap } from "../src/setupPlaceholder"; import { neighbourSeaText } from "../src/worldgen/NewMapSetupModal"; import type { ProcGrid } from "../src/worldgen/procedural/common"; @@ -299,11 +299,43 @@ describe("defaultPaletteFor (new-map palette by map type)", () => { const pal = (name: string, terrains: TerrainColor[]) => ({ name, terrains }); const fresh = [pal("Limited", LIMITED_TERRAIN_PALETTE), pal("Expanded", DEFAULT_TERRAIN_PALETTE)]; - it("world users get Expanded when installed (G7b), else their first overland palette", () => { - expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: fresh })).toBe("Expanded"); - expect(defaultPaletteFor({ mapKinds: ["world", "space"], terrainPalettes: fresh })).toBe("Expanded"); - expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [pal("Space - Sector", SPACE_SECTOR_TERRAINS), ...fresh] })).toBe("Expanded"); - expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [pal("Mine", LIMITED_TERRAIN_PALETTE), pal("Limited", LIMITED_TERRAIN_PALETTE)] })).toBe("Mine"); + it("uses the Palette for new maps setting (seeded with Expanded, G7b), else the first overland palette", () => { + const d = "Expanded"; + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: fresh, defaultPalette: d })).toBe("Expanded"); + expect(defaultPaletteFor({ mapKinds: ["world", "space"], terrainPalettes: fresh, defaultPalette: d })).toBe("Expanded"); + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [pal("Space - Sector", SPACE_SECTOR_TERRAINS), ...fresh], defaultPalette: d })).toBe("Expanded"); + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [pal("Mine", LIMITED_TERRAIN_PALETTE), pal("Limited", LIMITED_TERRAIN_PALETTE)], defaultPalette: d })).toBe("Mine"); + // Unset: the first overland palette, whatever it is called. + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: fresh })).toBe("Limited"); + }); + + it("no palette is special by name: any palette can be the default, renamed or not", () => { + const mine = [pal("Crayons", LIMITED_TERRAIN_PALETTE), pal("Big box", DEFAULT_TERRAIN_PALETTE)]; + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: mine, defaultPalette: "Big box" })).toBe("Big box"); + // A setting naming a deleted palette falls back to the first palette, not to a name. + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: mine, defaultPalette: "Expanded" })).toBe("Crayons"); + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: mine, defaultPalette: "Gone" })).toBe("Crayons"); + // A space palette as the default while space is off: skipped. + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [pal("Stars", SPACE_SECTOR_TERRAINS), ...mine], defaultPalette: "Stars" })).toBe("Crayons"); + }); + + it("with every palette deleted, still picks something", () => { + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [] })).toBe("Expanded"); + expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: [] })).toBe("Space - Sector"); + }); + + it("a rename repoints maps, the default and child palettes", () => { + const settings = { + maps: [{ paletteName: "Sector" }, { paletteName: "Other" }], + defaultPalette: "Sector", + terrainPalettes: [{ childPalette: "Sector", submapDefaults: { a: { palette: "Sector" }, b: { palette: "X" } } }], + }; + repointPaletteName(settings, "Sector", "Galaxy"); + expect(settings.maps.map((m) => m.paletteName)).toEqual(["Galaxy", "Other"]); + expect(settings.defaultPalette).toBe("Galaxy"); + expect(settings.terrainPalettes[0].childPalette).toBe("Galaxy"); + expect(settings.terrainPalettes[0].submapDefaults.a.palette).toBe("Galaxy"); + expect(settings.terrainPalettes[0].submapDefaults.b.palette).toBe("X"); }); it("a fresh install starts on Expanded", () => { @@ -318,26 +350,27 @@ describe("defaultPaletteFor (new-map palette by map type)", () => { expect(paletteHint("Space - Sector")).toBe(""); }); - it("space-only users get a space palette, Space - Sector first", () => { - expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: fresh })).toBe("Space - Sector"); + it("space-only users get their first space palette, else the first space preset", () => { + expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: fresh, defaultPalette: "Expanded" })).toBe("Space - Sector"); expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: [...fresh, pal("Space - System", SPACE_SYSTEM_TERRAINS)] })).toBe("Space - System"); expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: [...fresh, pal("Space - System", SPACE_SYSTEM_TERRAINS), pal("Space - Sector", SPACE_SECTOR_TERRAINS)], + defaultPalette: "Space - Sector", })).toBe("Space - Sector"); }); - it("world users with no overland palette installed get the Expanded preset", () => { + it("world users with no overland palette installed get the first overland preset", () => { expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [pal("Space - Sector", SPACE_SECTOR_TERRAINS)] })).toBe("Expanded"); }); // GEN1 = B: Expanded is the default for new installs only. it("existing installs keep their first overland palette even with Expanded installed", () => { const existing = [pal("Limited", LIMITED_TERRAIN_PALETTE), pal("Expanded", DEFAULT_TERRAIN_PALETTE)]; - expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: existing, expandedByDefault: false })).toBe("Limited"); - expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: existing, expandedByDefault: true })).toBe("Expanded"); + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: existing, defaultPalette: resolveDefaultPalette({ hexFolder: "x" }) })).toBe("Limited"); + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: existing, defaultPalette: resolveDefaultPalette(null) })).toBe("Expanded"); // Space users are unaffected either way. - expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: existing, expandedByDefault: false })).toBe("Space - Sector"); + expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: existing, defaultPalette: "" })).toBe("Space - Sector"); }); it("fresh install vs update is decided from the raw saved data, and a saved answer wins", () => { @@ -346,6 +379,12 @@ describe("defaultPaletteFor (new-map palette by map type)", () => { expect(resolveExpandedDefault({ hexFolder: "world/hexes", maps: [] })).toBe(false); expect(resolveExpandedDefault({ hexFolder: "x", expandedByDefault: true })).toBe(true); expect(resolveExpandedDefault({ expandedByDefault: false })).toBe(false); + // The setting is seeded from it once, then the saved value wins. + expect(resolveDefaultPalette(null)).toBe("Expanded"); + expect(resolveDefaultPalette({ hexFolder: "x" })).toBe(""); + expect(resolveDefaultPalette({ hexFolder: "x", expandedByDefault: true })).toBe("Expanded"); + expect(resolveDefaultPalette({ defaultPalette: "Crayons", expandedByDefault: true })).toBe("Crayons"); + expect(resolveDefaultPalette({ defaultPalette: "" })).toBe(""); }); }); @@ -496,9 +535,12 @@ describe("Overland Sea default next to a neighbour (fresh-eyes r4)", () => { expect(seaSideFromNeighbours(below, cells)).toEqual({ side: "east", why: "end", seam: "north" }); }); - it("reads untyped terrain by name, skips corners, and is undefined with no neighbour", () => { - const cells = new Map([["9_2", { terrain: "ocean" }], ["9_-1", { terrain: "grass" }], ["9_3", { terrain: "ocean" }]]); + it("reads terrain by type, never by name, skips corners, and is undefined with no neighbour", () => { + const cells = new Map([["9_2", { terrain: "Brine", type: "water" }], ["9_-1", { terrain: "grass", type: "grassland" }], ["9_3", { terrain: "Brine", type: "water" }]]); expect(seaSideFromNeighbours(g, cells)?.side).toBe("west"); + // An untyped "ocean" isn't read as water. + const untyped = new Map([["9_2", { terrain: "ocean" }], ["9_3", { terrain: "ocean" }]]); + expect(seaSideFromNeighbours(g, untyped)).toBeUndefined(); expect(seaSideFromNeighbours(g, undefined)).toBeUndefined(); expect(seaSideFromNeighbours(g, new Map())).toBeUndefined(); }); diff --git a/tests/worldgenGenerators.test.ts b/tests/worldgenGenerators.test.ts index 796dc653..16f32b70 100644 --- a/tests/worldgenGenerators.test.ts +++ b/tests/worldgenGenerators.test.ts @@ -18,6 +18,7 @@ import { } from "../src/worldgen/generators"; import { findViolation, parseModelMarkdown, type HexWfcModel } from "../packages/hex-wfc/src"; import type HexmakerPlugin from "../src/HexmakerPlugin"; +import type { TerrainColor } from "../src/types"; /** * In-memory vault + plugin stub. Hex notes are represented only by their @@ -259,18 +260,36 @@ describe("default impassable terrain", () => { adjacency: [], }; - it("uses the generator's shallows, ocean and trench, in any case", () => { - expect(defaultImpassable(base)).toEqual(["Shallows", "ocean", "TRENCH"]); - expect(generatorSettings(base).impassable).toEqual(["Shallows", "ocean", "TRENCH"]); + // The palette says what is impassable (type group or the Impassable + // column), in any case; never the terrain's name. + const palette: TerrainColor[] = [ + { name: "grass", color: "#0f0", type: "grassland" }, + { name: "shallows", color: "#00f", type: "shallows" }, + { name: "Ocean", color: "#00f", type: "water" }, + { name: "trench", color: "#00f", type: "deep-water" }, + { name: "hills", color: "#aa0", type: "hills" }, + ]; + + it("uses the terrains the palette marks impassable, in any case", () => { + expect(defaultImpassable(base, palette)).toEqual(["Shallows", "ocean", "TRENCH"]); + expect(generatorSettings(base, palette).impassable).toEqual(["Shallows", "ocean", "TRENCH"]); + }); + + it("goes by the palette, not the names: flagged, untyped or none", () => { + const flagged: TerrainColor[] = palette.map((t) => (t.name === "hills" ? { ...t, impassable: true } : t)); + expect(defaultImpassable(base, flagged)).toEqual(["Shallows", "ocean", "TRENCH", "Hills"]); + const untyped: TerrainColor[] = palette.map(({ type: _t, ...rest }) => rest); + expect(defaultImpassable(base, untyped)).toEqual([]); + expect(defaultImpassable(base, [])).toEqual([]); }); it("only covers terrains the generator has", () => { - expect(defaultImpassable({ ...base, terrains: [{ name: "Grass", weight: 1 }] })).toEqual([]); + expect(defaultImpassable({ ...base, terrains: [{ name: "Grass", weight: 1 }] }, palette)).toEqual([]); }); it("steps aside once the generator saves its own list, even an empty one", () => { - expect(defaultImpassable({ ...base, settings: { impassable: ["Hills"] } })).toBeUndefined(); - expect(generatorSettings({ ...base, settings: { impassable: [] } }).impassable).toEqual([]); + expect(defaultImpassable({ ...base, settings: { impassable: ["Hills"] } }, palette)).toBeUndefined(); + expect(generatorSettings({ ...base, settings: { impassable: [] } }, palette).impassable).toEqual([]); }); }); diff --git a/tests/worldgenImpassableHint.test.ts b/tests/worldgenImpassableHint.test.ts index 7d062fc6..36fabad4 100644 --- a/tests/worldgenImpassableHint.test.ts +++ b/tests/worldgenImpassableHint.test.ts @@ -49,12 +49,14 @@ describe("impassable suggestions", () => { expect(suggestImpassable(model(coast, paths), new Map(), ["sea"])).toEqual([]); }); - it("without paths, only suggests big terrain that looks like water", () => { - const colors = new Map([["deepblue", "#2a4d9b"], ["grass", "#5a9a3a"], ["Lake", "#999999"]]); - const m = model({ deepblue: 300, grass: 400, Lake: 100, forest: 200 }); - const hints = suggestImpassable(m, colors); - expect(hints.map((h) => h.terrain)).toEqual(["deepblue", "Lake"]); + it("without paths, only suggests big terrain that looks like water or the palette marks impassable", () => { + const colors = new Map([["deepblue", "#2a4d9b"], ["grass", "#5a9a3a"], ["Lake", "#999999"], ["Glass", "#999999"]]); + const m = model({ deepblue: 300, grass: 400, Lake: 100, Glass: 100, forest: 200 }); + // Named like water but neither blue nor marked: not suggested (never by name). + expect(suggestImpassable(m, colors).map((h) => h.terrain)).toEqual(["deepblue"]); + const hints = suggestImpassable(m, colors, [], new Set(["Glass"])); + expect(hints.map((h) => h.terrain)).toEqual(["deepblue", "Glass"]); expect(hints[0].reason).toContain("colour"); - expect(hints[1].reason).toContain("name"); + expect(hints[1].reason).toContain("palette marks it impassable"); }); }); From bbb941356e2ab73ba1e4096c5b4940a69bcbb86e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 18:50:54 -0400 Subject: [PATCH 226/558] fix(palettes): write colours as inline code so Obsidian doesn't read them as tags (#46) Palette notes wrote colours as bare `#14223d`, which Obsidian reads as a tag (a pill in reading view, an entry in the tag list). The terrain table (Color, Icon color) and the Path types table (Color) now write every colour, hex or any other CSS colour, as inline code. Empty cells stay empty. Reading stays forgiving: `#14223d` in backticks, bare #14223d, 14223d (3 or 6 digits get their #) and any case or inner spaces all read as the same colour; hex is lower-cased. Existing notes convert on the plugin's next write of the note and once on load through the P1 refresh. The conversion rewrites only the colour cells and keeps every other character, line endings included. Before the first load-time pass, every palette note is backed up (gzip JSON via backup.ts, backups/palette-colours-/); if the backup fails the pass waits for the next load. settings.paletteColorsCode records that it ran. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/palettes/PaletteStore.ts | 72 +++++++-- src/palettes/colorCell.ts | 77 +++++++++ src/palettes/paletteNote.ts | 39 +++-- src/palettes/pathTypeTable.ts | 26 ++- src/types.ts | 5 + tests/fixtures/compat/palette-bare-colours.md | 25 +++ tests/impassable.test.ts | 2 +- tests/paletteColors.test.ts | 151 ++++++++++++++++++ tests/paletteDerived.test.ts | 36 ++--- tests/palettes.test.ts | 128 ++++++++++++++- tests/pathTypeTable.test.ts | 7 +- 12 files changed, 518 insertions(+), 54 deletions(-) create mode 100644 src/palettes/colorCell.ts create mode 100644 tests/fixtures/compat/palette-bare-colours.md create mode 100644 tests/paletteColors.test.ts diff --git a/package.json b/package.json index a48817fd..7c90c073 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/submaps.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/submaps.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/submaps.test.ts tests/paletteColors.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/submaps.test.ts tests/paletteColors.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index 4c6e0a6c..1977aa74 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -14,9 +14,11 @@ import { submapDefaultsKey, terrainsEqual, updatePaletteNote, + wrapPaletteColors, } from "./paletteNote"; import { PALETTE_PRESETS, uniquePaletteName } from "./presets"; -import { clonePathTypes, parsePathTypes, pathTypesKey, setPathTypes } from "./pathTypeTable"; +import { clonePathTypes, parsePathTypes, pathTypesKey, setPathTypes, wrapPathTypeColors } from "./pathTypeTable"; +import { writeJsonBackup } from "../backup"; import { fillLegacyPathTypes } from "./pathTypeLegacy"; import { DEFAULT_PATH_TYPES } from "../constants"; import { inferTerrainType } from "../terrainTypes"; @@ -78,12 +80,21 @@ function applyNoteMeta(pal: TerrainPalette, content: string, legacy = false): bo * table with unreadable rows is left alone. */ export function refreshNoteDerived(content: string, pathTypes?: PathType[]): string { - const next = refreshPaletteDerived(content); + const next = wrapPathTypeColors(refreshPaletteDerived(content)); const paths = parsePathTypes(next); if (!paths || paths.skipped.length || !paths.implicit) return next; return setPathTypes(next, pathTypes ?? paths.types); } +/** + * The note with every colour cell (terrain Color and Icon color, path type + * Color) written as inline code, so Obsidian doesn't read `#14223d` as a + * tag. Nothing else in the note changes; the same string when nothing needs to. + */ +export function wrapNoteColors(content: string): string { + return wrapPathTypeColors(wrapPaletteColors(content)); +} + /** A fresh note for a palette, metadata included. */ function newNote(pal: TerrainPalette): string { const note = setSubmapDefaults(buildPaletteNote(pal.terrains, pal.childPalette), pal.submapDefaults); @@ -289,14 +300,27 @@ export class PaletteStore { settings.terrainTypesSeeded = true; dirty = true; } + // Colours in palette notes became inline code (Obsidian read `#14223d` + // as a tag). Before the first pass that converts them, every palette + // note is backed up; if that fails, the load-time pass waits for the + // next load (a note the plugin rewrites in the meantime still converts). + let refresh = true; + if (!settings.paletteColorsCode) { + refresh = await this.backupBeforeColorConversion(); + if (refresh) { + settings.paletteColorsCode = true; + dirty = true; + } + } this.ready = true; // Write seeded types into the notes now, in the same queued step. Queued // separately, an unload in between left notes untyped while settings // said seeding was done — and notes win on the next load. if (seeded || filled) await this.syncNow(); // Notes from older builds (or edited by hand since) get their derived - // cells shown: the Impassable column, inferred types in parentheses. - for (const file of this.paletteFiles()) await this.refreshDerived(file); + // cells shown (the Impassable column, inferred types in parentheses) + // and their colours written as inline code. + if (refresh) for (const file of this.paletteFiles()) await this.refreshDerived(file); if (!settings.pathTypesExplicit) { settings.pathTypesExplicit = true; dirty = true; @@ -304,6 +328,33 @@ export class PaletteStore { if (dirty) await this.persist(); } + /** + * Save the full text of every palette note (gzipped JSON in the plugin's + * backups folder) when any of them still has colours that aren't inline + * code. Returns false, after saying so, if the backup couldn't be saved. + */ + private async backupBeforeColorConversion(): Promise { + const { vault } = this.plugin.app; + const notes: Record = {}; + let needed = false; + for (const file of this.paletteFiles()) { + const content = await vault.read(file); + notes[file.path] = content; + if (parsePaletteNote(content) && wrapNoteColors(content) !== content) needed = true; + } + if (!needed) return true; + try { + const dir = `${this.plugin.manifest.dir}/backups/palette-colours-${new Date().toISOString().slice(0, 10)}`; + const json = JSON.stringify({ kind: "palette-colours", savedAt: new Date().toISOString(), notes }); + await writeJsonBackup(vault.adapter, dir, "palette-notes", json); + return true; + } catch (e) { + console.error("Hexmaker: couldn't back up palette notes; their colours weren't converted", e); + new Notice("Hexmaker: couldn't save a backup of the palette notes, so their colours weren't converted yet. It will try again next time.", 10000); + return false; + } + } + /** * Replace the in-memory palette list with the notes on disk, reusing the * existing palette objects (matched by name) so open views and modals keep @@ -425,13 +476,14 @@ export class PaletteStore { this.bind(pal, target, current); continue; } + // A note the user is typing in keeps its text (derived cells and + // colour cells are brought up to date once they leave it). + const editing = this.isBeingEdited(target); + const base = parsed && terrainsEqual(parsed, pal.terrains) + ? editing ? current : refreshPaletteDerived(current) + : updatePaletteNote(current, pal.terrains); const withMeta = setSubmapDefaults( - setChildPalette( - parsed && terrainsEqual(parsed, pal.terrains) - ? this.isBeingEdited(target) ? current : refreshPaletteDerived(current) - : updatePaletteNote(current, pal.terrains), - pal.childPalette, - ), + setChildPalette(editing ? base : wrapPathTypeColors(base), pal.childPalette), pal.submapDefaults, ); const next = pal.pathTypes ? setPathTypes(withMeta, pal.pathTypes) : withMeta; diff --git a/src/palettes/colorCell.ts b/src/palettes/colorCell.ts new file mode 100644 index 00000000..b5e6fa8d --- /dev/null +++ b/src/palettes/colorCell.ts @@ -0,0 +1,77 @@ +// Colour cells in palette notes. +// +// Obsidian reads `#14223d` (a `#` followed by a letter) in a note's body as +// a tag: a tag pill in reading view and an entry in the vault's tag list. So +// colours are written as inline code, `` `#14223d` ``, which is never a tag +// and still reads as the colour in the raw note. +// +// Reading is forgiving: `` `#14223d` ``, `#14223d`, `14223d` (a bare 3- or +// 6-digit hex gets its `#`), `` ` #14223D ` `` all read as `#14223d`. Hex is +// lower-cased; any other CSS colour (`rgb(…)`, `violet`) is kept as typed. + +const HASH_HEX = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i; +const BARE_HEX = /^([0-9a-f]{3}|[0-9a-f]{6})$/i; + +/** The colour a cell holds ("" for an empty cell). */ +export function parseColorCell(raw: string | undefined): string { + const v = (raw ?? "").trim().replace(/^`+/, "").replace(/`+$/, "").trim(); + if (HASH_HEX.test(v)) return v.toLowerCase(); + if (BARE_HEX.test(v)) return `#${v.toLowerCase()}`; + return v; +} + +/** A colour as written into a note: inline code, or "" when there's none. */ +export function colorCell(color: string | undefined): string { + const v = parseColorCell(color); + return v ? `\`${v}\`` : ""; +} + +/** Whether a cell's text isn't what the plugin would write for it (an empty cell is fine). */ +export function colorCellStale(raw: string | undefined): boolean { + const v = (raw ?? "").trim(); + return v !== "" && v !== colorCell(v); +} + +/** [start, end) of each cell's text (between pipes) in a table row, honouring `\|`. */ +function cellSpans(line: string): [number, number][] { + let start = 0; + let end = line.length; + while (start < end && /\s/.test(line[start])) start++; + while (end > start && /\s/.test(line[end - 1])) end--; + if (line[start] === "|") start++; + if (end > start && line[end - 1] === "|" && line[end - 2] !== "\\") end--; + const spans: [number, number][] = []; + let from = start; + for (let i = start; i < end; i++) { + if (line[i] === "\\" && line[i + 1] === "|") { i++; continue; } + if (line[i] === "|") { spans.push([from, i]); from = i + 1; } + } + spans.push([from, end]); + return spans; +} + +/** + * Rewrite just the colour cells of table rows `rows` (indices into `lines`, + * which may keep a trailing `\r`) at the cell positions `columns`, leaving + * every other character of the line as it was. Returns true if any changed. + */ +export function wrapColorCellsInRows(lines: string[], rows: Iterable, columns: number[]): boolean { + let changed = false; + for (const i of rows) { + const line = lines[i]; + const spans = cellSpans(line); + // Right to left, so earlier offsets stay valid. + for (const col of [...columns].sort((a, b) => b - a)) { + const span = spans[col]; + if (!span) continue; + let [a, b] = span; + while (a < b && /\s/.test(line[a])) a++; + while (b > a && /\s/.test(line[b - 1])) b--; + const raw = lines[i].slice(a, b); + if (!colorCellStale(raw)) continue; + lines[i] = lines[i].slice(0, a) + colorCell(raw) + lines[i].slice(b); + changed = true; + } + } + return changed; +} diff --git a/src/palettes/paletteNote.ts b/src/palettes/paletteNote.ts index 7eb84ace..e9c1d304 100644 --- a/src/palettes/paletteNote.ts +++ b/src/palettes/paletteNote.ts @@ -1,6 +1,7 @@ import type { SubmapDefault, TerrainColor } from "../types"; import { impassableNoteCell, parseImpassableCell } from "../impassable"; import { isDerivedCell, parseTerrainTypeCell, terrainTypeCell } from "../terrainTypes"; +import { colorCell, parseColorCell, wrapColorCellsInRows } from "./colorCell"; // Plain-text palette notes. // @@ -9,8 +10,11 @@ import { isDerivedCell, parseTerrainTypeCell, terrainTypeCell } from "../terrain // // | Terrain | Color | Icon | Icon color | Category | Type | Impassable | // | --- | --- | --- | --- | --- | --- | --- | -// | ocean | #29507f | | | sea | water | (yes) | -// | crags | #777777 | | | | (mountains) | yes | +// | ocean | `#29507f` | | | sea | water | (yes) | +// | crags | `#777777` | | | | (mountains) | yes | +// +// Colours are written as inline code so Obsidian doesn't read `#29507f` as +// a tag; plain, bare-hex and any-case spellings read too (colorCell.ts). // // Columns are matched by header name (case-insensitive, any order), so a // hand-edited or shared note only needs the Terrain and Color columns. The @@ -141,9 +145,10 @@ export function parsePaletteNote(content: string): TerrainColor[] | null { if (col && cells[idx]) row[col] = cells[idx]; }); if (!row.name) continue; - const entry: TerrainColor = { name: row.name, color: row.color || "#888888" }; + const entry: TerrainColor = { name: row.name, color: parseColorCell(row.color) || "#888888" }; if (row.icon) entry.icon = row.icon; - if (row.iconColor) entry.iconColor = row.iconColor; + const iconColor = parseColorCell(row.iconColor); + if (iconColor) entry.iconColor = iconColor; if (row.category) entry.category = row.category; // A type typed by hand in any case, or as its label, reads as its id; // a derived "(mountains)" is unset; anything else is kept as typed (and @@ -176,7 +181,7 @@ export function serializePaletteTable( `| ${headers.map(() => "---").join(" | ")} |`, ]; for (const t of terrains) { - const values = [t.name, t.color, t.icon, t.iconColor, t.category, terrainTypeCell(t), impassableNoteCell(t)]; + const values = [t.name, colorCell(t.color), t.icon, colorCell(t.iconColor), t.category, terrainTypeCell(t), impassableNoteCell(t)]; const mine = extra?.rows.get(t.name.toLowerCase()) ?? {}; for (const h of own) values.push(mine[h]); const cells = values.map(escapeCell); @@ -363,7 +368,7 @@ export function buildPaletteNote(terrains: TerrainColor[], childPalette?: string "---", "", "Hexmap World Creator terrain palette. The note name is the palette name. Each table row is one terrain:", - "colors are any CSS color, icons are file names from the icon picker, categories group", + "colors are any CSS color (in backticks, like `#3b82f6`, so they aren't read as tags), icons are file names from the icon picker, categories group", "terrains in the picker, and the type says what a terrain is (water, forest, star…) for", "generators and the hex table. Edit here, in the palette editor, or from the terrain tool on", "the hex map. Copy this note into another vault's palettes folder to share it.", @@ -428,9 +433,25 @@ export function paletteDerivedStale(content: string): boolean { * from what it says), or unchanged when they already are. */ export function refreshPaletteDerived(content: string): string { - if (!paletteDerivedStale(content)) return content; - const terrains = parsePaletteNote(content); - return terrains ? updatePaletteNote(content, terrains) : content; + const wrapped = wrapPaletteColors(content); + if (!paletteDerivedStale(wrapped)) return wrapped; + const terrains = parsePaletteNote(wrapped); + return terrains ? updatePaletteNote(wrapped, terrains) : wrapped; +} + +/** + * The note with the terrain table's Color and Icon color cells written as + * inline code (`` `#14223d` ``), so Obsidian doesn't read them as tags. Only + * those cells change: every other character, line endings included, is kept. + * Unchanged (the same string) when they already are. + */ +export function wrapPaletteColors(content: string): string { + const lines = content.split("\n"); + const span = findPaletteTable(lines.map((l) => l.replace(/\r$/, ""))); + if (!span) return content; + const cols = span.columns.flatMap((c, i) => (c === "color" || c === "iconColor" ? [i] : [])); + const rows = Array.from({ length: span.end - span.start - 2 }, (_, k) => span.start + 2 + k); + return wrapColorCellsInRows(lines, rows, cols) ? lines.join("\n") : content; } /** Structural equality used to skip no-op rewrites. */ diff --git a/src/palettes/pathTypeTable.ts b/src/palettes/pathTypeTable.ts index 5e2b442e..7b56a31b 100644 --- a/src/palettes/pathTypeTable.ts +++ b/src/palettes/pathTypeTable.ts @@ -1,6 +1,7 @@ import type { PathAutoRoute, PathLineStyle, PathRouting, PathType } from "../types"; import { parseImpassableCell } from "../impassable"; import { legacyAutoRoute, legacyAvoidsImpassable, legacyRouting } from "./pathTypeLegacy"; +import { colorCell, parseColorCell, wrapColorCellsInRows } from "./colorCell"; // The "Path types" section of a palette note: the kinds of path (roads, // rivers, jump routes…) that maps using this palette can draw. @@ -9,8 +10,10 @@ import { legacyAutoRoute, legacyAvoidsImpassable, legacyRouting } from "./pathTy // // | Path | Color | Width | Style | Routing | Avoid impassable | Auto-route | // | --- | --- | --- | --- | --- | --- | --- | -// | Road | #a16207 | 4 | solid | through | yes | direct | -// | River | #3b82f6 | 3 | solid | meander | no | winding | +// | Road | `#a16207` | 4 | solid | through | yes | direct | +// | River | `#3b82f6` | 3 | solid | meander | no | winding | +// +// Colours are inline code so Obsidian doesn't read them as tags (colorCell.ts). // // Every behaviour is a column, written out for every row: nothing follows a // path type's name (PA5). A blank or missing cell reads as the plain default @@ -196,7 +199,7 @@ export function parsePathTypes(content: string, opts: ParsePathTypesOptions = {} const avoidImpassable = avoid ?? (opts.legacy ? legacyAvoidsImpassable(name) : true); const t: PathType = { name, - color: row.color?.trim() || "#888888", + color: parseColorCell(row.color) || "#888888", width: parseWidth(row.width), lineStyle: parseStyle(row.style), routing: routing ?? (opts.legacy ? legacyRouting(name) : "through"), @@ -224,7 +227,7 @@ export function serializePathTypes( for (const t of types) { const own = extra?.rows.get(t.name) ?? {}; const avoid = t.avoidImpassable === false ? "no" : "yes"; - const cells = [t.name, t.color, String(t.width), t.lineStyle, t.routing, avoid, t.autoRoute ?? "direct", ...extraHeaders.map((h) => own[h])]; + const cells = [t.name, colorCell(t.color), String(t.width), t.lineStyle, t.routing, avoid, t.autoRoute ?? "direct", ...extraHeaders.map((h) => own[h])]; lines.push(`| ${cells.map(escapeCell).join(" | ")} |`); } return lines.join("\n"); @@ -269,4 +272,19 @@ export function setPathTypes(content: string, types: PathType[]): string { return `${base}\n${PATH_TYPES_HEADING}\n\n${PATH_TYPES_INTRO}\n\n${serializePathTypes(types)}\n`; } +/** + * The note with the path types table's Color cells written as inline code + * (`` `#a16207` ``), so Obsidian doesn't read them as tags. Only those cells + * change: every other character, line endings included, is kept. Unchanged + * (the same string) when they already are. + */ +export function wrapPathTypeColors(content: string): string { + const lines = content.split("\n"); + const span = findPathTypesTable(lines.map((l) => l.replace(/\r$/, ""))); + if (!span || !span.columns.includes("name")) return content; + const cols = span.columns.flatMap((c, i) => (c === "color" ? [i] : [])); + const rows = Array.from({ length: span.end - span.start - 2 }, (_, k) => span.start + 2 + k); + return wrapColorCellsInRows(lines, rows, cols) ? lines.join("\n") : content; +} + export const clonePathTypes = (types: readonly PathType[]): PathType[] => types.map((t) => ({ ...t })); diff --git a/src/types.ts b/src/types.ts index a1578485..2ae936d6 100644 --- a/src/types.ts +++ b/src/types.ts @@ -282,6 +282,11 @@ export interface HexmakerPluginSettings { * palette notes are read with the old name rules (pathTypeLegacy.ts). */ pathTypesExplicit?: boolean; + /** + * True once palette notes' colours were written as inline code + * (`` `#14223d` ``, not a tag), after a backup of the notes. + */ + paletteColorsCode?: boolean; /** Enabled map types (see src/mapKinds.ts). Unset = all. */ mapKinds: string[]; /** Simple or Advanced (see src/featureLevel.ts). */ diff --git a/tests/fixtures/compat/palette-bare-colours.md b/tests/fixtures/compat/palette-bare-colours.md new file mode 100644 index 00000000..6c3569a2 --- /dev/null +++ b/tests/fixtures/compat/palette-bare-colours.md @@ -0,0 +1,25 @@ +--- +hexmaker-palette: 1 +child-palette: "Local" +--- + +A palette note as builds before colour cells became inline code wrote it +(and as people type it): colours are plain `#hex`, which Obsidian reads as +tags. Kept as is: tests read and convert it. + +| Terrain | Color | Icon | Icon color | Category | Type | Impassable | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | +| ocean | #14223d | | | sea | water | (yes) | deep #blue water | +| grass | 69A168 | bw-grassland.png | #FFF | lowlands | (grassland) | (no) | spaced out | +| crags | `#777777` | | violet | | (mountains) | (no) | | +| ash \| cinder | rgb(51, 51, 51) | bw-volcano.png | | | | (no) | escaped pipe | + +Text between the tables, with a real #tag that stays a tag. + +## Path types + +| Path | Color | Width | Style | Routing | Avoid impassable | Auto-route | +| --- | --- | --- | --- | --- | --- | --- | +| Road | #a16207 | 4 | solid | through | yes | direct | +| River | ` #3B82F6 ` | 3 | solid | meander | no | winding | +| Trail | | 2 | dashed | edge | yes | direct | diff --git a/tests/impassable.test.ts b/tests/impassable.test.ts index 0ce99185..b8e438e2 100644 --- a/tests/impassable.test.ts +++ b/tests/impassable.test.ts @@ -72,7 +72,7 @@ describe("palette note Impassable column", () => { it("is always written, the type's default in parentheses (#46 P1)", () => { const table = serializePaletteTable([{ name: "ocean", color: "#29507f", type: "water" }]); expect(table).toContain("| Impassable |"); - expect(table).toContain("| ocean | #29507f | | | | water | (yes) |"); + expect(table).toContain("| ocean | `#29507f` | | | | water | (yes) |"); }); it("round-trips overrides", () => { diff --git a/tests/paletteColors.test.ts b/tests/paletteColors.test.ts new file mode 100644 index 00000000..b1261db3 --- /dev/null +++ b/tests/paletteColors.test.ts @@ -0,0 +1,151 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { colorCell, colorCellStale, parseColorCell } from "../src/palettes/colorCell"; +import { buildPaletteNote, parsePaletteNote, updatePaletteNote, wrapPaletteColors } from "../src/palettes/paletteNote"; +import { parsePathTypes, setPathTypes, wrapPathTypeColors } from "../src/palettes/pathTypeTable"; +import { refreshNoteDerived, wrapNoteColors } from "../src/palettes/PaletteStore"; +import { classifyPaletteTable } from "../src/palettes/paletteReadingView"; +import type { PathType, TerrainColor } from "../src/types"; + +// Colours in palette notes are written as inline code (`#14223d`), because +// Obsidian reads a bare #14223d in a note's body as a tag. + +const FIXTURE = readFileSync(path.join(process.cwd(), "tests", "fixtures", "compat", "palette-bare-colours.md"), "utf8").replace(/\r\n/g, "\n"); + +const TERRAINS: TerrainColor[] = [ + { name: "ocean", color: "#14223d", category: "sea", type: "water" }, + { name: "grass", color: "#69a168", icon: "bw-grassland.png", iconColor: "#ffffff" }, + { name: "glow", color: "rgb(1, 2, 3)", iconColor: "violet" }, +]; +const PATHS: PathType[] = [ + { name: "Road", color: "#a16207", width: 4, lineStyle: "solid", routing: "through", avoidImpassable: true, autoRoute: "direct" }, + { name: "Ley", color: "hsl(280 60% 50%)", width: 2, lineStyle: "dotted", routing: "edge", avoidImpassable: false, autoRoute: "winding" }, +]; + +/** Body text outside inline code and frontmatter: where Obsidian looks for tags. */ +function tagsIn(note: string): string[] { + const body = note.replace(/^---\n[\s\S]*?\n---\n/, "").replace(/`[^`\n]*`/g, "").replace(/^ {4}.*$/gm, ""); + return body.match(/(? { + it("every spelling of a colour reads as the same colour", () => { + for (const raw of ["`#14223d`", "#14223d", "14223d", "` #14223D `", " #14223D ", "`14223D`"]) { + expect(parseColorCell(raw)).toBe("#14223d"); + } + expect(parseColorCell("abc")).toBe("#abc"); + expect(parseColorCell("#ABCD")).toBe("#abcd"); + expect(parseColorCell("`violet`")).toBe("violet"); + expect(parseColorCell("rgb(1, 2, 3)")).toBe("rgb(1, 2, 3)"); + expect(parseColorCell("")).toBe(""); + expect(parseColorCell("``")).toBe(""); + expect(parseColorCell(undefined)).toBe(""); + }); + + it("writes every colour as inline code; an empty cell stays empty", () => { + expect(colorCell("#14223D")).toBe("`#14223d`"); + expect(colorCell("violet")).toBe("`violet`"); + expect(colorCell("rgb(1, 2, 3)")).toBe("`rgb(1, 2, 3)`"); + expect(colorCell("")).toBe(""); + expect(colorCell(undefined)).toBe(""); + expect(colorCellStale("`#14223d`")).toBe(false); + expect(colorCellStale("")).toBe(false); + expect(colorCellStale("#14223d")).toBe(true); + expect(colorCellStale("`#14223D`")).toBe(true); + }); +}); + +describe("palette notes write colours as inline code", () => { + it("round-trips the terrain and path types tables", () => { + const note = setPathTypes(buildPaletteNote(TERRAINS), PATHS); + expect(note).toContain("| ocean | `#14223d` | | | sea | water |"); + expect(note).toContain("| grass | `#69a168` | bw-grassland.png | `#ffffff` |"); + expect(note).toContain("| glow | `rgb(1, 2, 3)` | | `violet` |"); + expect(note).toContain("| Road | `#a16207` | 4 |"); + expect(note).toContain("| Ley | `hsl(280 60% 50%)` | 2 |"); + expect(parsePaletteNote(note)).toEqual(TERRAINS); + expect(parsePathTypes(note)!.types).toEqual(PATHS); + expect(tagsIn(note)).toEqual([]); + // Nothing left to convert or refresh. + expect(wrapNoteColors(note)).toBe(note); + expect(refreshNoteDerived(note, PATHS)).toBe(note); + }); + + it("an in-app edit writes the whole terrain table with inline-code colours", () => { + const updated = updatePaletteNote(FIXTURE, parsePaletteNote(FIXTURE)!); + expect(updated).toContain("| ocean | `#14223d` |"); + expect(updated).toContain("| grass | `#69a168` | bw-grassland.png | `#fff` |"); + expect(updated).toContain("deep #blue water"); // the user's own column, as typed + }); +}); + +describe("older palette notes (bare colours)", () => { + it("still read, with every spelling (compat fixture)", () => { + expect(parsePaletteNote(FIXTURE)!.map((t) => [t.name, t.color, t.iconColor])).toEqual([ + ["ocean", "#14223d", undefined], + ["grass", "#69a168", "#fff"], + ["crags", "#777777", "violet"], + ["ash | cinder", "rgb(51, 51, 51)", undefined], + ]); + expect(parsePathTypes(FIXTURE)!.types.map((t) => [t.name, t.color])).toEqual([ + ["Road", "#a16207"], + ["River", "#3b82f6"], + ["Trail", "#888888"], + ]); + }); + + it("convert only the colour cells; every other character stays", () => { + const out = wrapNoteColors(FIXTURE); + const before = FIXTURE.split("\n"); + const after = out.split("\n"); + expect(after).toHaveLength(before.length); + const changed = before.flatMap((l, i) => (l === after[i] ? [] : [[l, after[i]]])); + expect(changed).toEqual([ + ["| ocean | #14223d | | | sea | water | (yes) | deep #blue water |", "| ocean | `#14223d` | | | sea | water | (yes) | deep #blue water |"], + ["| grass | 69A168 | bw-grassland.png | #FFF | lowlands | (grassland) | (no) | spaced out |", "| grass | `#69a168` | bw-grassland.png | `#fff` | lowlands | (grassland) | (no) | spaced out |"], + ["| crags | `#777777` | | violet | | (mountains) | (no) | |", "| crags | `#777777` | | `violet` | | (mountains) | (no) | |"], + ["| ash \\| cinder | rgb(51, 51, 51) | bw-volcano.png | | | | (no) | escaped pipe |", "| ash \\| cinder | `rgb(51, 51, 51)` | bw-volcano.png | | | | (no) | escaped pipe |"], + ["| Road | #a16207 | 4 | solid | through | yes | direct |", "| Road | `#a16207` | 4 | solid | through | yes | direct |"], + ["| River | ` #3B82F6 ` | 3 | solid | meander | no | winding |", "| River | `#3b82f6` | 3 | solid | meander | no | winding |"], + ]); + expect(parsePaletteNote(out)).toEqual(parsePaletteNote(FIXTURE)); + expect(parsePathTypes(out)!.types).toEqual(parsePathTypes(FIXTURE)!.types); + // The user's own #tag in their prose is theirs; no colour is a tag any more. + expect(tagsIn(FIXTURE)).toContain("#a16207"); + expect(tagsIn(out)).toEqual(["#blue", "#tag"]); + }); + + it("keep CRLF line endings when converted", () => { + const crlf = FIXTURE.replace(/\n/g, "\r\n"); + const out = wrapNoteColors(crlf); + expect(out).toBe(wrapNoteColors(FIXTURE).replace(/\n/g, "\r\n")); + }); + + it("convert idempotently: a second pass changes nothing", () => { + const once = wrapNoteColors(FIXTURE); + expect(wrapNoteColors(once)).toBe(once); + expect(wrapPaletteColors(once)).toBe(once); + expect(wrapPathTypeColors(once)).toBe(once); + const refreshed = refreshNoteDerived(FIXTURE); + expect(refreshNoteDerived(refreshed)).toBe(refreshed); + expect(tagsIn(refreshed)).toEqual(["#blue", "#tag"]); + }); + + it("a note with nothing to convert is returned as is", () => { + const plain = "Just text with #tag.\n\n| A | B |\n| - | - |\n| #fff | x |\n"; + expect(wrapNoteColors(plain)).toBe(plain); + }); +}); + +describe("reading view of a converted note", () => { + it("reads the colour out of the code chip (its text has no backticks)", () => { + const headers = ["Terrain", "Color", "Icon", "Icon color"]; + const view = classifyPaletteTable(headers, [["grass", "#69a168", "bw-grassland.png", "#ffffff"]]); + expect(view?.kind).toBe("terrains"); + if (view?.kind !== "terrains") return; + expect(view.color).toBe(1); + expect(view.tints.get("grass")).toBe("#ffffff"); + }); +}); diff --git a/tests/paletteDerived.test.ts b/tests/paletteDerived.test.ts index f8496e38..e39bfc66 100644 --- a/tests/paletteDerived.test.ts +++ b/tests/paletteDerived.test.ts @@ -29,11 +29,11 @@ describe("palette derived cells (P1)", () => { it("always writes the Impassable column, defaults in parentheses", () => { const table = serializePaletteTable(terrains); expect(table.split("\n")[0]).toBe("| Terrain | Color | Icon | Icon color | Category | Type | Impassable |"); - expect(row(table, "ocean")).toBe("| ocean | #29507f | | | | water | (yes) |"); - expect(row(table, "crags")).toBe("| crags | #777777 | | | | (mountains) | (no) |"); - expect(row(table, "ford")).toBe("| ford | #4a82a5 | | | | shallows | no |"); + expect(row(table, "ocean")).toBe("| ocean | `#29507f` | | | | water | (yes) |"); + expect(row(table, "crags")).toBe("| crags | `#777777` | | | | (mountains) | (no) |"); + expect(row(table, "ford")).toBe("| ford | `#4a82a5` | | | | shallows | no |"); // Nothing to infer: the type stays blank, the default still shows. - expect(row(table, "Mirror Mere")).toBe("| Mirror Mere | #0000ff | | | | | (no) |"); + expect(row(table, "Mirror Mere")).toBe("| Mirror Mere | `#0000ff` | | | | | (no) |"); }); it("round-trips: parenthesised values read back as unset", () => { @@ -49,13 +49,13 @@ describe("palette derived cells (P1)", () => { it("a hand edit that removes the parentheses makes the value explicit", () => { const note = buildPaletteNote(terrains) - .replace("| crags | #777777 | | | | (mountains) | (no) |", "| crags | #777777 | | | | mountains | yes |") - .replace("| ocean | #29507f | | | | water | (yes) |", "| ocean | #29507f | | | | water | yes |"); + .replace("| crags | `#777777` | | | | (mountains) | (no) |", "| crags | `#777777` | | | | mountains | yes |") + .replace("| ocean | `#29507f` | | | | water | (yes) |", "| ocean | `#29507f` | | | | water | yes |"); const parsed = parsePaletteNote(note)!; expect(parsed.find((t) => t.name === "crags")).toEqual({ name: "crags", color: "#777777", type: "mountains", impassable: true }); // Same as the default, but now the user's own: kept explicit, written plain. expect(parsed.find((t) => t.name === "ocean")).toEqual({ name: "ocean", color: "#29507f", type: "water", impassable: true }); - expect(row(serializePaletteTable(parsed), "ocean")).toBe("| ocean | #29507f | | | | water | yes |"); + expect(row(serializePaletteTable(parsed), "ocean")).toBe("| ocean | `#29507f` | | | | water | yes |"); }); it("older builds read the new cells as unset", () => { @@ -82,8 +82,8 @@ describe("palette derived cells (P1)", () => { ]); expect(paletteDerivedStale(old)).toBe(true); const fresh = refreshPaletteDerived(old); - expect(fresh).toContain("| sea | #00f | | | | water | (yes) |"); - expect(fresh).toContain("| crags | #777 | | | | (mountains) | (no) |"); + expect(fresh).toContain("| sea | `#00f` | | | | water | (yes) |"); + expect(fresh).toContain("| crags | `#777` | | | | (mountains) | (no) |"); expect(fresh).toContain("Intro."); expect(fresh).toContain("Outro."); expect(parsePaletteNote(fresh)).toEqual(parsePaletteNote(old)); @@ -95,18 +95,18 @@ describe("palette derived cells (P1)", () => { const note = buildPaletteNote(terrains); expect(paletteDerivedStale(note)).toBe(false); // The user types a type: the Impassable default it implies changes. - const typed = note.replace("| crags | #777777 | | | | (mountains) | (no) |", "| crags | #777777 | | | | water | (no) |"); + const typed = note.replace("| crags | `#777777` | | | | (mountains) | (no) |", "| crags | `#777777` | | | | water | (no) |"); expect(paletteDerivedStale(typed)).toBe(true); - expect(refreshPaletteDerived(typed)).toContain("| crags | #777777 | | | | water | (yes) |"); + expect(refreshPaletteDerived(typed)).toContain("| crags | `#777777` | | | | water | (yes) |"); // Filled-in values are the user's, whatever they say. - const own = note.replace("| crags | #777777 | | | | (mountains) | (no) |", "| crags | #777777 | | | | Mountains | Y |"); + const own = note.replace("| crags | `#777777` | | | | (mountains) | (no) |", "| crags | `#777777` | | | | Mountains | Y |"); expect(paletteDerivedStale(own)).toBe(false); }); it("in-app edits regenerate the derived cells", () => { const note = buildPaletteNote(terrains); const next = terrains.map((t) => (t.name === "crags" ? { ...t, type: "water" } : t)); - expect(updatePaletteNote(note, next)).toContain("| crags | #777777 | | | | water | (yes) |"); + expect(updatePaletteNote(note, next)).toContain("| crags | `#777777` | | | | water | (yes) |"); }); it("cell helpers", () => { @@ -127,8 +127,8 @@ describe("path types write every option out (PA5)", () => { it("writes explicit values and round-trips", () => { const table = serializePathTypes(types); - expect(row(table, "Road")).toBe("| Road | #a16207 | 4 | solid | through | yes | direct |"); - expect(row(table, "River")).toBe("| River | #3b82f6 | 3 | solid | meander | no | winding |"); + expect(row(table, "Road")).toBe("| Road | `#a16207` | 4 | solid | through | yes | direct |"); + expect(row(table, "River")).toBe("| River | `#3b82f6` | 3 | solid | meander | no | winding |"); const back = parsePathTypes(`## Path types\n\n${table}\n`)!; expect(back.types).toEqual(types); expect(back.implicit).toBe(false); @@ -138,12 +138,12 @@ describe("path types write every option out (PA5)", () => { it("refreshNoteDerived fills blank path cells and the terrain cells, and leaves a full note alone", () => { const old = "---\nhexmaker-palette: 1\n---\n\n| Terrain | Color |\n| --- | --- |\n| lake | #00f |\n\n## Path types\n\n| Path | Color | Width | Style | Routing | Avoid impassable |\n| --- | --- | --- | --- | --- | --- |\n| Ley line | #3b82f6 | 3 | solid | meander | |\n"; const fresh = refreshNoteDerived(old); - expect(fresh).toContain("| lake | #00f | | | | (water) | (yes) |"); - expect(fresh).toContain("| Ley line | #3b82f6 | 3 | solid | meander | yes | direct |"); + expect(fresh).toContain("| lake | `#00f` | | | | (water) | (yes) |"); + expect(fresh).toContain("| Ley line | `#3b82f6` | 3 | solid | meander | yes | direct |"); expect(refreshNoteDerived(fresh)).toBe(fresh); // With the palette's own types (read with the old rules while migrating), those are written. const migrated = refreshNoteDerived(old, [{ ...types[1], name: "Ley line" }]); - expect(migrated).toContain("| Ley line | #3b82f6 | 3 | solid | meander | no | winding |"); + expect(migrated).toContain("| Ley line | `#3b82f6` | 3 | solid | meander | no | winding |"); }); }); diff --git a/tests/palettes.test.ts b/tests/palettes.test.ts index 8bb58323..cfeeb09b 100644 --- a/tests/palettes.test.ts +++ b/tests/palettes.test.ts @@ -226,6 +226,21 @@ class FakeVault { this.files.set(f.path, content); this.writes++; }; + /** Files written through the adapter (backups), outside the vault's notes. */ + raw = new Map(); + failBackups = false; + adapter = { + exists: async (p: string) => this.raw.has(p) || [...this.raw.keys()].some((k) => k.startsWith(p + "/")), + mkdir: async () => {}, + write: async (p: string, data: string) => { + if (this.failBackups) throw new Error("disk full"); + this.raw.set(p, data); + }, + writeBinary: async (p: string, data: ArrayBuffer) => { + if (this.failBackups) throw new Error("disk full"); + this.raw.set(p, data); + }, + }; rename(from: string, to: string) { const c = this.files.get(from); if (c === undefined) throw new Error(`missing: ${from}`); @@ -249,6 +264,7 @@ function makeHarness(settingsPatch: Partial = {}) { let saves = 0; const plugin = { settings, + manifest: { dir: ".obsidian/plugins/hexmaker" }, app: { vault, fileManager: { @@ -489,7 +505,7 @@ describe("PaletteStore: path types live in palettes", () => { const h = makeHarness(); await h.store.init(); const p = "world/palettes/Limited.md"; - h.vault.files.set(p, h.vault.files.get(p)!.replace("| River | #3b82f6 | 3 |", "| Stream | #3b82f6 | 2 |")); + h.vault.files.set(p, h.vault.files.get(p)!.replace("| River | `#3b82f6` | 3 |", "| Stream | `#3b82f6` | 2 |")); h.store.onModify(h.file(p)); await h.store.sync(); const pal = h.settings.terrainPalettes.find((x) => x.name === "Limited")!; @@ -583,8 +599,8 @@ describe("PaletteStore derived cells", () => { await h.store.init(); const note = h.vault.files.get("world/palettes/Limited.md")!; expect(note).toContain("My notes."); - expect(note).toContain("| sea | #0000ff | | | | water | (yes) |"); - expect(note).toContain("| crags | #777777 | | | | (mountains) | (no) |"); + expect(note).toContain("| sea | `#0000ff` | | | | water | (yes) |"); + expect(note).toContain("| crags | `#777777` | | | | (mountains) | (no) |"); expect(h.settings.terrainPalettes.find((p) => p.name === "Limited")!.terrains.slice(0, 2)).toEqual([ { name: "sea", color: "#0000ff", type: "water" }, { name: "crags", color: "#777777" }, @@ -603,7 +619,7 @@ describe("PaletteStore derived cells", () => { await h.store.sync(); const pal = h.settings.terrainPalettes.find((x) => x.name === "Limited")!; expect(pal.terrains).toEqual([{ name: "crags", color: "#777777", type: "water" }]); - expect(h.vault.files.get(p)).toContain("| crags | #777777 | | | | water | (yes) |"); + expect(h.vault.files.get(p)).toContain("| crags | `#777777` | | | | water | (yes) |"); }); it("waits until the user leaves a note they're typing in", async () => { @@ -658,14 +674,112 @@ describe("PaletteStore path type migration (PA5)", () => { await h.store.init(); const pal = h.settings.terrainPalettes.find((x) => x.name === "Limited")!; expect(pal.pathTypes!.find((t) => t.name === "Creek")).toMatchObject({ routing: "meander", avoidImpassable: false, autoRoute: "winding" }); - expect(h.vault.files.get(p)).toContain("| Creek | #39f | 2 | solid | meander | no | winding |"); - expect(h.vault.files.get(p)).toContain("| Road | #a16207 | 4 | solid | through | yes | direct |"); + expect(h.vault.files.get(p)).toContain("| Creek | `#39f` | 2 | solid | meander | no | winding |"); + expect(h.vault.files.get(p)).toContain("| Road | `#a16207` | 4 | solid | through | yes | direct |"); expect(h.settings.pathTypesExplicit).toBe(true); // After the migration a hand-typed row with blanks gets the plain defaults, whatever its name. h.vault.files.set(p, h.vault.files.get(p)! + "| River two | #00f | 2 | solid | | | |\n"); h.store.onModify(h.file(p)); await h.store.sync(); expect(pal.pathTypes!.find((t) => t.name === "River two")).toMatchObject({ routing: "through", avoidImpassable: true, autoRoute: "direct" }); - expect(h.vault.files.get(p)).toContain("| River two | #00f | 2 | solid | through | yes | direct |"); + expect(h.vault.files.get(p)).toContain("| River two | `#00f` | 2 | solid | through | yes | direct |"); + }); +}); + +// Colours as inline code, not tags: the one-time conversion on load. +describe("PaletteStore colour conversion", () => { + const BARE = [ + "---", + "hexmaker-palette: 1", + "---", + "", + "My notes, with a #tag of my own.", + "", + "| Terrain | Color | Icon | Icon color | Category | Type | Impassable | Mine |", + "| --- | --- | --- | --- | --- | --- | --- | --- |", + "| sea | #0000ff | | #FFF | | water | (yes) | keep me |", + "| crags | 777777 | | | | (mountains) | (no) | |", + "", + "## Path types", + "", + "| Path | Color | Width | Style | Routing | Avoid impassable | Auto-route |", + "| --- | --- | --- | --- | --- | --- | --- |", + "| Road | #a16207 | 4 | solid | through | yes | direct |", + "", + ].join("\n"); + const P = "world/palettes/Limited.md"; + const BACKUP = /^\.obsidian\/plugins\/hexmaker\/backups\/palette-colours-\d{4}-\d{2}-\d{2}\/palette-notes\.json(\.gz)?$/; + + async function readBackup(data: string | ArrayBuffer): Promise<{ kind: string; notes: Record }> { + if (typeof data === "string") return JSON.parse(data); + const stream = new Blob([data]).stream().pipeThrough(new DecompressionStream("gzip")); + return JSON.parse(await new Response(stream).text()); + } + + it("backs up the palette notes, then converts their colours and nothing else", async () => { + const h = makeHarness({ palettesMigrated: true, terrainTypesSeeded: true, pathTypesExplicit: true }); + await h.vault.createFolder("world/palettes"); + h.vault.files.set(P, BARE); + await h.store.init(); + + const backups = [...h.vault.raw.keys()]; + expect(backups).toHaveLength(1); + expect(backups[0]).toMatch(BACKUP); + const saved = await readBackup(h.vault.raw.get(backups[0])!); + expect(saved.kind).toBe("palette-colours"); + expect(saved.notes[P]).toBe(BARE); + + const note = h.vault.files.get(P)!; + expect(note).toBe( + BARE.replace("| #0000ff | | #FFF |", "| `#0000ff` | | `#fff` |") + .replace("| 777777 |", "| `#777777` |") + .replace("| #a16207 |", "| `#a16207` |"), + ); + expect(h.settings.paletteColorsCode).toBe(true); + + // Idempotent: loading again neither backs up nor writes. + const writes = h.vault.writes; + await h.store.init(); + await h.store.sync(); + expect(h.vault.raw.size).toBe(1); + expect(h.vault.writes).toBe(writes); + expect(h.vault.files.get(P)).toBe(note); + }); + + it("changes nothing when the backup can't be saved, and tries again next load", async () => { + const h = makeHarness({ palettesMigrated: true, terrainTypesSeeded: true, pathTypesExplicit: true }); + await h.vault.createFolder("world/palettes"); + h.vault.files.set(P, BARE); + h.vault.failBackups = true; + await h.store.init(); + expect(h.vault.files.get(P)).toBe(BARE); + expect(h.settings.paletteColorsCode).toBeFalsy(); + + h.vault.failBackups = false; + await h.store.init(); + expect(h.vault.raw.size).toBe(1); + expect(h.vault.files.get(P)).toContain("| sea | `#0000ff` |"); + expect(h.settings.paletteColorsCode).toBe(true); + }); + + it("needs no backup when every note is already converted", async () => { + const h = makeHarness(); + await h.store.init(); // fresh notes are written with inline-code colours + expect(h.vault.raw.size).toBe(0); + expect(h.settings.paletteColorsCode).toBe(true); + for (const content of h.vault.files.values()) expect(content).not.toMatch(/\| #[0-9a-f]{3,8} \|/i); + }); + + it("a later hand edit with a bare colour converts like any other refresh", async () => { + const h = makeHarness(); + await h.store.init(); + const note = h.vault.files.get(P)!; + const typed = note.replace(/\| `(#[0-9a-f]{6})` \|/, "| $1 |"); + expect(typed).not.toBe(note); + h.vault.files.set(P, typed); + h.store.onModify(h.file(P)); + await h.store.sync(); + expect(h.vault.files.get(P)).toBe(note); + expect(h.vault.raw.size).toBe(0); }); }); diff --git a/tests/pathTypeTable.test.ts b/tests/pathTypeTable.test.ts index 9c6fd69e..16a58e8e 100644 --- a/tests/pathTypeTable.test.ts +++ b/tests/pathTypeTable.test.ts @@ -51,7 +51,7 @@ describe("palette path types table", () => { expect(types[2]).toMatchObject({ routing: "through", avoidImpassable: true, autoRoute: "direct" }); // Written back with every option filled in. const out = setPathTypes(note, types); - expect(out).toContain("| Creek | #39f | 2 | solid | meander | no | winding |"); + expect(out).toContain("| Creek | `#39f` | 2 | solid | meander | no | winding |"); expect(parsePathTypes(out)!.types).toEqual(types); expect(parsePathTypes(out)!.implicit).toBe(false); }); @@ -70,7 +70,8 @@ describe("palette path types table", () => { expect(parsed.skipped).toHaveLength(2); expect(parsed.types.map((t) => t.name)).toEqual(["Road", "River"]); const rewritten = setPathTypes(note, parsed.types); - expect(rewritten).toContain("| road | #000000 |"); + // Kept as typed, in an indented block (code, so its colour isn't a tag). + expect(rewritten).toContain(" | road | #000000 |"); expect(rewritten).toContain("couldn't read"); expect(parsePathTypes(rewritten)!.skipped).toEqual([]); }); @@ -90,7 +91,7 @@ describe("palette path types table", () => { const types = parsePathTypes(note)!.types; types[0].color = "#000000"; const out = setPathTypes(note, types); - expect(out).toContain("| Road | #000000 | 4 | solid | through | yes | direct | 1 per 3 hexes |"); + expect(out).toContain("| Road | `#000000` | 4 | solid | through | yes | direct | 1 per 3 hexes |"); expect(out).toContain("Intro."); expect(out).toContain("Outro."); }); From f26bbbb90a6cfb33b367b1ce886e669bef2c49d5 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 18:54:32 -0400 Subject: [PATCH 227/558] feat(paths): phase 4 rendering: lattice geometry, paths service, em path layer, PNG - src/paths/pathGeometry.ts: through/meander/edge polylines in lattice units (R=1, absolute coords, epsilon tie-breaks), fork/join start points, lattice lane gap, strokes (width/dash in hex units), calibrateAffine. - src/paths/PathsService.ts (plugin.paths): one resolver + RouteCache per map, readiness gate (MapStore + PaletteStore ready), resolved()/ resolvedPathChains()/strokes(). pathTypeStyle is the single StyleFor source (PA5 switch is one line). - src/paths/mapPaths.ts: storedMapPaths, the Phase-3 adapter (legacyChainsToPaths(map.pathChains)). - HexMapView: path layer is a lattice SVG placed in em with a one-time three-hex calibration; not rebuilt on zoom bake. Icons moved to their own px layer (rebuilt on bake), no per-hex layout reads. Ghost strip and seam joins read resolved chains. - PNG: same strokes x R; "Bolder paths" export option (default on = old x1.4 look); hex centres now use absolute coordinates (fixes wrong stagger for odd grid offsets). - Read-only consumers switched: hexcrawlManual, RegionNavigateModal, regionContext, submapContext, setupPlaceholder. PathTypeEditorModal via typeRefs helpers (still on pathChains while the adapter is in place). - Tests: pathGeometry (R=1 vs R=50, edge ties, forks/joins), pathRender (late palette gate, screen == PNG strokes, type refs); ghostPaths source check and placeholder fixture updated. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 16 + src/export/MapExportModal.ts | 10 +- src/export/exportNames.ts | 2 + src/export/exporters/hexcrawlManual.ts | 6 +- src/export/handoutLabels.ts | 7 +- src/export/mapPngRenderer.ts | 85 +--- src/hex-map/HexMapView.ts | 582 ++++++++++++------------- src/hex-map/PathTypeEditorModal.ts | 22 +- src/hex-map/RegionNavigateModal.ts | 2 +- src/hex-map/hexGeometry.ts | 181 +------- src/palettes/PaletteStore.ts | 5 + src/paths/PathsService.ts | 178 ++++++++ src/paths/mapPaths.ts | 20 + src/paths/pathGeometry.ts | 428 ++++++++++++++++++ src/paths/typeRefs.ts | 49 +++ src/setupPlaceholder.ts | 7 +- src/worldgen/regionContext.ts | 2 +- src/worldgen/submapContext.ts | 2 +- styles.css | 14 +- tests/ghostPaths.test.ts | 6 +- tests/helpers/simVault.ts | 18 +- tests/pathGeometry.test.ts | 238 ++++++++++ tests/pathRender.test.ts | 203 +++++++++ tests/worldgenFirstMap.test.ts | 2 +- 25 files changed, 1528 insertions(+), 561 deletions(-) create mode 100644 src/paths/PathsService.ts create mode 100644 src/paths/mapPaths.ts create mode 100644 src/paths/pathGeometry.ts create mode 100644 src/paths/typeRefs.ts create mode 100644 tests/pathGeometry.test.ts create mode 100644 tests/pathRender.test.ts diff --git a/package.json b/package.json index 9152cc04..b61242e3 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 2783e3d2..6e71cccc 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -29,6 +29,7 @@ import { } from "./constants"; import { SetupWizardView } from "./SetupWizardView"; import { PaletteStore } from "./palettes/PaletteStore"; +import { PathsService } from "./paths/PathsService"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; import { enabledKinds, isIconHiddenByKind, isSpacePalette, resolveMapKinds, terrainsForTables } from "./mapKinds"; import { enableFeature, hasFeature, resolveFeatureLevel, shouldNudge, type AdvancedFeature, type FeatureLevel } from "./featureLevel"; @@ -92,6 +93,21 @@ export default class HexmakerPlugin extends Plugin { paletteStore = new PaletteStore(this); /** Per-hex map data, backed by one map note per map (src/maps). */ mapStore = new MapStore(this); + /** + * Every map's paths resolved to hex chains (one resolver, a route cache + * per map). Readers use `paths.resolvedPathChains(map)`; nothing is + * resolved until the map's terrain and palette are loaded. + */ + paths = new PathsService({ + // PHASE-3: becomes this.mapStore.isReady(map) && the palette check. + isMapReady: () => this.mapStore.isReady() && this.paletteStore.isReady(), + getMap: (name) => this.getMap(name), + orientation: () => this.settings.hexOrientation, + stagger: (map) => map.staggerOffset ?? this.settings.staggerOffset ?? "odd", + pathTypes: (map) => this.getMapPathTypes(map), + palette: (map) => this.getMapPalette(map), + hexData: (map) => this.mapStore.all(map), + }); async onload() { await this.loadSettings(); diff --git a/src/export/MapExportModal.ts b/src/export/MapExportModal.ts index 1cc5511e..002e975a 100644 --- a/src/export/MapExportModal.ts +++ b/src/export/MapExportModal.ts @@ -108,6 +108,11 @@ export function renderMapExportForm( const showCoords = inlineCheck(layerRow, "Coordinates", ticks.showCoords); const showIcons = inlineCheck(layerRow, "Icons", ticks.showIcons); const showPaths = inlineCheck(layerRow, "Paths", ticks.showPaths); + const boldPaths = inlineCheck(layerRow, "Bolder paths", prefs.boldPaths ?? true, + "Draw roads and rivers thicker than on the map so they read in print. Off: the same thickness as on the map."); + const syncBold = () => { boldPaths.disabled = !showPaths.checked; }; + showPaths.addEventListener("change", syncBold); + syncBold(); const showHexNames = inlineCheck(layerRow, "Hex names", ticks.showHexNames); const showTokens = inlineCheck(layerRow, "Tokens", ticks.showTokens, "Tokens and their names. Hidden tokens are never drawn."); const showLinkBadges = inlineCheck(layerRow, "Link badges", ticks.showLinkBadges, @@ -161,12 +166,13 @@ export function renderMapExportForm( [mapName]: { ...(fileName && fileName !== mapName ? { fileName } : {}), hexRadius: clampInt(parseInt(sizeSelect.value, 10), 10, 200, 50), + ...(boldPaths.checked ? {} : { boldPaths: false }), layers, }, }; void plugin.saveData(plugin.settings); }; - for (const input of [nameInput, sizeSelect, ...Object.values(layerChecks)]) { + for (const input of [nameInput, sizeSelect, boldPaths, ...Object.values(layerChecks)]) { input.addEventListener("change", remember); } @@ -219,6 +225,7 @@ export function renderMapExportForm( showCoords: showCoords.checked, showIcons: showIcons.checked, showPaths: showPaths.checked, + boldPaths: boldPaths.checked, showFactionOverlay: showFactionOverlay.checked, showRegionOverlay: showRegionOverlay.checked, showHexNames: showHexNames.checked, @@ -249,6 +256,7 @@ export function renderMapExportForm( player: playerEdition.checked, showIcons: o.showIcons, showPaths: o.showPaths, + boldPaths: o.boldPaths, showFactionOverlay: o.showFactionOverlay, showRegionOverlay: o.showRegionOverlay, showHexNames: o.showHexNames, diff --git a/src/export/exportNames.ts b/src/export/exportNames.ts index 38553688..473d32da 100644 --- a/src/export/exportNames.ts +++ b/src/export/exportNames.ts @@ -70,6 +70,8 @@ export interface MapExportPrefs { fileName?: string; /** The Output size preset (hex radius in px). */ hexRadius?: number; + /** "Bolder paths" (unset = on, the PNG's usual look). */ + boldPaths?: boolean; layers?: Partial>; } diff --git a/src/export/exporters/hexcrawlManual.ts b/src/export/exporters/hexcrawlManual.ts index 3c12e81b..f9a0ce32 100644 --- a/src/export/exporters/hexcrawlManual.ts +++ b/src/export/exporters/hexcrawlManual.ts @@ -45,6 +45,8 @@ export interface ManualExportOptions { hexRadius?: number; showIcons?: boolean; showPaths?: boolean; + /** Paths bolder than on screen (see MapPngRenderOptions.boldPaths). Default true. */ + boldPaths?: boolean; showFactionOverlay?: boolean; showRegionOverlay?: boolean; /** Hex names on the maps. Default true. */ @@ -218,6 +220,7 @@ export async function collectManualData( hexRadius: opts.hexRadius ?? 60, showIcons: opts.showIcons ?? true, showPaths: opts.showPaths ?? true, + boldPaths: opts.boldPaths ?? true, showFactionOverlay: opts.showFactionOverlay ?? false, showRegionOverlay: opts.showRegionOverlay ?? false, showHexNames: opts.showHexNames ?? true, @@ -292,7 +295,8 @@ export async function collectManualData( } const pathTypes = new Map(plugin.getMapPathTypes(map.name).map((t) => [t.name, t])); const pathCounts = new Map(); - for (const c of map.pathChains ?? []) pathCounts.set(c.typeName, (pathCounts.get(c.typeName) ?? 0) + c.hexes.length); + // Routed hexes per type (the paths service; empty until the map is loaded). + for (const c of plugin.paths.resolvedPathChains(map.name)) pathCounts.set(c.typeName, (pathCounts.get(c.typeName) ?? 0) + c.hexes.length); const paths = [...pathCounts].map(([name, count]) => { const t = pathTypes.get(name); return { diff --git a/src/export/handoutLabels.ts b/src/export/handoutLabels.ts index e8140553..1508d37e 100644 --- a/src/export/handoutLabels.ts +++ b/src/export/handoutLabels.ts @@ -7,6 +7,7 @@ import type { CoordPlacement } from "../coordStyle"; import type { TokenSize } from "../types"; import { BADGE_LAYOUT, DEFAULT_BADGE_SIZE, type BadgeSize } from "../hex-map/linkBadges"; +import { SCREEN_HEX_RADIUS } from "../paths/pathGeometry"; /** * Y of a hex name's baseline centre. Coordinates default to the bottom, so @@ -25,10 +26,8 @@ export function pngHexNameY( : cy - hexRadius * 0.55; } -/** The map's hex radius on screen at zoom 1, px (2.2em at 16px). */ -const SCREEN_HEX_RADIUS = 35.2; -/** How much bolder than on screen paths are drawn in the PNG. */ -const PNG_PATH_BOLD = 1.4; +/** How much bolder than on screen paths are drawn in the PNG ("Bolder paths"). */ +export const PNG_PATH_BOLD = 1.4; /** * Stroke width of a path in the PNG (round 7 U18: paths were too thin in diff --git a/src/export/mapPngRenderer.ts b/src/export/mapPngRenderer.ts index 324abc25..fe406a5f 100644 --- a/src/export/mapPngRenderer.ts +++ b/src/export/mapPngRenderer.ts @@ -13,16 +13,8 @@ */ import { getIcon, Notice, TFile, type App } from "obsidian"; -import { - hexCenter, - hexPolygonPoints, - buildEdgePts, - buildMeanderPts, - smoothPath, - sharpPath, - offsetPolyline, - computeLaneOffsets, -} from "../hex-map/hexGeometry"; +import { hexCenter, hexPolygonPoints, smoothPath, sharpPath } from "../hex-map/hexGeometry"; +import { applyAffine } from "../paths/pathGeometry"; import { ensureExportFolder, exportedMessage, openExported } from "./exportFolder"; import { getTerrainFromFile, @@ -44,6 +36,7 @@ import { pngHexNameY, pngTokenRadius, pngPathWidth, + PNG_PATH_BOLD, pngTokenSpread, wrapHexName, } from "./handoutLabels"; @@ -52,7 +45,7 @@ import { usedTerrainEntries } from "../hex-map/terrainLegend"; import { hexNameTone } from "../hex-map/hexNameLayer"; import { DEFAULT_TOKEN_FILL, groupSize, tokenGroupOffsets, tokenNamePlacement } from "../hex-map/tokenDefaults"; import { getIconUrl, normalizeFolder } from "../utils"; -import { UNKNOWN_PATH_TYPE } from "../constants"; +import { SCREEN_HEX_RADIUS } from "../paths/pathGeometry"; import { drawPatternTile } from "../overlayPatterns"; import { coordHaloColor, pngCoordFontFamily, pngCoordFontPx, pngCoordY } from "../coordStyle"; import type HexmakerPlugin from "../HexmakerPlugin"; @@ -84,6 +77,12 @@ export interface MapPngRenderOptions { showIcons?: boolean; /** Include road/river/path chains. Default true. */ showPaths?: boolean; + /** + * Draw paths bolder than on screen (×1.4 strokes, lanes and dashes), so + * roads and rivers read on a printed handout (round 7 U18). The shape + * is the same either way. Default true (the export's usual look). + */ + boldPaths?: boolean; /** * Restrict rendering to a sub-rectangle of the grid. When set, only hexes * inside the half-open range `[colStart, colEnd) × [rowStart, rowEnd)` are @@ -134,6 +133,7 @@ export async function renderMapToPngBlob( const showCoords = opts.showCoords ?? true; const showIcons = opts.showIcons ?? true; const showPaths = opts.showPaths ?? true; + const boldPaths = opts.boldPaths ?? true; const showFactionOverlay = opts.showFactionOverlay ?? false; const showRegionOverlay = opts.showRegionOverlay ?? false; const showHexNames = opts.showHexNames ?? false; @@ -180,7 +180,8 @@ export async function renderMapToPngBlob( const centerMap = new Map(); for (let row = rowStart; row < rowEnd; row++) { for (let col = colStart; col < colEnd; col++) { - const c = hexCenter(col, row, orientation, R, stagger); + // Absolute coordinates, as on screen: a hex's stagger follows its own x / y. + const c = hexCenter(col + ox, row + oy, orientation, R, stagger); centerMap.set(`${col + ox}_${row + oy}`, c); } } @@ -499,47 +500,16 @@ export async function renderMapToPngBlob( // parallel lanes so a road and a river on the same hexes render side by side // (issue #30), matching HexMapView's on-screen behaviour. if (showPaths) { - const types = plugin.getMapPathTypes(map.name); - const renderables = types.flatMap((pt) => - map.pathChains - .filter((c) => c.typeName === pt.name) - .map((chain) => ({ chain, pt })), - ); - // Paths whose type isn't in the palette still print, plain grey (as on screen). - const known = new Set(types.map((t) => t.name)); - for (const chain of map.pathChains) { - if (!known.has(chain.typeName)) renderables.push({ chain, pt: { ...UNKNOWN_PATH_TYPE, name: chain.typeName } }); + // The same lattice polylines the map view draws (src/paths/pathGeometry.ts), + // scaled by this image's hex radius: paths look the same as on screen, + // only bolder when asked (decision 4 of the path-anchors design). + const strokes = plugin.paths.strokes(map.name, { laneScale: boldPaths ? PNG_PATH_BOLD : 1 }); + const affine = { sx: R, sy: R, tx: padding - minX, ty: padding - minY }; + for (const st of strokes) { + const width = boldPaths ? pngPathWidth(st.width * SCREEN_HEX_RADIUS, R) : st.width * R; + const k = width / (st.width * R || 1); + drawPath(ctx, applyAffine(st.pts, affine), st.color, width, st.dash.map((d) => d * R * k), st.smooth); } - const laneOffset = computeLaneOffsets( - renderables.map((r) => ({ - hexes: r.chain.hexes, - width: r.pt.width, - typeName: r.pt.name, - })), - ); - renderables.forEach(({ chain, pt }, idx) => { - const dash = dashFor(pt.lineStyle); - let pts; - let smooth: boolean; - if (pt.routing === "edge") { - pts = buildEdgePts(chain.hexes, shifted, isFlat, R); - smooth = false; - } else if (pt.routing === "meander") { - pts = buildMeanderPts(chain.hexes, shifted); - smooth = true; - } else { - pts = chain.hexes - .map((k) => shifted.get(k)) - .filter((p): p is { cx: number; cy: number } => !!p); - smooth = true; - } - if (pts.length < 2) return; - // Lanes, stroke and dashes grow with the image's hex size (U18). - const width = pngPathWidth(pt.width, R); - const k = width / (pt.width || 1); - pts = offsetPolyline(pts, laneOffset[idx] * k); - drawPath(ctx, pts, pt.color, width, dash.map((d) => d * k), smooth); - }); } // Hex names, over paths, on the side of the hex away from its coordinates. @@ -1167,17 +1137,6 @@ function getHexFactionLinks(app: App, file: TFile): string[] { } -function dashFor(style: "solid" | "dashed" | "dotted"): number[] { - switch (style) { - case "dashed": - return [12, 8]; - case "dotted": - return [2, 6]; - default: - return []; - } -} - // ── Icon loading ─────────────────────────────────────────────────────────── async function loadIcons( diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 08b7902a..1f233388 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -22,7 +22,6 @@ import { getFactionColorFromFile, getRegionColorFromFile, getFactionStyleFromFil import { buildSvgPattern, colorToIdToken, type OverlayPatternKey } from "../overlayPatterns"; import { renderHexPreview } from "./overlayPatternControls"; import { - UNKNOWN_PATH_TYPE, VIEW_TYPE_HEX_MAP, VIEW_TYPE_HEX_TABLE, VIEW_TYPE_RANDOM_TABLES, @@ -46,15 +45,17 @@ import { PathPickerModal } from "./PathPickerModal"; import { addRoutedLeg, findRoute } from "./autoRoute"; import { impassableNames, noRouteMessage, pathAvoidsImpassable, pathMeanders } from "../impassable"; import type { MapData, PathChain, TokenEntry } from "../types"; +import { hexNeighbors, smoothPath, sharpPath } from "./hexGeometry"; import { - hexNeighbors, - smoothPath, - sharpPath, - offsetPolyline, - computeLaneOffsets, - buildMeanderPts, - buildEdgePts, -} from "./hexGeometry"; + applyAffine, + calibrateAffine, + END_DOT_PX, + fmt, + latticeCenter, + pxToLattice, + type LatticeAffine, + type LatticeGrid, +} from "../paths/pathGeometry"; import { GotoHexModal } from "./GotoHexModal"; import { HexHelpModal } from "./HexHelpModal"; import { FolderTreePickerModal } from "./FolderTreePickerModal"; @@ -166,6 +167,19 @@ const GM_ICON_HEX_SUBGRID: [number, number][] = [ [+0.34, +0.55], // SE ]; +/** The path layer's measurement of one grid (see calibratePathLayer). */ +interface PathLayerCalibration { + grid: HTMLElement; + lattice: LatticeGrid; + /** Lattice units → em in the grid's frame. */ + affine: LatticeAffine; + /** A hex's drawn radius, em: path widths (lattice units) scale by it. */ + hexRadius: number; + /** A hex element's size, em. */ + hexW: number; + hexH: number; +} + export class HexMapView extends ItemView { plugin: HexmakerPlugin; private zoom = 1; @@ -192,7 +206,7 @@ export class HexMapView extends ItemView { const [x, y] = a.split("_").map(Number); return hexNeighbors(x, y, orientation, stagger).some(([nx, ny]) => `${nx}_${ny}` === b); }; - return seamJoins(region.pathChains, s.shadow, (m) => this.plugin.getMap(m)?.pathChains, touches); + return seamJoins(this.plugin.paths.resolvedPathChains(region.name), s.shadow, (m) => this.plugin.paths.resolvedPathChains(m), touches); } private coordGridSize = { w: 1, h: 1 }; private coordLabels = new Map(); @@ -3582,19 +3596,14 @@ export class HexMapView extends ItemView { const F = this.zoom; const currentFs = parseFloat(getComputedStyle(this.viewportEl).fontSize); - // Tear down the path SVG FIRST, before the font-size mutation below. - // The path SVG holds coord labels at pixel positions computed against - // the pre-bake hex sizes. After font-size grows the hexes, those - // pixel positions point to where the hexes USED to be, so any paint - // frame between the font-size change and the SVG rebuild shows - // labels visibly shifted up-left from the hexes. By removing the - // SVG (and its `duckmage-svg-labels-active` class) here, the - // intermediate frame shows only the HTML labels in - // `.duckmage-coord-labels-layer`, which sit at a % of the grid and so - // track the hex layout across font-size changes. The new path SVG is rebuilt - // via `updatePathOverlay()` further down. Sandbox repro of the + // The path layer is placed in em (lattice units, see renderPathOverlay), + // so it grows with the font size and is NOT rebuilt here. The icon + // layer over it holds px positions computed against the pre-bake hex + // sizes: tear it down FIRST, before the font-size mutation below, so no + // paint frame shows icons stranded where the hexes used to be; it is + // rebuilt via `updatePathIcons()` further down. Sandbox repro of the // pre-fix slip: dev/coord-slip-sandbox.html. - this.viewportEl.querySelector("svg.duckmage-path-svg")?.remove(); + this.viewportEl.querySelector("svg.duckmage-path-icons-svg")?.remove(); this.viewportEl.removeClass("duckmage-svg-labels-active"); // Same for the faction/region overlays — they also hold pre-bake // pixel positions and would visibly mis-align during the transition. @@ -3643,7 +3652,7 @@ export class HexMapView extends ItemView { }; void this.plugin.saveSettings(); - this.updatePathOverlay(); + this.updatePathIcons(); this.updateFactionOverlay(); this.updateRegionOverlay(); this.updateTokenLayer(); @@ -4122,7 +4131,7 @@ export class HexMapView extends ItemView { this.shadowJoinKey = seamJoinKey(joins); const joinedAt = (run: { map: string; typeName: string }, key: string) => joins.find((j) => j.map === run.map && j.typeName === run.typeName && j.other === key); - const ghostPaths = ghostPathRuns(shadow, (m) => this.plugin.getMap(m)?.pathChains).flatMap((run) => { + const ghostPaths = ghostPathRuns(shadow, (m) => this.plugin.paths.resolvedPathChains(m)).flatMap((run) => { const pt = typeOf(run.map, run.typeName); if (!pt) return []; const pts = ghostRunPoints(run, centreEm); @@ -5688,17 +5697,69 @@ export class HexMapView extends ItemView { } } - private renderPathOverlay(gridContainer: HTMLElement): void { - this.viewportEl?.querySelector("svg.duckmage-path-svg")?.remove(); - this.viewportEl?.removeClass("duckmage-svg-labels-active"); - // Restore any icons that were hidden when the previous SVG elevated them - gridContainer - .querySelectorAll(".duckmage-hex-icon[data-svg-elevated]") - .forEach((img) => { - img.show(); - img.removeAttribute("data-svg-elevated"); - }); + /** + * The path layer's calibration (lattice → em for this grid) and what it + * was last drawn with. Measured once per grid (renderGrid rebuilds the + * grid); in em, so zoom bakes need no rebuild. + */ + private pathCalib: PathLayerCalibration | null = null; + private pathLayerKey = ""; + + /** + * Measure the grid once for the path layer: three hexes (the origin, the + * far end of its row, the far end of its column), all reads, no writes. + * Their centres fix the affine from lattice units to em in the grid's own + * frame, which absorbs the CSS gap and any calibrated grid transform. + */ + private calibratePathLayer(gridContainer: HTMLElement, region: MapData): PathLayerCalibration | null { + if (this.pathCalib?.grid === gridContainer) return this.pathCalib; + const { x: ox, y: oy } = region.gridOffset; + const { cols, rows } = region.gridSize; + const isFlat = this.plugin.settings.hexOrientation === "flat"; + const lattice: LatticeGrid = { orientation: this.plugin.settings.hexOrientation, stagger: this.getActiveStagger() }; + const hexAt = (x: number, y: number) => gridContainer.querySelector(`.duckmage-hex[data-x="${x}"][data-y="${y}"]`); + const origin = hexAt(ox, oy); + if (!origin) return null; + const style = getComputedStyle(gridContainer); + const em = parseFloat(style.fontSize) || 16; + const g = gridContainer.getBoundingClientRect(); + // Client px → the grid's own px (the viewport zoom and grid transforms + // scale both); the computed width is fractional, unlike offsetWidth. + const layoutW = parseFloat(style.width) || gridContainer.offsetWidth; + const layoutH = parseFloat(style.height) || gridContainer.offsetHeight; + const sx = layoutW ? g.width / layoutW : 1; + const sy = layoutH ? g.height / layoutH : 1; + const centre = (el: HTMLElement) => { + const r = el.getBoundingClientRect(); + return { x: (r.left + r.width / 2 - g.left) / sx / em, y: (r.top + r.height / 2 - g.top) / sy / em, w: r.width / sx / em, h: r.height / sy / em }; + }; + const A = centre(origin); + if (!A.w || !A.h) return null; + const farX = cols > 1 ? hexAt(ox + cols - 1, oy) : null; + const farY = rows > 1 ? hexAt(ox, oy + rows - 1) : null; + const hexRadius = isFlat ? A.w / 2 : A.h / 2; + const affine = calibrateAffine( + { key: `${ox}_${oy}`, at: A }, + farX ? { key: `${ox + cols - 1}_${oy}`, at: centre(farX) } : null, + farY ? { key: `${ox}_${oy + rows - 1}`, at: centre(farY) } : null, + lattice, + hexRadius, + ); + this.pathCalib = { grid: gridContainer, lattice, affine, hexRadius, hexW: A.w, hexH: A.h }; + this.pathLayerKey = ""; + return this.pathCalib; + } + /** + * Paths of the open map: resolved by the plugin's paths service (nothing + * until the map's terrain and palette are loaded), turned into lattice + * polylines (src/paths/pathGeometry.ts, the same ones the PNG export + * draws), placed in em. One `` per branch. + * Stroke widths scale with the hexes (lattice units × the hex radius), so + * the map looks the same at every zoom. Rebuilt only when what it draws + * changes; zoom bakes leave it alone. + */ + private renderPathOverlay(gridContainer: HTMLElement): void { const region = this.getActiveMap(); // A path edit that starts or ends a seam join redraws the neighbour // strip, so its road reaches the shared edge too (round 6 U8). @@ -5706,215 +5767,162 @@ export class HexMapView extends ItemView { if (this.lastShadow?.map === region.name && seamJoinKey(joins) !== this.shadowJoinKey) { this.renderNeighbourShadow(gridContainer, region); } - const gmLayerActive = region.showGmLayer ?? true; - const hasContent = - region.pathChains.some((c) => c.hexes.length > 0) || - this.activePathEnd !== null || - (gmLayerActive && gridContainer.querySelector("[data-gm-icons]") !== null); - if (!hasContent) return; - // Build hex center map — offsetLeft/offsetTop are unaffected by CSS transform - const centerMap = new Map(); - let hexW = 0, - hexH = 0; - gridContainer - .querySelectorAll(".duckmage-hex") - .forEach((hexEl) => { - const x = Number(hexEl.dataset.x); - const y = Number(hexEl.dataset.y); - if (hexW === 0) { - hexW = hexEl.offsetWidth; - hexH = hexEl.offsetHeight; + // ── Reads (one calibration per grid) ── + const calib = this.calibratePathLayer(gridContainer, region); + // The same strokes the PNG export draws (plugin.paths.strokes); only + // the seam stubs are the view's own. + const strokes = calib + ? this.plugin.paths.strokes(region.name, { + seamEnd: (typeName, hex) => joins.find((j) => j.typeName === typeName && j.own === hex)?.other, + }) + : []; + const em = (pts: { cx: number; cy: number }[]) => + applyAffine(pts, calib!.affine).map((p) => ({ cx: Number(fmt(p.cx)), cy: Number(fmt(p.cy)) })); + const scale = calib?.hexRadius ?? 0; + const lines = strokes.map((s) => { + const pts = em(s.pts); + return { + s, + d: s.smooth ? smoothPath(pts) : sharpPath(pts), + width: fmt(s.width * scale), + dash: s.dash.map((d) => fmt(d * scale)).join(" "), + }; + }); + // Small circle to mark the active endpoint (only in path mode) + let dot: { cx: string; cy: string; r: string; sw: string; color: string } | null = null; + if (calib && this.drawingMode === "path" && this.activePathEnd) { + const activeType = this.activePathTypeName ? this.mapPathTypes().find((p) => p.name === this.activePathTypeName) : undefined; + const [c] = em([latticeCenter(this.activePathEnd, calib.lattice)]); + dot = { + cx: fmt(c.cx), + cy: fmt(c.cy), + r: fmt(pxToLattice(END_DOT_PX.r) * scale), + sw: fmt(pxToLattice(END_DOT_PX.stroke) * scale), + color: activeType?.color ?? "#888888", + }; + } + const key = JSON.stringify([lines.map((l) => [l.s.path, l.s.branch, l.d, l.width, l.dash, l.s.color]), dot]); + const existing = gridContainer.querySelector("svg.duckmage-path-svg"); + + // ── Writes ── + if (!existing || key !== this.pathLayerKey) { + existing?.remove(); + this.pathLayerKey = key; + if (lines.length || dot) { + const svgNS = "http://www.w3.org/2000/svg"; + const svg = activeDocument.createElementNS(svgNS, "svg"); + svg.classList.add("duckmage-path-svg"); + // One user unit = 1em of the grid (it overflows for seam stubs). + svg.setAttribute("width", "1em"); + svg.setAttribute("height", "1em"); + svg.setAttribute("viewBox", "0 0 1 1"); + for (const l of lines) { + const path = activeDocument.createElementNS(svgNS, "path"); + path.setAttribute("class", "duckmage-svg-path-line"); + path.setAttribute("d", l.d); + path.setAttribute("stroke", l.s.color); + path.setAttribute("stroke-width", l.width); + path.setAttribute("stroke-linecap", "round"); + path.setAttribute("stroke-linejoin", "round"); + path.setAttribute("fill", "none"); + if (l.dash) path.setAttribute("stroke-dasharray", l.dash); + path.setAttribute("data-path", l.s.path); + path.setAttribute("data-branch", String(l.s.branch)); + svg.appendChild(path); } - let ox = hexEl.offsetWidth / 2; - let oy = hexEl.offsetHeight / 2; - let cur: HTMLElement | null = hexEl; - // Walk only up to gridContainer so coords are gridContainer-relative. - // The SVG itself lives inside gridContainer and inherits any - // gridDisplay transform — otherwise the overlay drifts away from - // the scaled hex grid on calibrated maps. - while (cur && cur !== gridContainer) { - ox += cur.offsetLeft; - oy += cur.offsetTop; - cur = cur.offsetParent as HTMLElement | null; + if (dot) { + const circle = activeDocument.createElementNS(svgNS, "circle"); + circle.setAttribute("class", "duckmage-svg-path-line"); + circle.setAttribute("cx", dot.cx); + circle.setAttribute("cy", dot.cy); + circle.setAttribute("r", dot.r); + circle.setAttribute("fill", dot.color); + circle.setAttribute("stroke", "white"); + circle.setAttribute("stroke-width", dot.sw); + circle.setAttribute("opacity", "0.9"); + svg.appendChild(circle); } - centerMap.set(`${x}_${y}`, { cx: ox, cy: oy }); - }); - - const svgNS = "http://www.w3.org/2000/svg"; - const svg = activeDocument.createElementNS(svgNS, "svg"); - svg.classList.add("duckmage-path-svg"); - const w = gridContainer.offsetLeft + gridContainer.offsetWidth + 20; - const h = gridContainer.offsetTop + gridContainer.offsetHeight + 20; - svg.setAttribute("width", String(w)); - svg.setAttribute("height", String(h)); + // Under the icon layer (elevated and GM icons sit above paths). + const icons = gridContainer.querySelector("svg.duckmage-path-icons-svg"); + if (icons) gridContainer.insertBefore(svg, icons); + else gridContainer.appendChild(svg); + } + } + this.renderPathIconsLayer(gridContainer); + } - const DASH_ARRAYS: Record = { - solid: "", - dashed: "8 4", - dotted: "2 4", - }; + /** Redraw only the icon layer (after a zoom bake: its sizes are in px). */ + private updatePathIcons(): void { + const gridContainer = this.viewportEl?.querySelector(".duckmage-hex-map-grid"); + if (gridContainer) this.renderPathIconsLayer(gridContainer); + } - const appendPath = ( - pts: { cx: number; cy: number }[], - color: string, - strokeWidth: number, - dashArray = "", - smooth = true, - ) => { - const path = activeDocument.createElementNS(svgNS, "path"); - path.setAttribute("class", "duckmage-svg-path-line"); - path.setAttribute("d", smooth ? smoothPath(pts) : sharpPath(pts)); - path.setAttribute("stroke", color); - path.setAttribute("stroke-width", String(strokeWidth)); - path.setAttribute("stroke-linecap", "round"); - path.setAttribute("stroke-linejoin", "round"); - path.setAttribute("fill", "none"); - if (dashArray) path.setAttribute("stroke-dasharray", dashArray); - svg.appendChild(path); - }; + /** + * Override icons elevated above the paths, and GM-layer icons: their own + * SVG over the path layer, placed from the path layer's calibration (no + * per-hex layout reads). Rebuilt on zoom bakes (icon and badge sizes are + * px, as they always were). + */ + private renderPathIconsLayer(gridContainer: HTMLElement): void { + gridContainer.querySelector("svg.duckmage-path-icons-svg")?.remove(); + this.viewportEl?.removeClass("duckmage-svg-labels-active"); + // Restore any icons that were hidden when the previous SVG elevated them + gridContainer + .querySelectorAll(".duckmage-hex-icon[data-svg-elevated]") + .forEach((img) => { + img.show(); + img.removeAttribute("data-svg-elevated"); + }); - const isFlat = this.plugin.settings.hexOrientation === "flat"; - const hexRadius = isFlat ? hexW / 2 : hexH / 2; - - // Flatten every chain into a render list in path-type definition order, - // pairing each chain with its resolved type. Stable order = draw order. - const types = this.mapPathTypes(); - const renderables = types.flatMap((pt) => - region.pathChains - .filter((c) => c.typeName === pt.name) - .map((chain) => ({ chain, pt })), - ); - // A path whose type isn't in this map's palette (renamed or removed in - // the palette note) still shows, plain grey, rather than vanishing. - const known = new Set(types.map((t) => t.name)); - for (const chain of region.pathChains) { - if (!known.has(chain.typeName)) - renderables.push({ chain, pt: { ...UNKNOWN_PATH_TYPE, name: chain.typeName } }); - } - - // Assign each chain a perpendicular "lane" offset so chains that share a - // route (e.g. a road and a river on the same hexes) render side by side - // instead of one stroke covering the other (issue #30). Chains that don't - // share any segment with another keep offset 0 → pixel-identical output. - // Ends that meet a neighbour's path across the seam reach on to the - // shared edge (round 6 U8). The neighbour hex is off this grid, so its - // centre is extrapolated from the grid's pitch. - const stagger = this.getActiveStagger(); - const shifted = (n: number) => ((stagger === "odd" ? n % 2 !== 0 : n % 2 === 0) ? 1 : 0); - let colPitch = 0; - let rowPitch = 0; - if (joins.length > 0) { - for (const [k, c] of centerMap) { - const [x, y] = k.split("_").map(Number); - const r = centerMap.get(`${x + 1}_${y}`); - const b = centerMap.get(`${x}_${y + 1}`); - if (!colPitch && r) colPitch = r.cx - c.cx; - if (!rowPitch && b) rowPitch = b.cy - c.cy; - if (colPitch && rowPitch) break; - } - } - const beyond = (own: string, other: string): { cx: number; cy: number } | null => { - const e = centerMap.get(own); - if (!e || !colPitch || !rowPitch) return null; - const [ex, ey] = own.split("_").map(Number); - const [nx, ny] = other.split("_").map(Number); - return isFlat - ? { cx: e.cx + (nx - ex) * colPitch, cy: e.cy + (ny - ey) * rowPitch + ((shifted(nx) - shifted(ex)) * rowPitch) / 2 } - : { cx: e.cx + (nx - ex) * colPitch + ((shifted(ny) - shifted(ey)) * colPitch) / 2, cy: e.cy + (ny - ey) * rowPitch }; - }; - const seamEnd = (typeName: string, own: string | undefined) => { - if (own === undefined) return null; - const j = joins.find((jj) => jj.typeName === typeName && jj.own === own); - const n = j ? beyond(j.own, j.other) : null; - const e = centerMap.get(own); - return n && e ? seamPoint(e, n) : null; + const region = this.getActiveMap(); + const gmLayerActive = region.showGmLayer ?? true; + const overrides = Array.from(gridContainer.querySelectorAll("[data-icon-override]")); + const gmHexes = gmLayerActive ? Array.from(gridContainer.querySelectorAll("[data-gm-icons]")) : []; + if (!overrides.length && !gmHexes.length) return; + const calib = this.calibratePathLayer(gridContainer, region); + if (!calib) return; + + // ── Reads: the font size (em → px) and the layer's size, once ── + const emPx = parseFloat(getComputedStyle(gridContainer).fontSize) || 16; + const svgW = gridContainer.offsetLeft + gridContainer.offsetWidth + 20; + const svgH = gridContainer.offsetTop + gridContainer.offsetHeight + 20; + const w = calib.hexW * emPx; + const h = calib.hexH * emPx; + const at = (hexEl: HTMLElement) => { + const [p] = applyAffine([latticeCenter(`${hexEl.dataset.x!}_${hexEl.dataset.y!}`, calib.lattice)], calib.affine); + return { cx: p.cx * emPx, cy: p.cy * emPx }; }; - const laneOffset = computeLaneOffsets( - renderables.map((r) => ({ - hexes: r.chain.hexes, - width: r.pt.width, - typeName: r.pt.name, - })), - ); - - renderables.forEach(({ chain, pt }, idx) => { - const dash = DASH_ARRAYS[pt.lineStyle] ?? ""; - let pts: { cx: number; cy: number }[]; - let smooth: boolean; - if (pt.routing === "meander") { - pts = buildMeanderPts(chain.hexes, centerMap); - smooth = true; - } else if (pt.routing === "edge") { - pts = buildEdgePts(chain.hexes, centerMap, isFlat, hexRadius); - smooth = false; - } else { - pts = chain.hexes - .map((k) => centerMap.get(k)) - .filter((p): p is { cx: number; cy: number } => !!p); - smooth = true; - } - if (pt.routing !== "edge" && pts.length >= 1) { - const head = seamEnd(pt.name, chain.hexes[0]); - const tail = chain.hexes.length > 1 ? seamEnd(pt.name, chain.hexes[chain.hexes.length - 1]) : null; - if (head) pts = [head, ...pts]; - if (tail) pts = [...pts, tail]; - } - if (pts.length < 2) return; - pts = offsetPolyline(pts, laneOffset[idx]); - appendPath(pts, pt.color, pt.width, dash, smooth); - }); + // ── Writes ── + const svgNS = "http://www.w3.org/2000/svg"; + const svg = activeDocument.createElementNS(svgNS, "svg"); + svg.classList.add("duckmage-path-icons-svg"); + svg.setAttribute("width", String(svgW)); + svg.setAttribute("height", String(svgH)); - // Small circle to mark the active endpoint (only visible in path mode) - if (this.drawingMode === "path" && this.activePathEnd) { - const activeType = this.activePathTypeName - ? this.mapPathTypes().find( - (p) => p.name === this.activePathTypeName, - ) - : undefined; - const color = activeType?.color ?? "#888888"; - const pos = centerMap.get(this.activePathEnd); - if (pos) { - const circle = activeDocument.createElementNS(svgNS, "circle"); - circle.setAttribute("class", "duckmage-svg-path-line"); - circle.setAttribute("cx", String(pos.cx)); - circle.setAttribute("cy", String(pos.cy)); - circle.setAttribute("r", "5"); - circle.setAttribute("fill", color); - circle.setAttribute("stroke", "white"); - circle.setAttribute("stroke-width", "1.5"); - circle.setAttribute("opacity", "0.9"); - svg.appendChild(circle); + // Elevate override icons above roads/rivers by rendering them inside the SVG. + for (const hexEl of overrides) { + const iconName = hexEl.dataset.iconOverride!; + const pos = at(hexEl); + const origImg = hexEl.querySelector(".duckmage-hex-icon"); + if (origImg) { + origImg.hide(); + origImg.setAttribute("data-svg-elevated", "1"); } + const imgEl = activeDocument.createElementNS(svgNS, "image"); + const iconW = w * 0.78; + const iconH = h * 0.78; + imgEl.setAttribute("x", String(pos.cx - iconW / 2)); + imgEl.setAttribute("y", String(pos.cy - iconH / 2)); + imgEl.setAttribute("width", String(iconW)); + imgEl.setAttribute("height", String(iconH)); + imgEl.setAttribute("href", getIconUrl(this.plugin, iconName)); + imgEl.setAttribute("opacity", "0.75"); + imgEl.setAttribute("class", "duckmage-svg-icon-override"); + svg.appendChild(imgEl); } - // Elevate override icons above roads/rivers by rendering them inside the SVG. - gridContainer - .querySelectorAll("[data-icon-override]") - .forEach((hexEl) => { - const iconName = hexEl.dataset.iconOverride!; - const key = `${hexEl.dataset.x!}_${hexEl.dataset.y!}`; - const pos = centerMap.get(key); - if (!pos) return; - const origImg = hexEl.querySelector(".duckmage-hex-icon"); - if (origImg) { - origImg.hide(); - origImg.setAttribute("data-svg-elevated", "1"); - } - const imgEl = activeDocument.createElementNS(svgNS, "image"); - const iconW = hexEl.offsetWidth * 0.78; - const iconH = hexEl.offsetHeight * 0.78; - imgEl.setAttribute("x", String(pos.cx - iconW / 2)); - imgEl.setAttribute("y", String(pos.cy - iconH / 2)); - imgEl.setAttribute("width", String(iconW)); - imgEl.setAttribute("height", String(iconH)); - imgEl.setAttribute("href", getIconUrl(this.plugin, iconName)); - imgEl.setAttribute("opacity", "0.75"); - imgEl.setAttribute("class", "duckmage-svg-icon-override"); - svg.appendChild(imgEl); - }); - // NOTE: coord labels are NO LONGER rendered in the SVG. The SVG // copies were a stable source of "label drift on zoom" — the SVG's // pixel positions are computed against pre-bake hex sizes, so any @@ -5935,67 +5943,57 @@ export class HexMapView extends ItemView { // down. Up to 7 unique icons display; further additions are kept // in frontmatter but don't render. A "×N" badge appears on a slot // when its icon was added 2+ times. - if (gmLayerActive) { - gridContainer - .querySelectorAll("[data-gm-icons]") - .forEach((hexEl) => { - const list = this.parseGmIconsDataset(hexEl.dataset.gmIcons); - if (list.length === 0) return; - const key = `${hexEl.dataset.x!}_${hexEl.dataset.y!}`; - const pos = centerMap.get(key); - if (!pos) return; - - // Count occurrences per icon, preserving first-seen order. - const counts = new Map(); - for (const ic of list) counts.set(ic, (counts.get(ic) ?? 0) + 1); - const slots = Array.from(counts.entries()).slice(0, GM_ICON_HEX_SUBGRID.length); - const slotCount = slots.length; - - const w = hexEl.offsetWidth; - const h = hexEl.offsetHeight; - // Spread = half the hex's short dimension so the sub-grid fits - // comfortably inside the parent hex's bounds. - const spread = Math.min(w, h) * 0.42; - // Icon size shrinks as the sub-grid fills so neighbouring icons - // don't overlap. Single-icon hexes keep ~legacy size. - const sizeFactor = slotCount === 1 ? 0.40 - : slotCount <= 2 ? 0.30 - : slotCount <= 4 ? 0.26 - : 0.22; - const size = Math.round(w * sizeFactor); - - slots.forEach(([iconName, count], slotIdx) => { - const [odx, ody] = GM_ICON_HEX_SUBGRID[slotIdx]; - // Icons are positioned by top-left corner; subtract half the - // size so the icon CENTER lands on the sub-grid slot. - const ix = pos.cx + odx * spread - size / 2; - const iy = pos.cy + ody * spread - size / 2; - const imgEl = activeDocument.createElementNS(svgNS, "image"); - imgEl.setAttribute("x", String(ix)); - imgEl.setAttribute("y", String(iy)); - imgEl.setAttribute("width", String(size)); - imgEl.setAttribute("height", String(size)); - imgEl.setAttribute("href", getIconUrl(this.plugin, iconName)); - imgEl.setAttribute("class", "duckmage-svg-gm-icon"); - svg.appendChild(imgEl); - - if (count > 1) { - // Badge sits at the bottom-right corner of the icon glyph, - // tucked inside the icon's bounding box so it tracks the - // icon even at small sizes (was drifting away with the old - // `* 0.9 / * 1.02` offset which scaled badge-to-icon - // distance independent of the actual icon position). - const badgeEl = activeDocument.createElementNS(svgNS, "text"); - badgeEl.setAttribute("x", String(ix + size)); - badgeEl.setAttribute("y", String(iy + size)); - badgeEl.setAttribute("text-anchor", "end"); - badgeEl.setAttribute("dominant-baseline", "alphabetic"); - badgeEl.setAttribute("class", "duckmage-svg-gm-icon-count"); - badgeEl.textContent = `×${count}`; - svg.appendChild(badgeEl); - } - }); - }); + for (const hexEl of gmHexes) { + const list = this.parseGmIconsDataset(hexEl.dataset.gmIcons); + if (list.length === 0) continue; + const pos = at(hexEl); + + // Count occurrences per icon, preserving first-seen order. + const counts = new Map(); + for (const ic of list) counts.set(ic, (counts.get(ic) ?? 0) + 1); + const slots = Array.from(counts.entries()).slice(0, GM_ICON_HEX_SUBGRID.length); + const slotCount = slots.length; + + // Spread = half the hex's short dimension so the sub-grid fits + // comfortably inside the parent hex's bounds. + const spread = Math.min(w, h) * 0.42; + // Icon size shrinks as the sub-grid fills so neighbouring icons + // don't overlap. Single-icon hexes keep ~legacy size. + const sizeFactor = slotCount === 1 ? 0.40 + : slotCount <= 2 ? 0.30 + : slotCount <= 4 ? 0.26 + : 0.22; + const size = Math.round(w * sizeFactor); + + slots.forEach(([iconName, count], slotIdx) => { + const [odx, ody] = GM_ICON_HEX_SUBGRID[slotIdx]; + // Icons are positioned by top-left corner; subtract half the + // size so the icon CENTER lands on the sub-grid slot. + const ix = pos.cx + odx * spread - size / 2; + const iy = pos.cy + ody * spread - size / 2; + const imgEl = activeDocument.createElementNS(svgNS, "image"); + imgEl.setAttribute("x", String(ix)); + imgEl.setAttribute("y", String(iy)); + imgEl.setAttribute("width", String(size)); + imgEl.setAttribute("height", String(size)); + imgEl.setAttribute("href", getIconUrl(this.plugin, iconName)); + imgEl.setAttribute("class", "duckmage-svg-gm-icon"); + svg.appendChild(imgEl); + + if (count > 1) { + // Badge sits at the bottom-right corner of the icon glyph, + // tucked inside the icon's bounding box so it tracks the + // icon even at small sizes. + const badgeEl = activeDocument.createElementNS(svgNS, "text"); + badgeEl.setAttribute("x", String(ix + size)); + badgeEl.setAttribute("y", String(iy + size)); + badgeEl.setAttribute("text-anchor", "end"); + badgeEl.setAttribute("dominant-baseline", "alphabetic"); + badgeEl.setAttribute("class", "duckmage-svg-gm-icon-count"); + badgeEl.textContent = `×${count}`; + svg.appendChild(badgeEl); + } + }); } this.viewportEl?.addClass("duckmage-svg-labels-active"); diff --git a/src/hex-map/PathTypeEditorModal.ts b/src/hex-map/PathTypeEditorModal.ts index 91b4ca3d..bdb91416 100644 --- a/src/hex-map/PathTypeEditorModal.ts +++ b/src/hex-map/PathTypeEditorModal.ts @@ -4,6 +4,7 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import type { PathType, PathLineStyle, PathRouting } from "../types"; import { buildPathPreviewSvg } from "./PathPickerModal"; import { pathAvoidsImpassable } from "../impassable"; +import { countPathsOfType, removePathTypeFromChains, renamePathTypeInChains } from "../paths/typeRefs"; export class PathTypeEditorModal extends HexmakerModal { private pendingName: string; @@ -140,14 +141,14 @@ export class PathTypeEditorModal extends HexmakerModal { deleteBtn.addEventListener("click", () => { if (confirmDiv) { confirmDiv.remove(); confirmDiv = null; return; } - const chainCount = this.plugin.mapsOnPalette(this.paletteName).reduce( - (sum, r) => sum + r.pathChains.filter(c => c.typeName === this.originalName).length, + const pathCount = this.plugin.mapsOnPalette(this.paletteName).reduce( + (sum, r) => sum + countPathsOfType(this.plugin.paths.storedPaths(r), this.originalName), 0, ); confirmDiv = contentEl.createDiv({ cls: "duckmage-terrain-editor-confirm" }); - if (chainCount > 0) { + if (pathCount > 0) { confirmDiv.createEl("p", { - text: `This type is used in ${chainCount} chain(s). Deleting it will remove those chains. Continue?`, + text: `This type is used by ${pathCount} path(s). Deleting it will remove those paths. Continue?`, cls: "duckmage-terrain-editor-confirm-msg", }); } else { @@ -186,12 +187,12 @@ export class PathTypeEditorModal extends HexmakerModal { this.entry.routing = this.pendingRouting; this.entry.avoidImpassable = this.pendingAvoid; - // If name changed, update all pathChain typeName refs + // If name changed, point every path of this type at the new name. + // PHASE-3: while maps store pathChains (src/paths/mapPaths.ts) this edits + // the chains; then renamePathTypeInPaths(map.paths, …). if (nameChanged) { for (const region of this.plugin.mapsOnPalette(this.paletteName)) { - for (const chain of region.pathChains) { - if (chain.typeName === this.originalName) chain.typeName = this.pendingName; - } + renamePathTypeInChains(region.pathChains, this.originalName, this.pendingName); } } @@ -208,9 +209,10 @@ export class PathTypeEditorModal extends HexmakerModal { const idx = list.indexOf(this.entry); if (idx !== -1) list.splice(idx, 1); - // Remove matching chains on maps that use this palette + // Remove the paths of this type on maps that use this palette. + // PHASE-3: then removePathTypeFromPaths(map.paths, …). for (const region of this.plugin.mapsOnPalette(this.paletteName)) { - region.pathChains = region.pathChains.filter(c => c.typeName !== this.originalName); + region.pathChains = removePathTypeFromChains(region.pathChains, this.originalName); } await this.plugin.saveSettings(); diff --git a/src/hex-map/RegionNavigateModal.ts b/src/hex-map/RegionNavigateModal.ts index 50acfab9..68ad9d0a 100644 --- a/src/hex-map/RegionNavigateModal.ts +++ b/src/hex-map/RegionNavigateModal.ts @@ -36,7 +36,7 @@ export class RegionNavigateModal extends HexmakerModal { this.plugin.settings.hexOrientation, paletteColors(this.plugin, map.paletteName), undefined, - (map.pathChains ?? []).map((p) => ({ type: p.typeName, hexes: p.hexes })), + this.plugin.paths.resolvedPathChains(name).map((p) => ({ type: p.typeName, hexes: p.hexes })), pathColors(this.plugin, this.plugin.mapPaletteName(name)), 360, 12, diff --git a/src/hex-map/hexGeometry.ts b/src/hex-map/hexGeometry.ts index 4f5650b2..466ead6d 100644 --- a/src/hex-map/hexGeometry.ts +++ b/src/hex-map/hexGeometry.ts @@ -208,7 +208,7 @@ export function offsetPolyline(pts: Pt[], offset: number): Pt[] { ty /= len; // Canonicalise tangent direction so the perpendicular at a given point on // the route is the same no matter which way the chain runs. - if (tx < 0 || (tx === 0 && ty < 0)) { + if (tx < -1e-9 || (Math.abs(tx) <= 1e-9 && ty < 0)) { tx = -tx; ty = -ty; } @@ -301,180 +301,5 @@ export function computeLaneOffsets( return offsets; } -// ── Chain routing helpers ───────────────────────────────────────────────────── - -/** - * "Meander" routing: smooth bezier curves through edge midpoints between hex centers. - * Falls back to raw centers for chains shorter than 3 hexes. - */ -export function buildMeanderPts( - hexes: string[], - centerMap: Map, -): Pt[] { - const centers = hexes - .map((k) => centerMap.get(k)) - .filter((p): p is Pt => !!p); - if (centers.length < 3) return centers; - const pts: Pt[] = []; - for (let i = 0; i < centers.length - 1; i++) - pts.push({ - cx: (centers[i].cx + centers[i + 1].cx) / 2, - cy: (centers[i].cy + centers[i + 1].cy) / 2, - }); - return pts; -} - -/** - * "Edge" routing: traces strictly along hex polygon boundary lines. - * - * Approach: - * 1. For each hex in the chain, the 6 vertices are computed from that hex's own centre - * (not from the midpoint between two centres), so the path always lands on the actual - * hex outline regardless of the CSS gap between hexes. - * 2. For each consecutive pair (Hi, Hi+1) the "edge index" on Hi's side is snapped from - * the pixel direction angle to the nearest of the 6 edge midpoint angles. - * 3. A greedy look-ahead picks which of the two shared-edge vertices to use on each edge, - * minimising the cross-product (turn cost) — this keeps collinear chains on one side. - * 4. For every internal hex the path traverses the *shorter arc* of that hex's boundary - * between the entry vertex (from the previous edge) and the exit vertex (for the next - * edge), including any intermediate polygon corner vertices. This is the critical step - * that makes the path hug the actual hex edge lines rather than cutting diagonally. - */ -export function buildEdgePts( - hexes: string[], - centerMap: Map, - isFlat: boolean, - hexRadius: number, -): Pt[] { - const centers = hexes - .map((k) => centerMap.get(k)) - .filter((p): p is Pt => !!p); - if (centers.length < 2) return centers; - const n = centers.length; - const TAU = 2 * Math.PI; - - // Angle of vertex 0 for this orientation. - // Flat-top → vertices at 0°, 60°, 120°, 180°, 240°, 300° (right, lower-right, …) - // Pointy-top → vertices at 30°, 90°, 150°, 210°, 270°, 330° (upper-right, bottom, …) - const vStart = isFlat ? 0 : Math.PI / 6; - - // The 6 vertices of a hex centred at C, clockwise from vStart. - const hexVerts = (C: Pt): Pt[] => - Array.from({ length: 6 }, (_, i) => ({ - cx: C.cx + hexRadius * Math.cos(vStart + (i * Math.PI) / 3), - cy: C.cy + hexRadius * Math.sin(vStart + (i * Math.PI) / 3), - })); - - // Snap a direction angle θ to the nearest edge index (0–5). - // Edge i spans vertex i → vertex (i+1)%6; its midpoint is at vStart + (i+0.5)×60°. - const snapEdge = (theta: number): number => { - let best = 0, - bestD = Infinity; - for (let i = 0; i < 6; i++) { - const mid = vStart + (i + 0.5) * (Math.PI / 3); - let d = (((theta - mid) % TAU) + TAU) % TAU; - if (d > Math.PI) d = TAU - d; - if (d < bestD) { - bestD = d; - best = i; - } - } - return best; - }; - - // Shorter arc from vertex index `from` to `to` on the 6-cycle, inclusive. - const shortArc = (from: number, to: number): number[] => { - if (from === to) return [from]; - const cw = (to - from + 6) % 6; - const ccw = (from - to + 6) % 6; - const out: number[] = []; - if (cw <= ccw) { - for (let k = 0; k <= cw; k++) out.push((from + k) % 6); - } else { - for (let k = 0; k <= ccw; k++) out.push((from - k + 6) % 6); - } - return out; - }; - - // For each edge i (between centers[i] and centers[i+1]): - // edgeIdx[i] = which edge of centers[i]'s hex faces centers[i+1]. - const edgeIdx = centers.slice(0, -1).map((A, i) => { - const B = centers[i + 1]; - return snapEdge(Math.atan2(B.cy - A.cy, B.cx - A.cx)); - }); - - // choice[i] ∈ {0,1}: which of the two edge-i vertices to use on centers[i]'s side. - // 0 → verts[edgeIdx[i]] 1 → verts[(edgeIdx[i]+1)%6] - const choice: number[] = Array.from({ length: n - 1 }, () => 0); - let prev: Pt = centers[0]; - for (let i = 0; i < n - 1; i++) { - const vA = hexVerts(centers[i]); - const Va = vA[edgeIdx[i]], - Vb = vA[(edgeIdx[i] + 1) % 6]; - if (i < n - 2) { - // Look-ahead: pick the vertex pair (this edge + next edge) with the lowest turn cost. - const vB = hexVerts(centers[i + 1]); - const VaN = vB[edgeIdx[i + 1]], - VbN = vB[(edgeIdx[i + 1] + 1) % 6]; - const cost = (v: Pt, vn: Pt) => - Math.abs( - (v.cx - prev.cx) * (vn.cy - v.cy) - - (v.cy - prev.cy) * (vn.cx - v.cx), - ); - let bestCost = Infinity, - bestC = 0; - for (const [v, ci] of [ - [Va, 0], - [Vb, 1], - ] as [Pt, number][]) { - for (const vn of [VaN, VbN]) { - const co = cost(v, vn); - if (co < bestCost) { - bestCost = co; - bestC = ci; - } - } - } - choice[i] = bestC; - prev = vA[(edgeIdx[i] + bestC) % 6]; - } else { - // Last edge: pick the vertex closest to the previously chosen point. - const dA = (Va.cx - prev.cx) ** 2 + (Va.cy - prev.cy) ** 2; - const dB = (Vb.cx - prev.cx) ** 2 + (Vb.cy - prev.cy) ** 2; - choice[i] = dA <= dB ? 0 : 1; - } - } - - // Build the result path. - // For internal hex k the path traverses the shorter boundary arc from the "entry vertex" - // (the vertex on hex k that matches the exit vertex chosen for edge k-1) to the "exit - // vertex" (the chosen vertex for edge k). - // - // Entry vertex on hex k from edge k-1: - // If choice[k-1]=0, the vertex on centers[k-1] was edgeIdx[k-1]. - // The matching vertex on hex k's side is (edgeIdx[k-1] + 4 - choice[k-1]) % 6. - // (The factor of 4 accounts for the ±30° / 180° flip between the two hex perspectives.) - const result: Pt[] = [centers[0]]; - - for (let k = 0; k < n; k++) { - const verts = hexVerts(centers[k]); - if (k === 0) { - // First hex: just add the chosen exit vertex. - result.push(verts[(edgeIdx[0] + choice[0]) % 6]); - } else if (k === n - 1) { - // Last hex: add entry vertex then the hex centre. - const entryIdx = (edgeIdx[n - 2] + 4 - choice[n - 2]) % 6; - result.push(verts[entryIdx]); - result.push(centers[k]); - } else { - // Internal hex: traverse the shorter arc from entry to exit. - const entryIdx = (edgeIdx[k - 1] + 4 - choice[k - 1]) % 6; - const exitIdx = (edgeIdx[k] + choice[k]) % 6; - const arc = shortArc(entryIdx, exitIdx); - // arc[0] == entryIdx, which coincides (zero gap) with the last pushed point — skip it. - for (let j = 1; j < arc.length; j++) result.push(verts[arc[j]]); - } - } - - return result; -} +// Chain polylines (through / meander / edge) live in src/paths/pathGeometry.ts, +// in lattice units, shared by the map view and the PNG export. diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index cfdee4bf..0cb970bb 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -124,6 +124,11 @@ export class PaletteStore { constructor(private plugin: HexmakerPlugin) {} + /** The palette notes have been read (palettes, impassable flags and path types are final). */ + isReady(): boolean { + return this.ready; + } + folder(): string { const configured = normalizeFolder(this.plugin.settings.palettesFolder ?? ""); if (configured) return configured; diff --git a/src/paths/PathsService.ts b/src/paths/PathsService.ts new file mode 100644 index 00000000..5c177534 --- /dev/null +++ b/src/paths/PathsService.ts @@ -0,0 +1,178 @@ +/** + * The plugin's paths service: every map's anchored paths, resolved to hex + * chains through one shared resolver and one route cache per map. The map + * view, the PNG export, the ghost strip, the hexcrawl manual and the + * read-only consumers (region navigate, region/submap context) all read + * `resolvedPathChains(map)` (the old PathChain shape). + * + * Pure (no Obsidian imports): the plugin hands it a PathsHost. + * + * Determinism: a map's routes depend only on its paths, its palette's + * impassable terrains, the terrain shown on each hex (own, else the map's + * base terrain), its bounds, the orientation, the stagger and each path + * type's explicit style. READINESS GATE: until the map's terrain and its + * palette are loaded, nothing is resolved (an empty list): routing with a + * half-loaded palette would draw a road straight through a lake and then + * jump when the palette arrives. Never an intermediate route. + */ + +import type { MapData, MapPath, PathChain, PathType, TerrainColor } from "../types"; +import { impassableNames, pathAvoidsImpassable, pathMeanders } from "../impassable"; +import type { RouteContext, SegmentStyle } from "./router"; +import { contextSignature } from "./router"; +import { RouteCache } from "./routeCache"; +import { resolvePaths, resolvedToChains, type ResolvedBranch, type StyleFor } from "./resolve"; +import { storedMapPaths } from "./mapPaths"; +import { buildPathStrokes, type LatticeGrid, type PathStroke, type StrokeOptions } from "./pathGeometry"; +import { UNKNOWN_PATH_TYPE } from "../constants"; + +/** + * A path type's routing style: THE place the router's avoid/winding flags + * come from (the resolver's StyleFor is built from it). `undefined` for a + * type not in the palette (the resolver then uses DEFAULT_SEGMENT_STYLE). + * + * PA5 SWITCH (fix/46-palettes-generators): the return line below is today's + * effective mapping (the existing helpers in src/impassable.ts). When PA5 + * is merged it becomes exactly + * return t && { avoid: t.avoidImpassable, winding: t.autoRoute === "winding" }; + * and nothing else changes. No other code reads avoid or winding. + */ +export function pathTypeStyle(t: PathType | undefined): SegmentStyle | undefined { + return t && { avoid: pathAvoidsImpassable(t), winding: pathMeanders(t) }; +} + +/** StyleFor over a map's path types (first of a name wins, as the palette does). */ +export function styleForTypes(types: readonly PathType[]): StyleFor { + const byName = new Map(); + for (const t of types) if (!byName.has(t.name)) byName.set(t.name, t); + return (name) => pathTypeStyle(byName.get(name)); +} + +/** What the service needs from the plugin. */ +export interface PathsHost { + /** + * The readiness gate: the map's terrain AND its palette are loaded. + * (Wired to MapStore.isReady() + PaletteStore.isReady(); Phase 3's + * per-map MapStore.isReady(map) slots in there.) + */ + isMapReady(map: string): boolean; + getMap(name: string): MapData | undefined; + orientation(): "flat" | "pointy"; + /** The stagger the map is drawn with (its own, else the plugin's). */ + stagger(map: MapData): "odd" | "even"; + /** The map's path types (its palette's). */ + pathTypes(map: string): readonly PathType[]; + /** The map's palette terrains. */ + palette(map: string): readonly TerrainColor[]; + /** The map's hexes with data (own terrain). */ + hexData(map: string): ReadonlyMap; +} + +interface Memo { + key: string; + resolved: ResolvedBranch[]; + chains: PathChain[]; +} + +export class PathsService { + private caches = new Map(); + private memo = new Map(); + + constructor(private host: PathsHost) {} + + /** The map's stored paths (anchors), whatever its readiness. */ + storedPaths(map: MapData): MapPath[] { + return storedMapPaths(map); + } + + /** Can this map's paths be resolved yet (terrain and palette loaded)? */ + isReady(mapName: string): boolean { + return !!this.host.getMap(mapName) && this.host.isMapReady(mapName); + } + + /** The map's routing context now, or null when it isn't ready. */ + context(mapName: string): RouteContext | null { + const map = this.host.getMap(mapName); + if (!map || !this.host.isMapReady(mapName)) return null; + const { x: ox, y: oy } = map.gridOffset; + const { cols, rows } = map.gridSize; + const bounds = { minX: ox, minY: oy, maxX: ox + cols - 1, maxY: oy + rows - 1 }; + const names = new Set(impassableNames([...this.host.palette(mapName)])); + const blocked = new Set(); + if (names.size) { + const hexes = this.host.hexData(mapName); + const base = map.baseTerrain; + if (base && names.has(base)) { + // Every hex without its own terrain shows the base: walk the bounds. + for (let x = bounds.minX; x <= bounds.maxX; x++) { + for (let y = bounds.minY; y <= bounds.maxY; y++) { + const k = `${x}_${y}`; + const t = hexes.get(k)?.terrain || base; + if (names.has(t)) blocked.add(k); + } + } + } else { + for (const [k, h] of hexes) if (h.terrain && names.has(h.terrain)) blocked.add(k); + } + } + return { orientation: this.host.orientation(), stagger: this.host.stagger(map), bounds, blocked }; + } + + /** The map's route cache (kept across calls; a context change keeps the old routes as previous()). */ + cacheFor(mapName: string): RouteCache { + let c = this.caches.get(mapName); + if (!c) this.caches.set(mapName, (c = new RouteCache())); + return c; + } + + /** The map's paths resolved to branches; [] until the map is ready. */ + resolved(mapName: string): ResolvedBranch[] { + return this.compute(mapName)?.resolved ?? []; + } + + /** The map's resolved branches as PathChains (for read-only consumers); [] until ready. */ + resolvedPathChains(mapName: string): PathChain[] { + return this.compute(mapName)?.chains ?? []; + } + + /** The map's lattice (orientation and stagger), or null for an unknown map. */ + lattice(mapName: string): LatticeGrid | null { + const map = this.host.getMap(mapName); + return map ? { orientation: this.host.orientation(), stagger: this.host.stagger(map) } : null; + } + + /** + * The map's path strokes in lattice units: what the map view and the PNG + * export both draw (only the final affine differs). [] until ready. + */ + strokes(mapName: string, opts: Omit = {}): PathStroke[] { + const grid = this.lattice(mapName); + if (!grid) return []; + return buildPathStrokes(this.resolved(mapName), this.host.pathTypes(mapName), grid, { ...opts, unknownType: UNKNOWN_PATH_TYPE }); + } + + /** Forget a map's cached routes (map deleted or renamed). */ + forget(mapName: string): void { + this.caches.delete(mapName); + this.memo.delete(mapName); + } + + private compute(mapName: string): Memo | null { + const map = this.host.getMap(mapName); + const ctx = this.context(mapName); + if (!map || !ctx) return null; + const paths = storedMapPaths(map); + const types = this.host.pathTypes(mapName); + const styleFor = styleForTypes(types); + const styles = [...new Set(paths.map((p) => p.typeName))] + .map((n) => { const s = styleFor(n); return `${n}=${s ? `${+s.avoid}${+s.winding}` : "?"}`; }) + .join(","); + const key = `${contextSignature(ctx)}|${styles}|${JSON.stringify(paths.map((p) => [p.name, p.typeName, p.branches.map((b) => b.anchors)]))}`; + const hit = this.memo.get(mapName); + if (hit && hit.key === key) return hit; + const resolved = resolvePaths(paths, ctx, styleFor, this.cacheFor(mapName)); + const memo: Memo = { key, resolved, chains: resolvedToChains(resolved) }; + this.memo.set(mapName, memo); + return memo; + } +} diff --git a/src/paths/mapPaths.ts b/src/paths/mapPaths.ts new file mode 100644 index 00000000..91e65bfe --- /dev/null +++ b/src/paths/mapPaths.ts @@ -0,0 +1,20 @@ +/** + * The ONE place a map's stored paths are read as anchored MapPaths. + * Pure, no Obsidian imports. + */ + +import type { MapData, MapPath } from "../types"; +import { legacyChainsToPaths } from "./legacy"; + +/** + * ┌──────────────────────────────────────────────────────────────────────┐ + * │ PHASE-3 ADAPTER. Until the map note stores `MapData.paths` (format │ + * │ with `## Path routes`, built on feat/path-mapnote), a map's paths │ + * │ are its legacy `pathChains`, each chain one path with every hex as │ + * │ an anchor (lossless: it resolves to exactly the old chain). Phase 3 │ + * │ replaces ONLY this function's body with `return map.paths ?? [];`. │ + * └──────────────────────────────────────────────────────────────────────┘ + */ +export function storedMapPaths(map: Partial>): MapPath[] { + return legacyChainsToPaths(map.pathChains ?? []); +} diff --git a/src/paths/pathGeometry.ts b/src/paths/pathGeometry.ts new file mode 100644 index 00000000..95506a17 --- /dev/null +++ b/src/paths/pathGeometry.ts @@ -0,0 +1,428 @@ +/** + * Path geometry in LATTICE units: resolved hex chains → the polylines the + * map view and the PNG export draw. Pure, no Obsidian or DOM imports. + * + * The lattice is the hex grid with cell radius R = 1 (hexGeometry.hexCenter + * at radius 1, absolute "x_y" coordinates). Everything here (points, stroke + * widths, dashes, lane gaps, end dots) is in those units, so a polyline is + * the same at every zoom and in every export; only the final affine differs + * (screen: lattice → em, measured once per grid; PNG: × the export's R). + * + * Nothing here reads the DOM, the zoom or a path's name. + */ + +import type { HexKey, PathType } from "../types"; +import type { ResolvedBranch } from "./resolve"; +import { computeLaneOffsets, hexCenter, offsetPolyline } from "../hex-map/hexGeometry"; + +export type Pt = { cx: number; cy: number }; + +/** The map's hex radius on screen at zoom 1, px (2.2em at 16px). Path type + * widths are in screen px at that size, so width / this = lattice units. */ +export const SCREEN_HEX_RADIUS = 35.2; + +/** Ties in geometry compare within this (exact lattice coords + float noise). */ +export const GEOM_EPS = 1e-9; + +export interface LatticeGrid { + orientation: "flat" | "pointy"; + stagger: "odd" | "even"; +} + +/** px at the default zoom → lattice units. */ +export function pxToLattice(px: number): number { + return px / SCREEN_HEX_RADIUS; +} + +const parseKey = (key: HexKey): [number, number] => { + const i = key.indexOf("_"); + return [Number(key.slice(0, i)), Number(key.slice(i + 1))]; +}; + +/** Centre of hex `key` on the lattice (cell radius 1, absolute coordinates). */ +export function latticeCenter(key: HexKey, grid: LatticeGrid): Pt { + const [x, y] = parseKey(key); + return hexCenter(x, y, grid.orientation, 1, grid.stagger); +} + +/** Where two touching hexes share an edge. */ +const mid = (a: Pt, b: Pt): Pt => ({ cx: (a.cx + b.cx) / 2, cy: (a.cy + b.cy) / 2 }); + +// ── Drawing styles ─────────────────────────────────────────────────────────── + +/** "through": hex centres. */ +export function throughPoints(hexes: readonly HexKey[], grid: LatticeGrid): Pt[] { + return hexes.map((k) => latticeCenter(k, grid)); +} + +/** "meander": edge midpoints (curved by the smooth path); centres below 3 hexes. */ +export function meanderPoints(hexes: readonly HexKey[], grid: LatticeGrid): Pt[] { + const c = throughPoints(hexes, grid); + if (c.length < 3) return c; + const pts: Pt[] = []; + for (let i = 0; i < c.length - 1; i++) pts.push(mid(c[i], c[i + 1])); + return pts; +} + +/** Angle of vertex 0: flat-top 0°, pointy-top 30°. Vertices go clockwise (y down). */ +const vStartOf = (isFlat: boolean) => (isFlat ? 0 : Math.PI / 6); + +function hexVertices(c: Pt, isFlat: boolean, r: number): Pt[] { + const v0 = vStartOf(isFlat); + return Array.from({ length: 6 }, (_, i) => ({ + cx: c.cx + r * Math.cos(v0 + (i * Math.PI) / 3), + cy: c.cy + r * Math.sin(v0 + (i * Math.PI) / 3), + })); +} + +/** Shorter arc of vertex indices on the 6-cycle, both ends included (cw on a tie). */ +function shortArc(from: number, to: number): number[] { + if (from === to) return [from]; + const cw = (to - from + 6) % 6; + const ccw = (from - to + 6) % 6; + const out: number[] = []; + if (cw <= ccw) for (let k = 0; k <= cw; k++) out.push((from + k) % 6); + else for (let k = 0; k <= ccw; k++) out.push((from - k + 6) % 6); + return out; +} + +/** + * "edge": along the hex outlines, from centre to centre. `centers` are + * consecutive neighbours; `r` is the CELL radius (on the lattice 1, so the + * outline runs down the middle of the gap between hexes and two + * neighbours' vertices coincide). Ties (equal turn cost, equal distance) + * compare within GEOM_EPS and the lower index wins, so the same chain gives + * the same outline at every scale. + */ +export function edgePointsFromCenters(centers: readonly Pt[], isFlat: boolean, r: number): Pt[] { + if (centers.length < 2) return [...centers]; + const n = centers.length; + const TAU = 2 * Math.PI; + const v0 = vStartOf(isFlat); + const eps = GEOM_EPS * Math.max(1, r * r); + + // Edge of centers[i]'s hex facing centers[i+1] (edge i spans vertex i → i+1). + const snapEdge = (theta: number): number => { + let best = 0; + let bestD = Infinity; + for (let i = 0; i < 6; i++) { + const m = v0 + (i + 0.5) * (Math.PI / 3); + let d = (((theta - m) % TAU) + TAU) % TAU; + if (d > Math.PI) d = TAU - d; + if (d < bestD - GEOM_EPS) { + bestD = d; + best = i; + } + } + return best; + }; + const edgeIdx = centers.slice(0, -1).map((A, i) => { + const B = centers[i + 1]; + return snapEdge(Math.atan2(B.cy - A.cy, B.cx - A.cx)); + }); + + // Which of the two shared vertices each edge crossing uses: least turn + // (look-ahead one edge); the last edge takes the vertex nearer the line so far. + const choice: number[] = new Array(n - 1).fill(0); + let prev: Pt = centers[0]; + for (let i = 0; i < n - 1; i++) { + const vA = hexVertices(centers[i], isFlat, r); + const Va = vA[edgeIdx[i]]; + const Vb = vA[(edgeIdx[i] + 1) % 6]; + if (i < n - 2) { + const vB = hexVertices(centers[i + 1], isFlat, r); + const VaN = vB[edgeIdx[i + 1]]; + const VbN = vB[(edgeIdx[i + 1] + 1) % 6]; + const cost = (v: Pt, vn: Pt) => + Math.abs((v.cx - prev.cx) * (vn.cy - v.cy) - (v.cy - prev.cy) * (vn.cx - v.cx)); + let bestCost = Infinity; + let bestC = 0; + for (const [v, ci] of [[Va, 0], [Vb, 1]] as [Pt, number][]) { + for (const vn of [VaN, VbN]) { + const co = cost(v, vn); + if (co < bestCost - eps) { + bestCost = co; + bestC = ci; + } + } + } + choice[i] = bestC; + prev = vA[(edgeIdx[i] + bestC) % 6]; + } else { + const dA = (Va.cx - prev.cx) ** 2 + (Va.cy - prev.cy) ** 2; + const dB = (Vb.cx - prev.cx) ** 2 + (Vb.cy - prev.cy) ** 2; + choice[i] = dA <= dB + eps ? 0 : 1; + } + } + + // Each inner hex: the shorter arc of its outline from the entry vertex to + // the exit vertex. The entry vertex on hex k matching vertex + // (edgeIdx + choice) of hex k-1 is (edgeIdx + 4 - choice) % 6. + const result: Pt[] = [centers[0]]; + for (let k = 0; k < n; k++) { + const verts = hexVertices(centers[k], isFlat, r); + if (k === 0) { + result.push(verts[(edgeIdx[0] + choice[0]) % 6]); + } else if (k === n - 1) { + result.push(verts[(edgeIdx[n - 2] + 4 - choice[n - 2]) % 6]); + result.push(centers[k]); + } else { + const entry = (edgeIdx[k - 1] + 4 - choice[k - 1]) % 6; + const exit = (edgeIdx[k] + choice[k]) % 6; + const arc = shortArc(entry, exit); + for (let j = 1; j < arc.length; j++) result.push(verts[arc[j]]); + } + } + return result; +} + +/** "edge" on the lattice. */ +export function edgePoints(hexes: readonly HexKey[], grid: LatticeGrid): Pt[] { + return edgePointsFromCenters(throughPoints(hexes, grid), grid.orientation === "flat", 1); +} + +export type PathRouting = PathType["routing"]; + +/** One chain's polyline in a drawing style (lattice units). */ +export function chainPoints(hexes: readonly HexKey[], routing: PathRouting, grid: LatticeGrid): Pt[] { + if (routing === "meander") return meanderPoints(hexes, grid); + if (routing === "edge") return edgePoints(hexes, grid); + return throughPoints(hexes, grid); +} + +/** Smooth (curved through the points) or sharp, per drawing style. */ +export function isSmooth(routing: PathRouting): boolean { + return routing !== "edge"; +} + +// ── Forks and joins ────────────────────────────────────────────────────────── + +const near = (a: Pt, b: Pt, tol = 1e-6) => Math.abs(a.cx - b.cx) <= tol && Math.abs(a.cy - b.cy) <= tol; + +/** + * Where a branch that starts on another branch of its path (a fork) begins, + * so it leaves the parent's line instead of floating beside it: + * - through: the fork hex's centre (already shared, nothing to do); + * - meander: the midpoint between the fork hex and the parent's neighbour + * (in the parent chain) whose direction is closest to the fork's first + * step: a Y-shaped split; + * - edge: the vertex of the fork hex on the parent's outline nearest the + * fork's own exit vertex, then round the fork hex's outline to it. + * + * Returns the fork's points with its start adjusted (a new array), or the + * points unchanged. `parentIdx` is the fork hex's index in `parentHexes`. + */ +export function joinForkStart( + forkPts: readonly Pt[], + forkHexes: readonly HexKey[], + parentHexes: readonly HexKey[], + parentIdx: number, + parentPts: readonly Pt[], + routing: PathRouting, + grid: LatticeGrid, +): Pt[] { + if (forkHexes.length < 2 || forkPts.length < 1) return [...forkPts]; + if (routing === "meander") { + if (parentHexes.length < 3) return [...forkPts]; // parent drawn through centres + const c0 = latticeCenter(forkHexes[0], grid); + const c1 = latticeCenter(forkHexes[1], grid); + const sx = c1.cx - c0.cx; + const sy = c1.cy - c0.cy; + let best: Pt | null = null; + let bestDot = -Infinity; + for (const j of [parentIdx - 1, parentIdx + 1]) { + if (j < 0 || j >= parentHexes.length) continue; + const c = latticeCenter(parentHexes[j], grid); + const dx = c.cx - c0.cx; + const dy = c.cy - c0.cy; + const len = Math.hypot(dx, dy) || 1; + const dot = (dx * sx + dy * sy) / len; + if (dot > bestDot + GEOM_EPS) { + bestDot = dot; + best = c; + } + } + return best ? [mid(c0, best), ...forkPts] : [...forkPts]; + } + if (routing === "edge") { + const isFlat = grid.orientation === "flat"; + const c0 = latticeCenter(forkHexes[0], grid); + if (parentPts.some((p) => near(p, c0))) return [...forkPts]; // parent ends here + if (forkPts.length < 2) return [...forkPts]; + const exit = forkPts[1]; + let best: Pt | null = null; + let bestD = Infinity; + for (const p of parentPts) { + if (Math.abs(Math.hypot(p.cx - c0.cx, p.cy - c0.cy) - 1) > 1e-6) continue; + const d = (p.cx - exit.cx) ** 2 + (p.cy - exit.cy) ** 2; + if (d < bestD - GEOM_EPS) { + bestD = d; + best = p; + } + } + if (!best) return [...forkPts]; + const v0 = vStartOf(isFlat); + const idxOf = (p: Pt) => { + const a = Math.atan2(p.cy - c0.cy, p.cx - c0.cx) - v0; + return ((Math.round(a / (Math.PI / 3)) % 6) + 6) % 6; + }; + const verts = hexVertices(c0, isFlat, 1); + const arc = shortArc(idxOf(best), idxOf(exit)); + return [...arc.slice(0, -1).map((i) => verts[i]), ...forkPts.slice(1)]; + } + return [...forkPts]; +} + +// ── Strokes ────────────────────────────────────────────────────────────────── + +/** Stroke dash patterns in px at the default zoom (as the map always drew them). */ +const DASH_PX: Record = { dashed: [8, 4], dotted: [2, 4] }; + +/** The end dot of the path being drawn: radius and outline, px at the default zoom. */ +export const END_DOT_PX = { r: 5, stroke: 1.5 }; + +export interface PathStroke { + /** MapPath.name and branch index (data-path / data-branch on screen). */ + path: string; + branch: number; + typeName: string; + /** Lattice units; lane offset applied. */ + pts: Pt[]; + smooth: boolean; + color: string; + /** Stroke width, lattice units. */ + width: number; + /** Dash pattern, lattice units ([] = solid). */ + dash: number[]; +} + +export interface StrokeOptions { + /** For a type not in the palette (drawn plain grey under its own name). */ + unknownType: PathType; + /** + * The hex just across the seam (in this map's frame) where a branch end + * meets a neighbour's path of the same type, if any: that end is drawn on + * to the shared edge (round 6 U8). Not for the edge style. + */ + seamEnd?: (typeName: string, hex: HexKey) => HexKey | undefined; + /** Multiplies lane gaps (an export drawn bolder keeps lanes apart). Default 1. */ + laneScale?: number; +} + +/** + * Resolved branches → strokes, in draw order: the palette's type order, + * then types not in the palette (first seen first); within a type, the + * resolver's order. Lanes (computeLaneOffsets) separate different types + * sharing a route; same-type branches share a lane and merge. + */ +export function buildPathStrokes( + resolved: readonly ResolvedBranch[], + types: readonly PathType[], + grid: LatticeGrid, + opts: StrokeOptions, +): PathStroke[] { + const typeByName = new Map(); + for (const t of types) if (!typeByName.has(t.name)) typeByName.set(t.name, t); + const order: { rb: ResolvedBranch; pt: PathType }[] = []; + for (const t of typeByName.values()) { + for (const rb of resolved) if (rb.typeName === t.name) order.push({ rb, pt: t }); + } + const unknown: string[] = []; + for (const rb of resolved) if (!typeByName.has(rb.typeName) && !unknown.includes(rb.typeName)) unknown.push(rb.typeName); + for (const name of unknown) { + for (const rb of resolved) if (rb.typeName === name) order.push({ rb, pt: { ...opts.unknownType, name } }); + } + + const lanes = computeLaneOffsets(order.map(({ rb, pt }) => ({ hexes: rb.hexes, width: pt.width, typeName: pt.name }))); + const laneScale = opts.laneScale ?? 1; + + // Each branch's own polyline first (forks need their parent's). + const own = order.map(({ rb, pt }) => chainPoints(rb.hexes, pt.routing, grid)); + const indexOf = new Map(); + order.forEach(({ rb }, i) => indexOf.set(`${rb.path}\u0000${rb.branch}`, i)); + const parentOf = (rb: ResolvedBranch, branch: number) => indexOf.get(`${rb.path}\u0000${branch}`); + + const out: PathStroke[] = []; + order.forEach(({ rb, pt }, i) => { + let pts = own[i]; + if (rb.forkFrom) { + const p = parentOf(rb, rb.forkFrom.branch); + if (p !== undefined) pts = joinForkStart(pts, rb.hexes, order[p].rb.hexes, rb.forkFrom.hexIdx, own[p], pt.routing, grid); + } + if (rb.joinTo) { + const p = parentOf(rb, rb.joinTo.branch); + if (p !== undefined) { + pts = joinForkStart([...pts].reverse(), [...rb.hexes].reverse(), order[p].rb.hexes, rb.joinTo.hexIdx, own[p], pt.routing, grid).reverse(); + } + } + if (pt.routing !== "edge" && opts.seamEnd && pts.length >= 1) { + const head = rb.forkFrom ? undefined : opts.seamEnd(pt.name, rb.hexes[0]); + const last = rb.hexes[rb.hexes.length - 1]; + const tail = rb.hexes.length > 1 && !rb.joinTo ? opts.seamEnd(pt.name, last) : undefined; + if (head) pts = [mid(latticeCenter(rb.hexes[0], grid), latticeCenter(head, grid)), ...pts]; + if (tail) pts = [...pts, mid(latticeCenter(last, grid), latticeCenter(tail, grid))]; + } + if (pts.length < 2) return; + pts = offsetPolyline(pts, pxToLattice(lanes[i]) * laneScale); + out.push({ + path: rb.path, + branch: rb.branch, + typeName: pt.name, + pts, + smooth: isSmooth(pt.routing), + color: pt.color, + width: pxToLattice(pt.width), + dash: (DASH_PX[pt.lineStyle] ?? []).map(pxToLattice), + }); + }); + return out; +} + +// ── Affine (lattice → screen / export) ─────────────────────────────────────── + +/** An axis-aligned affine: X = tx + x·sx, Y = ty + y·sy. */ +export interface LatticeAffine { + sx: number; + sy: number; + tx: number; + ty: number; +} + +export function applyAffine(pts: readonly Pt[], a: LatticeAffine): Pt[] { + return pts.map((p) => ({ cx: a.tx + p.cx * a.sx, cy: a.ty + p.cy * a.sy })); +} + +/** + * The affine mapping lattice centres onto measured centres: the origin hex + * `o`, its right neighbour (x+1, same y) and the hex below (same x, y+1). + * Either neighbour may be missing (a one-column or one-row grid): its scale + * is then the other one's, else `fallback`. + */ +export function calibrateAffine( + origin: { key: HexKey; at: { x: number; y: number } }, + right: { key: HexKey; at: { x: number; y: number } } | null, + below: { key: HexKey; at: { x: number; y: number } } | null, + grid: LatticeGrid, + fallback: number, +): LatticeAffine { + const lo = latticeCenter(origin.key, grid); + let sx = 0; + let sy = 0; + if (right) { + const lr = latticeCenter(right.key, grid); + if (Math.abs(lr.cx - lo.cx) > GEOM_EPS) sx = (right.at.x - origin.at.x) / (lr.cx - lo.cx); + } + if (below) { + const lb = latticeCenter(below.key, grid); + if (Math.abs(lb.cy - lo.cy) > GEOM_EPS) sy = (below.at.y - origin.at.y) / (lb.cy - lo.cy); + } + if (!sx) sx = sy || fallback; + if (!sy) sy = sx; + return { sx, sy, tx: origin.at.x - lo.cx * sx, ty: origin.at.y - lo.cy * sy }; +} + +/** Round for SVG output: fixed decimals keep `d` stable and short. */ +export function fmt(n: number): string { + const r = Math.round(n * 1e4) / 1e4; + return Object.is(r, -0) ? "0" : String(r); +} diff --git a/src/paths/typeRefs.ts b/src/paths/typeRefs.ts new file mode 100644 index 00000000..af773aaf --- /dev/null +++ b/src/paths/typeRefs.ts @@ -0,0 +1,49 @@ +/** + * A path type's references across a map's paths (PathTypeEditorModal: + * rename and delete a type). Type names are references into the palette, + * compared exactly; nothing here interprets them. Pure. + */ + +import type { MapPath, PathChain } from "../types"; + +/** How many paths use type `name`. */ +export function countPathsOfType(paths: readonly MapPath[], name: string): number { + return paths.filter((p) => p.typeName === name).length; +} + +/** Point every path of type `from` at `to` (in place). Returns how many changed. */ +export function renamePathTypeInPaths(paths: MapPath[], from: string, to: string): number { + let n = 0; + for (const p of paths) { + if (p.typeName === from) { + p.typeName = to; + n++; + } + } + return n; +} + +/** The paths without those of type `name` (a deleted type takes its paths with it). */ +export function removePathTypeFromPaths(paths: readonly MapPath[], name: string): MapPath[] { + return paths.filter((p) => p.typeName !== name); +} + +/** + * The same two edits on legacy chains, for as long as maps store + * `pathChains` (the Phase-3 adapter in mapPaths.ts). Phase 3 switches the + * modal to the MapPath functions above and deletes these. + */ +export function renamePathTypeInChains(chains: PathChain[], from: string, to: string): number { + let n = 0; + for (const c of chains) { + if (c.typeName === from) { + c.typeName = to; + n++; + } + } + return n; +} + +export function removePathTypeFromChains(chains: readonly PathChain[], name: string): PathChain[] { + return chains.filter((c) => c.typeName !== name); +} diff --git a/src/setupPlaceholder.ts b/src/setupPlaceholder.ts index 9dfac950..9e9ce21d 100644 --- a/src/setupPlaceholder.ts +++ b/src/setupPlaceholder.ts @@ -6,6 +6,9 @@ * mystery entry in the map list, so the wizard removes it. */ +import type { PathChain } from "./types"; +import { storedMapPaths } from "./paths/mapPaths"; + export const PLACEHOLDER_MAP_NAME = "default"; /** @@ -16,7 +19,7 @@ export const PLACEHOLDER_MAP_NAME = "default"; export function isUnusedPlaceholderMap( map: { name: string; - pathChains?: unknown[]; + pathChains?: PathChain[]; parent?: unknown; world?: unknown; backgroundImage?: unknown; @@ -32,6 +35,6 @@ export function isUnusedPlaceholderMap( ): boolean { if (map.name !== PLACEHOLDER_MAP_NAME) return false; if (usage.hexCount > 0 || usage.referenced) return false; - if ((map.pathChains?.length ?? 0) > 0 || map.parent || map.world || map.backgroundImage) return false; + if (storedMapPaths(map).length > 0 || map.parent || map.world || map.backgroundImage) return false; return usage.folderEntries.every((n) => n === `_${PLACEHOLDER_MAP_NAME}.md`); } diff --git a/src/worldgen/regionContext.ts b/src/worldgen/regionContext.ts index a6349c53..44747f70 100644 --- a/src/worldgen/regionContext.ts +++ b/src/worldgen/regionContext.ts @@ -36,7 +36,7 @@ export function buildRegionContext(plugin: HexmakerPlugin, region: NewRegion): G const map = plugin.getMap(cell.map); if (!map) continue; const there = `${cell.x}_${cell.y}`; - for (const chain of map.pathChains ?? []) { + for (const chain of plugin.paths.resolvedPathChains(cell.map)) { if (!chain.hexes.includes(there)) continue; const [sx, sy] = key.split("_").map(Number); const inside = hexNeighbors(sx, sy, orientation, region.stagger).find(([nx, ny]) => inGrid(nx, ny)); diff --git a/src/worldgen/submapContext.ts b/src/worldgen/submapContext.ts index c01d06b9..aaecf363 100644 --- a/src/worldgen/submapContext.ts +++ b/src/worldgen/submapContext.ts @@ -44,7 +44,7 @@ export function buildSubmapContext( // submap can carry the road / river across instead of losing it. const key = `${x}_${y}`; const routingOf = new Map(plugin.getPathTypes(map.paletteName).map((p) => [p.name, p.routing])); - for (const chain of map.pathChains ?? []) { + for (const chain of plugin.paths.resolvedPathChains(mapName)) { chain.hexes.forEach((h, i) => { if (h !== key) return; const from = sideTo(chain.hexes[i - 1]); diff --git a/styles.css b/styles.css index 0f35d061..32aa9e6b 100644 --- a/styles.css +++ b/styles.css @@ -356,8 +356,20 @@ cursor: grabbing; } -/* SVG overlay for paths, coordinate labels and elevated icons */ +/* SVG overlay for paths: one user unit = 1em of the grid (lattice + polylines placed in em), so zoom bakes resize it without a rebuild. */ .duckmage-path-svg { + position: absolute; + top: 0; + left: 0; + overflow: visible; + pointer-events: none; + z-index: 5; +} + +/* Elevated override icons and GM icons, over the paths (px, rebuilt on + zoom bakes). Same z-index as the paths; later in the DOM, so on top. */ +.duckmage-path-icons-svg { position: absolute; top: 0; left: 0; diff --git a/tests/ghostPaths.test.ts b/tests/ghostPaths.test.ts index 446289de..44fc6c1a 100644 --- a/tests/ghostPaths.test.ts +++ b/tests/ghostPaths.test.ts @@ -78,11 +78,13 @@ describe("ghostRunPoints", () => { describe("HexMapView draws them in the strip", () => { const view = readFileSync(path.join(process.cwd(), "src", "hex-map", "HexMapView.ts"), "utf8").replace(/\r\n/g, "\n"); - it("from the neighbours' own path chains, read-only, on the strip layer", () => { + // Path anchors phase 4: the neighbours' chains are their RESOLVED paths + // (routed with each neighbour's own terrain and palette by the paths service). + it("from the neighbours' resolved path chains, read-only, on the strip layer", () => { const m = /private renderNeighbourShadow[\s\S]*?\n {2}\}\n/.exec(view); expect(m).not.toBeNull(); const body = m![0]; - expect(body).toMatch(/ghostPathRuns\(shadow, \(m\) => this\.plugin\.getMap\(m\)\?\.pathChains\)/); + expect(body).toMatch(/ghostPathRuns\(shadow, \(m\) => this\.plugin\.paths\.resolvedPathChains\(m\)\)/); expect(body).toMatch(/svg\.classList\.add\("duckmage-region-shadow-paths"\)/); expect(body).toMatch(/layer\.appendChild\(svg\)/); // Reads (place/offsetWidth) before the first write (createDiv). diff --git a/tests/helpers/simVault.ts b/tests/helpers/simVault.ts index 7c1a1388..8283a7bb 100644 --- a/tests/helpers/simVault.ts +++ b/tests/helpers/simVault.ts @@ -273,7 +273,8 @@ export class MockApp { // ─── Plugin ──────────────────────────────────────────────────────────────── -import { DEFAULT_SETTINGS } from "../../src/constants"; +import { DEFAULT_PATH_TYPES, DEFAULT_SETTINGS } from "../../src/constants"; +import { PathsService } from "../../src/paths/PathsService"; import type { HexmakerPluginSettings } from "../../src/types"; export class MockHexmakerPlugin { @@ -282,6 +283,16 @@ export class MockHexmakerPlugin { manifest = { dir: ".obsidian/plugins/duckmage-plugin", id: "duckmage" }; // Field that real plugin uses for icon URL resolution. vaultIconsSet = new Set(); + /** The paths service, as the real plugin has it (always ready; terrain from hex frontmatter is not consulted). */ + paths = new PathsService({ + isMapReady: () => true, + getMap: (name) => this.getMap(name), + orientation: () => this.settings.hexOrientation, + stagger: (map) => map.staggerOffset ?? this.settings.staggerOffset ?? "odd", + pathTypes: (map) => this.getMapPathTypes(map), + palette: (map) => this.getMapPalette(map), + hexData: () => new Map(), + }); constructor(outDir: string) { this.app = new MockApp(outDir); @@ -299,6 +310,11 @@ export class MockHexmakerPlugin { return this.settings.maps.find((m) => m.name === mapName); } + getMapPathTypes(mapName: string) { + const map = this.getMap(mapName); + return this.settings.terrainPalettes.find((p) => p.name === map?.paletteName)?.pathTypes ?? DEFAULT_PATH_TYPES; + } + getMapPalette(mapName: string) { const map = this.getMap(mapName); return ( diff --git a/tests/pathGeometry.test.ts b/tests/pathGeometry.test.ts new file mode 100644 index 00000000..a53e9ab0 --- /dev/null +++ b/tests/pathGeometry.test.ts @@ -0,0 +1,238 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import type { MapPath, PathType } from "../src/types"; +import { hexCenter, hexNeighbors } from "../src/hex-map/hexGeometry"; +import { + applyAffine, + buildPathStrokes, + calibrateAffine, + chainPoints, + edgePointsFromCenters, + latticeCenter, + pxToLattice, + type LatticeGrid, + type Pt, +} from "../src/paths/pathGeometry"; +import { contextRouter } from "../src/paths/routeCache"; +import { resolvePath } from "../src/paths/resolve"; +import type { RouteContext } from "../src/paths/router"; +import { UNKNOWN_PATH_TYPE } from "../src/constants"; + +type O = "flat" | "pointy"; +type S = "odd" | "even"; +const GRIDS: LatticeGrid[] = (["flat", "pointy"] as O[]).flatMap((orientation) => + (["odd", "even"] as S[]).map((stagger) => ({ orientation, stagger })), +); +const ROUTINGS = ["through", "meander", "edge"] as const; + +function rng(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** A random walk of neighbouring hexes (may cross itself, like hand-drawn rivers). */ +function walk(grid: LatticeGrid, seed: number, len: number): string[] { + const r = rng(seed); + let x = Math.floor(r() * 10) - 3; + let y = Math.floor(r() * 10) - 3; + const out = [`${x}_${y}`]; + for (let i = 1; i < len; i++) { + const nb = hexNeighbors(x, y, grid.orientation, grid.stagger); + [x, y] = nb[Math.floor(r() * 6)]; + out.push(`${x}_${y}`); + } + return out; +} + +const close = (a: Pt[], b: Pt[], tol: number) => { + expect(a.length).toBe(b.length); + a.forEach((p, i) => { + expect(Math.abs(p.cx - b[i].cx)).toBeLessThan(tol); + expect(Math.abs(p.cy - b[i].cy)).toBeLessThan(tol); + }); +}; + +const type = (name: string, routing: PathType["routing"], width = 4): PathType => + ({ name, color: "#000", width, lineStyle: "solid", routing }); + +describe("pathGeometry: lattice units", () => { + it("lattice centres are hexGeometry centres at radius 1, in absolute coordinates", () => { + for (const g of GRIDS) { + for (const [x, y] of [[0, 0], [3, 4], [-1, -4], [7, 2]]) { + const c = hexCenter(x, y, g.orientation, 1, g.stagger); + expect(latticeCenter(`${x}_${y}`, g)).toEqual(c); + // The PNG's hexes at radius R sit exactly on lattice × R. + const big = hexCenter(x, y, g.orientation, 50, g.stagger); + expect(Math.abs(big.cx - c.cx * 50)).toBeLessThan(1e-9); + expect(Math.abs(big.cy - c.cy * 50)).toBeLessThan(1e-9); + } + } + }); + + it("gives the identical polyline at R=1 and R=50 (and odd scales) after scaling, every style", () => { + for (const g of GRIDS) { + for (let seed = 1; seed <= 25; seed++) { + const hexes = walk(g, seed, 2 + (seed % 12)); + for (const routing of ROUTINGS) { + const lattice = chainPoints(hexes, routing, g); + for (const R of [50, 37.3, 0.013]) { + // Built directly at radius R (as a pixel renderer would) … + const centres = hexes.map((k) => { + const [x, y] = k.split("_").map(Number); + return hexCenter(x, y, g.orientation, R, g.stagger); + }); + const atR = routing === "edge" + ? edgePointsFromCenters(centres, g.orientation === "flat", R) + : routing === "meander" && centres.length >= 3 + ? centres.slice(0, -1).map((c, i) => ({ cx: (c.cx + centres[i + 1].cx) / 2, cy: (c.cy + centres[i + 1].cy) / 2 })) + : centres; + // … equals the lattice polyline scaled by R: no tie flips with scale. + close(atR, applyAffine(lattice, { sx: R, sy: R, tx: 0, ty: 0 }), 1e-6 * Math.max(1, R)); + } + } + } + } + }); + + it("breaks edge ties deterministically (exact ties on straight runs take the first vertex)", () => { + for (const g of GRIDS) { + // A straight run: every turn-cost comparison is an exact tie. + const hexes = g.orientation === "flat" ? ["2_0", "2_1", "2_2", "2_3", "2_4"] : ["0_2", "1_2", "2_2", "3_2", "4_2"]; + const a = chainPoints(hexes, "edge", g); + const b = chainPoints([...hexes], "edge", g); + expect(a).toEqual(b); + // The outline keeps to one side of the centres (no zig-zag from flipped ties). + const axis = g.orientation === "flat" ? "cx" : "cy"; + const c0 = latticeCenter(hexes[0], g)[axis]; + const sides = new Set(a.slice(1, -1).map((p) => Math.sign(Math.round((p[axis] - c0) * 1e6)))); + sides.delete(0); + expect(sides.size).toBe(1); + } + }); + + it("edge routing runs on the cell outline: neighbours share vertices exactly", () => { + for (const g of GRIDS) { + const pts = chainPoints(walk(g, 7, 9), "edge", g); + for (let i = 1; i < pts.length; i++) { + const step = Math.hypot(pts[i].cx - pts[i - 1].cx, pts[i].cy - pts[i - 1].cy); + // Centre→vertex and vertex→vertex steps are both exactly 1 on the lattice + // (0 where a scribble walks back over its own outline). + expect(Math.min(step, Math.abs(step - 1))).toBeLessThan(1e-9); + } + } + }); +}); + +describe("pathGeometry: forks join their parent", () => { + const ctx = (o: O, s: S): RouteContext => ({ orientation: o, stagger: s, bounds: { minX: 0, minY: 0, maxX: 15, maxY: 15 }, blocked: new Set() }); + for (const g of GRIDS) { + for (const routing of ROUTINGS) { + it(`${g.orientation}/${g.stagger}, ${routing}: the fork's first point is on the parent's polyline`, () => { + // Main line along a row/column, fork from its middle hex going off sideways. + const main = g.orientation === "flat" ? ["2_2", "3_2", "4_2", "5_2", "6_2", "7_2"] : ["2_2", "2_3", "2_4", "2_5", "2_6", "2_7"]; + const fork = main[3]; + const [fx, fy] = fork.split("_").map(Number); + const off = g.orientation === "flat" ? `${fx}_${fy + 4}` : `${fx + 4}_${fy}`; + const path: MapPath = { name: "Road", typeName: "T", branches: [{ anchors: main }, { anchors: [fork, off] }] }; + const resolved = resolvePath(path, contextRouter(ctx(g.orientation, g.stagger))); + expect(resolved[1].forkFrom).toEqual({ branch: 0, hexIdx: 3 }); + const strokes = buildPathStrokes(resolved, [type("T", routing)], g, { unknownType: UNKNOWN_PATH_TYPE }); + expect(strokes).toHaveLength(2); + const [parent, child] = strokes; + const start = child.pts[0]; + const onParent = parent.pts.some((p) => Math.abs(p.cx - start.cx) < 1e-9 && Math.abs(p.cy - start.cy) < 1e-9); + expect(onParent).toBe(true); + // And it starts at the fork hex: within one cell radius of its centre. + const c = latticeCenter(fork, g); + expect(Math.hypot(start.cx - c.cx, start.cy - c.cy)).toBeLessThanOrEqual(1 + 1e-9); + }); + } + } + + it("a join (last anchor on another branch) ends on the parent's polyline too", () => { + const g: LatticeGrid = { orientation: "flat", stagger: "odd" }; + const main = ["2_2", "3_2", "4_2", "5_2", "6_2", "7_2"]; + const path: MapPath = { name: "Loop", typeName: "T", branches: [{ anchors: main }, { anchors: ["4_6", "5_2"] }] }; + const resolved = resolvePath(path, contextRouter({ orientation: "flat", stagger: "odd", bounds: { minX: 0, minY: 0, maxX: 15, maxY: 15 }, blocked: new Set() })); + expect(resolved[1].joinTo?.branch).toBe(0); + for (const routing of ["meander", "edge"] as const) { + const [parent, child] = buildPathStrokes(resolved, [type("T", routing)], g, { unknownType: UNKNOWN_PATH_TYPE }); + const end = child.pts[child.pts.length - 1]; + expect(parent.pts.some((p) => Math.abs(p.cx - end.cx) < 1e-9 && Math.abs(p.cy - end.cy) < 1e-9)).toBe(true); + } + }); +}); + +describe("pathGeometry: strokes", () => { + const g: LatticeGrid = { orientation: "flat", stagger: "odd" }; + const rb = (path: string, typeName: string, hexes: string[]) => ({ path, typeName, branch: 0, hexes, anchorIdx: [0, hexes.length - 1], fallbackSegments: [] }); + + it("widths, dashes and lane gaps are in lattice units (px / 35.2)", () => { + const road: PathType = { name: "Road", color: "#a00", width: 4, lineStyle: "dashed", routing: "through" }; + const river: PathType = { name: "River", color: "#00a", width: 6, lineStyle: "solid", routing: "through" }; + const shared = ["1_1", "2_1", "3_1"]; + const [r, v] = buildPathStrokes([rb("Road", "Road", shared), rb("River", "River", shared)], [road, river], g, { unknownType: UNKNOWN_PATH_TYPE }); + expect(r.width).toBeCloseTo(4 / 35.2, 12); + expect(r.dash).toEqual([8 / 35.2, 4 / 35.2]); + expect(v.dash).toEqual([]); + // Two types on one route: lanes either side, gap (widest + 2) px. + const c = latticeCenter("2_1", g); + const offR = r.pts[1].cy - c.cy; + const offV = v.pts[1].cy - c.cy; + expect(offR - offV).toBeCloseTo(-pxToLattice(8), 9); + }); + + it("draw order is the palette's type order, then unknown types (grey, under their own name)", () => { + const a = type("A", "through"); + const b = type("B", "through"); + const strokes = buildPathStrokes( + [rb("x", "Zed", ["0_0", "1_0"]), rb("y", "B", ["0_2", "1_2"]), rb("z", "A", ["0_4", "1_4"])], + [a, b], g, { unknownType: UNKNOWN_PATH_TYPE }, + ); + expect(strokes.map((s) => s.typeName)).toEqual(["A", "B", "Zed"]); + expect(strokes[2].color).toBe(UNKNOWN_PATH_TYPE.color); + }); + + it("one-hex branches draw nothing; seam ends reach the shared edge", () => { + const t = type("T", "through"); + expect(buildPathStrokes([rb("p", "T", ["3_3"])], [t], g, { unknownType: UNKNOWN_PATH_TYPE })).toEqual([]); + const [s] = buildPathStrokes([rb("p", "T", ["0_1", "1_1"])], [t], g, { + unknownType: UNKNOWN_PATH_TYPE, + seamEnd: (_t, hex) => (hex === "0_1" ? "-1_1" : undefined), + }); + const a = latticeCenter("0_1", g); + const b = latticeCenter("-1_1", g); + expect(s.pts[0]).toEqual({ cx: (a.cx + b.cx) / 2, cy: (a.cy + b.cy) / 2 }); + }); +}); + +describe("calibrateAffine", () => { + it("maps lattice centres onto measured centres (gap and grid transforms absorbed)", () => { + for (const g of GRIDS) { + // A fake screen: cells of radius 2.4em plus 0.3em of gap per axis, offset. + const sx = 2.5, sy = 2.3, tx = 4, ty = -1; + const at = (k: string) => { const c = latticeCenter(k, g); return { x: tx + c.cx * sx, y: ty + c.cy * sy }; }; + const a = calibrateAffine({ key: "3_4", at: at("3_4") }, { key: "12_4", at: at("12_4") }, { key: "3_15", at: at("3_15") }, g, 1); + expect(a.sx).toBeCloseTo(sx, 9); + expect(a.sy).toBeCloseTo(sy, 9); + for (const k of ["0_0", "7_9", "-2_3"]) { + const [p] = applyAffine([latticeCenter(k, g)], a); + expect(p.cx).toBeCloseTo(at(k).x, 9); + expect(p.cy).toBeCloseTo(at(k).y, 9); + } + } + }); + + it("a one-row or one-column grid falls back to the other axis, then the hex radius", () => { + const g: LatticeGrid = { orientation: "flat", stagger: "odd" }; + const a = calibrateAffine({ key: "0_0", at: { x: 1, y: 1 } }, null, null, g, 2.2); + expect(a.sx).toBe(2.2); + expect(a.sy).toBe(2.2); + }); +}); diff --git a/tests/pathRender.test.ts b/tests/pathRender.test.ts new file mode 100644 index 00000000..8fc5b209 --- /dev/null +++ b/tests/pathRender.test.ts @@ -0,0 +1,203 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import type { MapData, PathChain, PathType, TerrainColor } from "../src/types"; +import { PathsService, pathTypeStyle, styleForTypes, type PathsHost } from "../src/paths/PathsService"; +import { storedMapPaths } from "../src/paths/mapPaths"; +import { applyAffine, latticeCenter } from "../src/paths/pathGeometry"; +import { hexCenter } from "../src/hex-map/hexGeometry"; +import { countPathsOfType, removePathTypeFromChains, removePathTypeFromPaths, renamePathTypeInChains, renamePathTypeInPaths } from "../src/paths/typeRefs"; +import { legacyChainsToPaths } from "../src/paths/legacy"; + +const ROAD: PathType = { name: "Road", color: "#a33", width: 4, lineStyle: "solid", routing: "through", avoidImpassable: true }; +const TRAIL: PathType = { name: "Trail", color: "#555", width: 2, lineStyle: "dashed", routing: "meander", avoidImpassable: true }; +const WATER: TerrainColor = { name: "lake", color: "#00f", impassable: true }; +const GRASS: TerrainColor = { name: "grass", color: "#0f0", impassable: false }; + +/** + * A sim vault for the paths service: a map whose terrain and palette load + * separately (as MapStore and PaletteStore do at startup), with a lake + * across the straight line of a road whose two anchors are far apart. + */ +function simVault(chains: PathChain[], over: Partial = {}) { + const map = { name: "coast", paletteName: "P", gridSize: { cols: 9, rows: 7 }, gridOffset: { x: 0, y: 0 }, pathChains: chains, ...over } as MapData; + const state = { + terrainLoaded: false, + paletteLoaded: false, + // Before the palette note is read, the palette in memory has no flags. + palette: [{ name: "lake", color: "#00f" }, GRASS] as TerrainColor[], + hexes: new Map(), + types: [ROAD, TRAIL], + }; + const host: PathsHost = { + isMapReady: () => state.terrainLoaded && state.paletteLoaded, + getMap: (n) => (n === map.name ? map : undefined), + orientation: () => "flat", + stagger: () => "odd", + pathTypes: () => state.types, + palette: () => state.palette, + hexData: () => state.hexes, + }; + const loadTerrain = () => { + // A wall of lake down column 4, except a gap at the bottom row. + for (let y = 0; y < 6; y++) state.hexes.set(`4_${y}`, { terrain: "lake" }); + state.terrainLoaded = true; + }; + const loadPalette = () => { + state.palette = [WATER, GRASS]; + state.paletteLoaded = true; + }; + return { map, state, host, svc: new PathsService(host), loadTerrain, loadPalette }; +} + +describe("paths service: the readiness gate (late palette load)", () => { + it("draws nothing until terrain AND palette are loaded, then the final route, never an intermediate", () => { + const v = simVault([{ typeName: "Road", hexes: ["1_2", "7_2"] }]); + const seen: string[][] = []; + const look = () => seen.push(v.svc.resolvedPathChains("coast").flatMap((c) => c.hexes)); + + look(); // nothing loaded + v.loadTerrain(); + look(); // terrain in, palette still loading: routing now would cross the lake + expect(v.svc.isReady("coast")).toBe(false); + v.loadPalette(); + look(); // both: the final route + look(); // and it stays put + + expect(seen[0]).toEqual([]); + expect(seen[1]).toEqual([]); + const final = seen[2]; + expect(final[0]).toBe("1_2"); + expect(final[final.length - 1]).toBe("7_2"); + // Around the lake: through the gap at the bottom, never a lake hex. + expect(final.some((k) => /^4_[0-5]$/.test(k))).toBe(false); + expect(final).toContain("4_6"); + expect(seen[3]).toEqual(final); + // Every non-empty answer is the final one. + for (const s of seen) if (s.length) expect(s).toEqual(final); + }); + + it("strokes() and resolved() are empty while not ready", () => { + const v = simVault([{ typeName: "Road", hexes: ["1_2", "2_2"] }]); + v.loadTerrain(); + expect(v.svc.resolved("coast")).toEqual([]); + expect(v.svc.strokes("coast")).toEqual([]); + v.loadPalette(); + expect(v.svc.strokes("coast")).toHaveLength(1); + }); + + it("re-resolves when terrain changes (blocked set), and reuses the result when nothing did", () => { + const v = simVault([{ typeName: "Road", hexes: ["1_2", "7_2"] }]); + v.loadTerrain(); + v.loadPalette(); + const a = v.svc.resolvedPathChains("coast"); + expect(v.svc.resolvedPathChains("coast")).toBe(a); // memoised + v.state.hexes.set("4_6", { terrain: "lake" }); // close the gap + const b = v.svc.resolvedPathChains("coast"); + expect(b).not.toBe(a); + // Walled off: the segment falls back to the straight hex line (drawn, never dropped). + expect(b[0].hexes[0]).toBe("1_2"); + expect(b[0].hexes[b[0].hexes.length - 1]).toBe("7_2"); + }); + + it("a hand-drawn (dense) chain resolves to exactly its hexes, terrain notwithstanding", () => { + const hexes = ["2_1", "3_1", "4_1", "5_1", "6_1"]; // straight through the lake + const v = simVault([{ typeName: "Road", hexes }]); + v.loadTerrain(); + v.loadPalette(); + expect(v.svc.resolvedPathChains("coast")).toEqual([{ typeName: "Road", hexes }]); + }); + + it("the base terrain counts as shown terrain for hexes without their own", () => { + const v = simVault([{ typeName: "Road", hexes: ["1_1", "7_1"] }], { baseTerrain: "lake" }); + v.state.terrainLoaded = true; + for (let x = 0; x < 9; x++) v.state.hexes.set(`${x}_0`, { terrain: "grass" }); // a grass row on top + v.loadPalette(); + const [c] = v.svc.resolvedPathChains("coast"); + expect(c.hexes.length).toBeGreaterThan(2); + expect(c.hexes.slice(1, -1).every((k) => k.endsWith("_0"))).toBe(true); + }); +}); + +describe("paths service: style comes from the explicit type fields, in one place", () => { + it("pathTypeStyle: undefined for a type not in the palette, never guessed from a name", () => { + expect(pathTypeStyle(undefined)).toBeUndefined(); + const f = styleForTypes([ROAD]); + expect(f("Road")).toEqual({ avoid: true, winding: false }); + expect(f("River")).toBeUndefined(); + }); + + it("is the only reader of avoid/winding (the PA5 switch is one line)", () => { + const src = readFileSync(path.join(process.cwd(), "src", "paths", "PathsService.ts"), "utf8"); + expect(src.match(/pathAvoidsImpassable\(|pathMeanders\(/g)?.length).toBe(2); + expect(src).toMatch(/return t && \{ avoid: pathAvoidsImpassable\(t\), winding: pathMeanders\(t\) \};/); + for (const f of ["src/hex-map/HexMapView.ts", "src/export/mapPngRenderer.ts", "src/paths/pathGeometry.ts"]) { + const body = readFileSync(path.join(process.cwd(), f), "utf8"); + // The renderers never route by themselves (the draw tool's own route click aside). + expect(body).not.toMatch(/resolvePaths\(/); + } + }); +}); + +describe("PNG and screen draw the same polylines", () => { + it("both take plugin.paths.strokes(...) (lattice units); only the affine differs", () => { + const view = readFileSync(path.join(process.cwd(), "src", "hex-map", "HexMapView.ts"), "utf8").replace(/\r\n/g, "\n"); + const png = readFileSync(path.join(process.cwd(), "src", "export", "mapPngRenderer.ts"), "utf8").replace(/\r\n/g, "\n"); + const overlay = /private renderPathOverlay[\s\S]*?\n {2}\}\n/.exec(view)![0]; + expect(overlay).toMatch(/this\.plugin\.paths\.strokes\(region\.name, \{\n\s*seamEnd:/); + expect(png).toMatch(/plugin\.paths\.strokes\(map\.name, \{ laneScale: boldPaths \? PNG_PATH_BOLD : 1 \}\)/); + // No layout reads in the overlay's stroke loop: the only reads are the calibration's. + expect(overlay).not.toMatch(/offsetLeft|offsetTop|offsetWidth|getBoundingClientRect/); + }); + + it("for a fixture map (odd grid offset), the screen and PNG polylines are the same lattice polyline", () => { + const chains: PathChain[] = [ + { typeName: "Road", hexes: ["3_2", "4_2", "5_2", "5_3"] }, + { typeName: "Trail", hexes: ["3_2", "4_2", "5_2", "6_2", "7_3"] }, + { typeName: "Road", hexes: ["7_3", "7_4"] }, + ]; + const v = simVault(chains, { gridOffset: { x: 3, y: 1 } }); + v.state.terrainLoaded = true; + v.loadPalette(); + const screen = v.svc.strokes("coast", { seamEnd: () => undefined }); + const pngPlain = v.svc.strokes("coast", { laneScale: 1 }); + expect(pngPlain).toEqual(screen); + // A road and a trail share 3_2–5_2: lanes apart, the same on both. + expect(screen).toHaveLength(3); + // The PNG places hexes at hexCenter(x, y, R) of ABSOLUTE coordinates; + // the polyline × R lands on those centres (through-routed road). + const R = 50; + const road = screen.find((s) => s.typeName === "Road" && s.pts.length === 2)!; + const [p] = applyAffine([road.pts[0]], { sx: R, sy: R, tx: 0, ty: 0 }); + const c = hexCenter(7, 3, "flat", R, "odd"); + expect(p.cx).toBeCloseTo(c.cx, 9); + expect(p.cy).toBeCloseTo(c.cy, 9); + expect(latticeCenter("7_3", { orientation: "flat", stagger: "odd" }).cx * R).toBeCloseTo(c.cx, 9); + // Bolder paths: lanes scale with the strokes; the shape's centreline doesn't move. + const bold = v.svc.strokes("coast", { laneScale: 1.4 }); + expect(bold.find((s) => s.pts.length === 2)!.pts).toEqual(road.pts); + }); +}); + +describe("the Phase-3 adapter and type references", () => { + it("storedMapPaths reads legacy chains as dense-anchor paths (one place, replaced by Phase 3)", () => { + const chains: PathChain[] = [{ typeName: "Road", hexes: ["1_1", "2_1"] }, { typeName: "Road", hexes: ["5_5"] }]; + expect(storedMapPaths({ pathChains: chains })).toEqual(legacyChainsToPaths(chains)); + expect(storedMapPaths({})).toEqual([]); + }); + + it("renames and removes a type across MapPaths and (for now) chains", () => { + const paths = legacyChainsToPaths([{ typeName: "Road", hexes: ["1_1"] }, { typeName: "River", hexes: ["2_2"] }, { typeName: "Road", hexes: ["3_3"] }]); + expect(countPathsOfType(paths, "Road")).toBe(2); + expect(renamePathTypeInPaths(paths, "Road", "Highway")).toBe(2); + expect(paths.map((p) => p.typeName)).toEqual(["Highway", "River", "Highway"]); + // Names are labels: a rename of the type leaves path names alone. + expect(paths.map((p) => p.name)).toEqual(["Road", "River", "Road 2"]); + expect(removePathTypeFromPaths(paths, "Highway").map((p) => p.typeName)).toEqual(["River"]); + + const chains: PathChain[] = [{ typeName: "Road", hexes: ["1_1"] }, { typeName: "River", hexes: ["2_2"] }]; + expect(renamePathTypeInChains(chains, "Road", "Highway")).toBe(1); + expect(removePathTypeFromChains(chains, "River")).toEqual([{ typeName: "Highway", hexes: ["1_1"] }]); + }); +}); diff --git a/tests/worldgenFirstMap.test.ts b/tests/worldgenFirstMap.test.ts index 9598e0fa..25ddea0e 100644 --- a/tests/worldgenFirstMap.test.ts +++ b/tests/worldgenFirstMap.test.ts @@ -407,7 +407,7 @@ describe("isUnusedPlaceholderMap (the shipped 'default' map)", () => { expect(isUnusedPlaceholderMap(map, { ...unused, hexCount: 1 })).toBe(false); expect(isUnusedPlaceholderMap(map, { ...unused, folderEntries: ["_default.md", "3_4.md"] })).toBe(false); expect(isUnusedPlaceholderMap(map, { ...unused, referenced: true })).toBe(false); - expect(isUnusedPlaceholderMap({ ...map, pathChains: [{}] }, unused)).toBe(false); + expect(isUnusedPlaceholderMap({ ...map, pathChains: [{ typeName: "Road", hexes: ["1_1"] }] }, unused)).toBe(false); expect(isUnusedPlaceholderMap({ ...map, world: { id: "w", cx: 0, cy: 0 } }, unused)).toBe(false); }); }); From 2c8a312b72366222457cb0d4b2b012f707d249de Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 18:58:10 -0400 Subject: [PATCH 228/558] fix(overworld): sandbox findings: six neighbour crumbs fold into one Next to list, biome labels sized to the hex, cached-draw timing in the demo script Co-Authored-By: Claude Opus 5.5 --- dev/demo-world.mjs | 10 +++++----- src/hex-map/HexMapView.ts | 33 +++++++++++++++++++++++++-------- src/hex-map/overworldLayer.ts | 12 +++++++++--- 3 files changed, 39 insertions(+), 16 deletions(-) diff --git a/dev/demo-world.mjs b/dev/demo-world.mjs index 7ee9904d..1c556602 100644 --- a/dev/demo-world.mjs +++ b/dev/demo-world.mjs @@ -76,11 +76,11 @@ try { await sleep(2500); // second draw: bitmaps cached (only the composite) const first = await page.evaluate((id) => window.app.plugins.plugins[id].devTools.overworldStats(), PLUGIN_ID); - await page.evaluate((id) => { - const leaf = window.app.workspace.getLeavesOfType("duckmage-hex-map")[0]; - leaf?.view?.redraw?.(); - }, PLUGIN_ID); - await sleep(1500); + // Two redraws: the first may still follow the restored zoom; the second is the cached one. + for (let i = 0; i < 2; i++) { + await page.evaluate(() => window.app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view?.redraw?.()); + await sleep(1500); + } const cached = await page.evaluate((id) => window.app.plugins.plugins[id].devTools.overworldStats(), PLUGIN_ID); return { first, cached }; }; diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 0e11e68f..091b1b46 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -708,16 +708,33 @@ export class HexMapView extends ItemView { // hex's six neighbours, named by true bearing ("North-east: Fenmarch"). const home = regionHome(this.plugin, this.activeMapName); if (home) { - for (const n of regionNeighbourMaps(maps, home.overworld.name, home.layout, home.px, home.py)) { - const word = n.bearing[0].toUpperCase() + n.bearing.slice(1); - const title = `Neighbouring region to the ${n.bearing}: ${this.plugin.mapLabel(n.map.name)}`; - el.createEl("button", { + const near = regionNeighbourMaps(maps, home.overworld.name, home.layout, home.px, home.py); + const word = (b: string) => b[0].toUpperCase() + b.slice(1); + if (near.length <= 2) { + for (const n of near) { + const title = `Neighbouring region to the ${n.bearing}: ${this.plugin.mapLabel(n.map.name)}`; + el.createEl("button", { + cls: "duckmage-map-crumb duckmage-map-side-crumb", + text: `${word(n.bearing)}: ${this.plugin.mapLabel(n.map.name)}`, + attr: { title, "aria-label": title, "data-side": n.bearing }, + }).addEventListener("click", () => this.navigateToMap(n.map.name)); + } + } else { + // Up to six neighbours: one crumb that lists them, so the bar stays short. + const btn = el.createEl("button", { cls: "duckmage-map-crumb duckmage-map-side-crumb", - text: `${word}: ${this.plugin.mapLabel(n.map.name)}`, - attr: { title, "aria-label": title, "data-side": n.bearing }, - }).addEventListener("click", () => this.navigateToMap(n.map.name)); + text: `Next to (${near.length}) ▾`, + attr: { title: "The regions around this one", "aria-label": "The regions around this one" }, + }); + btn.addEventListener("click", (e) => { + const menu = new Menu(); + for (const n of near) { + menu.addItem((item) => item.setTitle(`${word(n.bearing)}: ${this.plugin.mapLabel(n.map.name)}`).onClick(() => this.navigateToMap(n.map.name))); + } + menu.showAtMouseEvent(e); + }); } - el.toggle(el.childElementCount > 0); + el.toggle(near.length > 0); return; } let side = neighbourCrumbs(this.plugin.getMap(this.activeMapName), maps); diff --git a/src/hex-map/overworldLayer.ts b/src/hex-map/overworldLayer.ts index 01ea861c..56493197 100644 --- a/src/hex-map/overworldLayer.ts +++ b/src/hex-map/overworldLayer.ts @@ -269,13 +269,19 @@ export class OverworldLayer { ctx.stroke(); } drawRiver(ctx, parseBiomeRiver(map.biomeRiver), at, Math.max(2, 3 * k * s / 20)); - ctx.fillStyle = "#000"; + // Biome names in the hex's upper half (its coordinates sit lower), sized + // to fit the hex: the preview's labels, scaled to the map's hexes. ctx.textAlign = "center"; - ctx.font = `${Math.round(Math.max(8, 9 * k * s / 20))}px system-ui`; + ctx.font = `600 ${Math.round(Math.max(8, 0.2 * k * s))}px system-ui`; + ctx.lineWidth = Math.max(2, 0.05 * k * s); + ctx.strokeStyle = "rgba(255, 255, 255, 0.85)"; + ctx.fillStyle = "#000"; for (const [key, b] of biomes) { const [x, y] = key.split("_").map(Number); const [X, Y] = at(x, y); - ctx.fillText((biomeInfo(b)?.label ?? "").slice(0, 10), X, Y + 3 * k * s / 20); + const text = biomeInfo(b)?.label ?? ""; + ctx.strokeText(text, X, Y - 0.3 * k * s); + ctx.fillText(text, X, Y - 0.3 * k * s); } } } From d97339f40675ff800b2e8791e69a9e0aa271fd61 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 18:58:21 -0400 Subject: [PATCH 229/558] fix(labels): a bigger hex-name size raises the readable floor Sandbox check: on a fitted 20x16 map every name sat at the 11px floor, so size L/XL changed nothing. The floor now scales with the size (never below the minimum). Co-Authored-By: Claude Opus 5.5 --- src/hex-map/hexNameLayer.ts | 4 +++- tests/r3Labels.test.ts | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/hex-map/hexNameLayer.ts b/src/hex-map/hexNameLayer.ts index 7604cde9..1019b354 100644 --- a/src/hex-map/hexNameLayer.ts +++ b/src/hex-map/hexNameLayer.ts @@ -254,7 +254,9 @@ export function renderHexNameLayer( if (!placements.length) return; const family = nameFontFamily(font.family, style.fontFamily); const measure = canvasMeasure(family, font.bold ? 700 : 400, font.italic); - const floorEm = readableFloorEm(gridFont, zoom); + // A bigger name size raises the floor too, so L / XL still read bigger + // when the map is zoomed out (never below the readable minimum). + const floorEm = readableFloorEm(gridFont, zoom) * Math.max(1, font.scale); // ── writes ── const layer = gridContainer.createDiv({ cls: HEX_NAMES_LAYER_CLASS }); diff --git a/tests/r3Labels.test.ts b/tests/r3Labels.test.ts index b9af544a..96227311 100644 --- a/tests/r3Labels.test.ts +++ b/tests/r3Labels.test.ts @@ -126,6 +126,11 @@ describe("NM3: hex names keep a readable size on screen", () => { expect(rule).toMatch(/white-space:\s*pre/); }); + it("a bigger name size raises the readable floor (L / XL still read bigger zoomed out)", () => { + const layer = read("src", "hex-map", "hexNameLayer.ts"); + expect(layer).toMatch(/readableFloorEm\(gridFont, zoom\) \* Math\.max\(1, font\.scale\)/); + }); + it("redraws names when the zoom settles (the floor depends on it)", () => { const src = read("src", "hex-map", "HexMapView.ts"); expect(src).toMatch(/if \(this\.zoom !== this\.namesZoom\)/); From f4425444a57d0d850bbb72b1844ff107915d4b8d Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 19:16:29 -0400 Subject: [PATCH 230/558] fix(merge): drop duplicate writeJsonBackup import Co-Authored-By: Claude Opus 5.5 --- src/palettes/PaletteStore.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index 0514eb64..922fd5f2 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -22,7 +22,6 @@ import { writeJsonBackup } from "../backup"; import { fillLegacyPathTypes } from "./pathTypeLegacy"; import { ADDED_PRESET_TERRAINS, DEFAULT_PATH_TYPES } from "../constants"; import { applyPresetTerrains, planPresetTerrains } from "./presetUpdates"; -import { writeJsonBackup } from "../backup"; import { inferTerrainType, refinedSpaceType } from "../terrainTypes"; import { repointPaletteName } from "./paletteOptions"; From e64e6981afe0b0c5a7a5ad15ee1dde7ec22260d1 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 19:18:00 -0400 Subject: [PATCH 231/558] feat(paths): map note format 5, named paths with anchors (phase 3) Map note: - ## Paths (Path | Type | Route | Notes; Route derived, carries the type and straight-segment warnings) and ## Path routes (Path | Branch | Anchors, pure input; a fork's first anchor is where it leaves the path). - Forgiving reader per plan section 2: coordinate forms and separators, header case/spacing/order, missing |---|, a path's rows in any order, names matched ignoring case and spacing (the next write fixes them), unreadable rows kept verbatim and listed, never half-imported; routes rows without a Paths row, Paths rows without routes, unknown types, duplicate names all handled. - Old Type | Hexes tables read forever via legacyChainsToPaths and written back in the new form (a table keeps only rows it couldn't read). - MAP_NOTE_FORMAT = 5 through the older-format backup flow; a note from a newer build is read as broken with a notice naming its format and saying to update. format-4.md pinned, plus the frozen format-4 reader to show a format-4 build sees format 5 as broken. MapStore: - MapData.paths is the stored model; pathChains is a compatibility view kept in step both ways (src/paths/chainView.ts). - Three-way merge of paths by name (mergePaths). - Older notes and data.json chains converted with compactLegacy (merge end-on chains, drop bare one-hex leftovers, fewest exact anchors), with a report saved next to the backup and one notice. - isReady(map) for the resolver gate (PathsService now uses it), routeContext/pathStyleFor (PA5 fields), onRouteContextChange; by default a context change pins routes (Decision 3). - storedMapPaths returns map.paths (data.json chains for maps whose note can't be read). Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- package.json | 4 +- src/HexmakerPlugin.ts | 4 +- src/hex-map/help.md | 4 +- src/maps/MapStore.ts | 380 +++- src/maps/mapNote.ts | 625 +++++-- src/paths/chainView.ts | 267 +++ src/paths/mapContext.ts | 89 + src/paths/mapPaths.ts | 16 +- src/types.ts | 12 + tests/compat.test.ts | 35 +- tests/compat/examples.ts | 4 +- .../compat/map-note-formats/format-4.md | 97 + .../map-note-formats/parser-format-4.ts | 1606 +++++++++++++++++ tests/mapNote.test.ts | 87 +- tests/mapNotePaths.test.ts | 532 ++++++ tests/mapStore.test.ts | 23 +- tests/submaps.test.ts | 4 +- 18 files changed, 3602 insertions(+), 191 deletions(-) create mode 100644 src/paths/chainView.ts create mode 100644 src/paths/mapContext.ts create mode 100644 tests/fixtures/compat/map-note-formats/format-4.md create mode 100644 tests/fixtures/compat/map-note-formats/parser-format-4.ts create mode 100644 tests/mapNotePaths.test.ts diff --git a/README.md b/README.md index 7126d856..fbb2321a 100644 --- a/README.md +++ b/README.md @@ -320,7 +320,9 @@ Open **Settings → Hexmap World Creator** to configure: Each map has one **map note** at `{hexFolder}/{map}/_{map}.md` (e.g. `RPG/world/hexes/Overworld/_Overworld.md`). It holds the map's settings in its frontmatter and a table with one row per hex that has map data: name, terrain, icon, GM icons, region, locations, region map (once a hex has one) and locked. Regions, locations and region maps are wikilinks (`[[Basin]]`, `[[_saltmere]], [[_old-mine]]`), so renaming a note in Obsidian updates them; plain names are read too and become links on the next save. Notes written before this (one Submap column, plain names) are converted once, after a backup in the plugin's `backups/` folder. Hexes with only the map's base terrain (or nothing) have no row. Painting updates the table; you can also edit the table by hand and the map follows. Anything you write in the note outside the "Hexes" and "Paths" tables is left alone. A collapsed **How to edit this note** box at the top explains the columns. -The plugin also writes a few things for you to read, worked out from the tables and the map's palette. A **Summary** section above the Hexes table shows the palette (as a link), the map's extent (`−7…30 × −8…16 (38×25)`), the base terrain, a terrain legend with hex counts, the regions on the map, its region settings, how many region maps and locations open from its hexes, and any terrain or path type that isn't in the palette (⚠). In **Paths**, the *Route* column shows where each path starts and ends (`3, 4 → 5, 4 (3 hexes)`), and a *Warning* column appears while a path's type isn't one of the palette's path types. These are never read back: they're rewritten on each save, so edits to them are replaced, and a deleted Summary comes back. Text you type under the Summary, or a Summary heading of your own, is left alone. Map notes from before this are given them once, after a backup. +Paths are stored by name in two tables. **Paths** has one row per path: *Path* (its name), *Type* (a path type from the palette), *Route* (written by the plugin) and *Notes* (yours). **Path routes** says where each path goes, as the hexes it passes through in order (`0, 8 → 9, 8 → 13, 8`); the map works out the way between them. A path's `main` row is its main line, and every other row of that path is a fork that leaves it at its first hex. The two tables are linked by the path's name, ignoring case and spacing, so to rename a path edit *Path* in both. Coordinates can be written `3, 4`, `3,4`, `3_4` or `(3, 4)`, separated by `→`, `->`, `>` or `;`. A routes row for a path missing from Paths makes that path (with no type until you give it one); a Paths row with no routes is kept as a path with no route yet. Older notes, which listed every hex of every path (`| Type | Hexes |`), are converted once, after a backup: pieces of the same type that touch end to end become one path with forks, one-hex leftovers with no notes are dropped, and each path keeps exactly the hexes it had. A report of what changed is saved next to the backup. An old `Type | Hexes` table pasted into a note is still read. + +The plugin also writes a few things for you to read, worked out from the tables and the map's palette. A **Summary** section above the Hexes table shows the palette (as a link), the map's extent (`−7…30 × −8…16 (38×25)`), the base terrain, a terrain legend with hex counts, the regions on the map, its region settings, how many region maps and locations open from its hexes, and any terrain or path type that isn't in the palette (⚠). In **Paths**, the *Route* column shows where each path's main line starts and ends, how many forks it has and how many hexes it covers (`0, 8 → 13, 8 · 2 forks · 31 hexes`), with a ⚠ when its type isn't one of the palette's path types, it has no type yet, or a stretch can't be routed and is drawn straight. These are never read back: they're rewritten on each save, so edits to them are replaced, and a deleted Summary comes back. Text you type under the Summary, or a Summary heading of your own, is left alone. Map notes from before this are given them once, after a backup. Hand edits are forgiving. Each setting is one plain property (the parent map and background image are links, e.g. `parent: "[[_coast]]"` with `parent-hex: 3, 4`), so the Properties panel can edit them too, and deleting a property resets that setting. In the tables, headers can be in any case and any order, you can add your own columns (they're kept), the `| --- |` row is optional, hexes can be written `3_4`, `3, 4` or as a link, and `yes`/`true`/`x`/`✓` all mean yes; the next save tidies the formatting without changing your values. Terrain and palette names in the wrong case are matched to the palette. A row or setting that can't be read is kept exactly as you wrote it and listed in a warning box in the note (and a notice), until you fix it. If the note can't be read at all (say the `---` lines around its properties get broken), the plugin won't write to it and shows a notice until you fix it; your text is never rebuilt over. diff --git a/package.json b/package.json index 3e5e717c..376c0515 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 5d0cd6b1..be951dff 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -106,8 +106,8 @@ export default class HexmakerPlugin extends Plugin { * resolved until the map's terrain and palette are loaded. */ paths = new PathsService({ - // PHASE-3: becomes this.mapStore.isReady(map) && the palette check. - isMapReady: () => this.mapStore.isReady() && this.paletteStore.isReady(), + // The map's terrain is loaded (MapStore) and the palettes (PaletteStore). + isMapReady: (map) => this.mapStore.isReady(map) && this.paletteStore.isReady(), getMap: (name) => this.getMap(name), orientation: () => this.settings.hexOrientation, stagger: (map) => map.staggerOffset ?? this.settings.staggerOffset ?? "odd", diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 4085d124..ee84ce0f 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -45,7 +45,9 @@ Hex names, terrain, icons, GM icons, regions, region maps and locations live in The **How to edit this note** box at the top of the map note explains the columns. Regions, locations and region maps are links (`[[Basin]]`, `[[_saltmere]]`), so renaming the note in Obsidian keeps the map right; plain names work too and become links on the next save. Notes from older versions (a single Submap column) are converted once, after a backup. Column order, header case and `3_4` vs `3, 4` don't matter, and your own columns and text are kept. A row that can't be read stays as you wrote it and is listed in a warning box until you fix it. If the note can't be read at all, the plugin stops saving to it and tells you, rather than writing over it. -The map note's **Summary** (above the Hexes table) and the *Route* and *Warning* columns in Paths are written by the plugin: extent, base terrain, a terrain legend with counts, regions, and a ⚠ for any terrain or path type not in the palette. They update on each save, so edits there are replaced. +The map note's **Summary** (above the Hexes table) and the *Route* column in Paths are written by the plugin: extent, base terrain, a terrain legend with counts, regions, each path's ends, forks and length, and a ⚠ for any terrain or path type not in the palette. They update on each save, so edits there are replaced. + +Paths are named. The **Paths** table lists each path (name, type, your notes); **Path routes** lists the hexes each one passes through in order, like `0, 8 → 9, 8 → 13, 8`, and the map draws the way between them. A path's `main` row is its main line; other rows are forks that leave it at their first hex. The tables are linked by name, so to rename a path edit it in both. Older notes that listed every hex of a path are converted once, after a backup, with a report of what changed beside it. --- diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index 048bc5ad..15eff6d4 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -1,10 +1,11 @@ import { Notice, TAbstractFile, TFile, TFolder, parseYaml } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; -import type { MapData } from "../types"; +import type { HexKey, MapData, MapPath, PathChain, PathType, TerrainColor } from "../types"; import { normalizeFolder } from "../utils"; import { buildMapNote, MAP_NOTE_FORMAT, + PATHS_FORMAT, READABLE_KEYS_FORMAT, mapNoteKey, parseMapNote, @@ -17,10 +18,33 @@ import { type MapNoteData, type MapNoteProblem, type MapNoteReadOptions, + type PathRouteStats, } from "./mapNote"; import { renamedHexes, syncHexNameAlias } from "./hexNames"; import { regionMirrorFixes } from "./submaps"; import { writeJsonBackup } from "../backup"; +import { impassableNames } from "../impassable"; +import type { RouteContext } from "../paths/router"; +import { RouteCache, type SegmentRouter } from "../paths/routeCache"; +import { resolvePaths, styleOf, type ResolvedBranch, type StyleFor } from "../paths/resolve"; +import { anchorsFor, compactLegacy, dedupeSteps, reproduces, routeFnFor, type CompactReport } from "../paths/fromHexes"; +import { pinChanged, segmentFn } from "../paths/edit"; +import { legacyChainsToPaths } from "../paths/legacy"; +import { pathNameKey, uniquePathName } from "../paths/names"; +import { mapRouteContext, pathTypeStyleFor } from "../paths/mapContext"; +import { buildView, emptyView, reconcile, type PathView } from "../paths/chainView"; + +/** A map's routing context changed (terrain, palette impassability, size, stagger). */ +export interface RouteContextChange { + map: string; + before: RouteContext; + after: RouteContext; + /** Routes under `before` (cached). */ + previous: SegmentRouter; + /** Routes under `after` (cached). */ + current: SegmentRouter; + styleFor: StyleFor; +} /** Hex-note frontmatter keys that hold map data (moved into the map note). */ export const HEX_DATA_KEYS = ["terrain", "icon", "gm-icons", "gm-icon", "region", "duckmage-submap", "locked"] as const; @@ -78,11 +102,33 @@ export class MapStore { private reviewTimer: number | undefined; /** Last reported unreadable rows per map (so a notice isn't repeated). */ private reported = new Map(); + /** Per map: which handed-out pathChains object is which branch (see chainView.ts). */ + private views = new Map(); + /** Per map: segment routes under its current routing context (and the previous one, for pinning). */ + private routeCaches = new Map(); + /** Maps still being moved out of hex-note frontmatter (their terrain isn't in memory yet). */ + private migrating = new Set(); + /** Per map: what converting its old every-hex paths did, saved next to its backup. */ + private pathReports = new Map(); + /** Old every-hex paths converted this session, per map (for the startup notice). */ + private converted: { map: string; report: CompactReport }[] = []; + private contextListeners = new Set<(e: RouteContextChange) => boolean | void>(); constructor(private plugin: HexmakerPlugin) {} - isReady(): boolean { - return this.ready; + /** + * No map: the store has loaded every map note. With a map: that map's + * terrain and palette are loaded too, so its paths can be resolved + * (routing earlier would route around an incomplete set of impassable + * hexes and the line would jump when the rest arrived). The palette store + * loads before this one (HexmakerPlugin: paletteStore.init().then(mapStore.init)). + */ + isReady(map?: string): boolean { + if (!this.ready) return false; + if (map === undefined) return true; + const ps = (this.plugin as { paletteStore?: { isReady?: () => boolean } }).paletteStore; + if (ps?.isReady && !ps.isReady()) return false; + return !!this.plugin.getMap(map) && !this.broken.has(map) && !this.migrating.has(map); } // ── paths ──────────────────────────────────────────────────────────── @@ -142,6 +188,7 @@ export class MapStore { else (h as Record)[k] = v; } if (Object.keys(h).length) t.set(key, h); else t.delete(key); + if ("terrain" in patch) this.terrainChanged(map); this.markDirty(map); this.emit(map); } @@ -154,15 +201,187 @@ export class MapStore { for (const k of Object.keys(h) as (keyof HexData)[]) if (h[k] === undefined || h[k] === "") delete h[k]; if (Object.keys(h).length) t.set(key, h); else t.delete(key); } + this.terrainChanged(map); this.markDirty(map); this.emit(map); } + /** Terrain changed: if that moves the map's routing context, routes are pinned (see routeCache). */ + private terrainChanged(name: string): void { + const map = this.plugin.getMap(name); + if (map && map.paths?.length && this.routeCaches.has(name) && this.isReady(name)) this.routeCache(map); + } + onChange(fn: (map: string) => void): () => void { this.listeners.add(fn); return () => this.listeners.delete(fn); } + // ── paths (anchored model) ─────────────────────────────────────────── + + /** + * A map's routing context changed (terrain painted impassable or back, a + * palette's impassable flags, the grid's size or stagger). A listener that + * returns true has dealt with it (phase 7: pin with a notice and "Reroute + * instead"); otherwise the store keeps every route where it was by adding + * anchors (Decision 3), silently. + */ + onRouteContextChange(fn: (e: RouteContextChange) => boolean | void): () => void { + this.contextListeners.add(fn); + return () => this.contextListeners.delete(fn); + } + + /** The map's routing inputs now (see paths/mapContext.ts). */ + routeContext(map: MapData): RouteContext { + const p = this.plugin as Partial> & { settings: { hexOrientation?: "flat" | "pointy"; staggerOffset?: "odd" | "even" } }; + let palette: TerrainColor[] = []; + try { palette = p.getMapPalette?.call(this.plugin, map.name) ?? []; } catch { /* no palette yet */ } + return mapRouteContext({ + orientation: p.settings.hexOrientation ?? "flat", + stagger: map.staggerOffset ?? p.settings.staggerOffset ?? "odd", + gridSize: map.gridSize, + gridOffset: map.gridOffset, + baseTerrain: map.baseTerrain, + terrainOf: this.all(map.name), + impassable: impassableNames(palette), + }); + } + + /** The routing style of each of the map's path types (their explicit fields only). */ + pathStyleFor(map: MapData): StyleFor { + const p = this.plugin as Partial>; + let types: PathType[] = []; + try { types = p.getMapPathTypes?.call(this.plugin, map.name) ?? []; } catch { /* none */ } + return pathTypeStyleFor(types); + } + + /** The map's segment cache, switched to its current context (pinning first if that changed). */ + routeCache(map: MapData): RouteCache { + let cache = this.routeCaches.get(map.name); + if (!cache) { cache = new RouteCache(); this.routeCaches.set(map.name, cache); } + const before = cache.context; + const after = this.routeContext(map); + if (!cache.setContext(after) || !before) return cache; + const previous = cache.previous()!; + const styleFor = this.pathStyleFor(map); + let handled = false; + for (const fn of this.contextListeners) { + try { if (fn({ map: map.name, before, after, previous, current: cache, styleFor }) === true) handled = true; } + catch (e) { console.error("Hexmaker: route context listener failed", e); } + } + if (!handled && map.paths?.length) { + const { paths, pinned } = pinChanged(map.paths, segmentFn(previous, styleFor), segmentFn(cache, styleFor), after); + if (pinned.length) { + map.paths = paths; + if (!this.broken.has(map.name)) this.markDirty(map.name); + } + } + cache.dropPrevious(); + return cache; + } + + /** The map's paths resolved to hexes, or null until its terrain and palette are loaded. */ + resolved(name: string): ResolvedBranch[] | null { + const map = this.plugin.getMap(name); + if (!map || !this.isReady(name)) return null; + this.syncPaths(map); + return resolvePaths(map.paths ?? [], this.routeCache(map).context!, this.pathStyleFor(map), this.routeCache(map)); + } + + /** The map's paths (the stored model), with edits made through pathChains folded in. */ + paths(name: string): readonly MapPath[] { + const map = this.plugin.getMap(name); + if (!map) return []; + this.syncPaths(map); + return map.paths ?? []; + } + + /** Replace a map's paths (new tools): pathChains is rebuilt to match, the note written. */ + setPaths(name: string, paths: MapPath[]): void { + const map = this.plugin.getMap(name); + if (!map) return; + map.paths = paths; + this.rebuildView(map); + this.markDirty(name); + this.emit(name); + } + + /** Anchors that route back to exactly `hexes` (dense when nothing shorter does). */ + private anchorsOf(map: MapData, typeName: string, hexes: HexKey[]): HexKey[] { + if (!this.isReady(map.name)) return dedupeSteps(hexes); + const cache = this.routeCache(map); + const route = routeFnFor(cache, styleOf(this.pathStyleFor(map), typeName)); + const a = anchorsFor(hexes, route, cache.context!); + return reproduces(a, hexes, route) ? a : dedupeSteps(hexes); + } + + /** pathChains rebuilt from the paths (one chain per resolved branch). */ + private rebuildView(map: MapData): void { + const old = this.views.get(map.name); + // Needs the map's terrain in memory (the palette store loads first). + if (this.broken.has(map.name) || this.migrating.has(map.name)) { + this.views.set(map.name, emptyView()); + return; + } + const cache = this.routeCache(map); + const resolved = resolvePaths(map.paths ?? [], cache.context!, this.pathStyleFor(map), cache); + const { chains, view } = buildView(resolved, old?.removed); + map.pathChains = chains; + this.views.set(map.name, view); + } + + /** + * Fold edits made through the compatibility view (map.pathChains: the + * path tool, generators, type renames) into map.paths. + */ + private syncPaths(map: MapData): void { + if (!this.ready || this.broken.has(map.name) || this.migrating.has(map.name)) return; + if (!map.pathChains) map.pathChains = []; + const view = this.views.get(map.name) ?? emptyView(); + const r = reconcile(map.paths ?? [], map.pathChains, view, (t, h) => this.anchorsOf(map, t, h)); + this.views.set(map.name, r.view); + if (r.changed || !map.paths) map.paths = r.paths; + } + + /** + * Convert old every-hex paths (data.json chains, or a format 2–4 note's + * `Type | Hexes` rows): merge same-type chains that touch end to end, + * drop one-hex leftovers with no notes or extra columns (they stay in the + * backup and the report), and give each branch the fewest anchors that + * route back to exactly its hexes. `others` (already anchored) are kept + * first, unchanged. + */ + private convertLegacy(map: MapData, legacy: MapPath[], others: MapPath[]): void { + const cache = this.routeCache(map); + const { paths, report } = compactLegacy(legacy, cache.context!, { dropSingles: true, styleFor: this.pathStyleFor(map), cache }); + const taken = others.map((p) => p.name); + const named = paths.map((p) => { + const name = uniquePathName(p.name, taken); + taken.push(name); + return name === p.name ? p : { ...p, name }; + }); + map.paths = [...others, ...named]; + this.pathReports.set(map.name, report); + this.converted.push({ map: map.name, report }); + } + + /** Save a map's path-conversion report next to its backup (once). */ + private async savePathReport(map: string): Promise { + const report = this.pathReports.get(map); + this.pathReports.delete(map); + if (!report || !report.pathsIn) return; + const adapter = this.plugin.app.vault.adapter; + try { + const dir = this.backupDir(); + if (!(await adapter.exists(dir))) await adapter.mkdir(dir); + let path = `${dir}/${map}-paths-report.md`; + for (let n = 2; await adapter.exists(path); n++) path = `${dir}/${map}-paths-report-${n}.md`; + await adapter.write(path, pathReportText(map, report)); + } catch (e) { + console.error(`Hexmap World Creator: couldn't save the path report for ${map}`, e); + } + } + private emit(map: string): void { for (const fn of this.listeners) { try { fn(map); } catch (e) { console.error("Hexmaker: map listener failed", e); } @@ -224,7 +443,7 @@ export class MapStore { for (const map of this.uniqueMaps()) { if (this.broken.has(map.name)) continue; const r = await this.loadMap(map); - if (typeof r === "object") this.markBroken(map.name, this.notePath(map.name), r.unreadable); + if (typeof r === "object") this.markBroken(map.name, this.notePath(map.name), r.unreadable, r.newer); } this.plugin.refreshHexMap(); }); @@ -256,12 +475,15 @@ export class MapStore { } catch (e) { console.error("Hexmaker: couldn't read the palette for a map note's summary", e); } + const resolved = this.isReady(map.name) && map.paths?.length ? this.resolved(map.name) : null; + if (resolved) ctx.pathRoutes = pathRouteStats(map.paths ?? [], resolved); return ctx; } dataFor(map: MapData): MapNoteData { - const { name: _n, pathChains, savedViewport: _v, ...settings } = map; - return { settings: settings, hexes: this.table(map.name), paths: pathChains ?? [] }; + this.syncPaths(map); + const { name: _n, pathChains: _c, paths, savedViewport: _v, ...settings } = map; + return { settings: settings, hexes: this.table(map.name), paths: paths ?? [] }; } private async writeNote(map: MapData): Promise { @@ -275,7 +497,7 @@ export class MapStore { // we last read it (onModify not run yet). Never write over that. const r = readMapNote(current, this.readOpts(path)); if (!r || !r.ok) { - this.markBroken(map.name, path, r ? r.reason : NO_FRONTMATTER); + this.markBroken(map.name, path, r ? r.reason : NO_FRONTMATTER, r && !r.ok ? r.newer : undefined); return; } const seen = this.lastContent.get(path); @@ -291,6 +513,7 @@ export class MapStore { } this.backedUp.add(path); } + await this.savePathReport(map.name); const data = this.dataFor(map); const ctx = this.contextFor(map); const next = updateMapNote(current, map.name, data, ctx); @@ -335,13 +558,30 @@ export class MapStore { const m = map as unknown as Record; for (const f of RESETTABLE_FIELDS) if (!(f in data.settings) && !unreadable.has(f)) delete m[f]; } - map.pathChains = data.paths; this.hexes.set(map.name, this.matchCase(map, data.hexes)); + this.applyPaths(map, data); this.lastKey.set(map.name, mapNoteKey(this.dataFor(map))); // Loaded or hand-edited: taken as written. Derived parts catch up on the next write. this.lastDerived.set(map.name, JSON.stringify(this.contextFor(map))); } + /** + * The note's paths onto the map: old every-hex rows in an older note are + * converted (merged, compacted; see convertLegacy), the routing context is + * brought up to date (a hand edit that painted water under a road keeps + * the road), and pathChains is rebuilt to match. + */ + private applyPaths(map: MapData, data: MapNoteData): void { + const legacy = new Set(data.legacyPaths ?? []); + if (legacy.size && (data.format ?? 1) < PATHS_FORMAT) { + this.convertLegacy(map, data.paths.filter((p) => legacy.has(p.name)), data.paths.filter((p) => !legacy.has(p.name))); + } else { + map.paths = data.paths; + this.routeCache(map); + } + this.rebuildView(map); + } + /** * Palette and terrain names typed in another case ("forest" for "Forest") * read as the palette's own spelling; the next write puts that in the note. @@ -390,17 +630,23 @@ export class MapStore { if (k in ts) m[k] = ts[k]; else if ((theirs.format ?? 1) >= READABLE_KEYS_FORMAT && RESETTABLE_FIELDS.includes(k)) delete m[k]; } - if (!same(base.paths, theirs.paths)) map.pathChains = theirs.paths; + this.syncPaths(map); + const merged = mergePaths(base.paths, theirs.paths, map.paths ?? []); + if (!same(merged, map.paths ?? [])) { + map.paths = merged; + this.routeCache(map); + this.rebuildView(map); + } } /** "loaded", "missing" (no note: migrate), or why it can't be read (leave it alone). */ - private async loadMap(map: MapData): Promise<"loaded" | "missing" | { unreadable: string }> { + private async loadMap(map: MapData): Promise<"loaded" | "missing" | { unreadable: string; newer?: number }> { const file = this.plugin.app.vault.getAbstractFileByPath(this.notePath(map.name)); if (!(file instanceof TFile)) return "missing"; const content = await this.plugin.app.vault.read(file); const r = readMapNote(content, this.readOpts(file.path)); this.lastContent.set(file.path, content); - if (!r || !r.ok) return { unreadable: r ? r.reason : NO_FRONTMATTER }; + if (!r || !r.ok) return { unreadable: r ? r.reason : NO_FRONTMATTER, newer: r && !r.ok ? r.newer : undefined }; this.apply(map, r.data); if ((r.data.format ?? 1) < MAP_NOTE_FORMAT) this.dirty.add(map.name); else if (r.data.problems?.length) this.toReview.add(map.name); @@ -412,11 +658,13 @@ export class MapStore { * writing over it (a rebuild would lose the user's text), and say so once * with a notice that stays until it reads again. */ - private markBroken(map: string, path: string, reason: string): void { + private markBroken(map: string, path: string, reason: string, newer?: number): void { if (this.broken.has(map)) return; this.broken.add(map); this.brokenNotices.set(map, new Notice( - `Hexmap World Creator: can't read the map note ${path}: ${reason}. Changes to this map aren't saved until it's fixed; fix it in the note and the map reloads from it.`, + newer + ? `Hexmap World Creator: the map note ${path} is in map-note format ${newer}, from a newer version of the plugin. Update Hexmap World Creator to use this map; until then changes to it aren't saved.` + : `Hexmap World Creator: can't read the map note ${path}: ${reason}. Changes to this map aren't saved until it's fixed; fix it in the note and the map reloads from it.`, 0, )); } @@ -442,7 +690,7 @@ export class MapStore { if (!r || !r.ok) { // Broken mid-session (a lost `---`, a renamed table header…): the // next paint must not rebuild the note over the user's text. - this.markBroken(map.name, file.path, r ? r.reason : NO_FRONTMATTER); + this.markBroken(map.name, file.path, r ? r.reason : NO_FRONTMATTER, r && !r.ok ? r.newer : undefined); return; } this.markReadable(map.name); @@ -525,6 +773,9 @@ export class MapStore { const t = this.hexes.get(oldName); if (t) { this.hexes.delete(oldName); this.hexes.set(newName, t); } if (this.broken.delete(oldName)) this.broken.add(newName); + for (const m of [this.views, this.routeCaches] as Map[]) { + if (m.has(oldName)) { m.set(newName, m.get(oldName)); m.delete(oldName); } + } const { vault, fileManager } = this.plugin.app; const moved = vault.getAbstractFileByPath(`${this.mapFolder(newName)}/_${oldName}.md`); if (moved instanceof TFile) await fileManager.renameFile(moved, this.notePath(newName)); @@ -552,6 +803,8 @@ export class MapStore { forgetMap(name: string): void { this.hexes.delete(name); + this.views.delete(name); + this.routeCaches.delete(name); this.lastKey.delete(name); this.lastDerived.delete(name); this.dirty.delete(name); @@ -580,9 +833,10 @@ export class MapStore { // notes are already cleaned, so that would write an empty map. // Keep the note, hold edits in memory only, and say so. unreadable.push(map); - this.markBroken(map.name, this.notePath(map.name), r.unreadable); + this.markBroken(map.name, this.notePath(map.name), r.unreadable, r.newer); } } + for (const m of toMigrate) this.migrating.add(m.name); this.ready = true; if (toMigrate.length) await this.migrate(toMigrate); // Hex notes still carrying map data after a load (an interrupted @@ -598,10 +852,29 @@ export class MapStore { if (map) await this.writeNote(map); } await this.review(); + this.reportConversions(); this.plugin.refreshHexMap(); }); } + /** One notice for the old every-hex paths converted this session. */ + private reportConversions(): void { + const done = this.converted.filter((c) => c.report.pathsIn > 0); + this.converted = []; + if (!done.length) return; + const sum = (f: (r: CompactReport) => number) => done.reduce((n, c) => n + f(c.report), 0); + const chains = sum((r) => r.pathsIn), paths = sum((r) => r.pathsOut), singles = sum((r) => r.singlesDropped.length); + const merged = sum((r) => r.merged.length), inexact = sum((r) => r.inexact.length); + new Notice( + `Hexmap World Creator: paths on ${done.length} map${done.length === 1 ? "" : "s"} moved to the new format: ${chains} old path${chains === 1 ? "" : "s"} became ${paths}` + + (merged ? ` (${merged} joined from touching pieces)` : "") + + (singles ? `; ${singles} one-hex leftover${singles === 1 ? " was" : "s were"} dropped` : "") + + (inexact ? `; ${inexact} kept every hex as written` : "") + + `. The old notes and a report per map are in ${this.backupDir()}.`, + 15000, + ); + } + private hexFiles(map: string): TFile[] { const folder = this.plugin.app.vault.getAbstractFileByPath(this.mapFolder(map)); if (!(folder instanceof TFolder)) return []; @@ -631,6 +904,11 @@ export class MapStore { if (Object.keys(h).length) hexes.set(file.basename, h); } this.hexes.set(map.name, hexes); + this.migrating.delete(map.name); + // data.json's every-hex paths become named, anchored paths (backed up below). + const oldChains: PathChain[] = (map.pathChains ?? []).map((c) => ({ ...c, hexes: [...c.hexes] })); + if (!map.paths) this.convertLegacy(map, legacyChainsToPaths(oldChains), []); + this.rebuildView(map); // Write, then read back and compare before touching any hex note. await this.writeNote(map); const written = this.plugin.app.vault.getAbstractFileByPath(this.notePath(map.name)); @@ -642,7 +920,8 @@ export class MapStore { } try { if (!(await adapter.exists(backupDir))) await adapter.mkdir(backupDir); - await adapter.write(`${backupDir}/${map.name}.json`, JSON.stringify({ map: map.name, hexes: [...hexes] }, null, 1)); + await adapter.write(`${backupDir}/${map.name}.json`, JSON.stringify({ map: map.name, hexes: [...hexes], pathChains: oldChains }, null, 1)); + await this.savePathReport(map.name); } catch (e) { console.error("Hexmaker: map-note backup failed", e); failed.push(map.name); @@ -735,7 +1014,7 @@ function problemSignature(problems: MapNoteProblem[] | undefined): string { export function withoutNotePaths(settings: S, holds: (name: string) => boolean): S { const maps = settings.maps.map((m) => { if (!holds(m.name)) return m; - const { pathChains: _paths, ...rest } = m; + const { pathChains: _chains, paths: _paths, ...rest } = m; return rest as MapData; }); return { ...settings, maps }; @@ -747,3 +1026,70 @@ function pick(a: HexData, like: HexData): HexData { for (const k of Object.keys(like) as (keyof HexData)[]) (out as Record)[k] = a[k]; return out; } + +/** + * Three-way merge of a map's paths by name (ignoring case and spacing): + * `base` is what the note held when we last read or wrote it, `theirs` what + * it holds now (hand edits, sync), `ours` the paths in memory (edits not yet + * written). A path they changed, added or removed takes their version; + * every other path keeps ours. Their order first, then paths only we added. + */ +export function mergePaths(base: readonly MapPath[], theirs: readonly MapPath[], ours: readonly MapPath[]): MapPath[] { + const key = (p: MapPath) => pathNameKey(p.name); + const b = new Map(base.map((p) => [key(p), p])); + const o = new Map(ours.map((p) => [key(p), p])); + const t = new Map(theirs.map((p) => [key(p), p])); + const same = (x: MapPath | undefined, y: MapPath | undefined) => JSON.stringify(x) === JSON.stringify(y); + const out: MapPath[] = []; + for (const p of theirs) { + const k = key(p); + if (!same(b.get(k), p)) out.push(p); // changed or added by hand + else if (o.has(k)) out.push(o.get(k)!); // ours (maybe edited); removed by us = gone + } + for (const p of ours) { + const k = key(p); + if (!t.has(k) && !b.has(k)) out.push(p); // added by us + } + return out; +} + +/** Per path (by pathNameKey): the hexes it covers and the segments drawn straight. */ +export function pathRouteStats(paths: readonly MapPath[], resolved: readonly ResolvedBranch[]): Record { + const out: Record = {}; + const byName = new Map(paths.map((p) => [p.name, p])); + const hexes = new Map>(); + for (const r of resolved) { + const k = pathNameKey(r.path); + let set = hexes.get(k); + if (!set) { set = new Set(); hexes.set(k, set); } + for (const h of r.hexes) set.add(h); + const st = (out[k] ??= { hexes: 0 }); + const anchors = byName.get(r.path)?.branches[r.branch]?.anchors ?? []; + for (const i of r.fallbackSegments) (st.fallbacks ??= []).push([anchors[i], anchors[i + 1]]); + } + for (const [k, set] of hexes) out[k].hexes = set.size; + return out; +} + +/** A map's path-conversion report, as a note next to its backup. */ +export function pathReportText(map: string, r: CompactReport): string { + const lines = [ + `# Paths of ${map}: converted to named paths with anchors`, + "", + `- Old paths (every hex listed): ${r.pathsIn}`, + `- New paths: ${r.pathsOut} (${r.branches} branches, ${r.anchors} anchors)`, + `- Joined from pieces that touched end to end: ${r.merged.length}`, + `- One-hex leftovers dropped (no notes): ${r.singlesDropped.length}`, + `- Duplicate strokes dropped (every step already drawn): ${r.duplicates.length}`, + `- Kept with every hex as an anchor (couldn't be shortened exactly): ${r.inexact.length}`, + "", + "Every new path draws exactly the steps of the old ones it came from. The old paths are in the backup next to this report.", + "Below, old paths are named by their type and their place among the old paths of that type (Road, Road 2, Road 3…); the new paths are named the same way, so a name here may now be a different path.", + ]; + if (r.merged.length) lines.push("", "## Joined", "", ...r.merged.map((m) => `- ${m.name}: ${m.from.join(", ")}`)); + if (r.duplicates.length) lines.push("", "## Duplicate strokes", "", ...r.duplicates.map((d) => `- ${d.name} (already drawn by ${d.into})`)); + if (r.singlesDropped.length) lines.push("", "## One-hex leftovers dropped", "", ...r.singlesDropped.map((d) => `- ${d.name} (${d.typeName}) at ${d.hex.replace("_", ", ")}`)); + if (r.inexact.length) lines.push("", "## Kept as written", "", ...r.inexact.map((n) => `- ${n}`)); + if (r.combinedText.length) lines.push("", "## Notes combined from joined pieces", "", ...r.combinedText.map((n) => `- ${n}`)); + return lines.join("\n") + "\n"; +} diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index 426b5642..cfc97ddc 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -1,5 +1,8 @@ -import type { MapData, PathChain, RegionSettings } from "../types"; import { parseNameFamily, parseNameSize, parseNameStyle } from "../hex-map/hexNameFont"; +import type { HexKey, MapData, MapPath, PathBranch, PathChain, RegionSettings } from "../types"; +import { formatAnchors, formatAnchor, parseAnchors } from "../paths/anchorText"; +import { legacyChainsToPaths } from "../paths/legacy"; +import { pathNameKey, uniquePathName } from "../paths/names"; /** * Map notes: one note per map ("hexes//_.md") holding the map's @@ -22,8 +25,12 @@ import { parseNameFamily, parseNameSize, parseNameStyle } from "../hex-map/hexNa * | Hex | Name | Terrain | Icon | GM icons | Region | Locations | Locked | * | 3_4 | Glass Wastes | dunes | | | [[Basin]] | [[_saltmere]], [[_old-mine]] | | * ## Paths - * | Type | Hexes | - * | Road | 3_4 4_4 5_4 | + * | Path | Type | Route | Notes | + * | King's Road | Road | 3, 4 → 9, 4 · 1 fork · 9 hexes | Paved. | + * ## Path routes + * | Path | Branch | Anchors | + * | King's Road | main | 3, 4 → 9, 4 | + * | King's Road | fork | 6, 4 → 6, 7 | * * Written to be read and edited by people (#42): * - every setting is one plain key (no JSON); other notes and images are @@ -55,14 +62,25 @@ import { parseNameFamily, parseNameSize, parseNameStyle } from "../hex-map/hexNa * Summary comes back. The Summary is only ever recognised by its * "Generated by Hexmaker" line, and only its own lines (that line, * bullets, the legend table) are replaced: anything else typed in there - * stays. map-note-formats/format-3.md pins format 3. + * stays. map-note-formats/format-3.md pins format 3; + * - format 5 stores paths as named paths with anchors (plan-path-anchors + * section 2): `## Paths` (Path | Type | Route | Notes; Route is derived) + * says what each path is, `## Path routes` (Path | Branch | Anchors, pure + * input) says where it goes. A path's rows are linked by name, ignoring + * case and spacing. The old every-hex `Type | Hexes` table is read forever + * (each row a path with every hex an anchor) and written back in the new + * form; MapStore compacts those when it converts an older note. + * map-note-formats/format-4.md pins format 4. */ export const MAP_NOTE_MARKER = "hexmaker-map"; /** Format written by this build (the marker's value). 1 = JSON values, * 2 = readable keys + one Submap column, 3 = Region map + Locations, links, - * 4 = derived Summary + Route/Warning path columns. */ -export const MAP_NOTE_FORMAT = 4; + * 4 = derived Summary + Route/Warning path columns, 5 = named paths with + * anchors (Paths + Path routes). */ +export const MAP_NOTE_FORMAT = 5; +/** First format with named, anchored paths (older notes hold every-hex chains). */ +export const PATHS_FORMAT = 5; /** First format with one readable key per setting (deleting a key resets it). */ export const READABLE_KEYS_FORMAT = 2; @@ -90,12 +108,12 @@ export interface HexData { /** Settings stored in a map note: MapData minus its name, paths and the * per-session viewport (which stays in data.json). */ -export type MapSettings = Omit; +export type MapSettings = Omit; /** Something in a map note that couldn't be read. It stays in the note as written. */ export interface MapNoteProblem { - /** "Hexes" / "Paths" table, or "settings" (frontmatter). */ - where: "Hexes" | "Paths" | "settings"; + /** "Hexes" / "Paths" / "Path routes" table, or "settings" (frontmatter). */ + where: "Hexes" | "Paths" | "Path routes" | "settings"; /** The row or `key: value` line, as written. */ text: string; reason: string; @@ -108,11 +126,18 @@ export interface MapNoteProblem { export interface MapNoteData { settings: Partial; hexes: Map; - paths: PathChain[]; + paths: MapPath[]; /** Format the note was written in (MAP_NOTE_FORMAT, or 1 for older notes). */ format?: number; /** What couldn't be read (rows, settings). Empty/absent = all of it read. */ problems?: MapNoteProblem[]; + /** + * Names of the paths read from an old every-hex `Type | Hexes` table + * (one dense-anchor path per row). Reading only: MapStore compacts them + * (merge, drop bare one-hex leftovers, fewer anchors) when it converts an + * older note. Never written. + */ + legacyPaths?: string[]; } export interface MapNoteReadOptions { @@ -120,7 +145,18 @@ export interface MapNoteReadOptions { resolveLink?: (link: string) => string | undefined; } -export type MapNoteRead = { ok: true; data: MapNoteData } | { ok: false; reason: string }; +export type MapNoteRead = + | { ok: true; data: MapNoteData } + /** `newer`: the note's format, when it was written by a newer build than this one. */ + | { ok: false; reason: string; newer?: number }; + +/** What the derived Route column says about a path's routed hexes (MapStore works it out). */ +export interface PathRouteStats { + /** Hexes the path covers (all branches, each hex once). */ + hexes: number; + /** Segments that couldn't be routed and are drawn as a straight line: [from, to]. */ + fallbacks?: [HexKey, HexKey][]; +} /** * What the derived parts (Summary, Paths' Route/Warning) need from outside @@ -133,6 +169,12 @@ export interface MapNoteContext { pathTypes?: string[]; /** The palette's note (vault path without .md), for the Summary's link. */ paletteNote?: string; + /** + * Routed facts per path, keyed by pathNameKey(name), for the Route column. + * The writer can't route (no terrain or palette here); without them Route + * says only what the anchors say (ends, forks). + */ + pathRoutes?: Record; } // ── loose YAML ─────────────────────────────────────────────────────────── @@ -388,7 +430,7 @@ const OWNED_KEYS = new Set([ ]); /** Fields never stored in the note. */ -const SKIP_FIELDS = new Set(["name", "pathChains", "savedViewport", "gridSize", "gridOffset"]); +const SKIP_FIELDS = new Set(["name", "pathChains", "paths", "savedViewport", "gridSize", "gridOffset"]); /** Fields this file writes readably (everything else goes to `hexmaker-*` keys). */ const KNOWN_FIELDS = new Set([ ...SIMPLE_KEYS.map(([f]) => f as string), "parent", "world", "backgroundImage", @@ -843,9 +885,18 @@ const FRONTMATTER = /^---[ \t]*\n(?:([\s\S]*?)\n)?---[ \t]*(\n|$)/; const HEX_HEADERS = ["Hex", "Name", "Terrain", "Icon", "GM icons", "Region", "Region map", "Locations", "Locked"]; /** Known columns written only when the table has them or some row needs them. */ const OPTIONAL_HEX_HEADERS = new Set(["region map"]); -const PATH_HEADERS = ["Type", "Route", "Warning", "Hexes"]; -/** Paths columns written from the data, never read back. */ +/** `## Paths` (format 5): what each path is. Route is derived. */ +const PATH_HEADERS = ["Path", "Type", "Route", "Notes"]; +/** `## Path routes`: where each path goes. Pure input, nothing derived. */ +const ROUTE_HEADERS = ["Path", "Branch", "Anchors"]; +/** Format 2–4's every-hex table (read forever; only rewritten to keep rows it couldn't read). */ +const LEGACY_PATH_HEADERS = ["Type", "Hexes"]; +/** Paths columns written from the data, never read back (Warning: format 4's, dropped). */ const DERIVED_PATH_COLS = new Set(["route", "warning"]); +/** A Path routes row with this Branch (any case) is a path's main line. */ +const MAIN_LABEL = "main"; +/** Branch written for a fork without a label of its own. */ +const FORK_LABEL = "fork"; /** Header → canonical column, ignoring case, spaces, dashes and markup. */ const HEX_COL_ALIASES: Record = { hex: "hex", name: "name", terrain: "terrain", icon: "icon", @@ -856,8 +907,17 @@ const HEX_COL_ALIASES: Record = { submap: "locations", submaps: "locations", locked: "locked", }; -const PATH_COL_ALIASES: Record = { type: "type", hexes: "hexes", route: "route", warning: "warning", warnings: "warning" }; -const CANONICAL: Record = Object.fromEntries([...HEX_HEADERS, ...PATH_HEADERS].map((h) => [h.toLowerCase(), h])); +const PATH_COL_ALIASES: Record = { + path: "path", paths: "path", pathname: "path", + type: "type", pathtype: "type", + hexes: "hexes", route: "route", warning: "warning", warnings: "warning", + notes: "notes", note: "notes", + branch: "branch", branches: "branch", fork: "branch", label: "branch", + anchors: "anchors", anchor: "anchors", waypoints: "anchors", +}; +const CANONICAL: Record = Object.fromEntries( + [...HEX_HEADERS, ...PATH_HEADERS, ...ROUTE_HEADERS, ...LEGACY_PATH_HEADERS, "Warning"].map((h) => [h.toLowerCase(), h]), +); const SEPARATOR_ROW = /^\s*\|?\s*:?[-=]+:?\s*(\|\s*:?[-=]*:?\s*)*\|?\s*$/; const normHeader = (h: string) => h.toLowerCase().replace(/[^a-z0-9]/g, ""); @@ -1062,48 +1122,67 @@ export function hexText(key: string): string { return m ? `${m[1]}, ${m[2]}` : key; } -/** A path's derived Route cell: `3, 4 → 5, 4 (3 hexes)`. */ -export function routeText(hexes: string[]): string { - if (!hexes.length) return ""; - const n = `(${hexes.length} ${hexes.length === 1 ? "hex" : "hexes"})`; - if (hexes.length === 1) return `${hexText(hexes[0])} ${n}`; - return `${hexText(hexes[0])} → ${hexText(hexes[hexes.length - 1])} ${n}`; -} +/** Route-column warning for a type the palette doesn't have. */ +export const TYPE_NOT_IN_PALETTE = "⚠ type not in palette"; +/** Route-column warning for a path with no type (made from a Path routes row alone). */ +export const NO_PATH_TYPE = "⚠ no type: fill in Type"; -/** A path's derived Warning cell: set when its type isn't one of the palette's path types. */ -export function pathWarning(p: PathChain, ctx: MapNoteContext = {}): string { +/** A path's type warning: no type, or a type that isn't one of the palette's path types. */ +export function pathWarning(p: Pick, ctx: MapNoteContext = {}): string { + if (!p.typeName.trim()) return NO_PATH_TYPE; const types = ctx.pathTypes; if (!types || !types.length || types.includes(p.typeName)) return ""; - return "⚠ not a path type in the palette"; -} - -function pathTable(paths: PathChain[], existing?: string[], keptRows: string[] = [], ctx: MapNoteContext = {}): string { - const id = (h: string) => PATH_COL_ALIASES[normHeader(h)] ?? ""; - const warnings = paths.map((p) => pathWarning(p, ctx)); - // Warning is only written while some path has one (and then dropped again). - const skip = new Set(warnings.some(Boolean) ? [] : ["warning"]); - const kept = existing?.filter((h) => !skip.has(id(h))); - let headers = columnOrder(PATH_HEADERS, PATH_COL_ALIASES, kept, extraHeaders(paths), skip); - // Derived columns the table didn't have go right after Type (and Route), - // before the long Hexes list, so they can be read at a glance. - if (kept) { - const had = new Set(kept.map(id)); - const added = headers.filter((h) => DERIVED_PATH_COLS.has(id(h)) && !had.has(id(h))); - if (added.length) { - headers = headers.filter((h) => !added.includes(h)); - let at = 0; - headers.forEach((h, i) => { if (id(h) === "type" || DERIVED_PATH_COLS.has(id(h))) at = i + 1; }); - headers.splice(at, 0, ...added); - } + return TYPE_NOT_IN_PALETTE; +} + +/** + * A path's derived Route cell: its main line's ends, the number of forks, + * the hexes it covers (when MapStore could route it), and any warning: + * `0, 8 → 13, 8 · 2 forks · 31 hexes · ⚠ type not in palette`. + */ +export function pathRouteText(p: MapPath, ctx: MapNoteContext = {}): string { + const parts: string[] = []; + const drawn = p.branches.filter((b) => b.anchors.length); + if (!drawn.length) parts.push("no route yet"); + else { + const main = drawn[0].anchors; + parts.push(main.length === 1 ? formatAnchor(main[0]) : `${formatAnchor(main[0])} → ${formatAnchor(main[main.length - 1])}`); + if (drawn.length > 1) parts.push(plural(drawn.length - 1, "fork")); + } + const stats = ctx.pathRoutes?.[pathNameKey(p.name)]; + if (stats && drawn.length) parts.push(plural(stats.hexes, "hex", "hexes")); + const w = pathWarning(p, ctx); + if (w) parts.push(w); + const fb = stats?.fallbacks ?? []; + if (fb.length) { + parts.push(`⚠ no route from ${formatAnchor(fb[0][0])} to ${formatAnchor(fb[0][1])}: drawn straight${fb.length > 1 ? ` (and ${fb.length - 1} more)` : ""}`); + } + return parts.join(" · "); +} + +const pathColId = (h: string) => PATH_COL_ALIASES[normHeader(h)] ?? ""; + +/** The `## Paths` table: one row per path (Route derived). */ +function pathsTable(paths: MapPath[], existing?: string[], keptRows: string[] = [], ctx: MapNoteContext = {}): string { + // Format 4's Warning column is folded into Route now. + const kept = existing?.filter((h) => pathColId(h) !== "warning"); + let headers = columnOrder(PATH_HEADERS, PATH_COL_ALIASES, kept, extraHeaders(paths)); + // Route, if the table didn't have it, goes right after Type, where it can be read at a glance. + if (kept && !kept.some((h) => pathColId(h) === "route")) { + const route = headers.find((h) => pathColId(h) === "route")!; + headers = headers.filter((h) => h !== route); + let at = headers.findIndex((h) => pathColId(h) === "type"); + if (at < 0) at = headers.findIndex((h) => pathColId(h) === "path"); + headers.splice(at + 1, 0, route); } const lines = tableHead(headers); - for (const [i, p] of paths.entries()) { + for (const p of paths) { const cells = headers.map((c) => { - const k = id(c); + const k = pathColId(c); + if (k === "path") return esc(p.name); if (k === "type") return esc(p.typeName); - if (k === "hexes") return p.hexes.join(" "); - if (k === "route") return routeText(p.hexes); - if (k === "warning") return esc(warnings[i]); + if (k === "route") return esc(pathRouteText(p, ctx)); + if (k === "notes") return esc(p.notes); return esc(extraValue(p.extra, c)); }); lines.push(`| ${cells.join(" | ")} |`); @@ -1112,6 +1191,37 @@ function pathTable(paths: PathChain[], existing?: string[], keptRows: string[] = return lines.join("\n"); } +/** A branch's Branch cell: `main` for a path's first, `fork` for the others, unless labelled. */ +function branchLabel(b: PathBranch, i: number): string { + return b.label?.trim() ? b.label : i === 0 ? MAIN_LABEL : FORK_LABEL; +} + +/** The `## Path routes` table: one row per branch with anchors, a path's main line first. */ +function routesTable(paths: MapPath[], existing?: string[], keptRows: string[] = []): string { + const rows = paths.flatMap((p) => p.branches.map((b, i) => ({ p, b, i })).filter((r) => r.b.anchors.length)); + const kept = existing?.filter((h) => !DERIVED_PATH_COLS.has(pathColId(h))); + const headers = columnOrder(ROUTE_HEADERS, PATH_COL_ALIASES, kept, extraHeaders(rows.map((r) => r.b))); + const lines = tableHead(headers); + for (const { p, b, i } of rows) { + const cells = headers.map((c) => { + const k = pathColId(c); + if (k === "path") return esc(p.name); + if (k === "branch") return esc(branchLabel(b, i)); + if (k === "anchors") return formatAnchors(b.anchors); + return esc(extraValue(b.extra, c)); + }); + lines.push(`| ${cells.join(" | ")} |`); + } + lines.push(...keptRows); + return lines.join("\n"); +} + +/** What's left of an old every-hex table once its rows moved: its header and the rows that couldn't be read. */ +function legacyRemainder(existing: string[], keptRows: string[]): string { + const headers = columnOrder(LEGACY_PATH_HEADERS, PATH_COL_ALIASES, existing.filter((h) => !DERIVED_PATH_COLS.has(pathColId(h))), []); + return [...tableHead(headers), ...keptRows].join("\n"); +} + /** [index, header] of the columns not known (first of any repeated name). */ function unknownColumns(t: Table): [number, string][] { const seen = new Set(); @@ -1190,32 +1300,252 @@ function readHexTable(lines: string[], t: Table | null): TableRead { - const out: PathChain[] = []; +/** [index, header] of the columns a reader doesn't use (not `used`, not derived), first of any repeated name. */ +function otherColumns(t: Table, used: string[]): [number, string][] { + const seen = new Set(); + const out: [number, string][] = []; + t.cols.forEach((c, i) => { + const h = t.headers[i]; + if (!h || used.includes(c) || DERIVED_PATH_COLS.has(c) || seen.has(h.toLowerCase())) return; + seen.add(h.toLowerCase()); + out.push([i, h]); + }); + return out; +} + +/** A path name as stored: trimmed, runs of spaces collapsed (matching ignores case too). */ +const cleanName = (s: string) => s.trim().replace(/\s+/g, " "); + +/** `## Paths` rows → paths without geometry (their branches come from Path routes). */ +function readPathsTable(lines: string[], t: Table | null): TableRead { + const out: MapPath[] = []; const bad: MapNoteProblem[] = []; if (!t) return { rows: out, bad }; - const ti = t.cols.indexOf("type"), hi = t.cols.indexOf("hexes"); - const unknown = unknownColumns(t); + const ni = t.cols.indexOf("path"), ti = t.cols.indexOf("type"), oi = t.cols.indexOf("notes"); + const other = otherColumns(t, ["path", "type", "notes"]); + const seen = new Set(); + for (let i = t.body; i < t.end; i++) { + const line = lines[i]; + if (isFiller(line)) continue; + const c = rowCells(line, t.headers.length); + const no = (reason: string) => bad.push({ where: "Paths", text: line.trim(), reason }); + const name = cleanName(c[ni] ?? ""); + if (!name) { no("no name in the Path column"); continue; } + if (seen.has(pathNameKey(name))) { no(`"${name}" is already a path above (each path needs its own name)`); continue; } + seen.add(pathNameKey(name)); + const p: MapPath = { name, typeName: ti >= 0 ? (c[ti] ?? "").trim() : "", branches: [] }; + const notes = oi >= 0 ? c[oi] : ""; + if (notes) p.notes = notes; + const extra = readExtra(c, other); + if (extra) p.extra = extra; + out.push(p); + } + return { rows: out, bad }; +} + +interface RouteRow { + name: string; + label?: string; + anchors: HexKey[]; + extra?: Record; +} + +/** `## Path routes` rows. A row is read whole or not at all. */ +function readRoutesTable(lines: string[], t: Table | null): TableRead { + const out: RouteRow[] = []; + const bad: MapNoteProblem[] = []; + if (!t) return { rows: out, bad }; + const ni = t.cols.indexOf("path"), bi = t.cols.indexOf("branch"), ai = t.cols.indexOf("anchors"); + const other = otherColumns(t, ["path", "branch", "anchors"]); + for (let i = t.body; i < t.end; i++) { + const line = lines[i]; + if (isFiller(line)) continue; + const c = rowCells(line, t.headers.length); + const no = (reason: string) => bad.push({ where: "Path routes", text: line.trim(), reason }); + const name = cleanName(c[ni] ?? ""); + if (!name) { no("no path name in the Path column"); continue; } + const r = parseAnchors(c[ai] ?? ""); + if ("error" in r) { no(`Anchors: ${r.error} (write them like 3, 4 → 9, 4)`); continue; } + const row: RouteRow = { name, anchors: r.anchors }; + const label = bi >= 0 ? (c[bi] ?? "").trim() : ""; + if (label) row.label = label; + const extra = readExtra(c, other); + if (extra) row.extra = extra; + out.push(row); + } + return { rows: out, bad }; +} + +/** One old every-hex row: its chain, and its name if the table had a Path column. */ +interface LegacyRow { + chain: PathChain; + name?: string; +} + +/** An old `Type | Hexes` table (formats 2–4, or pasted). */ +function readLegacyTable(lines: string[], t: Table | null): TableRead { + const out: LegacyRow[] = []; + const bad: MapNoteProblem[] = []; + if (!t) return { rows: out, bad }; + const ti = t.cols.indexOf("type"), hi = t.cols.indexOf("hexes"), ni = t.cols.indexOf("path"), oi = t.cols.indexOf("notes"); + const other = otherColumns(t, ["type", "hexes", "path", "notes"]); for (let i = t.body; i < t.end; i++) { const line = lines[i]; if (isFiller(line)) continue; const c = rowCells(line, t.headers.length); const no = (reason: string) => bad.push({ where: "Paths", text: line.trim(), reason }); - const type = c[ti] ?? ""; + const type = ti >= 0 ? c[ti] ?? "" : ""; const tokens = (c[hi] ?? "").split(/[\s,;→>]+/).filter(Boolean); const hexes = tokens.map(parseHexKey); if (!type) { no("no path type in the Type column"); continue; } if (!tokens.length) { no("no hexes in the Hexes column"); continue; } const badTok = tokens.find((_, j) => !hexes[j]); if (badTok !== undefined) { no(`"${badTok}" isn't a hex (list them like 3_4 4_4 5_4)`); continue; } - const p: PathChain = { typeName: type, hexes: hexes as string[] }; - const extra = readExtra(c, unknown); - if (extra) p.extra = extra; - out.push(p); + const chain: PathChain = { typeName: type, hexes: hexes as string[] }; + const extra = readExtra(c, other) ?? {}; + // legacyChainsToPaths makes a Notes column the path's notes. + if (oi >= 0 && c[oi]) extra[t.headers[oi]] = c[oi]; + if (Object.keys(extra).length) chain.extra = extra; + const row: LegacyRow = { chain }; + const name = ni >= 0 ? cleanName(c[ni] ?? "") : ""; + if (name) row.name = name; + out.push(row); } return { rows: out, bad }; } +/** + * The paths a note holds: its Paths rows in order, each with the branches of + * its Path routes rows (matched by name, ignoring case and spacing); then + * paths that only have routes rows (no type yet); then old every-hex rows, + * one dense-anchor path each. Rows of one path may be anywhere in the + * routes table: the first whose Branch is `main` (else its first row) is the + * main line, the others keep their order. + */ +function assemblePaths(entity: MapPath[], routes: RouteRow[], legacy: LegacyRow[]): { paths: MapPath[]; legacyNames: string[] } { + const paths = entity.map((p) => ({ ...p, branches: [] as PathBranch[] })); + const byKey = new Map(paths.map((p) => [pathNameKey(p.name), p])); + const groups = new Map(); + for (const r of routes) { + const k = pathNameKey(r.name); + const g = groups.get(k); + if (g) g.push(r); else groups.set(k, [r]); + } + for (const [k, rows] of groups) { + let main = rows.findIndex((r) => r.label?.toLowerCase() === MAIN_LABEL); + if (main < 0) main = 0; + const ordered = [rows[main], ...rows.filter((_, i) => i !== main)]; + const branches = ordered.map((r, i): PathBranch => { + const b: PathBranch = { anchors: r.anchors }; + const l = r.label?.toLowerCase(); + // `main` on the first row and `fork` on the others are what's written anyway. + if (r.label && !(i === 0 && l === MAIN_LABEL) && !(i > 0 && l === FORK_LABEL)) b.label = r.label; + if (r.extra) b.extra = r.extra; + return b; + }); + let p = byKey.get(k); + if (!p) { + p = { name: rows[0].name, typeName: "", branches: [] }; + byKey.set(k, p); + paths.push(p); + } + p.branches = branches; + } + const taken = paths.map((p) => p.name); + const fromLegacy = legacyChainsToPaths(legacy.map((r) => r.chain), [...taken, ...legacy.flatMap((r) => (r.name ? [r.name] : []))]); + const legacyNames: string[] = []; + fromLegacy.forEach((p, i) => { + const asked = legacy[i].name; + const name = asked ? uniquePathName(asked, taken) : p.name; + taken.push(name); + legacyNames.push(name); + paths.push({ ...p, name }); + }); + return { paths, legacyNames }; +} + +/** Where a note's path tables are. */ +interface PathTables { + /** `## Paths` (Path | Type | Route | Notes). */ + entity: Table | null; + /** `## Path routes` (Path | Branch | Anchors). */ + routes: Table | null; + /** Old every-hex tables (Type | Hexes) in the Paths section. */ + legacy: Table[]; + /** Why the path tables can't be read (a section with rows but no header we know). */ + broken: string | null; +} + +type PathTableKind = "entity" | "routes" | "legacy"; + +/** + * Find the path tables: the Paths table and old every-hex tables in the + * `## Paths` section, the routes table in `## Path routes` (or in the Paths + * section). With no such section, the first table anywhere whose header + * clearly is one (Path + Type, Path + Anchors, Type + Hexes). + */ +function findPathTables(lines: string[]): PathTables { + const starts: number[] = []; + for (let i = 0; i < lines.length; i++) { + if (isTableLine(lines[i]) && !SEPARATOR_ROW.test(lines[i]) && (i === 0 || !isTableLine(lines[i - 1]))) starts.push(i); + } + const kindOf = (i: number, strict: boolean): PathTableKind | null => { + const heads = splitRow(lines[i]); + if (heads.some((h) => HEX_COL_ALIASES[normHeader(h)] === "hex")) return null; + // Outside the path sections only a literal "Path" header counts (not "Name"). + const c = heads.map((h) => { + const id = PATH_COL_ALIASES[normHeader(h)] ?? ""; + return strict && id === "path" && normHeader(h) !== "path" ? "" : id; + }); + if (c.includes("path") && c.includes("anchors")) return "routes"; + if (c.includes("hexes") && (c.includes("type") || (!strict && c.includes("path")))) return "legacy"; + if (c.includes("path") && (!strict || c.includes("type"))) return "entity"; + return null; + }; + const pr = sectionRange(lines, "paths"); + const rr = sectionRange(lines, "pathroutes"); + const inR = (i: number, r: [number, number] | null) => !!r && i >= r[0] && i < r[1]; + const prRows = !!pr && sectionHasRows(lines, pr); + const rrRows = !!rr && sectionHasRows(lines, rr); + const at = (i: number | undefined) => (i === undefined ? null : tableAt(lines, i, PATH_COL_ALIASES)); + const first = (kind: PathTableKind, where: [number, number] | null) => starts.find((i) => inR(i, where) && kindOf(i, false) === kind); + const anywhere = (kind: PathTableKind) => starts.find((i) => !inR(i, pr) && !inR(i, rr) && kindOf(i, true) === kind); + + const entity = at(first("entity", pr) ?? (prRows ? undefined : anywhere("entity"))); + let legacy = starts.filter((i) => inR(i, pr) && kindOf(i, false) === "legacy"); + if (!legacy.length && !prRows) { + const l = anywhere("legacy"); + if (l !== undefined) legacy = [l]; + } + const routes = at(first("routes", rr) ?? first("routes", pr) ?? (rrRows ? undefined : anywhere("routes"))); + let broken: string | null = null; + if (prRows && !entity && !legacy.length && !(routes && inR(routes.start, pr))) { + broken = "the Paths table needs a header row with a Path column"; + } else if (rrRows && !(routes && inR(routes.start, rr))) { + broken = "the Path routes table needs a header row with Path and Anchors columns"; + } + return { entity, routes, legacy: legacy.map((i) => at(i)!), broken }; +} + +interface PathRead { + tables: PathTables; + paths: MapPath[]; + legacyNames: string[]; + /** Unreadable rows per table (kept as written). */ + entityBad: MapNoteProblem[]; + routesBad: MapNoteProblem[]; + legacyBad: MapNoteProblem[][]; +} + +function readPaths(lines: string[]): PathRead { + const tables = findPathTables(lines); + const entity = readPathsTable(lines, tables.entity); + const routes = readRoutesTable(lines, tables.routes); + const legacy = tables.legacy.map((t) => readLegacyTable(lines, t)); + const { paths, legacyNames } = assemblePaths(entity.rows, routes.rows, legacy.flatMap((l) => l.rows)); + return { tables, paths, legacyNames, entityBad: entity.bad, routesBad: routes.bad, legacyBad: legacy.map((l) => l.bad) }; +} + // ── callouts ───────────────────────────────────────────────────────────── const HELP_TITLE = /^>\s*\[!info\][+-]?\s*how to edit this (map )?note/i; @@ -1227,15 +1557,18 @@ const OLD_INTRO = "Hexmap World Creator map. Each hex's name, terrain, icons, re const HEX_HELP_LINE_V2 = "> - **Hexes**: one row per hex that has something set. *Hex* is the column and row, like `3_4`. *Terrain* and *Region* use names from the map's palette. *Icon* and *GM icons* are icon file names; separate several with commas. *Submap* is the map that opens from the hex. *Locked* `yes` keeps generators off it."; const HEX_HELP_LINE = "> - **Hexes**: one row per hex that has something set. *Hex* is the column and row, like `3_4`. *Terrain* uses names from the map's palette; *Region* links the region's note. *Icon* and *GM icons* are icon file names; separate several with commas. *Locations* links the maps that open from the hex (towns, dungeons…), separated by commas; *Region map*, when there is one, is the map of the hex itself. *Locked* `yes` keeps generators off it."; -/** Format 2–3's Paths help line, replaced when still word for word. */ +/** Format 2–3's and format 4's Paths help lines, replaced when still word for word. */ const PATH_HELP_LINE_V3 = "> - **Paths**: *Type* is a path type (Road, River…). *Hexes* lists its hexes in order, separated by spaces."; -const PATH_HELP_LINE = "> - **Paths**: *Type* is a path type (Road, River…). *Hexes* lists its hexes in order, separated by spaces. The plugin fills in *Route*, *Warning* and the **Summary** above from the tables; edits to those are replaced."; +const PATH_HELP_LINE_V4 = "> - **Paths**: *Type* is a path type (Road, River…). *Hexes* lists its hexes in order, separated by spaces. The plugin fills in *Route*, *Warning* and the **Summary** above from the tables; edits to those are replaced."; +const PATH_HELP_LINE = "> - **Paths**: one row per path. *Path* is its name, *Type* a path type from the palette (Road, River…), *Notes* are yours. The plugin fills in *Route* and the **Summary** above; edits to those are replaced."; +const ROUTES_HELP_LINE = "> - **Path routes**: where each path goes, as hexes in order like `0, 8 → 9, 8 → 13, 8`; the map draws the way between them. A path's `main` row is its main line; every other row is a fork that leaves the path at its first hex. To rename a path, edit *Path* in both tables."; export const HELP_CALLOUT = [ "> [!info]- How to edit this note", "> This note holds the map's data. Painting on the map updates it, and your edits here update the map.", HEX_HELP_LINE, PATH_HELP_LINE, + ROUTES_HELP_LINE, "> - Columns can be in any order, and you can add your own; they're kept. A row that can't be read is kept as written and flagged.", "> - The properties at the top are the map's settings. Delete one to reset it. Keys starting with `hexmaker-` come from other versions of the plugin; leave them be.", "> - Everything else in this note, like text you write below the tables, is yours: the plugin never changes it.", @@ -1341,8 +1674,10 @@ export function summaryLines(data: MapNoteData, ctx: MapNoteContext = {}): strin if (offPalette.length) { bullets.push(`- **⚠ Not in the palette:** ${offPalette.map(([t, n]) => `${t} (${plural(n, "hex", "hexes")})`).join(", ")}. Add ${offPalette.length === 1 ? "it" : "them"} to the palette, or repaint those hexes.`); } - const badTypes = [...new Set(data.paths.filter((p) => pathWarning(p, ctx)).map((p) => p.typeName))]; + const badTypes = [...new Set(data.paths.filter((p) => p.typeName.trim() && pathWarning(p, ctx)).map((p) => p.typeName))]; if (badTypes.length) bullets.push(`- **⚠ Path types not in the palette:** ${badTypes.join(", ")}`); + const untyped = data.paths.filter((p) => !p.typeName.trim()).map((p) => p.name); + if (untyped.length) bullets.push(`- **⚠ Paths with no type:** ${untyped.join(", ")}. Give ${untyped.length === 1 ? "it a type" : "them types"} in the Paths table.`); const out = [SUMMARY_HEADING, "", SUMMARY_MARKER, "", ...bullets]; if (counts.size || blank) { @@ -1417,9 +1752,8 @@ interface Parsed { front: FmRead; lines: string[]; hexT: Table | null; - pathT: Table | null; hexes: TableRead>; - paths: TableRead; + paths: PathRead; broken: string | null; } @@ -1434,32 +1768,41 @@ function parseParts(content: string, opts: MapNoteReadOptions): Parsed | null { // The generated Summary is never read: tables are looked for without it. const scan = withoutSummary(lines); const h = locateTable(scan, "hexes", HEX_COL_ALIASES, ["hex"], ["hex", "terrain"]); - const p = locateTable(scan, "paths", PATH_COL_ALIASES, ["type", "hexes"], ["type", "hexes"]); + const paths = readPaths(scan); let broken: string | null = null; if (h.broken) broken = "the Hexes table needs a header row with a Hex column"; - else if (p.broken) broken = "the Paths table needs a header row with Type and Hexes columns"; - return { fm, front, lines, hexT: h.table, pathT: p.table, hexes: readHexTable(scan, h.table), paths: readPathTable(scan, p.table), broken }; + else if (paths.tables.broken) broken = paths.tables.broken; + return { fm, front, lines, hexT: h.table, hexes: readHexTable(scan, h.table), paths, broken }; +} + +/** Why a note from a newer build isn't read (MapStore shows it in its notice). */ +export function newerFormatReason(format: number): string { + return `it's in map-note format ${format}, from a newer version of Hexmap World Creator (this version reads up to format ${MAP_NOTE_FORMAT}). Update the plugin to use this map`; } /** * Read a map note. null = not a map note (no frontmatter with - * `hexmaker-map`); `ok: false` = a map note whose tables can't be found, so - * it must not be written over until fixed. + * `hexmaker-map`); `ok: false` = a map note whose tables can't be found, or + * one written by a newer build (its format is newer than MAP_NOTE_FORMAT), + * so it must not be written over. */ export function readMapNote(content: string, opts: MapNoteReadOptions = {}): MapNoteRead | null { const p = parseParts(content, opts); if (!p) return null; + // A newer build may store things this one can't read (format 5's paths + // looked like a broken table to format 4): never read or write over it. + if (p.front.format > MAP_NOTE_FORMAT) return { ok: false, reason: newerFormatReason(p.front.format), newer: p.front.format }; if (p.broken) return { ok: false, reason: p.broken }; - return { - ok: true, - data: { - settings: p.front.settings, - hexes: p.hexes.rows, - paths: p.paths.rows, - format: p.front.format, - problems: [...p.front.problems, ...p.hexes.bad, ...p.paths.bad], - }, + const pr = p.paths; + const data: MapNoteData = { + settings: p.front.settings, + hexes: p.hexes.rows, + paths: pr.paths, + format: p.front.format, + problems: [...p.front.problems, ...p.hexes.bad, ...pr.entityBad, ...pr.legacyBad.flat(), ...pr.routesBad], }; + if (pr.legacyNames.length) data.legacyPaths = pr.legacyNames; + return { ok: true, data }; } /** Parse a map note, or null if it isn't one (or can't be read). */ @@ -1492,14 +1835,79 @@ export function buildMapNote(name: string, data: MapNoteData, ctx: MapNoteContex "", "## Paths", "", - pathTable(data.paths, undefined, [], ctx), + pathsTable(data.paths, undefined, [], ctx), + "", + "## Path routes", + "", + routesTable(data.paths), "", ].join("\n"); } +/** A table's lines followed by its warning callout, when it has rows it couldn't read. */ +function withCallout(table: string, bad: MapNoteProblem[]): string[] { + return [...table.split("\n"), ...(bad.length ? ["", ...problemCallout(bad, "table")] : [])]; +} + +/** + * Write the path tables into `lines` (callouts already stripped): the Paths + * table where it is (else where the first old every-hex table was, else a + * new `## Paths` section at the end), the Path routes table where it is + * (else a new `## Path routes` section after the Paths section). Old + * every-hex tables go once their rows have moved; one with rows that + * couldn't be read keeps just those, as written, with its callout. + */ +function writePathTables(lines: string[], paths: MapPath[], ctx: MapNoteContext): string[] { + const r = readPaths(withoutSummary(lines)); + const { tables } = r; + const edits: { start: number; end: number; with: string[] }[] = []; + const entityLines = withCallout(pathsTable(paths, tables.entity?.headers, r.entityBad.map((b) => b.text), ctx), r.entityBad); + let placed = false; + if (tables.entity) { + edits.push({ start: tables.entity.start, end: tables.entity.end, with: entityLines }); + placed = true; + } + tables.legacy.forEach((t, i) => { + const bad = r.legacyBad[i]; + const rest = bad.length ? withCallout(legacyRemainder(t.headers, bad.map((b) => b.text)), bad) : []; + if (!placed) { + edits.push({ start: t.start, end: t.end, with: [...entityLines, ...(rest.length ? ["", ...rest] : [])] }); + placed = true; + } else edits.push({ start: t.start, end: t.end, with: rest }); + }); + const routeLines = withCallout(routesTable(paths, tables.routes?.headers, r.routesBad.map((b) => b.text)), r.routesBad); + if (tables.routes) edits.push({ start: tables.routes.start, end: tables.routes.end, with: routeLines }); + let out = [...lines]; + for (const e of edits.sort((a, b) => b.start - a.start)) { + let end = e.end; + // A table that goes away takes one of the blank lines around it along. + if (!e.with.length && end < out.length && !out[end].trim() && e.start > 0 && !out[e.start - 1].trim()) end++; + out = [...out.slice(0, e.start), ...e.with, ...out.slice(end)]; + } + if (!placed) out = [...out, "", "## Paths", "", ...entityLines]; + if (!tables.routes) { + const scan = withoutSummary(out); + const pr = sectionRange(scan, "paths"); + let at: number; + if (pr) { + at = pr[1]; + while (at > pr[0] && !out[at - 1].trim()) at--; + } else { + at = findPathTables(scan).entity?.end ?? out.length; + if (at < out.length && !out[at].trim() && PROBLEM_TITLE.test(out[at + 1] ?? "")) { + at++; + while (at < out.length && /^\s*>/.test(out[at])) at++; + } + } + const after = at < out.length && out[at].trim() ? [""] : []; + out = [...out.slice(0, at), "", "## Path routes", "", ...routeLines, ...after, ...out.slice(at)]; + } + return out; +} + /** * Rewrite our parts of an existing map note — owned frontmatter keys, the - * two tables and Hexmaker's callouts — keeping everything else the user + * tables and Hexmaker's callouts — keeping everything else the user * added. Rows and settings that can't be read are kept as written and * listed in a warning callout. A format-1 note gets the help callout once. */ @@ -1521,24 +1929,24 @@ export function updateMapNote(content: string, name: string, data: MapNoteData, .filter((l) => l.trim()); let lines = [...parsed.lines]; - // Tables are rewritten in the column order the user gave them; unreadable rows stay at the end. - const replace = (find: () => Table | null, table: (existing?: string[]) => string, heading: string, problems: MapNoteProblem[], what: string) => { - const t = find(); - const callout = problems.length ? ["", ...problemCallout(problems, what)] : []; - if (t) lines = [...lines.slice(0, t.start), ...table(t.headers).split("\n"), ...callout, ...lines.slice(t.end)]; - else lines = [...lines, "", heading, "", ...table().split("\n"), ...callout]; - }; - const hexBad = parsed.hexes.bad, pathBad = parsed.paths.bad; - replace(() => locateTable(withoutSummary(lines), "hexes", HEX_COL_ALIASES, ["hex"], ["hex", "terrain"]).table, - (ex) => hexTable(data.hexes, data.settings.baseTerrain, ex, hexBad.map((b) => b.text)), "## Hexes", hexBad, "Hexes"); - replace(() => locateTable(withoutSummary(lines), "paths", PATH_COL_ALIASES, ["type", "hexes"], ["type", "hexes"]).table, - (ex) => pathTable(data.paths, ex, pathBad.map((b) => b.text), ctx), "## Paths", pathBad, "Paths"); + // The Hexes table is rewritten in the column order the user gave it; unreadable rows stay at the end. + const hexBad = parsed.hexes.bad; + const t = locateTable(withoutSummary(lines), "hexes", HEX_COL_ALIASES, ["hex"], ["hex", "terrain"]).table; + const hexLines = withCallout(hexTable(data.hexes, data.settings.baseTerrain, t?.headers, hexBad.map((b) => b.text)), hexBad); + if (t) lines = [...lines.slice(0, t.start), ...hexLines, ...lines.slice(t.end)]; + else lines = [...lines, "", "## Hexes", "", ...hexLines]; + lines = writePathTables(lines, data.paths, ctx); // Format 1 → 2: add the help box once (in place of the old one-line intro, if it's still there). // Format 2 → 3: the help box's Hexes line, if it's still the plugin's own words. - // Format 3 → 4: its Paths line (mentions the derived parts), likewise. + // Format 3/4 → 5: its Paths line becomes the Paths and Path routes lines, likewise. if (front.format < MAP_NOTE_FORMAT) { - lines = lines.map((l) => (l.trim() === HEX_HELP_LINE_V2 ? HEX_HELP_LINE : l.trim() === PATH_HELP_LINE_V3 ? PATH_HELP_LINE : l)); + lines = lines.flatMap((l) => { + const s = l.trim(); + if (s === HEX_HELP_LINE_V2) return [HEX_HELP_LINE]; + if (s === PATH_HELP_LINE_V3 || s === PATH_HELP_LINE_V4) return [PATH_HELP_LINE, ROUTES_HELP_LINE]; + return [l]; + }); } if (front.format < READABLE_KEYS_FORMAT && !lines.some((l) => HELP_TITLE.test(l))) { const intro = lines.findIndex((l) => l.trim() === OLD_INTRO); @@ -1564,27 +1972,38 @@ export function updateMapNote(content: string, name: string, data: MapNoteData, export function refreshProblemCallouts(content: string): string { const text = content.replace(/\r\n?/g, "\n"); const p = parseParts(text, {}); - if (!p || p.broken) return content; + if (!p || p.broken || p.front.format > MAP_NOTE_FORMAT) return content; let lines = [...p.lines]; - const insertAfter = (t: Table | null, bad: MapNoteProblem[], what: string) => { - if (!t || !bad.length) return; - lines = [...lines.slice(0, t.end), "", ...problemCallout(bad, what), ...lines.slice(t.end)]; - }; + const pt = p.paths.tables; + const order: [Table | null, MapNoteProblem[]][] = [ + [p.hexT, p.hexes.bad], + [pt.entity, p.paths.entityBad], + ...pt.legacy.map((t, i): [Table, MapNoteProblem[]] => [t, p.paths.legacyBad[i]]), + [pt.routes, p.paths.routesBad], + ]; // later table first so earlier indices stay valid - const order: [Table | null, MapNoteProblem[], string][] = [[p.hexT, p.hexes.bad, "Hexes"], [p.pathT, p.paths.bad, "Paths"]]; order.sort((a, b) => (b[0]?.end ?? -1) - (a[0]?.end ?? -1)); - for (const [t, bad, what] of order) insertAfter(t, bad, what); + for (const [t, bad] of order) { + if (!t || !bad.length) continue; + lines = [...lines.slice(0, t.end), "", ...problemCallout(bad, "table"), ...lines.slice(t.end)]; + } if (p.front.problems.length) lines = [...problemCallout(p.front.problems, "settings"), "", ...lines]; const out = text.slice(0, p.fm!.index + p.fm![0].length) + lines.join("\n"); return out === text ? content : out; } +/** A path as compared by mapNoteKey: everything that's written, in its written form. */ +function pathKey(p: MapPath): unknown[] { + const extra = (e?: Record) => (e && Object.values(e).some(Boolean) ? e : null); + return [p.name, p.typeName, p.notes ?? "", extra(p.extra), p.branches.filter((b) => b.anchors.length).map((b, i) => [branchLabel(b, i), b.anchors, extra(b.extra)])]; +} + /** Comparison key: same key ⇔ same map data (ignores formatting). */ export function mapNoteKey(data: MapNoteData): string { const s = data.settings as Record; const settings = Object.keys(s).filter((k) => s[k] !== undefined && !SKIP_FIELDS.has(k) || k === "gridSize" || k === "gridOffset").sort().map((k) => [k, s[k]]); const hexes = hexRowsToWrite(data.hexes, data.settings.baseTerrain); - return JSON.stringify([settings, hexes, data.paths.map((p) => (p.extra ? [p.typeName, p.hexes, p.extra] : [p.typeName, p.hexes]))]); + return JSON.stringify([settings, hexes, data.paths.map(pathKey)]); } /** Hex-note frontmatter keys that hold map data (they live in the map note). */ diff --git a/src/paths/chainView.ts b/src/paths/chainView.ts new file mode 100644 index 00000000..f04bb45a --- /dev/null +++ b/src/paths/chainView.ts @@ -0,0 +1,267 @@ +/** + * The COMPATIBILITY VIEW between the stored model (MapPath[]: named paths, + * anchors, branches) and the every-hex PathChain[] that code not yet + * switched to paths still reads and edits (map.pathChains: the path tool, + * generators, type rename/delete, exports). Pure, no Obsidian imports. + * + * - buildView: paths → one chain per resolved branch, remembering which + * (path, branch) each chain object came from. + * - reconcile: whatever was done to those chains since (hexes pushed or + * spliced in place, chains added, removed, split, replaced by undo + * snapshots, a type renamed) → the paths, keeping each path's name, + * notes, labels and extra columns. Unchanged branches keep their anchors + * exactly; a changed branch is re-anchored from its new hexes (anchorsOf, + * which the caller makes exact with fromHexes.anchorsFor). + * + * Matching a chain to where it came from, in order: the same object; else + * an unclaimed source with the same type and hexes (undo/redo snapshots are + * clones); else a recently removed branch with the same type and hexes + * (undoing a delete brings its path's name back); else an unclaimed source + * of the same type it shares a step with (a split: the pieces stay branches + * of that path); else it's a new path, named ``, ` 2`… + */ + +import type { HexKey, MapPath, PathBranch, PathChain } from "../types"; +import type { ResolvedBranch } from "./resolve"; +import { uniquePathName } from "./names"; +import { stepsOf } from "./fromHexes"; + +/** Where a handed-out chain came from, and what it held then. */ +export interface ChainSource { + path: string; + branch: number; + typeName: string; + hexes: HexKey[]; +} + +/** A branch that left the paths through the view (for undo). */ +interface RemovedBranch { + path: string; + typeName: string; + notes?: string; + extra?: Record; + branch: PathBranch; + hexes: HexKey[]; +} + +/** How many removed branches are remembered for undo. */ +const REMEMBER_REMOVED = 64; + +export interface PathView { + /** Every chain handed out, with its source as of the last build/reconcile. */ + sources: Map; + /** Branches removed through the view, newest last. */ + removed: RemovedBranch[]; +} + +export function emptyView(): PathView { + return { sources: new Map(), removed: [] }; +} + +/** The chains of resolved branches (one per branch with hexes) and their view. */ +export function buildView(resolved: readonly ResolvedBranch[], removed: RemovedBranch[] = []): { chains: PathChain[]; view: PathView } { + const chains: PathChain[] = []; + const sources = new Map(); + for (const r of resolved) { + if (!r.hexes.length) continue; + const c: PathChain = { typeName: r.typeName, hexes: [...r.hexes] }; + chains.push(c); + sources.set(c, { path: r.path, branch: r.branch, typeName: r.typeName, hexes: [...r.hexes] }); + } + return { chains, view: { sources, removed } }; +} + +const same = (a: readonly HexKey[], b: readonly HexKey[]) => a.length === b.length && a.every((k, i) => k === b[i]); + +function cloneBranch(b: PathBranch): PathBranch { + const out: PathBranch = { anchors: [...b.anchors] }; + if (b.label !== undefined) out.label = b.label; + if (b.extra) out.extra = { ...b.extra }; + return out; +} + +type Claim = + | { kind: "source"; src: ChainSource } + | { kind: "attach"; src: ChainSource } + | { kind: "restore"; dead: RemovedBranch } + | { kind: "new" }; + +interface OutBranch { + branch: PathBranch; + chain?: PathChain; +} + +/** + * Fold edits made to the view's chains back into the paths. Returns the new + * paths (the input is never mutated), the view to keep, and whether the + * paths changed. `anchorsOf(typeName, hexes)` turns a changed chain's hexes + * into anchors that route back to exactly those hexes. + */ +export function reconcile( + paths: readonly MapPath[], + chains: readonly PathChain[], + view: PathView, + anchorsOf: (typeName: string, hexes: HexKey[]) => HexKey[], +): { paths: MapPath[]; view: PathView; changed: boolean } { + const pathIdx = new Map(paths.map((p, i) => [p.name, i])); + const valid = (s: ChainSource) => { + const i = pathIdx.get(s.path); + return i !== undefined && s.branch >= 0 && s.branch < paths[i].branches.length; + }; + const sources = [...view.sources.values()].filter(valid); + const claimed = new Set(); + const removed = [...view.removed]; + const usedDead = new Set(); + const live = chains.filter((c) => c && Array.isArray(c.hexes) && c.hexes.length > 0); + const claims = new Map(); + + // 1. the same object + for (const c of live) { + const s = view.sources.get(c); + if (s && valid(s) && !claimed.has(s)) { + claimed.add(s); + claims.set(c, { kind: "source", src: s }); + } + } + // 2. an unclaimed source with the same type and hexes (snapshot clones) + for (const c of live) { + if (claims.has(c)) continue; + const s = sources.find((x) => !claimed.has(x) && x.typeName === c.typeName && same(x.hexes, c.hexes)); + if (s) { + claimed.add(s); + claims.set(c, { kind: "source", src: s }); + } + } + // 3. a removed branch with the same type and hexes (undo of a delete) + for (const c of live) { + if (claims.has(c)) continue; + for (let i = removed.length - 1; i >= 0; i--) { + const d = removed[i]; + if (!usedDead.has(d) && d.typeName === c.typeName && same(d.hexes, c.hexes)) { + usedDead.add(d); + claims.set(c, { kind: "restore", dead: d }); + break; + } + } + } + // 4. a step shared with an unclaimed source of the same type (split pieces) + for (const c of live) { + if (claims.has(c)) continue; + const steps = stepsOf([c.hexes]); + const s = sources.find((x) => !claimed.has(x) && x.typeName === c.typeName && [...stepsOf([x.hexes])].some((k) => steps.has(k))); + claims.set(c, s ? { kind: "attach", src: s } : { kind: "new" }); + } + + // Branch slots: ":" → the chain now holding it. + const slot = (s: ChainSource) => `${pathIdx.get(s.path)}:${s.branch}`; + const bySlot = new Map(); + const attached = new Map(); + for (const [c, cl] of claims) { + if (cl.kind === "source") bySlot.set(slot(cl.src), c); + else if (cl.kind === "attach") { + // The first piece takes the branch's place, the others follow it. + const k = slot(cl.src); + if (!bySlot.has(k) && !claimed.has(cl.src)) { bySlot.set(k, c); claimed.add(cl.src); } + else attached.set(k, [...(attached.get(k) ?? []), c]); + } + } + const viewed = new Set(sources.map(slot)); + + const changedHexes = (c: PathChain, s: ChainSource | undefined) => !s || !same(s.hexes, c.hexes); + const sourceOf = (c: PathChain): ChainSource | undefined => { + const cl = claims.get(c); + return cl && cl.kind === "source" ? cl.src : undefined; + }; + + const names = paths.map((p) => p.name); + const out: { path: MapPath; branches: OutBranch[] }[] = []; + const newPaths: { path: MapPath; branches: OutBranch[] }[] = []; + const forget = (p: MapPath, b: PathBranch, hexes: HexKey[]) => { + const d: RemovedBranch = { path: p.name, typeName: p.typeName, branch: cloneBranch(b), hexes: [...hexes] }; + if (p.notes !== undefined) d.notes = p.notes; + if (p.extra) d.extra = { ...p.extra }; + removed.push(d); + }; + + paths.forEach((p, i) => { + const branches: OutBranch[] = []; + let hadView = false; + p.branches.forEach((b, j) => { + const k = `${i}:${j}`; + if (viewed.has(k)) hadView = true; + const c = bySlot.get(k); + if (c) { + const src = sourceOf(c); + branches.push({ + branch: changedHexes(c, src) ? { ...cloneBranch(b), anchors: anchorsOf(c.typeName, [...c.hexes]) } : cloneBranch(b), + chain: c, + }); + } else if (viewed.has(k)) { + const src = sources.find((s) => slot(s) === k); + forget(p, b, src?.hexes ?? b.anchors); + } else { + branches.push({ branch: cloneBranch(b) }); // never handed out (no hexes yet): keep + } + for (const extraChain of attached.get(k) ?? []) { + branches.push({ branch: { anchors: anchorsOf(extraChain.typeName, [...extraChain.hexes]) }, chain: extraChain }); + } + }); + if (hadView && !branches.length) return; // every branch was removed: the path goes + const path: MapPath = { ...p, branches: [] }; + if (p.extra) path.extra = { ...p.extra }; + // A type changed on the chains: the path follows when all of them agree, + // else the branches of another type become a path of that type. + const types = new Set(branches.filter((b) => b.chain).map((b) => b.chain!.typeName)); + if (types.size === 1 && !types.has(p.typeName) && branches.every((b) => b.chain)) path.typeName = [...types][0]; + const keep: OutBranch[] = []; + const moved = new Map(); + for (const b of branches) { + const t = b.chain?.typeName; + if (t === undefined || t === path.typeName) keep.push(b); + else moved.set(t, [...(moved.get(t) ?? []), b]); + } + if (keep.length || !hadView) out.push({ path, branches: keep }); + for (const [t, bs] of moved) { + const name = uniquePathName(t, names); + names.push(name); + newPaths.push({ path: { name, typeName: t, branches: [] }, branches: bs }); + } + }); + + // Restored and new chains, in chain order. + for (const c of live) { + const cl = claims.get(c)!; + if (cl.kind === "restore") { + const d = cl.dead; + const host = [...out, ...newPaths].find((o) => o.path.name === d.path && o.path.typeName === d.typeName); + const ob: OutBranch = { branch: cloneBranch(d.branch), chain: c }; + if (host) host.branches.push(ob); + else { + const name = names.includes(d.path) && out.some((o) => o.path.name === d.path) ? uniquePathName(d.path, names) : d.path; + if (!names.includes(name)) names.push(name); + const path: MapPath = { name, typeName: d.typeName, branches: [] }; + if (d.notes !== undefined) path.notes = d.notes; + if (d.extra) path.extra = { ...d.extra }; + newPaths.push({ path, branches: [ob] }); + } + } else if (cl.kind === "new") { + const name = uniquePathName(c.typeName, names); + names.push(name); + newPaths.push({ path: { name, typeName: c.typeName, branches: [] }, branches: [{ branch: { anchors: anchorsOf(c.typeName, [...c.hexes]) }, chain: c }] }); + } + } + const restoredDead = new Set(usedDead); + const keptRemoved = removed.filter((d) => !restoredDead.has(d)).slice(-REMEMBER_REMOVED); + + const result: MapPath[] = []; + const nextSources = new Map(); + for (const o of [...out, ...newPaths]) { + const p: MapPath = { ...o.path, branches: o.branches.map((b) => b.branch) }; + result.push(p); + o.branches.forEach((b, j) => { + if (b.chain) nextSources.set(b.chain, { path: p.name, branch: j, typeName: b.chain.typeName, hexes: [...b.chain.hexes] }); + }); + } + const changed = JSON.stringify(result) !== JSON.stringify(paths); + return { paths: changed ? result : paths.map((p) => p), view: { sources: nextSources, removed: keptRemoved }, changed }; +} diff --git a/src/paths/mapContext.ts b/src/paths/mapContext.ts new file mode 100644 index 00000000..1bf8d4cf --- /dev/null +++ b/src/paths/mapContext.ts @@ -0,0 +1,89 @@ +/** + * A map's routing inputs, built in ONE place so every reader routes a map's + * paths the same way (MapStore's migration and compatibility view now, the + * plugin's paths service and the PNG export later). Pure, no Obsidian imports. + * + * Routes depend only on: orientation, stagger, the map's bounds, the hexes + * whose SHOWN terrain (own, else the map's base terrain) is impassable in + * the map's palette, and each path type's explicit style fields. Nothing + * here looks at a path's or a type's name. + */ + +import type { HexKey } from "../types"; +import { DEFAULT_SEGMENT_STYLE, type RouteContext, type SegmentStyle } from "./router"; +import type { StyleFor } from "./resolve"; + +export interface MapRouteInput { + orientation: "flat" | "pointy"; + stagger: "odd" | "even"; + gridSize: { cols: number; rows: number }; + gridOffset: { x: number; y: number }; + /** Terrain shown on hexes without their own. */ + baseTerrain?: string; + /** Hexes with their own terrain (hex key → terrain name). */ + terrainOf: Iterable<[HexKey, { terrain?: string } | undefined]>; + /** Names of the palette's impassable terrains. */ + impassable: Iterable; +} + +/** The routing context of a map (see the module comment). */ +export function mapRouteContext(m: MapRouteInput): RouteContext { + const bounds = { + minX: m.gridOffset.x, + minY: m.gridOffset.y, + maxX: m.gridOffset.x + m.gridSize.cols - 1, + maxY: m.gridOffset.y + m.gridSize.rows - 1, + }; + const impassable = new Set(m.impassable); + const blocked = new Set(); + if (impassable.size) { + const own = new Map(); + for (const [k, h] of m.terrainOf) own.set(k, h?.terrain || undefined); + const shown = (k: HexKey) => own.get(k) ?? m.baseTerrain; + if (m.baseTerrain && impassable.has(m.baseTerrain)) { + // Every hex without its own terrain shows the base: walk the grid. + for (let y = bounds.minY; y <= bounds.maxY; y++) { + for (let x = bounds.minX; x <= bounds.maxX; x++) { + const k = `${x}_${y}`; + const t = shown(k); + if (t && impassable.has(t)) blocked.add(k); + } + } + } else { + for (const [k, t] of own) { + if (!t || !impassable.has(t)) continue; + const [x, y] = k.split("_").map(Number); + if (x >= bounds.minX && x <= bounds.maxX && y >= bounds.minY && y <= bounds.maxY) blocked.add(k); + } + } + } + return { orientation: m.orientation, stagger: m.stagger, bounds, blocked }; +} + +/** What the style needs of a path type (PA5's explicit fields, when present). */ +export interface PathTypeStyleFields { + name: string; + /** Explicit "go around impassable terrain" (PA5 makes it required). */ + avoidImpassable?: boolean; + /** PA5's auto-route style: "direct" | "winding". */ + autoRoute?: string; +} + +/** + * A StyleFor from a palette's path types, reading ONLY their explicit + * fields: `avoidImpassable` when set, `autoRoute === "winding"`. A field + * that isn't there (palettes from before PA5) takes DEFAULT_SEGMENT_STYLE's + * value, never a guess from the type's name. A type not in the list is + * undefined (the resolver uses DEFAULT_SEGMENT_STYLE). + */ +export function pathTypeStyleFor(types: readonly PathTypeStyleFields[]): StyleFor { + const byName = new Map(); + for (const t of types) { + if (byName.has(t.name)) continue; + byName.set(t.name, { + avoid: typeof t.avoidImpassable === "boolean" ? t.avoidImpassable : DEFAULT_SEGMENT_STYLE.avoid, + winding: t.autoRoute === undefined ? DEFAULT_SEGMENT_STYLE.winding : t.autoRoute === "winding", + }); + } + return (name) => byName.get(name); +} diff --git a/src/paths/mapPaths.ts b/src/paths/mapPaths.ts index 91e65bfe..ab2aed03 100644 --- a/src/paths/mapPaths.ts +++ b/src/paths/mapPaths.ts @@ -7,14 +7,12 @@ import type { MapData, MapPath } from "../types"; import { legacyChainsToPaths } from "./legacy"; /** - * ┌──────────────────────────────────────────────────────────────────────┐ - * │ PHASE-3 ADAPTER. Until the map note stores `MapData.paths` (format │ - * │ with `## Path routes`, built on feat/path-mapnote), a map's paths │ - * │ are its legacy `pathChains`, each chain one path with every hex as │ - * │ an anchor (lossless: it resolves to exactly the old chain). Phase 3 │ - * │ replaces ONLY this function's body with `return map.paths ?? [];`. │ - * └──────────────────────────────────────────────────────────────────────┘ + * A map's stored paths: `MapData.paths`, which MapStore loads from the map + * note (format 5) and keeps in step with edits made through `pathChains`. + * A map the store holds no paths for (its note can't be read, so its paths + * are still only data.json's chains) falls back to those chains, each one + * path with every hex as an anchor (lossless: it resolves to the old chain). */ -export function storedMapPaths(map: Partial>): MapPath[] { - return legacyChainsToPaths(map.pathChains ?? []); +export function storedMapPaths(map: Partial>): MapPath[] { + return map.paths ?? legacyChainsToPaths(map.pathChains ?? []); } diff --git a/src/types.ts b/src/types.ts index f68ee52f..307a08e4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -165,6 +165,18 @@ export interface MapData { rumorsTable?: string; gridSize: { cols: number; rows: number }; gridOffset: { x: number; y: number }; + /** + * The map's paths, as stored (anchors + branches; map note format 5). + * The model: MapStore keeps it, and pathChains in step with it. + */ + paths?: MapPath[]; + /** + * COMPATIBILITY VIEW of `paths` for code not yet switched to them: one + * chain per resolved branch (every hex). MapStore keeps it in step both + * ways: it's rebuilt when `paths` change (load, hand edit, migration), and + * edits made to it (the path tool, generators, type renames) are folded + * back into `paths` on the next save (see src/paths/chainView.ts). + */ pathChains: PathChain[]; showCoords?: boolean; // undefined = true (backwards-compatible) showTerrainIcons?: boolean; // undefined = true diff --git a/tests/compat.test.ts b/tests/compat.test.ts index eca249c5..c6b5f8f5 100644 --- a/tests/compat.test.ts +++ b/tests/compat.test.ts @@ -92,7 +92,7 @@ describe("compat examples", () => { expect(d.hexes.get("6_2")).toEqual({ terrain: "grass", extra: { Notes: "a newer build's column" } }); expect(d.hexes.get("4_5")).toEqual({ terrain: "shallows" }); expect(d.paths.map((p) => p.typeName)).toEqual(["Road", "River"]); - expect(d.paths[1].hexes[0]).toBe("4_0"); + expect(d.paths[1].branches[0].anchors[0]).toBe("4_0"); }); it("map note rewritten by this build keeps its values and the user's text", () => { @@ -153,21 +153,44 @@ describe("map note formats", () => { expect(d.settings).toMatchObject({ displayName: "Compat Example", baseTerrain: "grass", parent: { map: "compat-world", hex: "3_4" }, originX: 2 }); expect(d.hexes.get("3_4")).toEqual({ name: "Glass Wastes", terrain: "hills", icon: "bw-castle.png", gmIcons: ["skull.png", "trap.png"], region: "Basin", regionMap: "compat-example-region", locations: ["compat-example-3-4", "compat-example-inn"], locked: true }); expect(d.hexes.get("6_2")).toEqual({ terrain: "grass", extra: { Notes: "a newer build's column" } }); + // Old every-hex rows read as paths with every hex an anchor, named after their type. expect(d.paths).toEqual([ - { typeName: "Road", hexes: Array.from({ length: 14 }, (_, x) => `${x}_8`) }, - { typeName: "River", hexes: ["4_0", "4_1", "4_2", "4_3", "4_4", "4_5"] }, + { name: "Road", typeName: "Road", branches: [{ anchors: Array.from({ length: 14 }, (_, x) => `${x}_8`) }] }, + { name: "River", typeName: "River", branches: [{ anchors: ["4_0", "4_1", "4_2", "4_3", "4_4", "4_5"] }] }, ]); + expect(d.legacyPaths).toEqual(["Road", "River"]); }); - it("format 3 converts once: the derived Summary and Route column are added, nothing else changes", () => { + it("format 4 reads every setting, hex and path (derived Route and Warning ignored, Notes kept)", () => { + const d = parseMapNote(read(formatsDir, "format-4.md")); + if (!d) throw new Error("format 4 note didn't parse"); + expect(d.format).toBe(4); + expect(d.problems).toEqual([]); + expect(d.settings).toMatchObject({ displayName: "Compat Example", baseTerrain: "grass", parent: { map: "compat-world", hex: "3_4" }, originX: 2 }); + expect(d.hexes.get("3_4")).toEqual({ name: "Glass Wastes", terrain: "hills", icon: "bw-castle.png", gmIcons: ["skull.png", "trap.png"], region: "Basin", regionMap: "compat-example-region", locations: ["compat-example-3-4", "compat-example-inn"], locked: true }); + expect(d.paths.map((p) => [p.name, p.typeName, p.branches.map((b) => b.anchors.join(" ")), p.notes ?? ""])).toEqual([ + ["Road", "Road", ["0_8 1_8 2_8 3_8 4_8 5_8 6_8 7_8 8_8 9_8 10_8 11_8 12_8 13_8"], "Paved as far as Saltmere."], + ["River", "River", ["4_0 4_1 4_2 4_3 4_4 4_5"], ""], + ["Road 2", "Road", ["9_8 9_9 9_10 9_11"], ""], + ["Old Track", "Old Track", ["2_2 3_2 4_2 5_1 6_1"], ""], + ["Road 3", "Road", ["12_2"], ""], + ]); + expect(d.legacyPaths).toEqual(["Road", "River", "Road 2", "Old Track", "Road 3"]); + }); + + it("format 3 converts once: the derived Summary is added, paths move to Paths + Path routes, nothing else changes", () => { const text = read(formatsDir, "format-3.md").replace("\n## Hexes", "\nMy notes.\n\n## Hexes"); const d = parseMapNote(text)!; const out = updateMapNote(text, "compat-example", d); expect(out).toMatch(new RegExp(`^hexmaker-map: ${MAP_NOTE_FORMAT}$`, "m")); expect(out).toContain("My notes.\n\n## Summary\n"); - expect(out).toContain("| Type | Route | Hexes |"); - expect(out).toContain("| River | 4, 0 → 4, 5 (6 hexes) | 4_0 4_1 4_2 4_3 4_4 4_5 |"); + expect(out).toContain("| Path | Type | Route | Notes |"); + expect(out).toContain("| River | River | 4, 0 → 4, 5 | |"); + expect(out).toContain("## Path routes\n\n| Path | Branch | Anchors |"); + expect(out).toContain("| River | main | 4, 0 → 4, 1 → 4, 2 → 4, 3 → 4, 4 → 4, 5 |"); + expect(out).not.toContain("| Type | Hexes |"); expect(out).toContain("The plugin fills in *Route*"); + expect(out).toContain("edit *Path* in both tables"); // The Hexes table is untouched. const hexTable = (s: string) => s.slice(s.indexOf("| Hex |"), s.indexOf("## Paths")); expect(hexTable(out)).toBe(hexTable(text)); diff --git a/tests/compat/examples.ts b/tests/compat/examples.ts index a4ba9043..b41dc3f9 100644 --- a/tests/compat/examples.ts +++ b/tests/compat/examples.ts @@ -9,6 +9,7 @@ import { cellKey, learnModel, modelToMarkdown, pathRouteKey, solve, type HexWfcM import { VERSION_KEY } from "../../src/compat"; import { serializeSave } from "../../src/worldgen/saveFormat"; import { buildMapNote, type HexData } from "../../src/maps/mapNote"; +import { legacyChainsToPaths } from "../../src/paths/legacy"; import type { MapData } from "../../src/types"; const COLS = 14, ROWS = 10, SEED = 7; @@ -134,6 +135,7 @@ export function exampleMapNote(version: string): string { return buildMapNote("compat-example", { settings, hexes, - paths: paths.map((p) => ({ typeName: p.type, hexes: p.hexes })), + // Every hex an anchor (what an older table converts to); the version snapshot pins this. + paths: legacyChainsToPaths(paths.map((p) => ({ typeName: p.type, hexes: p.hexes }))), }); } diff --git a/tests/fixtures/compat/map-note-formats/format-4.md b/tests/fixtures/compat/map-note-formats/format-4.md new file mode 100644 index 00000000..fec16ebb --- /dev/null +++ b/tests/fixtures/compat/map-note-formats/format-4.md @@ -0,0 +1,97 @@ +--- +hexmaker-map: 4 +display-name: Compat Example +palette: Default +cols: 14 +rows: 10 +offset-x: 0 +offset-y: 0 +stagger: odd +base-terrain: grass +swatch-terrain: forest +weather-table: "[[world/tables/weather]]" +created-with: "1.5.6" +show-coords: true +show-gm-layer: false +hidden-link-badges: [Quests] +grid-display-scale-x: 1.0123 +grid-display-offset-x: -3.3333 +parent: "[[_compat-world]]" +parent-hex: 3, 4 +world: w-compat +world-x: 1 +world-y: -1 +background-image: "[[world/maps/compat example.png]]" +background-x: 12.5 +background-y: -4 +background-scale: 1.25 +background-rotation: 0 +background-opacity: 0.8 +biome: preset-valley +biome-from: [preset-deep-forest] +hexmaker-origin-x: 2 +--- +# Compat Example + +> [!info]- How to edit this note +> This note holds the map's data. Painting on the map updates it, and your edits here update the map. +> - **Hexes**: one row per hex that has something set. *Hex* is the column and row, like `3_4`. *Terrain* uses names from the map's palette; *Region* links the region's note. *Icon* and *GM icons* are icon file names; separate several with commas. *Locations* links the maps that open from the hex (towns, dungeons…), separated by commas; *Region map*, when there is one, is the map of the hex itself. *Locked* `yes` keeps generators off it. +> - **Paths**: *Type* is a path type (Road, River…). *Hexes* lists its hexes in order, separated by spaces. The plugin fills in *Route*, *Warning* and the **Summary** above from the tables; edits to those are replaced. +> - Columns can be in any order, and you can add your own; they're kept. A row that can't be read is kept as written and flagged. +> - The properties at the top are the map's settings. Delete one to reset it. Keys starting with `hexmaker-` come from other versions of the plugin; leave them be. +> - Everything else in this note, like text you write below the tables, is yours: the plugin never changes it. + +## Summary + +*Generated by Hexmaker from the tables below and the map's palette. Edits here are replaced.* + +- **Palette:** [[world/palettes/Default]] +- **Hexes:** 0…13 × 0…9 (14×10) +- **Base terrain:** grass (hexes not listed in the table) +- **Regions:** [[Basin]] (1 hex) +- **Maps from hexes:** 1 region map, 2 locations +- **Paths:** 5 +- **⚠ Path types not in the palette:** Old Track + +| Terrain | Hexes | +| --- | --- | +| grass (base) | 119 | +| shallows | 20 | +| hills | 1 | + +## Hexes + +| Hex | Name | Terrain | Icon | GM icons | Region | Region map | Locations | Locked | Notes | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 6_2 | | grass | | | | | | | a newer build's column | +| 3_3 | | shallows | | | | | | | | +| 4_3 | | shallows | | | | | | | | +| 5_3 | | shallows | | | | | | | | +| 2_4 | | shallows | | | | | | | | +| 3_4 | Glass Wastes | hills | bw-castle.png | skull.png, trap.png | [[Basin]] | [[_compat-example-region]] | [[_compat-example-3-4]], [[_compat-example-inn]] | yes | | +| 4_4 | | shallows | | | | | | | | +| 5_4 | | shallows | | | | | | | | +| 6_4 | | shallows | | | | | | | | +| 2_5 | | shallows | | | | | | | | +| 3_5 | | shallows | | | | | | | | +| 4_5 | | shallows | | | | | | | | +| 5_5 | | shallows | | | | | | | | +| 6_5 | | shallows | | | | | | | | +| 2_6 | | shallows | | | | | | | | +| 3_6 | | shallows | | | | | | | | +| 4_6 | | shallows | | | | | | | | +| 5_6 | | shallows | | | | | | | | +| 6_6 | | shallows | | | | | | | | +| 3_7 | | shallows | | | | | | | | +| 4_7 | | shallows | | | | | | | | +| 5_7 | | shallows | | | | | | | | + +## Paths + +| Type | Route | Warning | Hexes | Notes | +| --- | --- | --- | --- | --- | +| Road | 0, 8 → 13, 8 (14 hexes) | | 0_8 1_8 2_8 3_8 4_8 5_8 6_8 7_8 8_8 9_8 10_8 11_8 12_8 13_8 | Paved as far as Saltmere. | +| River | 4, 0 → 4, 5 (6 hexes) | | 4_0 4_1 4_2 4_3 4_4 4_5 | | +| Road | 9, 8 → 9, 11 (4 hexes) | | 9_8 9_9 9_10 9_11 | | +| Old Track | 2, 2 → 6, 1 (5 hexes) | ⚠ not a path type in the palette | 2_2 3_2 4_2 5_1 6_1 | | +| Road | 12, 2 (1 hex) | | 12_2 | | diff --git a/tests/fixtures/compat/map-note-formats/parser-format-4.ts b/tests/fixtures/compat/map-note-formats/parser-format-4.ts new file mode 100644 index 00000000..51a0cdd1 --- /dev/null +++ b/tests/fixtures/compat/map-note-formats/parser-format-4.ts @@ -0,0 +1,1606 @@ +// FROZEN: the map-note reader/writer of format 4 (src/maps/mapNote.ts at 2e65608), +// kept so tests can check how a format-4 build reads notes written by newer +// builds (it must see them as broken, never as wrong paths). Never edit. + +import type { MapData, PathChain, RegionSettings } from "../../../../src/types"; + +/** + * Map notes: one note per map ("hexes//_.md") holding the map's + * settings in frontmatter, every hex's map data in a "Hexes" table, and its + * roads/rivers in a "Paths" table. Hex notes only hold prose and links — + * a hex without content has no note at all. + * + * --- + * hexmaker-map: 2 + * palette: Default + * cols: 38 + * rows: 25 + * parent: "[[_the-north]]" + * parent-hex: 3, 4 + * … + * --- + * # The Coast + * > [!info]- How to edit this note + * ## Hexes + * | Hex | Name | Terrain | Icon | GM icons | Region | Locations | Locked | + * | 3_4 | Glass Wastes | dunes | | | [[Basin]] | [[_saltmere]], [[_old-mine]] | | + * ## Paths + * | Type | Hexes | + * | Road | 3_4 4_4 5_4 | + * + * Written to be read and edited by people (#42): + * - every setting is one plain key (no JSON); other notes and images are + * wikilinks, so Obsidian keeps them right when files are renamed; + * - reading is forgiving: Obsidian's Properties panel rewriting keys as + * block YAML, header case/spacing, column order, a missing `|---|` row, + * `3, 4` for `3_4`, yes/true/x/✓ … all read, and the next write puts them + * back in the usual form without changing any value; + * - nothing a person typed is dropped: rows and settings that can't be read + * stay exactly as written and are listed in a warning callout (cleared + * once fixed); text outside the tables, and frontmatter keys this file + * doesn't own, are the user's and survive rewrites; + * - notes written before this format (`hexmaker-map: 1`, JSON values) still + * read and are converted on their next write (MapStore backs them up + * first). The 1.5.6 compat fixture pins the old form; + * - format 2 had one "Submap" column and plain region names. Format 3 splits + * the submap into "Region map" (at most one: the hex's own region map, + * written only once some hex has one) and "Locations" (any number), and + * writes maps and regions as wikilinks (`[[_saltmere]]`, `[[Basin]]`) so + * renaming a note through Obsidian updates them. Plain names still read; + * a Submap column reads as Locations. Both are converted on the next write + * (backed up first, like format 1). tests/fixtures/compat/map-note-formats + * pins format 2; + * - format 4 adds derived parts, written from the data and never read back: + * a "## Summary" section (palette, extent, base terrain, a terrain legend + * with counts, regions, terrains not in the palette…) between the help + * box and the Hexes table, and Route / Warning columns in Paths. They're + * regenerated on every write: edits to them are replaced, and a deleted + * Summary comes back. The Summary is only ever recognised by its + * "Generated by Hexmaker" line, and only its own lines (that line, + * bullets, the legend table) are replaced: anything else typed in there + * stays. map-note-formats/format-3.md pins format 3. + */ + +export const MAP_NOTE_MARKER = "hexmaker-map"; +/** Format written by this build (the marker's value). 1 = JSON values, + * 2 = readable keys + one Submap column, 3 = Region map + Locations, links, + * 4 = derived Summary + Route/Warning path columns. */ +export const MAP_NOTE_FORMAT = 4; +/** First format with one readable key per setting (deleting a key resets it). */ +export const READABLE_KEYS_FORMAT = 2; + +/** Map data for one hex. Absent fields = nothing set. */ +export interface HexData { + /** The hex's own name ("Glass Wastes"): shown on the map, and its note's alias. */ + name?: string; + terrain?: string; + icon?: string; + gmIcons?: string[]; + region?: string; + /** The hex's Region map (at most one). Mirrors that map's own `parent` + + * `submapKind: region`, which win when they disagree (MapStore repairs). */ + regionMap?: string; + /** Location maps opened from this hex (towns, dungeons…), in the user's order. */ + locations?: string[]; + locked?: boolean; + /** + * Cells of Hexes-table columns this build doesn't know (header → value), + * in the table's column order. Kept opaque and written back unchanged, so + * an older build rewriting the note never drops a newer build's column. + */ + extra?: Record; +} + +/** Settings stored in a map note: MapData minus its name, paths and the + * per-session viewport (which stays in data.json). */ +export type MapSettings = Omit; + +/** Something in a map note that couldn't be read. It stays in the note as written. */ +export interface MapNoteProblem { + /** "Hexes" / "Paths" table, or "settings" (frontmatter). */ + where: "Hexes" | "Paths" | "settings"; + /** The row or `key: value` line, as written. */ + text: string; + reason: string; + /** Settings: the frontmatter key (kept as written on rewrite). */ + key?: string; + /** Settings: the MapData field it would have set (not reset while broken). */ + field?: string; +} + +export interface MapNoteData { + settings: Partial; + hexes: Map; + paths: PathChain[]; + /** Format the note was written in (MAP_NOTE_FORMAT, or 1 for older notes). */ + format?: number; + /** What couldn't be read (rows, settings). Empty/absent = all of it read. */ + problems?: MapNoteProblem[]; +} + +export interface MapNoteReadOptions { + /** Resolve a wikilink target to a vault path (metadataCache), if it can. */ + resolveLink?: (link: string) => string | undefined; +} + +export type MapNoteRead = { ok: true; data: MapNoteData } | { ok: false; reason: string }; + +/** + * What the derived parts (Summary, Paths' Route/Warning) need from outside + * the note. All optional: without them the checks are skipped, never guessed. + */ +export interface MapNoteContext { + /** Terrain names in the map's palette. Empty/absent: terrains aren't checked. */ + paletteTerrains?: string[]; + /** Path type names the map's palette has (plugin.getMapPathTypes). Empty/absent: not checked. */ + pathTypes?: string[]; + /** The palette's note (vault path without .md), for the Summary's link. */ + paletteNote?: string; +} + +// ── loose YAML ─────────────────────────────────────────────────────────── +// +// Frontmatter is read with a forgiving YAML subset instead of a strict +// parser: one typo must not make the whole map unreadable, and scalar +// typing stays ours (strict YAML 1.1 would read the hex `3_4` as 34). + +type YNode = + | { t: "s"; v: string; q: boolean } + | { t: "l"; v: YNode[] } + | { t: "m"; v: Map }; + +interface YBlock { + /** Top-level key, or null for comments. */ + key: string | null; + lines: string[]; +} + +const indentOf = (l: string) => /^[ \t]*/.exec(l)![0].replace(/\t/g, " ").length; +const isBlankOrComment = (l: string) => !l.trim() || /^\s*#/.test(l); +const KEY_LINE = /^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s#:"'][^:]*?)\s*:(?:\s+(.*?))?\s*$/; + +function unquoteKey(k: string): string { + if (/^".*"$/.test(k)) { try { return JSON.parse(k) as string; } catch { return k.slice(1, -1); } } + if (/^'.*'$/.test(k)) return k.slice(1, -1).replace(/''/g, "'"); + return k; +} + +/** Split frontmatter text into top-level blocks (a key line plus its indented/list lines). */ +function yamlBlocks(src: string): YBlock[] { + const out: YBlock[] = []; + for (const line of src.split("\n")) { + const top = !/^\s/.test(line) && line.trim() !== ""; + const kv = top && !line.startsWith("#") && !line.startsWith("-") ? KEY_LINE.exec(line) : null; + if (kv) out.push({ key: unquoteKey(kv[1]), lines: [line] }); + else if (out.length && (!top || line.startsWith("-"))) out[out.length - 1].lines.push(line); + else out.push({ key: null, lines: [line] }); + } + return out; +} + +/** Split `a, "b, c", [d, e]` at top-level commas. */ +function splitFlow(s: string): string[] { + const out: string[] = []; + let depth = 0, quote = "", cur = ""; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (quote) { + cur += c; + if (c === "\\" && quote === '"') { cur += s[++i] ?? ""; continue; } + if (c === quote) quote = ""; + } else if (c === '"' || c === "'") { quote = c; cur += c; } + else if (c === "[" || c === "{") { depth++; cur += c; } + else if (c === "]" || c === "}") { depth--; cur += c; } + else if (c === "," && depth === 0) { out.push(cur.trim()); cur = ""; } + else cur += c; + } + if (cur.trim()) out.push(cur.trim()); + return out; +} + +/** Index of the first `:` outside quotes/brackets (a flow-map key separator). */ +function flowColon(s: string): number { + let depth = 0, quote = ""; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (quote) { if (c === "\\") i++; else if (c === quote) quote = ""; } + else if (c === '"' || c === "'") quote = c; + else if (c === "[" || c === "{") depth++; + else if (c === "]" || c === "}") depth--; + else if (c === ":" && depth === 0) return i; + } + return -1; +} + +function scalarNode(raw: string): YNode { + let t = raw.trim(); + if (t.startsWith('"')) { + try { return { t: "s", v: JSON.parse(t) as string, q: true }; } catch { /* below */ } + const end = t.lastIndexOf('"'); + if (end > 0) { try { return { t: "s", v: JSON.parse(t.slice(0, end + 1)) as string, q: true }; } catch { /* below */ } } + return { t: "s", v: t.replace(/^"|"$/g, ""), q: true }; + } + if (t.startsWith("'")) return { t: "s", v: t.replace(/^'|'$/g, "").replace(/''/g, "'"), q: true }; + if (t.startsWith("[") && !t.startsWith("[[") && t.endsWith("]")) { + return { t: "l", v: splitFlow(t.slice(1, -1)).map(scalarNode) }; + } + if (t.startsWith("{") && t.endsWith("}")) { + const m = new Map(); + for (const item of splitFlow(t.slice(1, -1))) { + const c = flowColon(item); + if (c < 0) continue; + m.set(unquoteKey(item.slice(0, c).trim()), scalarNode(item.slice(c + 1))); + } + return { t: "m", v: m }; + } + // "foo # comment" is YAML for "foo"; "Thornwood #2" keeps its "#2". + t = t.replace(/\s+#\s.*$/, ""); + return { t: "s", v: t, q: false }; +} + +/** Parse a nested block (the lines under a `key:` with no inline value). */ +function blockNode(lines: string[]): YNode | undefined { + const body = lines.filter((l) => !isBlankOrComment(l)); + if (!body.length) return undefined; + const ind = Math.min(...body.map(indentOf)); + const atInd = (l: string) => indentOf(l) === ind; + if (body[0].trim().startsWith("-")) { + const items: string[][] = []; + for (const l of body) { + if (atInd(l) && /^\s*-(\s|$)/.test(l)) items.push([l.replace(/^(\s*)-\s?/, "$1 ")]); + else if (items.length) items[items.length - 1].push(l); + } + return { + t: "l", + v: items.map((it) => { + const first = it[0].trim(); + if (KEY_LINE.test(first) && !/^["'[{]/.test(first)) return blockNode(it) ?? { t: "s", v: "", q: false }; + return it.length > 1 ? scalarNode([first, ...it.slice(1).map((l) => l.trim())].join(" ")) : scalarNode(first); + }), + }; + } + const m = new Map(); + let key: string | null = null; + let rest = ""; + let kids: string[] = []; + const finish = () => { + if (key === null) return; + const node = valueNode(rest, kids); + if (node) m.set(key, node); + }; + for (const l of body) { + const kv = atInd(l) ? KEY_LINE.exec(l) : null; + if (kv) { finish(); key = unquoteKey(kv[1]); rest = kv[2] ?? ""; kids = []; } + else kids.push(l); + } + finish(); + return { t: "m", v: m }; +} + +/** The value of `key: rest` followed by `kids` (indented lines). */ +function valueNode(rest: string, kids: string[]): YNode | undefined { + const r = rest.trim(); + if (/^[|>][+-]?\d*$/.test(r)) { + const text = kids.filter((l) => l.trim()).map((l) => l.trim()); + return { t: "s", v: text.join(r.startsWith("|") ? "\n" : " "), q: true }; + } + if (r) { + const more = kids.filter((l) => !isBlankOrComment(l)).map((l) => l.trim()); + return scalarNode(more.length ? [r, ...more].join(" ") : r); + } + return blockNode(kids); +} + +function parseYamlLoose(src: string): { blocks: YBlock[]; values: Map } { + const blocks = yamlBlocks(src); + const values = new Map(); + for (const b of blocks) { + if (b.key === null) continue; + const kv = KEY_LINE.exec(b.lines[0])!; + const node = valueNode(kv[2] ?? "", b.lines.slice(1)); + values.set(b.key, node ?? { t: "s", v: "", q: false }); + } + return { blocks, values }; +} + +/** A plain JS value from a node (YAML core typing for unquoted scalars). */ +function toJs(n: YNode): unknown { + if (n.t === "l") return n.v.map(toJs); + if (n.t === "m") return Object.fromEntries([...n.v].map(([k, v]) => [k, toJs(v)])); + if (n.q) return n.v; + const t = n.v.trim(); + if (/^(true|false)$/i.test(t)) return t.toLowerCase() === "true"; + if (t === "" || t === "~" || /^null$/i.test(t)) return null; + if (/^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.test(t)) return Number(t); + return t; +} + +// ── frontmatter ────────────────────────────────────────────────────────── + +type Kind = "str" | "num" | "bool" | "list" | "note"; + +/** + * Settings given one plain key each: [MapData field, key, kind, old keys]. + * "note" = a vault note path written as a wikilink. + */ +const SIMPLE_KEYS: [keyof MapSettings, string, Kind, string[]?][] = [ + ["displayName", "display-name", "str"], + ["paletteName", "palette", "str"], + ["staggerOffset", "stagger", "str"], + ["baseTerrain", "base-terrain", "str"], + // "Terrain theme" in the map menu: the terrain whose colour marks the map in lists. + ["terrainType", "swatch-terrain", "str", ["terrain-theme"]], + ["weatherTable", "weather-table", "note"], + ["rumorsTable", "rumors-table", "note"], + ["createdWith", "created-with", "str"], + // "region" or "location": this map's role under its parent hex. + ["submapKind", "submap-kind", "str"], + ["showCoords", "show-coords", "bool"], + ["showTerrainIcons", "show-terrain-icons", "bool"], + ["showIconOverrides", "show-icon-overrides", "bool"], + ["showPaths", "show-paths", "bool"], + ["showFactionOverlay", "show-faction-overlay", "bool"], + ["showRegionOverlay", "show-region-overlay", "bool"], + ["showGmLayer", "show-gm-layer", "bool"], + ["showTokens", "show-tokens", "bool"], + ["showLinkBadges", "show-link-badges", "bool"], + ["hiddenLinkBadges", "hidden-link-badges", "list"], + ["linkBadgeSize", "link-badge-size", "str"], + ["showHexNames", "show-hex-names", "bool"], + ["showTokenNames", "show-token-names", "bool"], + ["gridDisplayScale", "grid-display-scale", "num"], + ["gridDisplayScaleX", "grid-display-scale-x", "num"], + ["gridDisplayScaleY", "grid-display-scale-y", "num"], + ["gridDisplayOffsetX", "grid-display-offset-x", "num"], + ["gridDisplayOffsetY", "grid-display-offset-y", "num"], +]; + +const PARENT_KEYS = ["parent", "parent-hex"]; +const WORLD_KEYS = ["world", "world-x", "world-y"]; +const BG_KEYS = ["background-image", "background-x", "background-y", "background-scale", "background-rotation", "background-opacity"]; +const SIZE_KEYS = ["cols", "rows", "offset-x", "offset-y"]; +const BIOME_KEY = "biome"; +const BIOME_FROM_KEY = "biome-from"; +/** Region settings (MapData.regions), one plain key each. */ +const REGION_KEYS = { + shape: "region-shape", + size: "region-size", + blend: "region-blend", + palette: "region-palette", + world: "region-world", + stagger: "region-stagger", + generator: "region-generator", +} as const; +/** Prefix for MapData fields this build doesn't know (`hexmaker-origin-x`). */ +const OTHER_PREFIX = "hexmaker-"; +/** Format 1's one-line JSON catch-all, still read. */ +const LEGACY_EXTRA_KEY = "hexmaker-extra"; +const RESERVED_OTHER = new Set(["map", "extra", "version"]); + +/** Frontmatter keys this file writes or used to write. Every other key is the user's. */ +function ownsKey(key: string): boolean { + return OWNED_KEYS.has(key) || key.startsWith(OTHER_PREFIX); +} +const OWNED_KEYS = new Set([ + MAP_NOTE_MARKER, ...SIZE_KEYS, ...PARENT_KEYS, ...WORLD_KEYS, ...BG_KEYS, BIOME_KEY, BIOME_FROM_KEY, ...Object.values(REGION_KEYS), + ...SIMPLE_KEYS.flatMap(([, k, , old]) => [k, ...(old ?? [])]), +]); + +/** Fields never stored in the note. */ +const SKIP_FIELDS = new Set(["name", "pathChains", "savedViewport", "gridSize", "gridOffset"]); +/** Fields this file writes readably (everything else goes to `hexmaker-*` keys). */ +const KNOWN_FIELDS = new Set([ + ...SIMPLE_KEYS.map(([f]) => f as string), "parent", "world", "backgroundImage", +]); + +/** + * Optional map settings a map note owns: a key deleted by hand resets that + * setting (MapStore). Required ones (palette, size, offset) keep their value. + */ +export const RESETTABLE_FIELDS: readonly string[] = [ + ...SIMPLE_KEYS.map(([f]) => f as string).filter((f) => f !== "paletteName"), + "parent", "world", "backgroundImage", "biome", "regions", +]; + +const FLOWER_CELLS = [7, 19, 37, 61, 91]; + +/** "hex flower" / "rectangle" (also hex, flower, rect, brick, square, block). */ +export function parseRegionShape(raw: string): RegionSettings["footprint"] | null { + const t = raw.trim().toLowerCase(); + if (/hex|flower/.test(t)) return "hex"; + if (/rect|brick|square|block/.test(t)) return "rect"; + return null; +} + +/** + * Region size as written: hex flowers by hex count ("37 hexes", also a + * radius 1–5 or "radius 3"), rectangles as "8x8" (also "8 x 8", "8×8", "8"). + * Returns the radius / side, or a reason it can't be read. + */ +export function parseRegionSize(raw: string, footprint: RegionSettings["footprint"]): number | string { + const t = raw.trim().toLowerCase(); + if (footprint === "hex") { + const r = /radius\s*(\d+)|r\s*=?\s*(\d+)/.exec(t); + if (r) { + const n = Number(r[1] ?? r[2]); + return n >= 1 && n <= 5 ? n : "a hex flower's radius is 1 to 5"; + } + const m = /^(\d+)/.exec(t); + if (!m) return "should be a hex count: 7, 19, 37, 61 or 91"; + const n = Number(m[1]); + if (FLOWER_CELLS.includes(n)) return FLOWER_CELLS.indexOf(n) + 1; + if (n >= 1 && n <= 5) return n; + return "should be a hex count: 7, 19, 37, 61 or 91"; + } + const m = /^(\d+)\s*(?:[x×*]\s*(\d+))?/.exec(t); + if (!m) return "should be a size like 8x8"; + if (m[2] && m[2] !== m[1]) return "regions are square: write it like 8x8"; + return Number(m[1]); +} + +/** Region size as written in the note ("37 hexes", "8x8"). */ +export function regionSizeText(s: Pick): string { + return s.footprint === "hex" ? `${3 * s.size * s.size + 3 * s.size + 1} hexes` : `${s.size}x${s.size}`; +} + +// ── links in table cells (format 3) ────────────────────────────────────── + +/** A name that can sit inside [[…]] unchanged. */ +const linkSafe = (s: string) => !!s && !/[[\]|#^]/.test(s); + +/** A map as a link to its map note (`[[_saltmere]]`), or the plain name if it can't be one. */ +export function mapLinkText(map: string): string { + return linkSafe(map) ? `[[_${map}]]` : map; +} + +/** A region (overlay area) as a link to its note (`[[Basin]]`), or plain. */ +export function regionLinkText(region: string): string { + return linkSafe(region) ? `[[${region}]]` : region; +} + +/** A note name from a cell entry: `[[a/b|c]]` → `b`; plain text stays as written. */ +function noteName(raw: string): string { + const t = raw.trim(); + const m = WIKILINK.exec(t); + if (!m) return t; + return m[1].trim().split("/").pop()!.replace(/\.md$/i, ""); +} + +/** A map name from a cell entry: a link to its map note (`[[_slug]]`), a path, or a name. */ +function mapName(raw: string): string { + const t = raw.trim(); + if (!WIKILINK.test(t)) return t; + return noteName(t).replace(/^_/, ""); +} + +/** Split a list cell at commas / semicolons outside [[ ]]. */ +export function splitLinkList(cell: string): string[] { + const out: string[] = []; + let depth = 0, cur = ""; + for (let i = 0; i < cell.length; i++) { + const c = cell[i]; + if (c === "[" && cell[i + 1] === "[") { depth++; cur += "[["; i++; continue; } + if (c === "]" && cell[i + 1] === "]") { depth = Math.max(0, depth - 1); cur += "]]"; i++; continue; } + if ((c === "," || c === ";") && depth === 0) { if (cur.trim()) out.push(cur.trim()); cur = ""; continue; } + cur += c; + } + if (cur.trim()) out.push(cur.trim()); + return out; +} + +/** Map names in a Locations / Region map cell, in order, without repeats. */ +export function parseMapList(cell: string | undefined): string[] { + if (!cell) return []; + const out: string[] = []; + for (const part of splitLinkList(cell)) { + const n = mapName(part); + if (n && !out.includes(n)) out.push(n); + } + return out; +} + +const kebab = (k: string) => k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()); +const camel = (k: string) => k.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase()); + +/** `hexmaker-` key for an unknown field, reversible by otherField. */ +function otherKey(field: string): string { + const k = /^[a-z][a-zA-Z0-9]*$/.test(field) && camel(kebab(field)) === field ? kebab(field) : field; + return OTHER_PREFIX + (RESERVED_OTHER.has(k) ? `field-${k}` : k); +} +function otherField(key: string): string | null { + let rest = key.slice(OTHER_PREFIX.length); + if (!rest || RESERVED_OTHER.has(rest)) return null; + if (rest.startsWith("field-") && RESERVED_OTHER.has(rest.slice(6))) rest = rest.slice(6); + return /^[a-z][a-z0-9-]*$/.test(rest) ? camel(rest) : rest; +} + +/** Plain when that reads back as the same string, else double-quoted. */ +function yamlString(v: string): string { + const plain = /^[\w][\w .,()/@'-]*$/.test(v) && !v.endsWith(" ") + && !/^(true|false|null|yes|no|on|off|~|[-+]?(\d[\d_.eE+-]*|\.\d+))$/i.test(v); + return plain ? v : JSON.stringify(v); +} + +/** Numbers to at most 4 decimals: settings, not measurements to the atom. */ +const fmtNum = (n: number) => String(Math.round(n * 10000) / 10000); + +function yamlScalar(v: unknown, inList = false): string { + if (typeof v === "number") return fmtNum(v); + if (typeof v === "boolean") return String(v); + if (v === null) return "null"; + const str = typeof v === "string" ? v : JSON.stringify(v); + return inList && /[,[\]{}]/.test(str) ? JSON.stringify(str) : yamlString(str); +} + +/** A YAML value: scalar, `[a, b]` list, or an indented block for objects. */ +function yamlValueLines(key: string, v: unknown, indent = ""): string[] { + if (Array.isArray(v)) { + if (v.every((x) => x === null || typeof x !== "object")) return [`${indent}${key}: [${v.map((x) => yamlScalar(x, true)).join(", ")}]`]; + return [`${indent}${key}: ${JSON.stringify(v)}`]; + } + if (v && typeof v === "object") { + const entries = Object.entries(v as Record).filter(([, x]) => x !== undefined); + if (!entries.length) return [`${indent}${key}: {}`]; + return [`${indent}${key}:`, ...entries.flatMap(([k, x]) => yamlValueLines(/^[\w-]+$/.test(k) ? k : JSON.stringify(k), x, indent + " "))]; + } + return [`${indent}${key}: ${yamlScalar(v)}`]; +} + +const linkTo = (target: string) => JSON.stringify(`[[${target}]]`); +const WIKILINK = /^!?\[\[([^\]|#]*)(?:[#|][^\]]*)?\]\]$/; + +/** A wikilink's target (`[[a/b|c]]` → `a/b`), or the plain text. */ +function unlink(s: string): string { + const m = WIKILINK.exec(s.trim()); + return (m ? m[1] : s).trim(); +} + +/** "x_y" from `3_4`, `3, 4`, `3,4`, `(3, 4)`, `3 4` or a link to the hex note. */ +export function parseHexKey(raw: string): string | null { + let s = unlink(raw); + s = s.slice(s.lastIndexOf("/") + 1).replace(/\.md$/i, ""); + const m = /^\(?\s*(-?\d+)\s*(?:[_,;]|\s)\s*(-?\d+)\s*\)?$/.exec(s); + return m ? `${Number(m[1])}_${Number(m[2])}` : null; +} + +const TRUE_WORDS = /^(yes|true|y|x|on|1|✓|✔|☑)$/i; +const FALSE_WORDS = /^(no|false|n|off|0|-|)$/i; + +interface FmRead { + settings: Partial; + format: number; + problems: MapNoteProblem[]; +} + +function readFrontmatter(src: string, opts: MapNoteReadOptions): FmRead { + const { values } = parseYamlLoose(src); + const out: Record = {}; + const problems: MapNoteProblem[] = []; + const has = (k: string) => values.has(k); + const textOf = (k: string) => { + const n = values.get(k); + return n && n.t === "s" ? n.v.trim() : undefined; + }; + const bad = (key: string, field: string, reason: string) => { + const n = values.get(key); + const shown = n ? (n.t === "s" ? n.v : JSON.stringify(toJs(n))) : ""; + problems.push({ where: "settings", key, field, text: `${key}: ${shown}`, reason }); + }; + const num = (key: string, field: string): number | undefined => { + const t = textOf(key); + if (t === undefined || t === "") { if (has(key) && values.get(key)!.t !== "s") bad(key, field, "should be a number"); return undefined; } + const n = Number(t.replace(/,/g, ".")); + if (Number.isFinite(n)) return n; + bad(key, field, "should be a number"); + return undefined; + }; + const noteLink = (raw: string, ext: string) => { + const target = unlink(raw); + if (!target) return undefined; + const resolved = opts.resolveLink?.(target); + if (resolved) return resolved; + return ext && !target.toLowerCase().endsWith(ext) ? target + ext : target; + }; + const marker = textOf(MAP_NOTE_MARKER); + const format = Number(marker) >= 2 ? Math.floor(Number(marker)) : 1; + + // grid size and offset + const cols = num("cols", "gridSize"), rows = num("rows", "gridSize"); + if (cols !== undefined && rows !== undefined) out.gridSize = { cols, rows }; + const ox = num("offset-x", "gridOffset"), oy = num("offset-y", "gridOffset"); + if (ox !== undefined && oy !== undefined) out.gridOffset = { x: ox, y: oy }; + + for (const [field, key, kind, old] of SIMPLE_KEYS) { + const k = has(key) ? key : old?.find(has); + if (!k) continue; + const node = values.get(k)!; + if (kind === "list") { + if (node.t === "l") out[field] = node.v.map((x) => (x.t === "s" ? x.v.trim() : "")).filter(Boolean); + else if (node.t === "s") { + const t = node.v.trim(); + if (t) out[field] = t.replace(/^\[|\]$/g, "").split(/[,;]/).map((x) => x.trim().replace(/^["']|["']$/g, "")).filter(Boolean); + } else bad(k, field, "should be a list"); + continue; + } + if (node.t !== "s") { bad(k, field, "should be a single value"); continue; } + const t = node.v.trim(); + if (t === "") continue; // `key:` left empty = not set + if (kind === "num") { const n = num(k, field); if (n !== undefined) out[field] = n; } + else if (kind === "bool") { + if (TRUE_WORDS.test(t)) out[field] = true; + else if (FALSE_WORDS.test(t)) out[field] = false; + else bad(k, field, "should be true or false"); + } else if (kind === "note") out[field] = noteLink(t, ".md"); + else if (field === "staggerOffset") { + if (/^(odd|even)$/i.test(t)) out[field] = t.toLowerCase(); + else bad(k, field, "should be odd or even"); + } else if (field === "submapKind") { + if (/^(region|location)$/i.test(t)) out[field] = t.toLowerCase(); + else bad(k, field, "should be region or location"); + } else out[field] = t; + } + + // parent: "[[_map]]" + parent-hex: 3, 4 — or format 1's {"map","hex"} + const parentNode = values.get("parent"); + if (parentNode) { + const legacy = parentNode.t === "m" ? toJs(parentNode) as Record : null; + if (legacy) { + const hex = parseHexKey(typeof legacy.hex === "string" ? legacy.hex : ""); + if (typeof legacy.map === "string" && legacy.map && hex) out.parent = { map: legacy.map, hex }; + else bad("parent", "parent", "should be a link to the parent map's note"); + } else if (parentNode.t === "s" && parentNode.v.trim()) { + let map = unlink(parentNode.v); + map = map.slice(map.lastIndexOf("/") + 1).replace(/\.md$/i, "").replace(/^_/, ""); + const hexRaw = textOf("parent-hex"); + const hex = hexRaw ? parseHexKey(hexRaw) : null; + if (!map) bad("parent", "parent", "should be a link to the parent map's note"); + else if (!hex) bad("parent-hex", "parent", hexRaw ? "isn't a hex (write it like 3, 4)" : "is missing (the hex this map opens from, like 3, 4)"); + else out.parent = { map, hex }; + } + } + + // world: + world-x / world-y — or format 1's {"id","cx","cy"} + const worldNode = values.get("world"); + if (worldNode) { + if (worldNode.t === "m") { + const w = toJs(worldNode) as Record; + const cx = Number(w.cx), cy = Number(w.cy); + if (typeof w.id === "string" && Number.isFinite(cx) && Number.isFinite(cy)) out.world = { id: w.id, cx, cy }; + else bad("world", "world", "should be the world's id"); + } else if (worldNode.t === "s" && worldNode.v.trim()) { + const cx = num("world-x", "world"), cy = num("world-y", "world"); + if (!has("world-x")) bad("world", "world", "needs world-x and world-y"); + else if (!has("world-y")) bad("world", "world", "needs world-y"); + else if (cx !== undefined && cy !== undefined) out.world = { id: worldNode.v.trim(), cx, cy }; + } + } + + // background-image: "[[image.png]]" + background-x/-y/-scale/-rotation/-opacity + const bgNode = values.get("background-image"); + if (bgNode) { + if (bgNode.t === "m") { + const b = toJs(bgNode) as Record; + if (typeof b.path === "string" && b.path) { + const bg: Record = { path: b.path, offsetX: Number(b.offsetX) || 0, offsetY: Number(b.offsetY) || 0, scale: Number(b.scale) || 1 }; + for (const k of ["rotation", "opacity"]) if (b[k] !== undefined && b[k] !== null && Number.isFinite(Number(b[k]))) bg[k] = Number(b[k]); + for (const [k, v] of Object.entries(b)) if (!(k in bg)) bg[k] = v; + out.backgroundImage = bg; + } else bad("background-image", "backgroundImage", "should be a link to the image"); + } else if (bgNode.t === "s" && bgNode.v.trim()) { + const bg: Record = { + path: noteLink(bgNode.v, ""), + offsetX: num("background-x", "backgroundImage") ?? 0, + offsetY: num("background-y", "backgroundImage") ?? 0, + scale: num("background-scale", "backgroundImage") ?? 1, + }; + const rot = num("background-rotation", "backgroundImage"); + if (rot !== undefined) bg.rotation = rot; + const op = num("background-opacity", "backgroundImage"); + if (op !== undefined) bg.opacity = op; + if (!problems.some((p) => p.field === "backgroundImage")) out.backgroundImage = bg; + } + } + + // biome: + biome-from: [a, b] + const gen = textOf(BIOME_KEY); + if (gen) { + const biome: { generator: string; from?: string[] } = { generator: gen }; + const fromNode = values.get(BIOME_FROM_KEY); + const from = !fromNode ? [] : fromNode.t === "l" ? fromNode.v.map((x) => (x.t === "s" ? x.v.trim() : "")).filter(Boolean) + : fromNode.t === "s" ? fromNode.v.replace(/^\[|\]$/g, "").split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).filter(Boolean) : []; + if (from.length) biome.from = from; + out.biome = biome; + } + + // region-shape: hex flower + region-size: 37 hexes (+ blend, palette, …) + const shapeRaw = textOf(REGION_KEYS.shape); + const sizeRaw = textOf(REGION_KEYS.size); + if (shapeRaw || sizeRaw) { + const footprint = shapeRaw ? parseRegionShape(shapeRaw) : null; + if (!footprint) bad(REGION_KEYS.shape, "regions", shapeRaw ? "should be hex flower or rectangle" : "is missing (hex flower or rectangle)"); + else { + const size = sizeRaw ? parseRegionSize(sizeRaw, footprint) : footprint === "hex" ? 3 : 8; + if (typeof size === "string") bad(REGION_KEYS.size, "regions", size); + else { + const r: RegionSettings = { footprint, size }; + const blend = textOf(REGION_KEYS.blend)?.toLowerCase(); + if (blend) { + if (blend === "narrow" || blend === "normal" || blend === "wide") r.blend = blend; + else bad(REGION_KEYS.blend, "regions", "should be narrow, normal or wide"); + } + const pal = textOf(REGION_KEYS.palette); + if (pal) r.palette = noteName(pal); + const world = textOf(REGION_KEYS.world); + if (world) r.worldId = world; + const st = textOf(REGION_KEYS.stagger)?.toLowerCase(); + if (st) { + if (st === "odd" || st === "even") r.stagger = st; + else bad(REGION_KEYS.stagger, "regions", "should be odd or even"); + } + const gen = textOf(REGION_KEYS.generator); + if (gen) r.generator = gen; + if (!problems.some((p) => p.field === "regions")) out.regions = r; + } + } + } + + // fields this build doesn't know: hexmaker- keys, then format 1's JSON catch-all + for (const [k, node] of values) { + if (!k.startsWith(OTHER_PREFIX) || k === MAP_NOTE_MARKER || k === LEGACY_EXTRA_KEY) continue; + const field = otherField(k); + if (field && !(field in out)) out[field] = toJs(node); + } + const legacy = values.get(LEGACY_EXTRA_KEY); + if (legacy && legacy.t === "m") { + for (const [k, v] of Object.entries(toJs(legacy) as Record)) if (!(k in out)) out[k] = v; + } + return { settings: out, format, problems }; +} + +function frontmatterLines(settings: Partial, keep: Set = new Set()): string[] { + const s = settings as Record; + const lines = [`${MAP_NOTE_MARKER}: ${MAP_NOTE_FORMAT}`]; + const put = (key: string, v: unknown) => { if (v !== undefined && !keep.has(key)) lines.push(...yamlValueLines(key, v)); }; + put("display-name", s.displayName); + put("palette", s.paletteName); + if (settings.gridSize) { put("cols", settings.gridSize.cols); put("rows", settings.gridSize.rows); } + if (settings.gridOffset) { put("offset-x", settings.gridOffset.x); put("offset-y", settings.gridOffset.y); } + for (const [field, key, kind] of SIMPLE_KEYS) { + if (field === "displayName" || field === "paletteName") continue; + const v = s[field]; + if (v === undefined) continue; + if (kind === "note" && typeof v === "string" && v) put(key, `[[${v.replace(/\.md$/i, "")}]]`); + else put(key, v); + } + const parent = s.parent as { map?: unknown; hex?: unknown } | undefined; + const parentHex = parent && typeof parent.hex === "string" ? /^(-?\d+)_(-?\d+)$/.exec(parent.hex) : null; + const parentReadable = !!parent && typeof parent.map === "string" && !!parent.map && !!parentHex && Object.keys(parent).length === 2; + if (parentReadable) { + if (!keep.has("parent")) lines.push(`parent: ${linkTo(`_${parent.map as string}`)}`); + put("parent-hex", `${parentHex[1]}, ${parentHex[2]}`); + } + const world = s.world as { id?: unknown; cx?: unknown; cy?: unknown } | undefined; + const worldReadable = !!world && typeof world.id === "string" && !!world.id && typeof world.cx === "number" && typeof world.cy === "number" && Object.keys(world).length === 3; + if (worldReadable) { put("world", world.id); put("world-x", world.cx); put("world-y", world.cy); } + const bg = s.backgroundImage as Record | undefined; + const bgReadable = !!bg && typeof bg.path === "string" && !!bg.path + && Object.keys(bg).every((k) => ["path", "offsetX", "offsetY", "scale", "rotation", "opacity"].includes(k)) + && ["offsetX", "offsetY", "scale", "rotation", "opacity"].every((k) => bg[k] === undefined || typeof bg[k] === "number"); + if (bgReadable) { + if (!keep.has("background-image")) lines.push(`background-image: ${linkTo(bg.path as string)}`); + put("background-x", bg.offsetX ?? 0); + put("background-y", bg.offsetY ?? 0); + put("background-scale", bg.scale ?? 1); + put("background-rotation", bg.rotation); + put("background-opacity", bg.opacity); + } + const biome = s.biome as { generator?: unknown; from?: unknown } | undefined; + const biomeReadable = !!biome && typeof biome.generator === "string" && biome.generator !== "" + && Object.keys(biome).every((k) => k === "generator" || k === "from") + && (biome.from === undefined || (Array.isArray(biome.from) && biome.from.every((v) => typeof v === "string"))); + if (biomeReadable) { + put(BIOME_KEY, biome.generator); + if (Array.isArray(biome.from) && biome.from.length) put(BIOME_FROM_KEY, biome.from); + } + const reg = s.regions as Partial | undefined; + const regKnown = ["footprint", "size", "blend", "palette", "worldId", "stagger", "generator"]; + const regionsReadable = !!reg && (reg.footprint === "hex" || reg.footprint === "rect") + && typeof reg.size === "number" && Number.isInteger(reg.size) && reg.size > 0 + && Object.keys(reg).every((k) => regKnown.includes(k) && (reg[k as keyof RegionSettings] === undefined || typeof reg[k as keyof RegionSettings] === (k === "size" ? "number" : "string"))); + if (regionsReadable) { + put(REGION_KEYS.shape, reg.footprint === "hex" ? "hex flower" : "rectangle"); + put(REGION_KEYS.size, regionSizeText(reg as RegionSettings)); + put(REGION_KEYS.blend, reg.blend); + put(REGION_KEYS.palette, reg.palette); + put(REGION_KEYS.world, reg.worldId); + put(REGION_KEYS.stagger, reg.stagger); + put(REGION_KEYS.generator, reg.generator); + } + const readable = new Set(KNOWN_FIELDS); + if (regionsReadable) readable.add("regions"); + if (!parentReadable) readable.delete("parent"); + if (!worldReadable) readable.delete("world"); + if (!bgReadable) readable.delete("backgroundImage"); + if (biomeReadable) readable.add("biome"); + for (const [k, v] of Object.entries(s)) { + if (v === undefined || readable.has(k) || SKIP_FIELDS.has(k)) continue; + put(otherKey(k), v); + } + return lines; +} + +const FRONTMATTER = /^---[ \t]*\n(?:([\s\S]*?)\n)?---[ \t]*(\n|$)/; + +// ── tables ─────────────────────────────────────────────────────────────── + +const HEX_HEADERS = ["Hex", "Name", "Terrain", "Icon", "GM icons", "Region", "Region map", "Locations", "Locked"]; +/** Known columns written only when the table has them or some row needs them. */ +const OPTIONAL_HEX_HEADERS = new Set(["region map"]); +const PATH_HEADERS = ["Type", "Route", "Warning", "Hexes"]; +/** Paths columns written from the data, never read back. */ +const DERIVED_PATH_COLS = new Set(["route", "warning"]); +/** Header → canonical column, ignoring case, spaces, dashes and markup. */ +const HEX_COL_ALIASES: Record = { + hex: "hex", name: "name", terrain: "terrain", icon: "icon", + gmicons: "gm icons", gmicon: "gm icons", region: "region", + regionmap: "region map", regionsubmap: "region map", + locations: "locations", location: "locations", + // Format 2's one-submap column: read as Locations, renamed on write. + submap: "locations", submaps: "locations", + locked: "locked", +}; +const PATH_COL_ALIASES: Record = { type: "type", hexes: "hexes", route: "route", warning: "warning", warnings: "warning" }; +const CANONICAL: Record = Object.fromEntries([...HEX_HEADERS, ...PATH_HEADERS].map((h) => [h.toLowerCase(), h])); +const SEPARATOR_ROW = /^\s*\|?\s*:?[-=]+:?\s*(\|\s*:?[-=]*:?\s*)*\|?\s*$/; +const normHeader = (h: string) => h.toLowerCase().replace(/[^a-z0-9]/g, ""); + +function splitRow(line: string): string[] { + let s = line.trim(); + if (s.startsWith("|")) s = s.slice(1); + if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1); + const cells: string[] = []; + let cur = ""; + for (let i = 0; i < s.length; i++) { + if (s[i] === "\\" && s[i + 1] === "|") { cur += "|"; i++; } + else if (s[i] === "|") { cells.push(cur.trim()); cur = ""; } + else cur += s[i]; + } + cells.push(cur.trim()); + return cells; +} + +/** A row's cells lined up with `n` headers: stray empty cells at either end (extra pipes) dropped. */ +function rowCells(line: string, n: number): string[] { + const c = splitRow(line); + while (c.length > n && c[0] === "") c.shift(); + while (c.length > n && c[c.length - 1] === "") c.pop(); + return c; +} + +const esc = (v: string | undefined) => (v ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " ").trim(); + +interface Table { + start: number; + /** First row after the header (and separator, if any). */ + body: number; + end: number; + /** Canonical column id per header ("hex", "gm icons", …) or "" for unknown. */ + cols: string[]; + /** Headers as written (trimmed). */ + headers: string[]; +} + +const isTableLine = (l: string) => l.includes("|") && !/^\s*[>#]/.test(l) && l.trim() !== ""; + +function tableAt(lines: string[], i: number, aliases: Record): Table { + const headers = splitRow(lines[i]); + const cols = headers.map((h) => aliases[normHeader(h)] ?? ""); + const body = i + 1 < lines.length && SEPARATOR_ROW.test(lines[i + 1]) && lines[i + 1].includes("-") ? i + 2 : i + 1; + let end = body; + while (end < lines.length && isTableLine(lines[end])) end++; + return { start: i, body, end, cols, headers }; +} + +const HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/; + +/** [start, end) of the body section under a `## ` heading. */ +function sectionRange(lines: string[], name: string): [number, number] | null { + for (let i = 0; i < lines.length; i++) { + const h = HEADING.exec(lines[i]); + if (!h || normHeader(h[2]) !== name) continue; + let end = i + 1; + while (end < lines.length) { + const n = HEADING.exec(lines[end]); + if (n && n[1].length <= h[1].length) break; + end++; + } + return [i + 1, end]; + } + return null; +} + +/** + * The table holding `need` columns: first one inside its section ("## Hexes" + * / "## Paths"), else the first anywhere with `strict` columns. `broken` = + * the section has table rows but no header with those columns. + */ +function locateTable(lines: string[], section: string, aliases: Record, need: string[], strict: string[]): { table: Table | null; broken: boolean } { + const has = (i: number, cols: string[]) => { + const t = splitRow(lines[i]).map((h) => aliases[normHeader(h)] ?? ""); + return cols.every((c) => t.includes(c)); + }; + const range = sectionRange(lines, section); + if (range) { + for (let i = range[0]; i < range[1]; i++) { + if (isTableLine(lines[i]) && !SEPARATOR_ROW.test(lines[i]) && has(i, need)) return { table: tableAt(lines, i, aliases), broken: false }; + } + } + for (let i = 0; i < lines.length; i++) { + if (isTableLine(lines[i]) && !SEPARATOR_ROW.test(lines[i]) && has(i, strict)) { + if (range && (i < range[0] - 1 || i >= range[1]) && sectionHasRows(lines, range)) break; + return { table: tableAt(lines, i, aliases), broken: false }; + } + } + return { table: null, broken: !!range && sectionHasRows(lines, range) }; +} + +function sectionHasRows(lines: string[], range: [number, number]): boolean { + for (let i = range[0]; i < range[1]; i++) if (/^\s*\|/.test(lines[i])) return true; + return false; +} + +/** Sort "x_y" keys by row then column, like reading a map. */ +export function compareHexKeys(a: string, b: string): number { + const [ax, ay] = a.split("_").map(Number); + const [bx, by] = b.split("_").map(Number); + return ay - by || ax - bx; +} + +/** Anything besides terrain set on a hex. */ +function hasNonTerrainData(h: HexData): boolean { + return !!(h.name || h.icon || (h.gmIcons && h.gmIcons.length) || h.region || h.regionMap || (h.locations && h.locations.length) || h.locked + || (h.extra && Object.values(h.extra).some(Boolean))); +} + +function isEmptyHex(h: HexData): boolean { + return !h.terrain && !hasNonTerrainData(h); +} + +/** Rows worth writing: hexes with any data, minus "just the base terrain". */ +export function hexRowsToWrite(hexes: Map, baseTerrain?: string): [string, HexData][] { + return [...hexes] + .filter(([, h]) => { + if (isEmptyHex(h)) return false; + const onlyBase = h.terrain === baseTerrain && !hasNonTerrainData(h); + return !(baseTerrain && onlyBase); + }) + .sort(([a], [b]) => compareHexKeys(a, b)); +} + +/** Unknown column headers across rows, in first-seen order. */ +function extraHeaders(rows: Iterable<{ extra?: Record }>): string[] { + const seen = new Set(); + for (const r of rows) for (const k of Object.keys(r.extra ?? {})) seen.add(k); + return [...seen]; +} + +function tableHead(headers: string[]): string[] { + return [`| ${headers.map(esc).join(" | ")} |`, `| ${headers.map(() => "---").join(" | ")} |`]; +} + +/** + * Headers to write, in order: the existing table's columns as the user + * arranged them (known ones in their usual spelling, unknown ones as typed, + * repeats and blanks dropped), then any known column it lacks (canonical + * order), then unknown columns that only the data has. + */ +function columnOrder(known: string[], aliases: Record, existing: string[] | undefined, extras: string[], skip: Set = new Set()): string[] { + const out: string[] = []; + const seen = new Set(); + const add = (h: string) => { + const id = aliases[normHeader(h)]; + const label = id ? CANONICAL[id] : h.trim(); + const k = id ?? label.toLowerCase(); + if (!label || seen.has(k)) return; + seen.add(k); + out.push(label); + }; + for (const h of existing ?? []) add(h); + // Optional known columns ("Region map") only once something needs them. + for (const h of known) if (!skip.has(aliases[normHeader(h)])) add(h); + for (const h of extras) add(h); + return out; +} + +/** An unknown column's value, matching its header case-insensitively. */ +function extraValue(extra: Record | undefined, header: string): string | undefined { + if (!extra) return undefined; + if (header in extra) return extra[header]; + const k = header.toLowerCase(); + for (const [h, v] of Object.entries(extra)) if (h.toLowerCase() === k) return v; + return undefined; +} + +const HEX_CELL: Record string | undefined> = { + hex: (k) => k, + name: (_k, h) => h.name, + terrain: (_k, h) => h.terrain, + icon: (_k, h) => h.icon, + "gm icons": (_k, h) => h.gmIcons?.join(", "), + region: (_k, h) => (h.region ? regionLinkText(h.region) : undefined), + "region map": (_k, h) => (h.regionMap ? mapLinkText(h.regionMap) : undefined), + locations: (_k, h) => h.locations?.map(mapLinkText).join(", "), + locked: (_k, h) => (h.locked ? "yes" : ""), +}; + +function hexTable(hexes: Map, baseTerrain?: string, existing?: string[], keptRows: string[] = []): string { + const rows = hexRowsToWrite(hexes, baseTerrain); + const skip = new Set([...OPTIONAL_HEX_HEADERS].filter((c) => c !== "region map" || !rows.some(([, h]) => h.regionMap))); + const headers = columnOrder(HEX_HEADERS, HEX_COL_ALIASES, existing, extraHeaders(rows.map(([, h]) => h)), skip); + const lines = tableHead(headers); + for (const [k, h] of rows) { + const cells = headers.map((c) => { + const known = HEX_CELL[HEX_COL_ALIASES[normHeader(c)] ?? ""]; + return known ? known(k, h) : extraValue(h.extra, c); + }); + lines.push(`| ${cells.map(esc).join(" | ")} |`); + } + lines.push(...keptRows); + return lines.join("\n"); +} + +/** A hex key as people write it: `3_4` → `3, 4`. */ +export function hexText(key: string): string { + const m = /^(-?\d+)_(-?\d+)$/.exec(key); + return m ? `${m[1]}, ${m[2]}` : key; +} + +/** A path's derived Route cell: `3, 4 → 5, 4 (3 hexes)`. */ +export function routeText(hexes: string[]): string { + if (!hexes.length) return ""; + const n = `(${hexes.length} ${hexes.length === 1 ? "hex" : "hexes"})`; + if (hexes.length === 1) return `${hexText(hexes[0])} ${n}`; + return `${hexText(hexes[0])} → ${hexText(hexes[hexes.length - 1])} ${n}`; +} + +/** A path's derived Warning cell: set when its type isn't one of the palette's path types. */ +export function pathWarning(p: PathChain, ctx: MapNoteContext = {}): string { + const types = ctx.pathTypes; + if (!types || !types.length || types.includes(p.typeName)) return ""; + return "⚠ not a path type in the palette"; +} + +function pathTable(paths: PathChain[], existing?: string[], keptRows: string[] = [], ctx: MapNoteContext = {}): string { + const id = (h: string) => PATH_COL_ALIASES[normHeader(h)] ?? ""; + const warnings = paths.map((p) => pathWarning(p, ctx)); + // Warning is only written while some path has one (and then dropped again). + const skip = new Set(warnings.some(Boolean) ? [] : ["warning"]); + const kept = existing?.filter((h) => !skip.has(id(h))); + let headers = columnOrder(PATH_HEADERS, PATH_COL_ALIASES, kept, extraHeaders(paths), skip); + // Derived columns the table didn't have go right after Type (and Route), + // before the long Hexes list, so they can be read at a glance. + if (kept) { + const had = new Set(kept.map(id)); + const added = headers.filter((h) => DERIVED_PATH_COLS.has(id(h)) && !had.has(id(h))); + if (added.length) { + headers = headers.filter((h) => !added.includes(h)); + let at = 0; + headers.forEach((h, i) => { if (id(h) === "type" || DERIVED_PATH_COLS.has(id(h))) at = i + 1; }); + headers.splice(at, 0, ...added); + } + } + const lines = tableHead(headers); + for (const [i, p] of paths.entries()) { + const cells = headers.map((c) => { + const k = id(c); + if (k === "type") return esc(p.typeName); + if (k === "hexes") return p.hexes.join(" "); + if (k === "route") return routeText(p.hexes); + if (k === "warning") return esc(warnings[i]); + return esc(extraValue(p.extra, c)); + }); + lines.push(`| ${cells.join(" | ")} |`); + } + lines.push(...keptRows); + return lines.join("\n"); +} + +/** [index, header] of the columns not known (first of any repeated name). */ +function unknownColumns(t: Table): [number, string][] { + const seen = new Set(); + const out: [number, string][] = []; + t.cols.forEach((c, i) => { + const h = t.headers[i]; + if (c || !h || seen.has(h.toLowerCase())) return; + seen.add(h.toLowerCase()); + out.push([i, h]); + }); + return out; +} + +/** A row's non-empty cells in unknown columns, or undefined when it has none. */ +function readExtra(cells: string[], unknown: [number, string][]): Record | undefined { + let out: Record | undefined; + for (const [i, header] of unknown) { + const v = cells[i]; + if (v) (out ??= {})[header] = v; + } + return out; +} + +interface TableRead { + rows: T; + /** Rows that couldn't be read, as written (kept at the table's end on rewrite). */ + bad: MapNoteProblem[]; +} + +const isFiller = (line: string) => SEPARATOR_ROW.test(line) || splitRow(line).every((c) => c === ""); + +function readHexTable(lines: string[], t: Table | null): TableRead> { + const out = new Map(); + const bad: MapNoteProblem[] = []; + if (!t) return { rows: out, bad }; + const col = (name: string) => t.cols.indexOf(name); + const ci = { hex: col("hex"), name: col("name"), terrain: col("terrain"), icon: col("icon"), gm: col("gm icons"), region: col("region"), regionMap: col("region map"), locked: col("locked") }; + // Locations may sit in more than one column (a Submap column next to a + // Locations one): all are read, in column order. + const locCols = t.cols.flatMap((c, i) => (c === "locations" ? [i] : [])); + const regionMapCols = t.cols.flatMap((c, i) => (c === "region map" ? [i] : [])); + const unknown = unknownColumns(t); + for (let i = t.body; i < t.end; i++) { + const line = lines[i]; + if (isFiller(line)) continue; + const c = rowCells(line, t.headers.length); + const no = (reason: string) => bad.push({ where: "Hexes", text: line.trim(), reason }); + const rawKey = c[ci.hex] ?? ""; + const key = parseHexKey(rawKey); + if (!key) { no(rawKey ? `"${rawKey}" isn't a hex (write it like 3_4)` : "no hex in the Hex column"); continue; } + if (out.has(key)) { no(`hex ${key} already has a row above`); continue; } + const get = (j: number) => (j >= 0 ? c[j] : "") || undefined; + const lockedRaw = get(ci.locked) ?? ""; + if (!TRUE_WORDS.test(lockedRaw) && !FALSE_WORDS.test(lockedRaw)) { no(`Locked should be yes or empty, not "${lockedRaw}"`); continue; } + const h: HexData = {}; + // Notes from before hex names have no Name column (index -1): no name. + if (get(ci.name)) h.name = get(ci.name); + if (get(ci.terrain)) h.terrain = get(ci.terrain); + if (get(ci.icon)) h.icon = get(ci.icon); + const gm = get(ci.gm); + if (gm) h.gmIcons = gm.split(/[,;]/).map((s) => s.trim()).filter(Boolean); + const region = get(ci.region); + if (region) h.region = noteName(region) || region; + // Region map: one map. More than one listed: the first is the region, + // the rest are kept as locations (nothing typed is dropped). + const regionMaps = regionMapCols.flatMap((j) => parseMapList(c[j])); + const locations = locCols.flatMap((j) => parseMapList(c[j])); + if (regionMaps.length) h.regionMap = regionMaps[0]; + const locs = [...regionMaps.slice(1), ...locations].filter((m, i, a) => m !== h.regionMap && a.indexOf(m) === i); + if (locs.length) h.locations = locs; + if (TRUE_WORDS.test(lockedRaw)) h.locked = true; + const extra = readExtra(c, unknown); + if (extra) h.extra = extra; + out.set(key, h); + } + return { rows: out, bad }; +} + +function readPathTable(lines: string[], t: Table | null): TableRead { + const out: PathChain[] = []; + const bad: MapNoteProblem[] = []; + if (!t) return { rows: out, bad }; + const ti = t.cols.indexOf("type"), hi = t.cols.indexOf("hexes"); + const unknown = unknownColumns(t); + for (let i = t.body; i < t.end; i++) { + const line = lines[i]; + if (isFiller(line)) continue; + const c = rowCells(line, t.headers.length); + const no = (reason: string) => bad.push({ where: "Paths", text: line.trim(), reason }); + const type = c[ti] ?? ""; + const tokens = (c[hi] ?? "").split(/[\s,;→>]+/).filter(Boolean); + const hexes = tokens.map(parseHexKey); + if (!type) { no("no path type in the Type column"); continue; } + if (!tokens.length) { no("no hexes in the Hexes column"); continue; } + const badTok = tokens.find((_, j) => !hexes[j]); + if (badTok !== undefined) { no(`"${badTok}" isn't a hex (list them like 3_4 4_4 5_4)`); continue; } + const p: PathChain = { typeName: type, hexes: hexes as string[] }; + const extra = readExtra(c, unknown); + if (extra) p.extra = extra; + out.push(p); + } + return { rows: out, bad }; +} + +// ── callouts ───────────────────────────────────────────────────────────── + +const HELP_TITLE = /^>\s*\[!info\][+-]?\s*how to edit this (map )?note/i; +const PROBLEM_TITLE = /^>\s*\[!warning\][+-]?\s*hexmaker couldn't read/i; +/** The one-line description format-1 notes opened with (plugin text, replaced by the help box). */ +const OLD_INTRO = "Hexmap World Creator map. Each hex's name, terrain, icons, region and submap live in the table below — edit it here or paint on the map. Hex notes hold descriptions and links, and only exist once a hex has some."; + +/** Format 2's Hexes help line (one Submap column), replaced when still word for word. */ +const HEX_HELP_LINE_V2 = "> - **Hexes**: one row per hex that has something set. *Hex* is the column and row, like `3_4`. *Terrain* and *Region* use names from the map's palette. *Icon* and *GM icons* are icon file names; separate several with commas. *Submap* is the map that opens from the hex. *Locked* `yes` keeps generators off it."; +const HEX_HELP_LINE = "> - **Hexes**: one row per hex that has something set. *Hex* is the column and row, like `3_4`. *Terrain* uses names from the map's palette; *Region* links the region's note. *Icon* and *GM icons* are icon file names; separate several with commas. *Locations* links the maps that open from the hex (towns, dungeons…), separated by commas; *Region map*, when there is one, is the map of the hex itself. *Locked* `yes` keeps generators off it."; + +/** Format 2–3's Paths help line, replaced when still word for word. */ +const PATH_HELP_LINE_V3 = "> - **Paths**: *Type* is a path type (Road, River…). *Hexes* lists its hexes in order, separated by spaces."; +const PATH_HELP_LINE = "> - **Paths**: *Type* is a path type (Road, River…). *Hexes* lists its hexes in order, separated by spaces. The plugin fills in *Route*, *Warning* and the **Summary** above from the tables; edits to those are replaced."; + +export const HELP_CALLOUT = [ + "> [!info]- How to edit this note", + "> This note holds the map's data. Painting on the map updates it, and your edits here update the map.", + HEX_HELP_LINE, + PATH_HELP_LINE, + "> - Columns can be in any order, and you can add your own; they're kept. A row that can't be read is kept as written and flagged.", + "> - The properties at the top are the map's settings. Delete one to reset it. Keys starting with `hexmaker-` come from other versions of the plugin; leave them be.", + "> - Everything else in this note, like text you write below the tables, is yours: the plugin never changes it.", +]; + +function problemCallout(problems: MapNoteProblem[], what: string): string[] { + const n = problems.length; + const head = what === "settings" + ? `> [!warning] Hexmaker couldn't read ${n === 1 ? "a setting" : `${n} settings`}` + : `> [!warning] Hexmaker couldn't read ${n === 1 ? "a row" : `${n} rows`} in this table`; + const tail = what === "settings" + ? "> The map keeps its previous value until you fix it above; this box then goes away." + : `> ${n === 1 ? "It's" : "They're"} kept as written at the end of the table. Fix ${n === 1 ? "it" : "them"} there and this box goes away.`; + const code = (s: string) => (s.includes("`") ? `\`\` ${s} \`\`` : `\`${s}\``); + return [head, tail, ...problems.map((p) => `> - ${code(p.text)}: ${p.reason}`)]; +} + +/** Remove Hexmaker's warning callouts (they're regenerated from what's in the note). */ +function stripProblemCallouts(lines: string[]): string[] { + const out: string[] = []; + for (let i = 0; i < lines.length; i++) { + if (!PROBLEM_TITLE.test(lines[i])) { out.push(lines[i]); continue; } + while (i + 1 < lines.length && /^\s*>/.test(lines[i + 1])) i++; + // the blank line it was inserted with: before it after a table, after it at the top + if (out.length && out[out.length - 1].trim() === "") out.pop(); + else if (i + 1 < lines.length && lines[i + 1].trim() === "") i++; + } + return out; +} + +// ── derived summary ────────────────────────────────────────────────────── + +const SUMMARY_HEADING = "## Summary"; +const SUMMARY_MARKER = "*Generated by Hexmaker from the tables below and the map's palette. Edits here are replaced.*"; +/** How the Summary is recognised as ours (a `## Summary` without it is the user's). */ +const SUMMARY_MARKER_RE = /^\s*[*_]*generated by hexmaker\b/i; + +const plural = (n: number, one: string, many = one + "s") => `${n} ${n === 1 ? one : many}`; +/** A coordinate for reading (true minus sign): −7. */ +const coord = (n: number) => (n < 0 ? `−${-n}` : String(n)); + +/** + * The Summary section: derived from the note's data and the palette, + * written on every write, never read. No headings inside (see summaryRange). + */ +export function summaryLines(data: MapNoteData, ctx: MapNoteContext = {}): string[] { + const s = data.settings; + const bullets: string[] = []; + const known = ctx.paletteTerrains?.length ? new Set(ctx.paletteTerrains) : null; + const unknown = (t: string) => !!known && !known.has(t); + + const pal = s.paletteName; + if (pal) { + const note = ctx.paletteNote; + bullets.push(`- **Palette:** ${note && linkSafe(note) && linkSafe(pal) ? (note.split("/").pop() === pal ? `[[${note}]]` : `[[${note}|${pal}]]`) : pal}`); + } + + // Terrain per hex: the grid's cells when it has a size, else the listed rows. + const counts = new Map(); + let blank = 0; + const base = s.baseTerrain; + const count = (t: string | undefined) => { if (t) counts.set(t, (counts.get(t) ?? 0) + 1); else blank++; }; + const g = s.gridSize, o = s.gridOffset ?? { x: 0, y: 0 }; + if (g && g.cols > 0 && g.rows > 0) { + bullets.push(`- **Hexes:** ${coord(o.x)}…${coord(o.x + g.cols - 1)} × ${coord(o.y)}…${coord(o.y + g.rows - 1)} (${g.cols}×${g.rows})`); + for (let y = o.y; y < o.y + g.rows; y++) { + for (let x = o.x; x < o.x + g.cols; x++) count(data.hexes.get(`${x}_${y}`)?.terrain || base); + } + } else { + for (const h of data.hexes.values()) if (h.terrain) count(h.terrain); + } + bullets.push(base + ? `- **Base terrain:** ${base} (hexes not listed in the table)${unknown(base) ? " ⚠ not in the palette" : ""}` + : "- **Base terrain:** none (hexes not listed have no terrain)"); + + const regions = new Map(); + let regionMaps = 0, locations = 0; + for (const h of data.hexes.values()) { + if (h.region) regions.set(h.region, (regions.get(h.region) ?? 0) + 1); + if (h.regionMap) regionMaps++; + locations += h.locations?.length ?? 0; + } + const byCount = (a: T, b: T) => b[1] - a[1] || a[0].localeCompare(b[0]); + if (regions.size) { + bullets.push(`- **Regions:** ${[...regions].sort(byCount).map(([r, n]) => `${regionLinkText(r)} (${plural(n, "hex", "hexes")})`).join(", ")}`); + } + const rs = s.regions; + if (rs) { + const parts = [`${rs.footprint === "hex" ? "hex flowers" : "rectangles"} of ${regionSizeText(rs)}`, `${rs.blend ?? "normal"} blend`]; + if (rs.palette) parts.push(`palette ${rs.palette}`); + if (rs.generator) parts.push(`generator ${rs.generator}`); + bullets.push(`- **Region settings:** ${parts.join(", ")}`); + } + if (regionMaps || locations) { + const parts = []; + if (regionMaps) parts.push(plural(regionMaps, "region map")); + if (locations) parts.push(plural(locations, "location")); + bullets.push(`- **Maps from hexes:** ${parts.join(", ")}`); + } + if (data.paths.length) bullets.push(`- **Paths:** ${data.paths.length}`); + + const offPalette = [...counts].filter(([t]) => unknown(t)).sort(byCount); + if (offPalette.length) { + bullets.push(`- **⚠ Not in the palette:** ${offPalette.map(([t, n]) => `${t} (${plural(n, "hex", "hexes")})`).join(", ")}. Add ${offPalette.length === 1 ? "it" : "them"} to the palette, or repaint those hexes.`); + } + const badTypes = [...new Set(data.paths.filter((p) => pathWarning(p, ctx)).map((p) => p.typeName))]; + if (badTypes.length) bullets.push(`- **⚠ Path types not in the palette:** ${badTypes.join(", ")}`); + + const out = [SUMMARY_HEADING, "", SUMMARY_MARKER, "", ...bullets]; + if (counts.size || blank) { + out.push("", "| Terrain | Hexes |", "| --- | --- |"); + for (const [t, n] of [...counts].sort(byCount)) { + const tags = [t === base ? "base" : "", unknown(t) ? "⚠ not in the palette" : ""].filter(Boolean); + out.push(`| ${esc(t)}${tags.length ? ` (${tags.join(", ")})` : ""} | ${n} |`); + } + if (blank) out.push(`| (no terrain) | ${blank} |`); + } + return out; +} + +/** + * [start, end) of the generated Summary: its heading through its own lines + * (the marker line, bullets, the legend table, blanks between). Anything + * else stops it, so text a person typed under it, or a table that follows, + * is never inside the range. null = no Summary carrying the marker line. + */ +function summaryRange(lines: string[]): [number, number] | null { + for (let i = 0; i < lines.length; i++) { + const h = HEADING.exec(lines[i]); + if (!h || normHeader(h[2]) !== "summary") continue; + let end = i + 1, marked = false, inLegend = false; + for (; end < lines.length; end++) { + const l = lines[end]; + if (!l.trim()) { inLegend = false; continue; } + if (SUMMARY_MARKER_RE.test(l)) { marked = true; continue; } + if (/^\s*[-*+]\s/.test(l)) continue; + if (isTableLine(l)) { + if (inLegend) continue; + const cols = splitRow(l).map(normHeader); + if (cols.length === 2 && cols[0] === "terrain" && cols[1] === "hexes") { inLegend = true; continue; } + } + break; + } + if (!marked) continue; + while (end > i + 1 && !lines[end - 1].trim()) end--; + return [i, end]; + } + return null; +} + +/** Lines with the Summary blanked (indices kept): it's never read as data. */ +function withoutSummary(lines: string[]): string[] { + const r = summaryRange(lines); + if (!r) return lines; + return lines.map((l, i) => (i >= r[0] && i < r[1] ? "" : l)); +} + +/** Put the Summary in: replace ours where it is, else add it just above the Hexes section. */ +function placeSummary(lines: string[], summary: string[]): string[] { + const r = summaryRange(lines); + if (r) return [...lines.slice(0, r[0]), ...summary, ...lines.slice(r[1])]; + const hexSec = sectionRange(lines, "hexes"); + let at = hexSec ? hexSec[0] - 1 : locateTable(lines, "hexes", HEX_COL_ALIASES, ["hex"], ["hex", "terrain"]).table?.start ?? -1; + if (at < 0) { + // No Hexes table found (can't happen after a write): after the help box, else the title. + const help = lines.findIndex((l) => HELP_TITLE.test(l)); + if (help >= 0) { at = help + 1; while (at < lines.length && /^\s*>/.test(lines[at])) at++; } + else { const t = lines.findIndex((l) => /^#\s/.test(l)); at = t + 1; } + } + const before = at > 0 && lines[at - 1].trim() !== "" ? [""] : []; + const after = at < lines.length && lines[at].trim() !== "" ? [""] : []; + return [...lines.slice(0, at), ...before, ...summary, ...after, ...lines.slice(at)]; +} + +// ── whole note ─────────────────────────────────────────────────────────── + +interface Parsed { + fm: RegExpExecArray | null; + front: FmRead; + lines: string[]; + hexT: Table | null; + pathT: Table | null; + hexes: TableRead>; + paths: TableRead; + broken: string | null; +} + +function parseParts(content: string, opts: MapNoteReadOptions): Parsed | null { + const text = content.replace(/\r\n?/g, "\n"); + const fm = FRONTMATTER.exec(text); + if (!fm) return null; + const fmText = fm[1] ?? ""; + if (!/^\s*["']?hexmaker-map["']?\s*:/m.test(fmText)) return null; + const front = readFrontmatter(fmText, opts); + const lines = stripProblemCallouts(text.slice(fm[0].length).split("\n")); + // The generated Summary is never read: tables are looked for without it. + const scan = withoutSummary(lines); + const h = locateTable(scan, "hexes", HEX_COL_ALIASES, ["hex"], ["hex", "terrain"]); + const p = locateTable(scan, "paths", PATH_COL_ALIASES, ["type", "hexes"], ["type", "hexes"]); + let broken: string | null = null; + if (h.broken) broken = "the Hexes table needs a header row with a Hex column"; + else if (p.broken) broken = "the Paths table needs a header row with Type and Hexes columns"; + return { fm, front, lines, hexT: h.table, pathT: p.table, hexes: readHexTable(scan, h.table), paths: readPathTable(scan, p.table), broken }; +} + +/** + * Read a map note. null = not a map note (no frontmatter with + * `hexmaker-map`); `ok: false` = a map note whose tables can't be found, so + * it must not be written over until fixed. + */ +export function readMapNote(content: string, opts: MapNoteReadOptions = {}): MapNoteRead | null { + const p = parseParts(content, opts); + if (!p) return null; + if (p.broken) return { ok: false, reason: p.broken }; + return { + ok: true, + data: { + settings: p.front.settings, + hexes: p.hexes.rows, + paths: p.paths.rows, + format: p.front.format, + problems: [...p.front.problems, ...p.hexes.bad, ...p.paths.bad], + }, + }; +} + +/** Parse a map note, or null if it isn't one (or can't be read). */ +export function parseMapNote(content: string, opts: MapNoteReadOptions = {}): MapNoteData | null { + const r = readMapNote(content, opts); + return r && r.ok ? r.data : null; +} + +/** Format of a map note's text: 1 for older notes, null when it isn't one. */ +export function mapNoteFormat(content: string): number | null { + const p = parseParts(content, {}); + return p ? p.front.format : null; +} + +/** A fresh map note. */ +export function buildMapNote(name: string, data: MapNoteData, ctx: MapNoteContext = {}): string { + return [ + "---", + ...frontmatterLines(data.settings), + "---", + `# ${data.settings.displayName || name}`, + "", + ...HELP_CALLOUT, + "", + ...summaryLines(data, ctx), + "", + "## Hexes", + "", + hexTable(data.hexes, data.settings.baseTerrain), + "", + "## Paths", + "", + pathTable(data.paths, undefined, [], ctx), + "", + ].join("\n"); +} + +/** + * Rewrite our parts of an existing map note — owned frontmatter keys, the + * two tables and Hexmaker's callouts — keeping everything else the user + * added. Rows and settings that can't be read are kept as written and + * listed in a warning callout. A format-1 note gets the help callout once. + */ +export function updateMapNote(content: string, name: string, data: MapNoteData, ctx: MapNoteContext = {}): string { + const text = content.replace(/\r\n?/g, "\n"); + const parsed = parseParts(text, {}); + if (!parsed) { + // Not readable as a map note: never rebuild over the text. Put a fresh + // frontmatter + tables on top and keep every line that was there. + const fresh = buildMapNote(name, data, ctx); + return text.trim() ? `${fresh}\n${text}` : fresh; + } + const { fm, front } = parsed; + // Settings that didn't read stay exactly as written (and aren't written by us). + const keep = new Set(front.problems.map((p) => p.key!).filter(Boolean)); + const userFm = yamlBlocks(fm![1] ?? "") + .filter((b) => b.key === null ? b.lines.some((l) => l.trim()) : !ownsKey(b.key) || keep.has(b.key)) + .flatMap((b) => b.lines) + .filter((l) => l.trim()); + let lines = [...parsed.lines]; + + // Tables are rewritten in the column order the user gave them; unreadable rows stay at the end. + const replace = (find: () => Table | null, table: (existing?: string[]) => string, heading: string, problems: MapNoteProblem[], what: string) => { + const t = find(); + const callout = problems.length ? ["", ...problemCallout(problems, what)] : []; + if (t) lines = [...lines.slice(0, t.start), ...table(t.headers).split("\n"), ...callout, ...lines.slice(t.end)]; + else lines = [...lines, "", heading, "", ...table().split("\n"), ...callout]; + }; + const hexBad = parsed.hexes.bad, pathBad = parsed.paths.bad; + replace(() => locateTable(withoutSummary(lines), "hexes", HEX_COL_ALIASES, ["hex"], ["hex", "terrain"]).table, + (ex) => hexTable(data.hexes, data.settings.baseTerrain, ex, hexBad.map((b) => b.text)), "## Hexes", hexBad, "Hexes"); + replace(() => locateTable(withoutSummary(lines), "paths", PATH_COL_ALIASES, ["type", "hexes"], ["type", "hexes"]).table, + (ex) => pathTable(data.paths, ex, pathBad.map((b) => b.text), ctx), "## Paths", pathBad, "Paths"); + + // Format 1 → 2: add the help box once (in place of the old one-line intro, if it's still there). + // Format 2 → 3: the help box's Hexes line, if it's still the plugin's own words. + // Format 3 → 4: its Paths line (mentions the derived parts), likewise. + if (front.format < MAP_NOTE_FORMAT) { + lines = lines.map((l) => (l.trim() === HEX_HELP_LINE_V2 ? HEX_HELP_LINE : l.trim() === PATH_HELP_LINE_V3 ? PATH_HELP_LINE : l)); + } + if (front.format < READABLE_KEYS_FORMAT && !lines.some((l) => HELP_TITLE.test(l))) { + const intro = lines.findIndex((l) => l.trim() === OLD_INTRO); + if (intro >= 0) lines.splice(intro, 1, ...HELP_CALLOUT); + else { + const first = lines.findIndex((l) => l.trim() !== ""); + const at = first >= 0 && /^#\s/.test(lines[first]) ? first + 1 : 0; + lines.splice(at, 0, ...(at ? ["", ...HELP_CALLOUT] : [...HELP_CALLOUT, ""])); + } + } + // The derived Summary: replaced where it is, or (new, or deleted by hand) put back above the Hexes. + lines = placeSummary(lines, summaryLines(data, ctx)); + const fmProblems = front.problems; + if (fmProblems.length) lines = [...problemCallout(fmProblems, "settings"), "", ...lines]; + return ["---", ...frontmatterLines(data.settings, keep), ...userFm, "---", ...lines].join("\n"); +} + +/** + * Only bring Hexmaker's warning callouts in line with what the note holds + * now (add, update or clear them), touching nothing else. For hand edits: + * the rest is normalised on the next real write. + */ +export function refreshProblemCallouts(content: string): string { + const text = content.replace(/\r\n?/g, "\n"); + const p = parseParts(text, {}); + if (!p || p.broken) return content; + let lines = [...p.lines]; + const insertAfter = (t: Table | null, bad: MapNoteProblem[], what: string) => { + if (!t || !bad.length) return; + lines = [...lines.slice(0, t.end), "", ...problemCallout(bad, what), ...lines.slice(t.end)]; + }; + // later table first so earlier indices stay valid + const order: [Table | null, MapNoteProblem[], string][] = [[p.hexT, p.hexes.bad, "Hexes"], [p.pathT, p.paths.bad, "Paths"]]; + order.sort((a, b) => (b[0]?.end ?? -1) - (a[0]?.end ?? -1)); + for (const [t, bad, what] of order) insertAfter(t, bad, what); + if (p.front.problems.length) lines = [...problemCallout(p.front.problems, "settings"), "", ...lines]; + const out = text.slice(0, p.fm!.index + p.fm![0].length) + lines.join("\n"); + return out === text ? content : out; +} + +/** Comparison key: same key ⇔ same map data (ignores formatting). */ +export function mapNoteKey(data: MapNoteData): string { + const s = data.settings as Record; + const settings = Object.keys(s).filter((k) => s[k] !== undefined && !SKIP_FIELDS.has(k) || k === "gridSize" || k === "gridOffset").sort().map((k) => [k, s[k]]); + const hexes = hexRowsToWrite(data.hexes, data.settings.baseTerrain); + return JSON.stringify([settings, hexes, data.paths.map((p) => (p.extra ? [p.typeName, p.hexes, p.extra] : [p.typeName, p.hexes]))]); +} + +/** Hex-note frontmatter keys that hold map data (they live in the map note). */ +const HEX_NOTE_DATA_KEY = /^(terrain|icon|gm-icons|gm-icon|region|duckmage-submap|locked|hexmaker-map)\s*:/; + +/** + * Prepare a new hex note's text: drop map-data keys a template may carry + * (the default one had `terrain:`) and point at the map note instead, so + * nobody edits a terrain field that the map no longer reads. + */ +export function withMapLink(content: string, mapName: string): string { + const link = `hexmaker-map: "[[_${mapName}]]"`; + const nl = content.includes("\r\n") ? "\r\n" : "\n"; + const m = /^---\r?\n([\s\S]*?)\r?\n?---(\r?\n|$)/.exec(content); + if (!m) return `---${nl}${link}${nl}---${nl}${content}`; + const kept: string[] = [link]; + let inDropped = false; + for (const line of m[1].split(/\r?\n/)) { + if (HEX_NOTE_DATA_KEY.test(line)) { inDropped = true; continue; } + // indented lines (list items) belong to the key above them + if (inDropped && /^\s+\S/.test(line)) continue; + inDropped = false; + if (line.trim()) kept.push(line); + } + return `---${nl}${kept.join(nl)}${nl}---${m[2] || nl}${content.slice(m[0].length)}`; +} diff --git a/tests/mapNote.test.ts b/tests/mapNote.test.ts index a3b0636f..b651f240 100644 --- a/tests/mapNote.test.ts +++ b/tests/mapNote.test.ts @@ -14,6 +14,10 @@ import { type HexData, type MapNoteData, } from "../src/maps/mapNote"; +import type { MapPath } from "../src/types"; + +/** An old every-hex path as the reader makes it: every hex an anchor, named after its type. */ +const dense = (typeName: string, hexes: string[], more: Partial = {}): MapPath => ({ name: typeName, typeName, branches: [{ anchors: hexes }], ...more }); const sample = (): MapNoteData => ({ settings: { @@ -37,8 +41,8 @@ const sample = (): MapNoteData => ({ ["5_5", {}], ]), paths: [ - { typeName: "Road", hexes: ["3_4", "4_4", "5_4"] }, - { typeName: "River | big", hexes: ["0_0", "0_1"] }, + { name: "King's Road", typeName: "Road", notes: "Paved | mostly", branches: [{ anchors: ["3_4", "5_4"] }, { anchors: ["4_4", "4_6"], label: "to the mill" }] }, + { name: "Big River", typeName: "River | big", branches: [{ anchors: ["0_0", "0_1"] }], extra: { Ford: "at 0, 1" } }, ], }); @@ -171,8 +175,9 @@ describe("unknown table columns (forward compatibility)", () => { expect(d.hexes.get("2_1")).toEqual({ terrain: "hills", locked: true }); // A hex whose only data is in an unknown column is still a row. expect(d.hexes.get("3_1")).toEqual({ extra: { "Ruler": "reedholm" } }); - expect(d.paths[0]).toEqual({ typeName: "Road", hexes: ["1_1", "2_1"], extra: { Name: "King's | Way" } }); - expect(d.paths[1]).toEqual({ typeName: "River", hexes: ["0_0", "0_1"] }); + expect(d.paths[0]).toEqual(dense("Road", ["1_1", "2_1"], { extra: { Name: "King's | Way" } })); + expect(d.paths[1]).toEqual(dense("River", ["0_0", "0_1"])); + expect(d.legacyPaths).toEqual(["Road", "River"]); }); it("round-trips unknown columns through parse → update → parse, in their original order", () => { @@ -196,12 +201,12 @@ describe("unknown table columns (forward compatibility)", () => { // what MapStore.set does: spread the old hex, patch known fields d.hexes.set("1_1", { ...d.hexes.get("1_1")!, terrain: "swamp", name: "Fen" }); d.hexes.set("3_1", { ...d.hexes.get("3_1")!, terrain: "grass" }); - d.paths[0] = { ...d.paths[0], hexes: [...d.paths[0].hexes, "3_1"] }; + d.paths[0] = { ...d.paths[0], branches: [{ anchors: [...d.paths[0].branches[0].anchors, "3_1"] }] }; const back = parseMapNote(updateMapNote(newer, "m", d))!; expect(back.hexes.get("1_1")).toEqual({ name: "Fen", terrain: "swamp", region: "Basin", extra: { "Ruler": "fenmarch", Rumours: "saltmere, old-mine" } }); expect(back.hexes.get("3_1")).toEqual({ terrain: "grass", extra: { "Ruler": "reedholm" } }); expect(back.paths[0].extra).toEqual({ Name: "King's | Way" }); - expect(back.paths[0].hexes).toEqual(["1_1", "2_1", "3_1"]); + expect(back.paths[0].branches[0].anchors).toEqual(["1_1", "2_1", "3_1"]); }); it("a hex with only the base terrain plus an unknown value is still written", () => { @@ -212,7 +217,8 @@ describe("unknown table columns (forward compatibility)", () => { it("notes without unknown columns are written exactly as before", () => { const note = buildMapNote("m", sample()); expect(note).toContain("| Hex | Name | Terrain | Icon | GM icons | Region | Locations | Locked |\n"); - expect(note).toContain("| Type | Route | Hexes |\n"); + expect(note).toContain("| Path | Type | Route | Notes | Ford |\n"); + expect(note).toContain("| Path | Branch | Anchors |\n"); }); it("keeps the column order (and header spelling) the user gave both tables", () => { @@ -230,10 +236,11 @@ describe("unknown table columns (forward compatibility)", () => { "", ].join("\n"); const d = parseMapNote(reordered)!; - // Converted to format 4 once: the derived Summary and Route column are added, nothing else moves. + // Converted once: the derived Summary is added, the old Paths table becomes Paths + Path routes (its extra column kept). const current = updateMapNote(reordered, "m", d); expect(current).toContain(reordered.slice(reordered.indexOf("| Terrain | Rumours"), reordered.indexOf("\n\n## Paths"))); - expect(current).toContain("| Name | Hexes | Type | Route |\n| --- | --- | --- | --- |\n| King's Way | 1_1 2_1 | Road | 1, 1 → 2, 1 (2 hexes) |"); + expect(current).toContain("| Path | Type | Route | Notes | Name |\n| --- | --- | --- | --- | --- |\n| Road | Road | 1, 1 → 2, 1 | | King's Way |"); + expect(current).toContain("## Path routes\n\n| Path | Branch | Anchors |\n| --- | --- | --- |\n| Road | main | 1, 1 → 2, 1 |"); expect(updateMapNote(current, "m", parseMapNote(current)!)).toBe(current); // an edit rewrites values in place, order unchanged (and the legend follows) d.hexes.set("2_1", { ...d.hexes.get("2_1")!, terrain: "swamp" }); @@ -319,7 +326,7 @@ describe("map notes: plain keys instead of JSON (#42)", () => { expect(fm).toContain("\nworld: wabc\nworld-x: 1\nworld-y: -1\n"); expect(fm).toContain('\nbackground-image: "[[maps/bg.png]]"\nbackground-x: 10\nbackground-y: -5\nbackground-scale: 1.5\nbackground-rotation: 0\nbackground-opacity: 0.8'); expect(fm).toContain("\nswatch-terrain: grass\n"); - expect(fm).toMatch(/^hexmaker-map: 4$/m); + expect(fm).toMatch(/^hexmaker-map: 5$/m); expect(fm).not.toMatch(/[{}]/); }); @@ -485,7 +492,7 @@ describe("map notes: forgiving tables (#42)", () => { expect(d.hexes.get("7_8")).toEqual({ terrain: "Swamp", locked: true }); expect(d.hexes.get("1_1")).toEqual({ terrain: "grass" }); expect(d.hexes.get("2_2")).toEqual({ terrain: "sand" }); - expect(d.paths).toEqual([{ typeName: "Road", hexes: ["3_4", "5_6", "7_8"] }]); + expect(d.paths).toEqual([dense("Road", ["3_4", "5_6", "7_8"])]); }); it("the next write tidies the formatting without changing any value, and keeps the column order", () => { @@ -496,7 +503,8 @@ describe("map notes: forgiving tables (#42)", () => { expect(lines[head]).toBe("| Terrain | Hex | GM icons | Locked | My Notes | Name | Icon | Region | Locations |"); expect(lines[head + 1]).toMatch(/^\| --- \|/); expect(out).toContain("| forest | 3_4 | skull.png, trap.png | yes | keep me | | | | |"); - expect(out).toContain("| Type | Route | Hexes |\n| --- | --- | --- |\n| Road | 3, 4 → 7, 8 (3 hexes) | 3_4 5_6 7_8 |"); + expect(out).toContain("| Path | Type | Route | Notes |\n| --- | --- | --- | --- |\n| Road | Road | 3, 4 → 7, 8 | |"); + expect(out).toContain("| Road | main | 3, 4 → 5, 6 → 7, 8 |"); expect(out).toContain("Some prose under the paths."); const back = parseMapNote(out)!; expect([...back.hexes].sort()).toEqual([...d.hexes].sort()); @@ -506,7 +514,7 @@ describe("map notes: forgiving tables (#42)", () => { }); describe("map notes: rows and settings that can't be read (#42)", () => { - const base = buildMapNote("m", { settings: { paletteName: "Default", gridSize: { cols: 5, rows: 5 } }, hexes: new Map([["1_1", { terrain: "grass" }]]), paths: [{ typeName: "Road", hexes: ["1_1", "2_1"] }] }); + const base = buildMapNote("m", { settings: { paletteName: "Default", gridSize: { cols: 5, rows: 5 } }, hexes: new Map([["1_1", { terrain: "grass" }]]), paths: [dense("Road", ["1_1", "2_1"])] }); const withRows = (rows: string[]) => base.replace("| 1_1 | | grass | | | | | |", ["| 1_1 | | grass | | | | | |", ...rows].join("\n")); it("keeps them as written at the end of the table and lists them in a warning callout", () => { @@ -537,13 +545,13 @@ describe("map notes: rows and settings that can't be read (#42)", () => { }); it("bad path rows are kept and reported the same way", () => { - const road = "| Road | 1, 1 → 2, 1 (2 hexes) | 1_1 2_1 |"; - const note = base.replace(road, `${road}\n| River | | 1_1 there |\n| | | 2_2 |`); + const road = "| Road | main | 1, 1 → 2, 1 |"; + const note = base.replace(road, `${road}\n| River | main | 1, 1 → there |\n| | fork | 2, 2 |`); const d = parseMapNote(note)!; - expect(d.paths).toEqual([{ typeName: "Road", hexes: ["1_1", "2_1"] }]); - expect(d.problems!.map((p) => p.where)).toEqual(["Paths", "Paths"]); + expect(d.paths).toEqual([dense("Road", ["1_1", "2_1"])]); + expect(d.problems!.map((p) => p.where)).toEqual(["Path routes", "Path routes"]); const out = updateMapNote(note, "m", d); - expect(out).toContain("| River | | 1_1 there |"); + expect(out).toContain("| River | main | 1, 1 → there |"); expect(out).toContain("> [!warning] Hexmaker couldn't read 2 rows in this table"); }); @@ -641,7 +649,7 @@ describe("map notes: the derived Summary (format 4, #46 M1)", () => { ["2_0", { terrain: "Mountain Ridge", locations: ["saltmere", "old-mine"] }], ["3_0", { name: "Lone Oak" }], ]), - paths: [{ typeName: "Road", hexes: ["0_0", "1_0", "2_0"] }, { typeName: "Trail", hexes: ["-7_-8"] }], + paths: [dense("Road", ["0_0", "1_0", "2_0"]), dense("Trail", ["-7_-8"])], }); const summaryOf = (note: string) => note.slice(note.indexOf("## Summary"), note.indexOf("## Hexes")); @@ -702,30 +710,35 @@ describe("map notes: the derived Summary (format 4, #46 M1)", () => { }); }); -describe("map notes: derived Paths columns (format 4, #46 M2)", () => { +describe("map notes: the derived Route column (format 5)", () => { const ctx = { pathTypes: ["Road", "River"] }; const data = (paths: MapNoteData["paths"]): MapNoteData => ({ settings: { paletteName: "Default" }, hexes: new Map(), paths }); - it("Route reads start → end and the length; Warning only while a type isn't in the palette", () => { - const note = buildMapNote("m", data([{ typeName: "Road", hexes: ["3_4", "4_4", "5_4"] }, { typeName: "Trail", hexes: ["-1_2"] }]), ctx); - expect(note).toContain("| Type | Route | Warning | Hexes |"); - expect(note).toContain("| Road | 3, 4 → 5, 4 (3 hexes) | | 3_4 4_4 5_4 |"); - expect(note).toContain("| Trail | -1, 2 (1 hex) | ⚠ not a path type in the palette | -1_2 |"); - const d = parseMapNote(note)!; + it("reads main-line ends and forks; with routed stats the hexes; warns about the type and straight segments", () => { + const road: MapPath = { name: "King's Road", typeName: "Road", branches: [{ anchors: ["0_8", "9_8", "13_8"] }, { anchors: ["9_8", "9_12"] }, { anchors: ["13_8", "15_5"] }] }; + const trail: MapPath = { name: "Old Track", typeName: "Trail", branches: [{ anchors: ["-1_2"] }] }; + const bare: MapPath = { name: "Plan", typeName: "Road", branches: [] }; + const note = buildMapNote("m", data([road, trail, bare]), { + ...ctx, + pathRoutes: { "king's road": { hexes: 31, fallbacks: [["9_8", "9_12"]] } }, + }); + expect(note).toContain("| King's Road | Road | 0, 8 → 13, 8 · 2 forks · 31 hexes · ⚠ no route from 9, 8 to 9, 12: drawn straight | |"); + expect(note).toContain("| Old Track | Trail | -1, 2 · ⚠ type not in palette | |"); + expect(note).toContain("| Plan | Road | no route yet | |"); // derived cells are never read back (not kept as unknown columns) - expect(d.paths).toEqual([{ typeName: "Road", hexes: ["3_4", "4_4", "5_4"] }, { typeName: "Trail", hexes: ["-1_2"] }]); + const d = parseMapNote(note)!; + expect(d.paths).toEqual([road, trail, bare]); d.paths[1].typeName = "River"; - const out = updateMapNote(note, "m", d, ctx); - expect(out).toContain("| Type | Route | Hexes |"); - expect(out).not.toContain("| Warning"); - expect(out).not.toContain("⚠"); + expect(updateMapNote(note, "m", d, ctx)).not.toContain("⚠"); }); - it("hand edits to Hexes regenerate Route; a hand-edited Route is replaced", () => { - const note = buildMapNote("m", data([{ typeName: "Road", hexes: ["3_4", "4_4"] }]), ctx); - const edited = note.replace("| Road | 3, 4 → 4, 4 (2 hexes) | 3_4 4_4 |", "| Road | the old road | 3_4 4_4 4_5 |"); - const d = parseMapNote(edited)!; - expect(d.paths).toEqual([{ typeName: "Road", hexes: ["3_4", "4_4", "4_5"] }]); - expect(updateMapNote(edited, "m", d, ctx)).toContain("| Road | 3, 4 → 4, 5 (3 hexes) | 3_4 4_4 4_5 |"); + it("a hand-edited Route is replaced; format 4's Warning column is dropped", () => { + const note = buildMapNote("m", data([dense("Road", ["3_4", "4_4"])]), ctx); + const edited = note.replace("| Road | Road | 3, 4 → 4, 4 | |", "| Road | Road | the old road | |"); + expect(updateMapNote(edited, "m", parseMapNote(edited)!, ctx)).toBe(note); + const withWarning = note.replace("| Path | Type | Route | Notes |\n| --- | --- | --- | --- |\n| Road | Road | 3, 4 → 4, 4 | |", "| Path | Type | Route | Warning | Notes |\n| --- | --- | --- | --- | --- |\n| Road | Road | 3, 4 → 4, 4 | ⚠ old | |"); + expect(parseMapNote(withWarning)!.paths).toEqual([dense("Road", ["3_4", "4_4"])]); + expect(updateMapNote(withWarning, "m", parseMapNote(withWarning)!, ctx)).toBe(note); }); }); + diff --git a/tests/mapNotePaths.test.ts b/tests/mapNotePaths.test.ts new file mode 100644 index 00000000..7fd588f7 --- /dev/null +++ b/tests/mapNotePaths.test.ts @@ -0,0 +1,532 @@ +/** + * Map note format 5 (plan-path-anchors section 2 and 6): named paths in + * `## Paths`, anchors in `## Path routes`, the forgiving reader, hand edits, + * old every-hex tables, the old-build guard, and MapStore's side (the + * three-way merge, legacy conversion, the compatibility view, readiness and + * pinning when the routing context changes). + */ +import { describe, it, beforeEach } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { Notice } from "obsidian"; +import { + buildMapNote, + MAP_NOTE_FORMAT, + mapNoteKey, + parseMapNote, + readMapNote, + refreshProblemCallouts, + updateMapNote, + type MapNoteData, +} from "../src/maps/mapNote"; +import * as format4 from "./fixtures/compat/map-note-formats/parser-format-4"; +import { MapStore, mergePaths } from "../src/maps/MapStore"; +import { MemVault } from "./helpers/memVault"; +import type { MapData, MapPath, PathChain } from "../src/types"; +import { DEFAULT_PATH_TYPES, DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { mapRouteContext, pathTypeStyleFor } from "../src/paths/mapContext"; +import { resolvePaths, resolvedToChains } from "../src/paths/resolve"; +import { compactLegacy, stepsOf } from "../src/paths/fromHexes"; +import { legacyChainsToPaths } from "../src/paths/legacy"; +import { impassableNames } from "../src/impassable"; +import { buildView, reconcile } from "../src/paths/chainView"; + +(globalThis as Record).window ??= globalThis; + +const compat = path.join(process.cwd(), "tests", "fixtures", "compat"); +const read = (...p: string[]) => readFileSync(path.join(compat, ...p), "utf8").replace(/\r\n/g, "\n"); + +const P = (name: string, typeName: string, ...branches: string[][]): MapPath => ({ name, typeName, branches: branches.map((anchors) => ({ anchors })) }); +const data = (paths: MapPath[]): MapNoteData => ({ settings: { paletteName: "Default", gridSize: { cols: 20, rows: 20 }, gridOffset: { x: 0, y: 0 } }, hexes: new Map(), paths }); + +/** A format-5 note with the given Paths and Path routes table lines. */ +const note5 = (paths: string[], routes: string[]) => [ + "---", `hexmaker-map: ${MAP_NOTE_FORMAT}`, "palette: Default", "cols: 20", "rows: 20", "offset-x: 0", "offset-y: 0", "---", "# m", "", + "## Hexes", "", "| Hex | Terrain |", "| --- | --- |", "| 1_1 | forest |", "", + "## Paths", "", ...paths, "", + "## Path routes", "", ...routes, "", +].join("\n"); + +const KINGS: MapPath = { + name: "King's Road", typeName: "Road", notes: "Paved as far as Saltmere.", + branches: [{ anchors: ["0_8", "9_8", "13_8"] }, { anchors: ["9_8", "9_12", "11_14"], label: "to Saltmere" }, { anchors: ["13_8", "15_5"] }], +}; + +describe("map note format 5: Paths + Path routes", () => { + it("round-trips names, types, notes, forks, labels and extra columns", () => { + const glass: MapPath = { name: "Glass River", typeName: "River", branches: [{ anchors: ["4_0", "4_5"], extra: { Ford: "at 4, 3" } }], extra: { Danger: "eels" } }; + const d = data([KINGS, glass]); + const text = buildMapNote("m", d); + expect(text).toContain("## Paths\n\n| Path | Type | Route | Notes | Danger |\n| --- | --- | --- | --- | --- |\n| King's Road | Road | 0, 8 → 13, 8 · 2 forks | Paved as far as Saltmere. | |\n| Glass River | River | 4, 0 → 4, 5 | | eels |"); + expect(text).toContain("## Path routes\n\n| Path | Branch | Anchors | Ford |\n| --- | --- | --- | --- |\n| King's Road | main | 0, 8 → 9, 8 → 13, 8 | |\n| King's Road | to Saltmere | 9, 8 → 9, 12 → 11, 14 | |\n| King's Road | fork | 13, 8 → 15, 5 | |\n| Glass River | main | 4, 0 → 4, 5 | at 4, 3 |"); + const back = parseMapNote(text)!; + expect(back.paths).toEqual([KINGS, glass]); + expect(back.problems).toEqual([]); + expect(back.legacyPaths).toBeUndefined(); + expect(mapNoteKey(back)).toBe(mapNoteKey(d)); + expect(updateMapNote(text, "m", back)).toBe(text); + }); + + it("the help box explains both tables and to rename a path in both", () => { + const text = buildMapNote("m", data([])); + expect(text).toContain("> - **Paths**: one row per path."); + expect(text).toContain("A path's `main` row is its main line; every other row is a fork that leaves the path at its first hex. To rename a path, edit *Path* in both tables."); + }); +}); + +describe("map note format 5: forgiving Path routes (section 2)", () => { + const paths = ["| Path | Type | Route | Notes |", "| --- | --- | --- | --- |", "| King's Road | Road | | |"]; + + it("reads every coordinate form and separator, and writes them back canonically", () => { + const forms: [string, string[]][] = [ + ["3, 4 → 9, 4", ["3_4", "9_4"]], + ["3,4 -> 9,4", ["3_4", "9_4"]], + ["3_4 > 9_4", ["3_4", "9_4"]], + ["(3, 4); (9, 4)", ["3_4", "9_4"]], + ["-1, -4 → 0, -3", ["-1_-4", "0_-3"]], + ["3, 4 9, 4 9, 6", ["3_4", "9_4", "9_6"]], + ]; + for (const [cell, anchors] of forms) { + const text = note5(paths, ["| Path | Branch | Anchors |", "| --- | --- | --- |", `| King's Road | main | ${cell} |`]); + const d = parseMapNote(text)!; + expect(d.problems).toEqual([]); + expect(d.paths[0].branches).toEqual([{ anchors }]); + const out = updateMapNote(text, "m", d); + expect(out).toContain(`| King's Road | main | ${anchors.map((k) => k.replace("_", ", ")).join(" → ")} |`); + } + }); + + it("header case, spacing, column order and a missing |---| row don't matter", () => { + const text = note5(["path | TYPE | notes", "King's Road | Road | old"], ["| anchors | Branch | PATH |", "| 3, 4 → 9, 4 | main | King's Road |"]); + const d = parseMapNote(text)!; + expect(d.problems).toEqual([]); + expect(d.paths).toEqual([{ name: "King's Road", typeName: "Road", notes: "old", branches: [{ anchors: ["3_4", "9_4"] }] }]); + const out = updateMapNote(text, "m", d); + // Route, which the table lacked, goes right after Type. + expect(out).toContain("| Path | Type | Route | Notes |\n| --- | --- | --- | --- |\n| King's Road | Road | 3, 4 → 9, 4 | old |"); + expect(out).toContain("| Anchors | Branch | Path |\n| --- | --- | --- |\n| 3, 4 → 9, 4 | main | King's Road |"); + expect(updateMapNote(out, "m", parseMapNote(out)!)).toBe(out); + }); + + it("a path's rows may be anywhere: the main row is the main line, the others keep their order", () => { + const text = note5(paths, [ + "| Path | Branch | Anchors |", "| --- | --- | --- |", + "| King's Road | fork | 13, 8 → 15, 5 |", + "| Other | main | 1, 1 → 2, 1 |", + "| King's Road | main | 0, 8 → 13, 8 |", + "| King's Road | west | 0, 8 → 0, 2 |", + ]); + const d = parseMapNote(text)!; + expect(d.paths[0].branches).toEqual([{ anchors: ["0_8", "13_8"] }, { anchors: ["13_8", "15_5"] }, { anchors: ["0_8", "0_2"], label: "west" }]); + const out = updateMapNote(text, "m", d); + expect(out).toContain("| King's Road | main | 0, 8 → 13, 8 |\n| King's Road | fork | 13, 8 → 15, 5 |\n| King's Road | west | 0, 8 → 0, 2 |\n| Other | main | 1, 1 → 2, 1 |"); + }); + + it("matches a routes row to its Paths row ignoring case and spacing; the next write fixes the spelling", () => { + const text = note5(paths, ["| Path | Branch | Anchors |", "| --- | --- | --- |", "| king's ROAD | main | 3, 4 → 9, 4 |"]); + const d = parseMapNote(text)!; + expect(d.paths).toHaveLength(1); + expect(d.paths[0].branches[0].anchors).toEqual(["3_4", "9_4"]); + expect(updateMapNote(text, "m", d)).toContain("| King's Road | main | 3, 4 → 9, 4 |"); + }); + + it("rows that can't be read are kept as written, listed, and never half-imported", () => { + const bad = [ + "| King's Road | fork | 3, 4 → nine, 4 |", + "| King's Road | fork | 3, 4, 9 |", + "| King's Road | fork | |", + "| | main | 1, 1 → 2, 2 |", + ]; + const text = note5(paths, ["| Path | Branch | Anchors |", "| --- | --- | --- |", "| King's Road | main | 3, 4 → 9, 4 |", ...bad]); + const d = parseMapNote(text)!; + expect(d.paths[0].branches).toEqual([{ anchors: ["3_4", "9_4"] }]); + expect(d.problems!.map((p) => [p.where, p.text])).toEqual(bad.map((b) => ["Path routes", b])); + expect(d.problems!.map((p) => p.reason)).toEqual([ + "Anchors: can't read \"nine, 4\" (write them like 3, 4 → 9, 4)", + "Anchors: an odd number of coordinates (3): every anchor needs an x and a y (write them like 3, 4 → 9, 4)", + "Anchors: no anchors (write them like 3, 4 → 9, 4)", + "no path name in the Path column", + ]); + const out = updateMapNote(text, "m", d); + const table = out.slice(out.indexOf("| Path | Branch")); + expect(table).toContain(["| King's Road | main | 3, 4 → 9, 4 |", ...bad, "", "> [!warning] Hexmaker couldn't read 4 rows in this table"].join("\n")); + expect(updateMapNote(out, "m", parseMapNote(out)!)).toBe(out); + // refreshing only the callouts of the hand-edited note puts the same box in + expect(refreshProblemCallouts(text)).toContain("> [!warning] Hexmaker couldn't read 4 rows in this table"); + }); +}); + +describe("map note format 5: the hand-edit table (section 2)", () => { + const routes = (...rows: string[]) => ["| Path | Branch | Anchors |", "| --- | --- | --- |", ...rows]; + const ctx = { pathTypes: ["Road", "River"] }; + + it("a routes row for a path not in Paths: created with no type, flagged, and given a Paths row on write", () => { + const text = note5(["| Path | Type | Route | Notes |", "| --- | --- | --- | --- |"], routes("| Old Track | main | 2, 2 → 6, 1 |")); + const d = parseMapNote(text)!; + expect(d.paths).toEqual([P("Old Track", "", ["2_2", "6_1"])]); + const out = updateMapNote(text, "m", d, ctx); + expect(out).toContain("| Old Track | | 2, 2 → 6, 1 · ⚠ no type: fill in Type | |"); + expect(out).toContain("- **⚠ Paths with no type:** Old Track."); + }); + + it("a Paths row with no routes rows is kept, with no route yet", () => { + const text = note5(["| Path | Type | Route | Notes |", "| --- | --- | --- | --- |", "| Plan | Road | | someday |"], routes()); + const d = parseMapNote(text)!; + expect(d.paths).toEqual([{ name: "Plan", typeName: "Road", notes: "someday", branches: [] }]); + expect(updateMapNote(text, "m", d, ctx)).toContain("| Plan | Road | no route yet | someday |"); + }); + + it("an unknown type is kept as typed and flagged in Route", () => { + const text = note5(["| Path | Type | Route | Notes |", "| --- | --- | --- | --- |", "| Old Track | Trail | | |"], routes("| Old Track | main | 2, 2 → 6, 1 |")); + const d = parseMapNote(text)!; + expect(d.paths[0].typeName).toBe("Trail"); + expect(updateMapNote(text, "m", d, ctx)).toContain("| Old Track | Trail | 2, 2 → 6, 1 · ⚠ type not in palette | |"); + }); + + it("a duplicate path name in Paths: the first wins, the duplicate is kept as written and flagged", () => { + const text = note5(["| Path | Type | Route | Notes |", "| --- | --- | --- | --- |", "| Road | Road | | |", "| road | River | | |"], routes("| Road | main | 1, 1 → 2, 1 |")); + const d = parseMapNote(text)!; + expect(d.paths).toEqual([P("Road", "Road", ["1_1", "2_1"])]); + expect(d.problems!.map((p) => [p.where, p.text])).toEqual([["Paths", "| road | River | | |"]]); + const out = updateMapNote(text, "m", d); + expect(out).toContain("| Road | Road | 1, 1 → 2, 1 | |\n| road | River | | |\n\n> [!warning]"); + }); + + it("a pasted old Type | Hexes table is read (every hex an anchor) and written back in the new form", () => { + const text = note5( + ["| Path | Type | Route | Notes |", "| --- | --- | --- | --- |", "| Road | Road | | |", "", "| Type | Hexes |", "| --- | --- |", "| River | 4_0 4_1 4_2 |", "| Road | 1_1 x_y |"], + routes("| Road | main | 1, 1 → 2, 1 |"), + ); + const d = parseMapNote(text)!; + expect(d.paths).toEqual([P("Road", "Road", ["1_1", "2_1"]), P("River", "River", ["4_0", "4_1", "4_2"])]); + expect(d.legacyPaths).toEqual(["River"]); + expect(d.problems!.map((p) => p.text)).toEqual(["| Road | 1_1 x_y |"]); + const out = updateMapNote(text, "m", d); + expect(out).toContain("| River | main | 4, 0 → 4, 1 → 4, 2 |"); + // The old table keeps only the row it couldn't read, with its warning. + expect(out).toContain("| Type | Hexes |\n| --- | --- |\n| Road | 1_1 x_y |\n\n> [!warning] Hexmaker couldn't read a row in this table"); + expect(out).not.toContain("4_0 4_1"); + const back = parseMapNote(out)!; + expect(back.paths).toEqual(d.paths); + expect(updateMapNote(out, "m", back)).toBe(out); + }); + + it("a fork row whose first anchor isn't on the path is read as written (its own stretch)", () => { + const text = note5(["| Path | Type | Route | Notes |", "| --- | --- | --- | --- |", "| Road | Road | | |"], routes("| Road | main | 1, 1 → 3, 1 |", "| Road | fork | 8, 8 → 9, 9 |")); + expect(parseMapNote(text)!.paths[0].branches).toEqual([{ anchors: ["1_1", "3_1"] }, { anchors: ["8_8", "9_9"] }]); + }); +}); + +describe("map note format 5: old and newer builds", () => { + it("(d) a format-4 build reads a format-5 note as broken, never with wrong paths", () => { + const text = buildMapNote("m", data([KINGS])); + const r = format4.readMapNote(text); + expect(r && r.ok).toBe(false); + expect(r && !r.ok && r.reason).toContain("Paths table"); + }); + + it("this build reads a note from a newer build as broken, naming the format and saying to update", () => { + const text = buildMapNote("m", data([KINGS])).replace(`hexmaker-map: ${MAP_NOTE_FORMAT}`, `hexmaker-map: ${MAP_NOTE_FORMAT + 1}`); + const r = readMapNote(text)!; + expect(r.ok).toBe(false); + if (r.ok) return; + expect(r.newer).toBe(MAP_NOTE_FORMAT + 1); + expect(r.reason).toContain(`map-note format ${MAP_NOTE_FORMAT + 1}`); + expect(r.reason).toContain("Update the plugin"); + }); + + it("format 4 still reads, and converts to Paths + Path routes with the help line replaced", () => { + const text = read("map-note-formats", "format-4.md"); + const d = parseMapNote(text)!; + expect(d.format).toBe(4); + const out = updateMapNote(text, "compat-example", d, { pathTypes: ["Road", "River"] }); + expect(out).toMatch(new RegExp(`^hexmaker-map: ${MAP_NOTE_FORMAT}$`, "m")); + expect(out).not.toContain("| Warning |"); + expect(out).toContain("| Road | Road | 0, 8 → 13, 8 | Paved as far as Saltmere. |"); + expect(out).toContain("To rename a path, edit *Path* in both tables."); + expect(out).not.toContain("*Hexes* lists its hexes"); + expect(mapNoteKey(parseMapNote(out)!)).toBe(mapNoteKey(d)); + }); +}); + +// ── MapStore ──────────────────────────────────────────────────────────────── + +const NOTE = "world/hexes/m/_m.md"; + +function plugin(vault: MemVault, maps: MapData[], palette = DEFAULT_TERRAIN_PALETTE) { + return { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", maps, hexOrientation: "flat" as const, staggerOffset: "odd" as const }, + getMap: (n: string) => maps.find((m) => m.name === n), + getMapPalette: () => palette, + getMapPathTypes: () => DEFAULT_PATH_TYPES, + saveData: async () => {}, + refreshHexMap: () => {}, + }; +} + +async function boot(vault: MemVault, maps: MapData[]) { + const p = plugin(vault, maps); + const store = new MapStore(p as never); + await store.init(); + return { p, store }; +} + +const fixtureMap = (extra: Partial = {}): MapData => ({ name: "m", paletteName: "Default", gridSize: { cols: 14, rows: 10 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", baseTerrain: "grass", pathChains: [], ...extra } as MapData); + +/** The fixture's terrain (from the 1.5.6 map note) as a routing context, the way MapStore builds it. */ +function fixtureContext() { + const d = parseMapNote(read("1.5.6", "map-note.md"))!; + return { + hexes: d.hexes, + ctx: mapRouteContext({ orientation: "flat", stagger: "odd", gridSize: { cols: 14, rows: 10 }, gridOffset: { x: 0, y: 0 }, baseTerrain: "grass", terrainOf: d.hexes, impassable: impassableNames(DEFAULT_TERRAIN_PALETTE) }), + }; +} + +const sameSteps = (a: Iterable, b: Iterable) => { + const x = stepsOf(a), y = stepsOf(b); + return x.size === y.size && [...x].every((s) => y.has(s)); +}; + +describe("migration from every-hex chains (section 6 tests a–c)", () => { + beforeEach(() => { Notice.shown = []; }); + + it("(a) format 3 rows read into dense anchors equal to the old hexes", () => { + const d = parseMapNote(read("map-note-formats", "format-3.md"))!; + expect(d.paths.map((p) => p.branches[0].anchors)).toEqual([ + Array.from({ length: 14 }, (_, x) => `${x}_8`), + ["4_0", "4_1", "4_2", "4_3", "4_4", "4_5"], + ]); + }); + + it("(b) a format-4 note converts once (backup + report), merges touching chains, drops bare one-hex leftovers, and draws the same steps", async () => { + const text = read("map-note-formats", "format-4.md"); + const before = parseMapNote(text)!; + const v = new MemVault({ [NOTE]: text }); + const m = [fixtureMap()]; + const { store } = await boot(v, m); + const now = v.files.get(NOTE)!; + expect(now).toMatch(new RegExp(`^hexmaker-map: ${MAP_NOTE_FORMAT}$`, "m")); + // the main road and its branch south from 9, 8 are one path now; the one-hex Road at 12, 2 is gone + const d = parseMapNote(now)!; + expect(d.paths.map((p) => [p.name, p.typeName, p.branches.length])).toEqual([["Road", "Road", 2], ["River", "River", 1], ["Old Track", "Old Track", 1]]); + expect(d.paths[0].notes).toBe("Paved as far as Saltmere."); + expect(d.paths[0].branches[1].anchors[0]).toBe("9_8"); + // every type's drawn steps are exactly the old chains' steps + const resolved = store.resolved("m")!; + for (const type of ["Road", "River", "Old Track"]) { + const old = before.paths.filter((p) => p.typeName === type && p.branches[0].anchors.length > 1).map((p) => p.branches[0].anchors); + expect(sameSteps(resolved.filter((r) => r.typeName === type).map((r) => r.hexes), old)).toBe(true); + } + // the compatibility view is those chains + expect(sameSteps(m[0].pathChains.map((c) => c.hexes), resolved.map((r) => r.hexes))).toBe(true); + // fewer anchors than hexes + expect(d.paths[0].branches[0].anchors.length).toBeLessThan(14); + const files = [...v.files.keys()].filter((k) => k.includes("/backups/map-notes-")).map((k) => k.split("/").pop()); + expect(files.sort()).toEqual(["m-map-note.md", "m-paths-report.md"]); + const report = v.files.get([...v.files.keys()].find((k) => k.endsWith("m-paths-report.md"))!)!; + expect(report).toContain("- Old paths (every hex listed): 5"); + expect(report).toContain("- One-hex leftovers dropped (no notes): 1"); + expect(report).toContain("- Road 3 (Road) at 12, 2"); + expect(report).toContain("- Road: Road, Road 2"); + expect(Notice.shown.some((n) => n.msg.includes("moved to the new format") && n.msg.includes("one-hex leftover"))).toBe(true); + // a restart rewrites nothing + v.writes = []; + await boot(v, [fixtureMap()]); + expect(v.writes).toEqual([]); + }); + + it("(c) the 1.5.6 map.json (data.json chains, no note yet) becomes format 5 drawing the same hexes", async () => { + const json = JSON.parse(read("1.5.6", "map.json")) as MapData; + const { hexes, ctx } = fixtureContext(); + // the store migrates hex notes; give it the fixture's terrain as hex notes + const files: Record = {}; + for (const [k, h] of hexes) if (h.terrain) files[`world/hexes/m/${k}.md`] = `---\nterrain: ${h.terrain}\n---\n`; + const v = new MemVault(files); + const m = [fixtureMap({ pathChains: json.pathChains })]; + const old = json.pathChains.map((c) => c.hexes); + const { store } = await boot(v, m); + const d = parseMapNote(v.files.get(NOTE)!)!; + expect(d.format).toBe(MAP_NOTE_FORMAT); + expect(d.paths.map((p) => p.name)).toEqual(["Road", "River"]); + // resolved chains equal the old chains, hex for hex + expect(store.resolved("m")!.map((r) => r.hexes)).toEqual(old); + // and the same holds for a resolver that only has the note and the palette + const styleFor = pathTypeStyleFor(DEFAULT_PATH_TYPES); + expect(resolvedToChains(resolvePaths(d.paths, ctx, styleFor)).map((c) => c.hexes)).toEqual(old); + expect(m[0].pathChains.map((c) => c.hexes)).toEqual(old); + // the old chains are in the backup + const backup = JSON.parse(v.files.get([...v.files.keys()].find((k) => k.endsWith("/m.json"))!)!); + expect(backup.pathChains.map((c: PathChain) => c.hexes)).toEqual(old); + }); + + it("drops only bare one-hex leftovers: one with notes or an extra column stays", () => { + const { ctx } = fixtureContext(); + const paths = legacyChainsToPaths([ + { typeName: "Road", hexes: ["1_1"] }, + { typeName: "Road", hexes: ["2_2"], extra: { Notes: "the old well" } }, + { typeName: "Road", hexes: ["3_3"], extra: { Owner: "Ada" } }, + ]); + const { paths: out, report } = compactLegacy(paths, ctx, { dropSingles: true, styleFor: pathTypeStyleFor(DEFAULT_PATH_TYPES) }); + expect(out.map((p) => [p.branches[0].anchors, p.notes ?? "", p.extra ?? {}])).toEqual([[["2_2"], "the old well", {}], [["3_3"], "", { Owner: "Ada" }]]); + expect(report.singlesDropped.map((s) => s.hex)).toEqual(["1_1"]); + }); +}); + +describe("map store: path edits, hand edits and the three-way merge", () => { + beforeEach(() => { Notice.shown = []; }); + + const fresh = async () => { + const v = new MemVault(); + const m = [fixtureMap({ pathChains: [{ typeName: "Road", hexes: ["0_0", "1_0", "2_0", "3_0"] }] })]; + const r = await boot(v, m); + return { v, m, ...r }; + }; + const modify = async (store: MapStore, p: ReturnType, v: MemVault, text: string) => { + v.files.set(NOTE, text); + store.onModify(p.app.vault.getAbstractFileByPath(NOTE) as never); + await store.flush(); + }; + + it("a hand edit to Path routes is imported (anchor added, formatting normalised, a garbage row reported)", async () => { + const { v, m, p, store } = await fresh(); + const text = v.files.get(NOTE)!; + const row = text.split("\n").find((l) => l.startsWith("| Road | main |"))!; + const edited = text.replace(row, "|road|MAIN| 0,0 -> 3,0 ; 3_3 |\n| Road | fork | banana |"); + await modify(store, p, v, edited); + expect(m[0].paths![0].branches[0].anchors).toEqual(["0_0", "3_0", "3_3"]); + // the compatibility view follows + expect(m[0].pathChains[0].hexes.slice(-1)).toEqual(["3_3"]); + expect(Notice.shown.some((n) => n.msg.includes("couldn't be read") && n.msg.includes("banana"))).toBe(true); + // the next write normalises and keeps the bad row with its warning + store.set("m", "5_5", { terrain: "forest" }); + await store.flush(); + const out = v.files.get(NOTE)!; + expect(out).toContain("| Road | main | 0, 0 → 3, 0 → 3, 3 |\n| Road | fork | banana |\n\n> [!warning] Hexmaker couldn't read a row in this table"); + }); + + it("three-way merge by name: our pending edit and their hand edit to another path both survive", async () => { + const v = new MemVault(); + const m = [fixtureMap({ pathChains: [{ typeName: "Road", hexes: ["0_0", "1_0"] }, { typeName: "River", hexes: ["5_0", "5_1"] }] })]; + const { store } = await boot(v, m); + // ours: extend the road through the old view (as the path tool does) + m[0].pathChains[0].hexes.push("2_0"); + // theirs, on disk, not seen by the store yet: rename the river's notes + const text = v.files.get(NOTE)!; + const river = text.split("\n").find((l) => l.startsWith("| River | River |"))!; + v.files.set(NOTE, text.replace(river, river.replace(/\| \|$/, "| muddy |"))); + store.set("m", "9_9", { terrain: "forest" }); // any write + await store.flush(); + const d = parseMapNote(v.files.get(NOTE)!)!; + expect(d.paths.find((p) => p.name === "River")!.notes).toBe("muddy"); + expect(store.resolved("m")!.find((r) => r.path === "Road")!.hexes).toEqual(["0_0", "1_0", "2_0"]); + }); + + it("mergePaths: theirs wins where they changed it, ours elsewhere; deletions on either side stick", () => { + const base = [P("A", "Road", ["1_1", "2_1"]), P("B", "Road", ["5_5", "6_5"]), P("C", "River", ["0_0", "0_1"])]; + const theirs = [P("A", "Road", ["1_1", "3_1"]), P("C", "River", ["0_0", "0_1"]), P("D", "Road", ["9_9", "9_8"])]; + const ours = [P("A", "Road", ["1_1", "2_1"]), P("B", "Road", ["5_5", "7_5"]), P("C", "River", ["0_0", "0_2"]), P("E", "Trail", ["4_4", "4_5"])]; + expect(mergePaths(base, theirs, ours).map((p) => [p.name, p.branches[0].anchors.join(" ")])).toEqual([ + ["A", "1_1 3_1"], // they changed it + ["C", "0_0 0_2"], // we changed it + ["D", "9_9 9_8"], // they added it + ["E", "4_4 4_5"], // we added it + ]); // B: they deleted it + }); + + it("isReady(map): not before load, not for a broken note, yes once terrain and palette are in", async () => { + const v = new MemVault({ [NOTE]: "---\nhexmaker-map: 5\n---\n## Hexes\n| Terrain |\n| --- |\n| x |\n" }); + const m = [fixtureMap(), fixtureMap({ name: "n" })]; + const p = plugin(v, m); + const store = new MapStore(p as never); + expect(store.isReady("n")).toBe(false); + expect(store.resolved("n")).toBeNull(); + await store.init(); + expect(store.isReady()).toBe(true); + expect(store.isReady("m")).toBe(false); // its note can't be read + expect(store.isReady("n")).toBe(true); + expect(store.resolved("n")).toEqual([]); + }); + + it("painting impassable terrain under a road keeps its route (anchors added); a context listener can take over", async () => { + const v = new MemVault(); + const m = [fixtureMap({ pathChains: [{ typeName: "Road", hexes: ["0_5", "1_5", "2_5", "3_5", "4_5", "5_5", "6_5"] }] })]; + const { store } = await boot(v, m); + const before = store.resolved("m")![0].hexes; + expect(m[0].paths![0].branches[0].anchors.length).toBeLessThan(before.length); + const anchors = m[0].paths![0].branches[0].anchors.length; + store.set("m", "3_5", { terrain: "shallows" }); // water: impassable by its type + expect(store.resolved("m")![0].hexes).toEqual(before); + expect(m[0].paths![0].branches[0].anchors.length).toBeGreaterThan(anchors); + // forest changes nothing + const pinned = JSON.stringify(m[0].paths); + store.set("m", "4_5", { terrain: "forest" }); + store.resolved("m"); + expect(JSON.stringify(m[0].paths)).toBe(pinned); + // a listener that handles it: the store doesn't pin + const seen: string[] = []; + store.onRouteContextChange((e) => { seen.push(e.map); return true; }); + store.set("m", "5_5", { terrain: "shallows" }); + expect(seen).toEqual(["m"]); + expect(JSON.stringify(m[0].paths)).toBe(pinned); + }); + + it("a format-6 note is broken with a notice that names the format and says to update", async () => { + const v = new MemVault({ [NOTE]: buildMapNote("m", data([KINGS])).replace(`hexmaker-map: ${MAP_NOTE_FORMAT}`, "hexmaker-map: 6") }); + const before = v.files.get(NOTE); + const { store } = await boot(v, [fixtureMap()]); + expect(store.holdsPaths("m")).toBe(false); + expect(Notice.shown.some((n) => n.msg.includes("map-note format 6") && n.msg.includes("Update Hexmap World Creator"))).toBe(true); + expect(v.files.get(NOTE)).toBe(before); + }); +}); + +describe("the compatibility view (pathChains ↔ paths)", () => { + const route = (hexes: string[]) => hexes; // dense anchors (exact by construction) + const anchorsOf = (_t: string, h: string[]) => route(h); + const view = (paths: MapPath[]) => buildView(paths.flatMap((p) => p.branches.map((b, i) => ({ path: p.name, typeName: p.typeName, branch: i, hexes: b.anchors, anchorIdx: [], fallbackSegments: [] })))); + + it("an in-place push edits that branch; names, notes and the other branches stay", () => { + const paths = [{ ...P("King's Road", "Road", ["0_0", "1_0"], ["1_0", "1_1"]), notes: "paved" }]; + const { chains, view: v } = view(paths); + chains[0].hexes.push("2_0"); + const r = reconcile(paths, chains, v, anchorsOf); + expect(r.changed).toBe(true); + expect(r.paths).toEqual([{ ...P("King's Road", "Road", ["0_0", "1_0", "2_0"], ["1_0", "1_1"]), notes: "paved" }]); + }); + + it("a new chain is a new path named after its type; a removed one goes, and undo brings its name back", () => { + const paths = [P("King's Road", "Road", ["0_0", "1_0"])]; + const { chains, view: v } = view(paths); + const r1 = reconcile(paths, [...chains, { typeName: "Road", hexes: ["5_5", "6_5"] }], v, anchorsOf); + expect(r1.paths.map((p) => p.name)).toEqual(["King's Road", "Road"]); + const r2 = reconcile(r1.paths, [], r1.view, anchorsOf); + expect(r2.paths).toEqual([]); + // undo: snapshot clones come back + const r3 = reconcile(r2.paths, [{ typeName: "Road", hexes: ["0_0", "1_0"] }], r2.view, anchorsOf); + expect(r3.paths.map((p) => p.name)).toEqual(["King's Road"]); + }); + + it("splitting a chain keeps both pieces as branches of the same path", () => { + const paths = [P("King's Road", "Road", ["0_0", "1_0", "2_0", "3_0", "4_0"])]; + const { chains, view: v } = view(paths); + const r = reconcile(paths, [{ typeName: "Road", hexes: ["0_0", "1_0"] }, { typeName: "Road", hexes: ["3_0", "4_0"] }], v, anchorsOf); + void chains; + expect(r.paths).toEqual([P("King's Road", "Road", ["0_0", "1_0"], ["3_0", "4_0"])]); + }); + + it("renaming a type on every chain of a path renames the path's type", () => { + const paths = [P("King's Road", "Road", ["0_0", "1_0"], ["1_0", "1_1"])]; + const { chains, view: v } = view(paths); + for (const c of chains) c.typeName = "Highway"; + expect(reconcile(paths, chains, v, anchorsOf).paths[0].typeName).toBe("Highway"); + }); + + it("nothing touched: unchanged", () => { + const paths = [P("King's Road", "Road", ["0_0", "1_0"])]; + const { chains, view: v } = view(paths); + expect(reconcile(paths, chains, v, anchorsOf).changed).toBe(false); + }); +}); diff --git a/tests/mapStore.test.ts b/tests/mapStore.test.ts index daaca3ec..b0d06e68 100644 --- a/tests/mapStore.test.ts +++ b/tests/mapStore.test.ts @@ -42,7 +42,7 @@ function plugin(vault: MemVault, maps: MapData[]) { } const maps = (): MapData[] => [ - { name: "coast", gridSize: { cols: 6, rows: 6 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "Road", hexes: ["1_2", "3_4"] }] } as MapData, + { name: "coast", gridSize: { cols: 6, rows: 6 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "Road", hexes: ["1_2", "2_2", "3_2"] }] } as MapData, { name: "coast-3-4", gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 0, y: 0 }, parent: { map: "coast", hex: "3_4" } } as MapData, ]; @@ -69,7 +69,9 @@ describe("map store: migration from hex-note frontmatter", () => { const note = parseMapNote(vault.files.get("world/hexes/coast/_coast.md")!)!; expect(note.hexes.get("3_4")?.locations).toEqual(["coast-3-4"]); - expect(note.paths).toEqual([{ typeName: "Road", hexes: ["1_2", "3_4"] }]); + // data.json's every-hex chain became a named, anchored path that draws the same hexes. + expect(note.paths.map((p) => [p.name, p.typeName])).toEqual([["Road", "Road"]]); + expect(store.resolved("coast")!.map((r) => r.hexes)).toEqual([["1_2", "2_2", "3_2"]]); expect(note.settings.gridSize).toEqual({ cols: 6, rows: 6 }); }); @@ -94,7 +96,7 @@ describe("map store: migration from hex-note frontmatter", () => { it("writes a JSON backup per map before cleaning", async () => { await boot(vault); const backups = [...vault.files.keys()].filter((p) => p.includes("/backups/map-notes-")); - expect(backups.map((p) => p.split("/").pop()).sort()).toEqual(["coast-3-4.json", "coast.json"]); + expect(backups.map((p) => p.split("/").pop()).sort()).toEqual(["coast-3-4.json", "coast-paths-report.md", "coast.json"]); const b = JSON.parse(vault.files.get(backups.find((p) => p.endsWith("/coast.json"))!)!); expect(new Map(b.hexes).get("3_4")).toMatchObject({ terrain: "forest", locked: true }); }); @@ -268,7 +270,7 @@ describe("map store: odd settings", () => { expect(store.get("asdf", "2_2")).toEqual({ terrain: "hills", icon: "tower.png" }); const note = parseMapNote(v.files.get("world/hexes/asdf/_asdf.md")!)!; expect(note.hexes.size).toBe(2); - expect(note.paths).toEqual([{ typeName: "Road", hexes: ["1_1", "2_2"] }]); + expect(note.paths).toEqual([{ name: "Road", typeName: "Road", branches: [{ anchors: ["1_1", "2_2"] }] }]); // and a restart keeps it const again = await boot(v, m); expect(again.store.get("asdf", "2_2")?.icon).toBe("tower.png"); @@ -360,7 +362,7 @@ describe("map store: a note broken by hand mid-session (#42)", () => { const { store } = await boot(v, oneMap()); store.set("m", "1_1", { terrain: "grass" }); await store.flush(); - const broken = v.files.get(NOTE)!.replace("hexmaker-map: 4", "hexmaker-mpa: 4"); + const broken = v.files.get(NOTE)!.replace("hexmaker-map: 5", "hexmaker-mpa: 5"); v.files.set(NOTE, broken); // onModify hasn't run yet store.set("m", "2_2", { terrain: "lava" }); await store.flush(); @@ -404,7 +406,7 @@ describe("map store: older map notes are converted once, after a backup (#42)", expect(backups.map((k) => k.split("/").pop())).toEqual(["m-map-note.md"]); expect(v.files.get(backups[0])).toBe(old); const now = v.files.get(NOTE)!; - expect(now).toContain("hexmaker-map: 4"); + expect(now).toContain("hexmaker-map: 5"); expect(now).toContain('parent: "[[_world]]"\nparent-hex: 3, 4'); expect(now).toContain('background-image: "[[art/bg.png]]"'); expect(now).toContain("hexmaker-origin-x: 0"); @@ -511,7 +513,7 @@ describe("map store: paths live only in the map note", () => { // In memory nothing changed. expect(m[0].pathChains).toHaveLength(1); // Their notes have them. - expect(parseMapNote(v.files.get("world/hexes/coast/_coast.md")!)!.paths).toEqual(m[0].pathChains); + expect(parseMapNote(v.files.get("world/hexes/coast/_coast.md")!)!.paths).toEqual(m[0].paths); }); it("a map whose note can't be read keeps its paths in data.json", async () => { @@ -529,7 +531,7 @@ describe("map store: paths live only in the map note", () => { const fresh = maps().map((x) => ({ ...x, pathChains: [] })); p.settings.maps.splice(0, p.settings.maps.length, ...fresh); await store.reloadFromNotes(); - expect(fresh[0].pathChains).toEqual([{ typeName: "Road", hexes: ["1_2", "3_4"] }]); + expect(fresh[0].pathChains).toEqual([{ typeName: "Road", hexes: ["1_2", "2_2", "3_2"] }]); await store.sync(); expect(parseMapNote(v.files.get("world/hexes/coast/_coast.md")!)!.paths).toHaveLength(1); }); @@ -558,7 +560,7 @@ describe("map store: format 2 notes and region mirrors (overworld phase 1)", () const { store } = await boot(v, world()); expect(store.get("m", "1_1")).toEqual({ terrain: "forest", region: "Basin", locations: ["town"] }); const now = v.files.get(NOTE)!; - expect(now).toContain("hexmaker-map: 4"); + expect(now).toContain("hexmaker-map: 5"); expect(now).toContain("Our notes."); expect(now).toContain("| 1_1 | forest | [[Basin]] | [[_town]] |"); expect(now).not.toContain("Submap"); @@ -601,7 +603,8 @@ describe("map store: derived Summary and Route (#46)", () => { const note = v.files.get(NOTE)!; expect(note).toContain("- **Palette:** [[world/palettes/Default]]"); expect(note).toContain("| lava (⚠ not in the palette) | 1 |"); - expect(note).toContain("| Trail | 1, 1 → 2, 1 (2 hexes) | ⚠ not a path type in the palette | 1_1 2_1 |"); + expect(note).toContain("| Trail | Trail | 1, 1 → 2, 1 · 2 hexes · ⚠ type not in palette | |"); + expect(note).toContain("| Trail | main | 1, 1 → 2, 1 |"); // Restart: the note is current, so it isn't written. v.writes.length = 0; const again = new MapStore(withPalette(v, oneMap(), ["grass"]) as never); diff --git a/tests/submaps.test.ts b/tests/submaps.test.ts index 9142dfc6..4d1703bf 100644 --- a/tests/submaps.test.ts +++ b/tests/submaps.test.ts @@ -45,7 +45,7 @@ describe("map note format 3: Region map and Locations", () => { it("renames Submap to Locations in place on the next write, as links, and marks format 4", () => { const text = note(["| 3_4 | forest | coast-3-4 |", "| 4_4 | hills | |"]); const out = updateMapNote(text, "m", parseMapNote(text)!); - expect(out).toMatch(/^hexmaker-map: 4$/m); + expect(out).toMatch(/^hexmaker-map: 5$/m); expect(out).toContain("| Hex | Terrain | Locations |"); expect(out).toContain("| 3_4 | forest | [[_coast-3-4]] |"); expect(out).not.toContain("Submap"); @@ -104,7 +104,7 @@ describe("map note format 3: Region map and Locations", () => { it("replaces the old help line only when it's still the plugin's own words", () => { const v2 = buildMapNote("m", { settings: { paletteName: "D" }, hexes: new Map(), paths: [] }) - .replace(/^hexmaker-map: 4$/m, "hexmaker-map: 2") + .replace(/^hexmaker-map: 5$/m, "hexmaker-map: 2") .replace(/^> - \*\*Hexes\*\*.*$/m, "> - **Hexes**: one row per hex that has something set. *Hex* is the column and row, like `3_4`. *Terrain* and *Region* use names from the map's palette. *Icon* and *GM icons* are icon file names; separate several with commas. *Submap* is the map that opens from the hex. *Locked* `yes` keeps generators off it."); const out = updateMapNote(v2, "m", parseMapNote(v2)!); expect(out).toContain("*Locations* links the maps"); From 6bfab9e9d0c6fa3df6bd208444c49df0b598d716 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 19:22:11 -0400 Subject: [PATCH 232/558] fix(palettes): a failed colour-conversion backup holds back every load-time note write The OW8 preset-terrain pass and the one-time seed/upgrade passes synced notes through the colour-wrapping writer even when the colour backup had failed. Now the backup runs first; when it fails nothing is written, the one-time flags stay unset and the preset-terrain pass is skipped, so all of it runs again (backup first) on the next load. Co-Authored-By: Claude Opus 5.5 --- src/palettes/PaletteStore.ts | 48 ++++++++++++++++++++++-------------- tests/palettes.test.ts | 28 +++++++++++++++++++++ 2 files changed, 57 insertions(+), 19 deletions(-) diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index 922fd5f2..5252e27b 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -336,21 +336,41 @@ export class PaletteStore { } if (await this.loadAll()) dirty = true; - // Terrains added to a bundled palette since it was installed: once each. - const added = await this.addNewPresetTerrains(); + // Colours in palette notes became inline code (Obsidian read `#14223d` + // as a tag). Before the first pass that converts them, every palette + // note is backed up. If that backup fails, NO load-time pass may + // rewrite a note (every note write puts colours in inline code): the + // one-time passes below still apply in memory for this session, but + // their flags stay unset and nothing is written, so all of it runs + // again, backup first, on the next load. (A note the plugin rewrites + // later because the user changed something still converts.) + let refresh = true; + if (!settings.paletteColorsCode) { + refresh = await this.backupBeforeColorConversion(); + if (refresh) { + settings.paletteColorsCode = true; + dirty = true; + } + } + const blocked = !refresh; + // Terrains added to a bundled palette since it was installed: once each + // (it takes its own backup; skipped entirely while notes can't change). + const added = blocked ? false : await this.addNewPresetTerrains(); if (added) dirty = true; // Path types moved from settings into palettes: every palette without // them gets the full old list, and the notes get their table below. const filled = fillPalettePathTypes(settings.terrainPalettes, settings.pathTypes) > 0; - if (filled) dirty = true; + if (filled && !blocked) dirty = true; // One-time: give existing palettes terrain types (from same-named // preset terrains, else inferred from the name). Later blanks are the // user's choice and stay blank. let seeded = false; if (!settings.terrainTypesSeeded) { seeded = seedTerrainTypes(settings.terrainPalettes) > 0; - settings.terrainTypesSeeded = true; - dirty = true; + if (!blocked) { + settings.terrainTypesSeeded = true; + dirty = true; + } } // One-time: write into the palettes what used to be inferred from // names at run time (space role types, a preset's child palette and @@ -359,18 +379,8 @@ export class PaletteStore { let upgraded = false; if (!settings.paletteDataUpgraded) { upgraded = upgradePaletteData(settings.terrainPalettes) > 0; - settings.paletteDataUpgraded = true; - dirty = true; - } - // Colours in palette notes became inline code (Obsidian read `#14223d` - // as a tag). Before the first pass that converts them, every palette - // note is backed up; if that fails, the load-time pass waits for the - // next load (a note the plugin rewrites in the meantime still converts). - let refresh = true; - if (!settings.paletteColorsCode) { - refresh = await this.backupBeforeColorConversion(); - if (refresh) { - settings.paletteColorsCode = true; + if (!blocked) { + settings.paletteDataUpgraded = true; dirty = true; } } @@ -378,12 +388,12 @@ export class PaletteStore { // Write seeded types into the notes now, in the same queued step. Queued // separately, an unload in between left notes untyped while settings // said seeding was done — and notes win on the next load. - if (seeded || filled || upgraded || added) await this.syncNow(); + if (!blocked && (seeded || filled || upgraded || added)) await this.syncNow(); // Notes from older builds (or edited by hand since) get their derived // cells shown (the Impassable column, inferred types in parentheses) // and their colours written as inline code. if (refresh) for (const file of this.paletteFiles()) await this.refreshDerived(file); - if (!settings.pathTypesExplicit) { + if (!settings.pathTypesExplicit && !blocked) { settings.pathTypesExplicit = true; dirty = true; } diff --git a/tests/palettes.test.ts b/tests/palettes.test.ts index 0f3dcf72..2f272c56 100644 --- a/tests/palettes.test.ts +++ b/tests/palettes.test.ts @@ -279,6 +279,8 @@ function makeHarness(settingsPatch: Partial = {}) { saves++; }, refreshHexMap: () => {}, + refreshPaletteEditors: () => {}, + ensureTablesForNewTerrains: async () => {}, getPaletteByName: (name: string) => settings.terrainPalettes.find((p) => p.name === name), }; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -754,6 +756,9 @@ describe("PaletteStore colour conversion", () => { await h.store.init(); expect(h.vault.files.get(P)).toBe(BARE); expect(h.settings.paletteColorsCode).toBeFalsy(); + // The other load-time passes wait too (nothing written, run again next load). + expect(h.settings.presetTerrainsAdded ?? []).toHaveLength(0); + expect(h.settings.paletteDataUpgraded).toBeFalsy(); h.vault.failBackups = false; await h.store.init(); @@ -762,6 +767,29 @@ describe("PaletteStore colour conversion", () => { expect(h.settings.paletteColorsCode).toBe(true); }); + it("a failed backup also holds back new preset terrains (OW8) and leaves bare colours alone", async () => { + const h = makeHarness({ palettesMigrated: true, terrainTypesSeeded: true, pathTypesExplicit: true }); + await h.vault.createFolder("world/palettes"); + const E = "world/palettes/Expanded.md"; + const expanded = h.settings.terrainPalettes.find((p) => p.name === "Expanded")!; + // An installed Expanded from before savanna/river delta, colours bare. + const old = expanded.terrains.filter((t) => !/savanna|river delta/i.test(t.name)); + const rows = old.map((t) => `| ${t.name} | ${t.color} |`).join("\n"); + const note = ["---", "hexmaker-palette: 1", "---", "", "| Terrain | Color |", "| --- | --- |", rows, ""].join("\n"); + h.vault.files.set(E, note); + h.vault.files.set(P, BARE); + h.vault.failBackups = true; + await h.store.init(); + expect(h.vault.files.get(E)).toBe(note); + expect(h.vault.files.get(P)).toBe(BARE); + expect(h.settings.presetTerrainsAdded ?? []).toHaveLength(0); + + h.vault.failBackups = false; + await h.store.init(); + expect(h.vault.files.get(E)).toMatch(/\| savanna \| `#/i); + expect(h.vault.files.get(E)).not.toMatch(/\| #[0-9a-f]{3,8} \|/i); + }); + it("needs no backup when every note is already converted", async () => { const h = makeHarness(); await h.store.init(); // fresh notes are written with inline-code colours From b35298d0a025ca6acfefd0840215ecf2b506f4e7 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 19:46:03 -0400 Subject: [PATCH 233/558] feat(paths): generators write anchored paths; route/orbit path types are options Phase 6 of the path-anchors plan. - toMapPaths (worldgen/generators.ts): generated hex paths become MapPaths against the target map's routing context. Chains of one type that join become one path with branches (the migration's merge); each branch gets the fewest anchors that route back to exactly the generated hexes (paths/fromGenerated.ts, anchorsFor). addGeneratedPaths writes them through MapStore.setPaths. - registry: toChains -> toPaths(paths, mapName). Callers (setup wizard, new-map modal, generator panel, walk region, regenerate) write through the map store, after placing a new region (placing sets the stagger the paths are routed with). Regenerate removes whole paths of the generator's types. - Learning a generator from a map reads plugin.paths.resolvedPathChains. - No name-based path types: Star scatter gets "Path type for routes" and Orbits "Path type for orbits", chosen from the palette's path types. Defaults come from the Space presets as data (PalettePreset.pathRoles). A palette with no path types offers only "None" and says so; a renamed type works through the option. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/SetupWizardView.ts | 16 +-- src/palettes/presets.ts | 17 ++++ src/paths/fromGenerated.ts | 91 +++++++++++++++++ src/worldgen/GeneratorPanel.ts | 18 ++-- src/worldgen/NewMapSetupModal.ts | 27 ++--- src/worldgen/generatorPathTypes.ts | 109 ++++++++++++++++++++ src/worldgen/generators.ts | 55 ++++++++--- src/worldgen/neighbours.ts | 14 ++- src/worldgen/procedural/starScatter.ts | 2 +- src/worldgen/registry.ts | 82 ++++++++++------ tests/contextPaths.test.ts | 73 +++++++++++++- tests/freshEyesR5Setup.test.ts | 2 +- tests/generatorPaths.test.ts | 131 +++++++++++++++++++++++++ tests/neighbourGenerators.test.ts | 42 +++++++- tests/proceduralGenerators.test.ts | 2 +- tests/worldgenFirstMap.test.ts | 131 ++++++++++++++++++++++++- tests/worldgenGenerators.test.ts | 13 ++- 18 files changed, 739 insertions(+), 90 deletions(-) create mode 100644 src/paths/fromGenerated.ts create mode 100644 src/worldgen/generatorPathTypes.ts create mode 100644 tests/generatorPaths.test.ts diff --git a/package.json b/package.json index 376c0515..5be4a9a4 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index 35223480..033257b0 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -9,7 +9,7 @@ import { MAP_KINDS, enabledKinds, isSpacePalette, terrainsForTables, type MapKin import { FEATURE_LEVEL_CHOICES, type FeatureLevel } from "./featureLevel"; import { randomSeed } from "../packages/hex-wfc/src"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "./worldgen/preview"; -import { pathColors } from "./worldgen/generators"; +import { addGeneratedPaths, pathColors } from "./worldgen/generators"; import { BLANK_ID, describeKind, @@ -157,7 +157,10 @@ function runGenerator( const saved = plugin.settings.hexOrientation; plugin.settings.hexOrientation = ctx.hexOrientation; try { - return kind.generate({ terrains, grid: wizardGrid(plugin, ctx), seed: ctx.seed, options: resolvedOptions(kind, ctx) }); + return kind.generate({ + terrains, grid: wizardGrid(plugin, ctx), seed: ctx.seed, options: resolvedOptions(kind, ctx), + pathTypes: plugin.getPathTypes(ctx.paletteName), + }); } finally { plugin.settings.hexOrientation = saved; } @@ -641,7 +644,7 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { optsBox.empty(); seaRandomOption = undefined; const kind = kinds.find((k) => k.id === ctx.generatorId); - for (const opt of kind ? kindOptions(kind, terrains()) : []) { + for (const opt of kind ? kindOptions(kind, terrains(), plugin.getPathTypes(ctx.paletteName)) : []) { const row = optsBox.createEl("label", { cls: "duckmage-wizard-generator-option" }); row.createSpan({ text: opt.label }); const sel = row.createEl("select"); @@ -759,11 +762,10 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { ); if ("error" in result) throw new Error(result.error); - // Generated paths (jump routes…) become map path chains. + // Generated paths (jump routes…) become the map's anchored paths. if (outcome?.ok && outcome.paths.length && kind) { - const map = plugin.getMap(result.name); - const { chains } = kind.toChains(outcome.paths, plugin.mapPaletteName(result.name)); - if (map && chains.length) map.pathChains.push(...chains); + const { paths } = kind.toPaths(outcome.paths, result.name); + addGeneratedPaths(plugin, result.name, paths); } ctx.generatedWith = outcome?.ok ? kind?.label : undefined; plugin.settings.defaultMap = result.name; diff --git a/src/palettes/presets.ts b/src/palettes/presets.ts index 13e70365..2c9bb794 100644 --- a/src/palettes/presets.ts +++ b/src/palettes/presets.ts @@ -25,6 +25,21 @@ export interface PalettePreset { kind: MapKind; /** Per-terrain submap setup (see SubmapDefault). */ submapDefaults?: Record; + /** + * Which of the preset's own path types the built-in generators draw with + * by default (data, so nothing in code picks a path type by its name). + * Only a default: each generator has an option to pick any of the + * palette's path types, so a renamed type works through that option. + */ + pathRoles?: PresetPathRoles; +} + +/** The generator path roles a preset can fill (see worldgen/generatorPathTypes.ts). */ +export interface PresetPathRoles { + /** Star scatter's routes between systems. */ + routes?: string; + /** Orbits' rings around the star. */ + orbits?: string; } export const SPACE_SECTOR_PALETTE_NAME = "Space - Sector"; @@ -151,6 +166,7 @@ export const PALETTE_PRESETS: PalettePreset[] = [ description: "Star charts: one hex per parsec, typed by mainworld. Adds jump and trade route path types.", terrains: SPACE_SECTOR_TERRAINS, pathTypes: SPACE_PATH_TYPES, + pathRoles: { routes: SPACE_PATH_TYPES[0].name }, childPalette: SPACE_SYSTEM_PALETTE_NAME, kind: "space", submapDefaults: SECTOR_SUBMAP_DEFAULTS, @@ -160,6 +176,7 @@ export const PALETTE_PRESETS: PalettePreset[] = [ description: "A single star system: stars, planets, belts, stations, and hazards. Adds an Orbit path type.", terrains: SPACE_SYSTEM_TERRAINS, pathTypes: SYSTEM_PATH_TYPES, + pathRoles: { orbits: SYSTEM_PATH_TYPES[0].name }, kind: "space", submapDefaults: SYSTEM_SUBMAP_DEFAULTS, }, diff --git a/src/paths/fromGenerated.ts b/src/paths/fromGenerated.ts new file mode 100644 index 00000000..a76c1678 --- /dev/null +++ b/src/paths/fromGenerated.ts @@ -0,0 +1,91 @@ +/** + * Generated hex paths → anchored MapPaths (generators: map creation, a new + * region next to another, regenerating a map). Pure, no Obsidian imports. + * + * Generators keep their own routing (terrain-cost Dijkstra, WFC paths), so + * their hexes are not what the editor router would draw. Each generated + * chain is turned into the fewest anchors that make the editor router + * reproduce it exactly (fromHexes.anchorsFor) under the TARGET map's routing + * context (its terrain, palette, bounds, orientation and stagger), which is + * exactly what the map draws once the paths are stored. + * + * Chains of one type that touch end-on become one path with branches, the + * same stroke-preserving merge the migration uses (mergeChains). Names are + * ``, ` 2`… unique against `taken`. + * + * A chain with a step between hexes that aren't neighbours (Star scatter's + * jump routes link two systems) can't be reproduced hex for hex: its hexes + * become anchors and the router fills in between (listed in `inexact`). + */ + +import type { HexKey, MapPath } from "../types"; +import type { RouteContext } from "./router"; +import { contextRouter, type SegmentRouter } from "./routeCache"; +import { routeBranch, styleOf, type StyleFor } from "./resolve"; +import { anchorsFor, dedupeSteps, mergeChains, reproduces, routeFnFor } from "./fromHexes"; +import { uniquePathName } from "./names"; + +/** A generated path already typed as a map path type. */ +export interface TypedHexChain { + typeName: string; + hexes: readonly HexKey[]; +} + +export interface GeneratedToPathsOptions { + /** The types' explicit routing style (avoid impassable, winding). */ + styleFor?: StyleFor; + /** Names already used on the map (new names avoid them). */ + taken?: Iterable; + /** A router for `ctx` to reuse (e.g. the map's RouteCache); else an uncached one. */ + router?: SegmentRouter; +} + +/** + * Generated chains → MapPaths (see the module comment). Types come out in + * order of first appearance; within a type, merged groups in order of their + * first chain. Chains of fewer than two distinct hexes are dropped (they + * draw nothing). + */ +export function generatedToMapPaths( + chains: readonly TypedHexChain[], + ctx: RouteContext, + opts: GeneratedToPathsOptions = {}, +): { paths: MapPath[]; inexact: string[] } { + const router = opts.router ?? contextRouter(ctx); + const taken = [...(opts.taken ?? [])]; + const byType = new Map(); + for (const c of chains) { + const hexes = dedupeSteps(c.hexes); + if (hexes.length < 2) continue; + const list = byType.get(c.typeName); + if (list) list.push(hexes); + else byType.set(c.typeName, [hexes]); + } + const paths: MapPath[] = []; + const inexact: string[] = []; + for (const [typeName, list] of byType) { + const style = styleOf(opts.styleFor, typeName); + const route = routeFnFor(router, style); + for (const g of mergeChains(list)) { + let exact = true; + const branches = g.branches.map((hexes) => { + const anchors = anchorsFor(hexes, route, ctx); + if (reproduces(anchors, hexes, route)) return { anchors }; + exact = false; + return { anchors: dedupeSteps(hexes) }; + }); + const name = uniquePathName(typeName, taken); + taken.push(name); + paths.push({ name, typeName, branches }); + if (!exact) inexact.push(name); + } + } + return { paths, inexact }; +} + +/** The hex chains a path's branches route to under `ctx` (for checks and tests). */ +export function routedBranches(path: MapPath, ctx: RouteContext, styleFor?: StyleFor, router?: SegmentRouter): HexKey[][] { + const r = router ?? contextRouter(ctx); + const style = styleOf(styleFor, path.typeName); + return path.branches.map((b) => routeBranch(b.anchors, style, r).hexes); +} diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index b50f609f..2a577608 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -26,7 +26,8 @@ import { combinedSourcesOf, sourceDirectionsOf, setGeneratorPalette, - toPathChains, + toMapPaths, + addGeneratedPaths, remakeBlend, saveGeneratorModel, type GeneratorFile, @@ -930,13 +931,6 @@ export class GeneratorPanel { new Notice(result.error); return; } - const { chains, missing } = toPathChains(this.plugin, r.paths, model, this.plugin.mapPaletteName(result.name)); - const created = this.plugin.getMap(result.name); - if (created && chains.length) { - created.pathChains = [...created.pathChains, ...chains]; - await this.plugin.saveSettings(); - } - if (missing.length) new Notice(`No path type named ${missing.join(", ")}, so those paths were skipped.`); if (connected) { // Record its biome (and what it was blended with) for later neighbours. const around = Object.values(regionNeighbourNames(this.plugin, connected)) @@ -950,6 +944,14 @@ export class GeneratorPanel { // Only clear the choice if it's still the one used; a newer one stays. if (GeneratorPanel.connect === usedConnect) GeneratorPanel.connect = null; } + // Generated paths become the map's anchored paths (after placing: + // that sets the stagger they're routed with). + const { paths, missing } = toMapPaths(this.plugin, r.paths, model, result.name); + if (paths.length) { + addGeneratedPaths(this.plugin, result.name, paths); + await this.plugin.saveSettings(); + } + if (missing.length) new Notice(`No path type named ${missing.join(", ")}, so those paths were skipped.`); new Notice(`Created map "${result.name}"${connected ? ` ${connected.side} of ${connected.anchor}` : ""}.`); GeneratorPanel.mapName = result.name; await this.plugin.showMap(result.name); diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index d9c549d4..6c88b9c1 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -17,7 +17,7 @@ import { enabledKinds, isSpacePalette } from "../mapKinds"; import { defaultSubmapLabel, uniqueMapSlug } from "../hex-map/submapNav"; import { randomSeed } from "../../packages/hex-wfc/src"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; -import { pathColors } from "./generators"; +import { addGeneratedPaths, pathColors } from "./generators"; import { renderPreviewLegend } from "../hex-map/terrainLegend"; import { IMAGE_EXTENSIONS, attachImageDropZone, getIconUrl, importBinaryFileToVault, mapBgImportFolder, selectAllOnFocus, slugify } from "../utils"; import { FileLinkSuggestModal } from "../hex-map/FileLinkSuggestModal"; @@ -606,7 +606,7 @@ export class NewMapSetupModal extends HexmakerModal { this.options.sea = seaHint.side; this.seaFromNeighbour = true; } - for (const opt of kind ? kindOptions(kind, terrains) : []) { + for (const opt of kind ? kindOptions(kind, terrains, this.plugin.getPathTypes(paletteSelect.value)) : []) { const r = this.row(optsBox, opt.label); const sel = this.labelled(r, r.createEl("select")); for (const c of opt.choices) sel.createEl("option", { value: c.value, text: c.label }); @@ -656,7 +656,7 @@ export class NewMapSetupModal extends HexmakerModal { if (this.cols * this.rows > PREVIEW_AUTO_LIMIT) { status.setText("Large map — the preview is skipped; terrain is generated on create."); } else { - const outcome = this.generate(kind, terrains); + const outcome = this.generate(kind, terrains, paletteSelect.value); this.lastOutcome = outcome; if (!outcome.ok) { status.setText(outcome.message); @@ -769,9 +769,10 @@ export class NewMapSetupModal extends HexmakerModal { * palette skip the path carry-over (a jump route through a sector hex * isn't a lane in the system). */ - private generate(kind: TerrainGeneratorKind, terrains: TerrainColor[]): GenerateOutcome { + private generate(kind: TerrainGeneratorKind, terrains: TerrainColor[], paletteName: string): GenerateOutcome { return runGenerator(this.plugin.settings.hexOrientation, kind, { terrains, grid: this.grid(), seed: this.seed, options: this.resolvedOptions(kind), context: this.context, region: this.placement, + pathTypes: this.plugin.getPathTypes(paletteName), }); } @@ -830,7 +831,7 @@ export class NewMapSetupModal extends HexmakerModal { const blank = this.kinds.find((k) => k.id === BLANK_ID); const effective = openGenerator ? blank : kind; if (effective && (effective.id !== BLANK_ID || this.context?.paths?.length)) { - outcome = (!openGenerator ? this.lastOutcome : undefined) ?? this.generate(effective, terrains); + outcome = (!openGenerator ? this.lastOutcome : undefined) ?? this.generate(effective, terrains, paletteName); if (!outcome.ok) { new Notice(outcome.message); return; @@ -865,19 +866,19 @@ export class NewMapSetupModal extends HexmakerModal { return; } - // Generated paths (jump routes, rivers…) become map path chains. + // Join the world grid next to the chosen neighbour (before the paths: + // placing sets the map's stagger, which the paths are routed with). + if (this.placement) await placeNewRegion(this.plugin, result.name, this.placement); + + // Generated paths (jump routes, rivers…) become the map's anchored paths. if (outcome?.ok && outcome.paths.length && kind) { - const { chains, missing } = kind.toChains(outcome.paths, this.plugin.mapPaletteName(result.name)); - const map = this.plugin.getMap(result.name); - if (map && chains.length) { - map.pathChains.push(...chains); + const { paths, missing } = kind.toPaths(outcome.paths, result.name); + if (paths.length) { + addGeneratedPaths(this.plugin, result.name, paths); await this.plugin.saveSettings(); } if (missing.length) new Notice(`Skipped paths with no matching path type: ${missing.join(", ")}`); } - - // Join the world grid next to the chosen neighbour. - if (this.placement) await placeNewRegion(this.plugin, result.name, this.placement); let backgroundImage: string | undefined; let bgPath = this.origin ? null : this.bgPath; if (!this.origin && this.bgFile) { diff --git a/src/worldgen/generatorPathTypes.ts b/src/worldgen/generatorPathTypes.ts new file mode 100644 index 00000000..dbd81985 --- /dev/null +++ b/src/worldgen/generatorPathTypes.ts @@ -0,0 +1,109 @@ +/** + * The path type a built-in generator draws its paths with: an explicit + * option ("Path type for routes" on Star scatter, "Path type for orbits" on + * Orbits) listing the target palette's own path types. Nothing here picks a + * type by its name (owner rule): the default comes from the Space presets + * as data (PalettePreset.pathRoles says which of the preset's types fills + * the role), and a palette whose types were renamed works through the + * option. Pure, no Obsidian imports. + */ + +import type { PathType } from "../types"; +import { PALETTE_PRESETS, type PalettePreset, type PresetPathRoles } from "../palettes/presets"; +import type { ProcOption } from "./procedural/common"; + +export type GeneratorPathRole = keyof PresetPathRoles; + +/** Option value: draw no paths. */ +export const NO_PATHS = "none"; +/** Option value: the palette's default for the role (see defaultPathTypeFor). */ +export const PRESET_PATH_TYPE = "default"; + +/** Option keys. */ +export const ROUTE_TYPE_KEY = "routeType"; +export const ORBIT_TYPE_KEY = "orbitType"; + +const LABELS: Record = { + routes: "Path type for routes", + orbits: "Path type for orbits", +}; + +/** + * The role's default on a palette with these path types: the type a preset + * names for the role (pathRoles), when the palette has a type of that name; + * else none. + */ +export function defaultPathTypeFor( + role: GeneratorPathRole, + types: readonly Pick[], + presets: readonly Pick[] = PALETTE_PRESETS, +): string | undefined { + const names = new Set(types.map((t) => t.name)); + for (const p of presets) { + const want = p.pathRoles?.[role]; + if (want && names.has(want)) return want; + } + return undefined; +} + +/** + * The option as shown for a palette: one choice per path type, plus + * "None (no paths)". A palette with no path types offers only None, and + * the choice says why. The default is the role's default (else None). + */ +export function pathTypeOption( + key: string, + role: GeneratorPathRole, + types: readonly Pick[] | undefined, + presets?: readonly Pick[], +): ProcOption { + const list = types ?? []; + if (!list.length) { + return { + key, + label: LABELS[role], + choices: [{ value: NO_PATHS, label: "None (this palette has no path types)" }], + default: NO_PATHS, + }; + } + const seen = new Set(); + const choices: ProcOption["choices"] = []; + for (const t of list) { + if (seen.has(t.name)) continue; + seen.add(t.name); + choices.push({ value: t.name, label: t.name }); + } + choices.push({ value: NO_PATHS, label: "None (no paths)" }); + return { key, label: LABELS[role], choices, default: defaultPathTypeFor(role, list, presets) ?? NO_PATHS }; +} + +/** + * The option with no palette known (the generator's static option list): + * its default is "the palette's default", resolved when generating. + */ +export function staticPathTypeOption(key: string, role: GeneratorPathRole): ProcOption { + return { + key, + label: LABELS[role], + choices: [{ value: PRESET_PATH_TYPE, label: "Palette default" }, { value: NO_PATHS, label: "None (no paths)" }], + default: PRESET_PATH_TYPE, + }; +} + +/** + * The path type to draw with, from the option's value: a type the palette + * has; None → undefined; anything else (the "default" value, or a type + * this palette doesn't have, e.g. a choice saved on another palette) → the + * role's default on this palette. + */ +export function chosenPathType( + value: string | undefined, + role: GeneratorPathRole, + types: readonly Pick[] | undefined, + presets?: readonly Pick[], +): string | undefined { + const list = types ?? []; + if (value !== undefined && list.some((t) => t.name === value)) return value; + if (value === NO_PATHS) return undefined; + return defaultPathTypeFor(role, list, presets); +} diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index bdb9f7d5..fd175d12 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -16,7 +16,8 @@ import { getFrontMatter, getTerrainFromFile, setTerrainInFile } from "../frontma import { normalizeFolder, slugify } from "../utils"; import { VERSION_KEY, pluginVersion } from "../compat"; import { isImpassable } from "../impassable"; -import type { TerrainColor } from "../types"; +import type { MapPath, TerrainColor } from "../types"; +import { generatedToMapPaths } from "../paths/fromGenerated"; import { learnModel, mergeModels, @@ -148,20 +149,45 @@ export function pathColors(plugin: HexmakerPlugin, paletteName: string | undefin } /** - * Generated paths as map path chains for a map on `paletteName`. Path types - * that palette doesn't have are dropped (and named in the returned warning - * list). + * Generated paths as anchored map paths for the map `mapName` (already + * created, with its terrain): typed by drawnPathType, path types its palette + * doesn't have dropped (and named in `missing`), then turned into MapPaths + * against that map's routing context (see paths/fromGenerated.ts): chains of + * one type that join become one path with branches, and each branch gets + * the fewest anchors that route back to exactly the generated hexes. New + * names avoid `taken` (default: the map's current path names). */ -export function toPathChains( +export function toMapPaths( plugin: HexmakerPlugin, - paths: { type: string; route?: string; hexes: string[] }[], + paths: readonly { type: string; route?: string; hexes: readonly string[] }[], model: HexWfcModel | undefined, - paletteName: string | undefined, -): { chains: { typeName: string; hexes: string[] }[]; missing: string[] } { - const known = new Set(plugin.getPathTypes(paletteName).map((t) => t.name)); + mapName: string, + taken?: Iterable, +): { paths: MapPath[]; missing: string[] } { + const map = plugin.getMap(mapName); + const known = new Set(plugin.getMapPathTypes(mapName).map((t) => t.name)); const typed = paths.map((p) => ({ typeName: drawnPathType(model, p), hexes: [...p.hexes] })); const missing = [...new Set(typed.map((p) => p.typeName).filter((t) => !known.has(t)))]; - return { chains: typed.filter((p) => known.has(p.typeName)), missing }; + if (!map) return { paths: [], missing }; + const store = plugin.mapStore; + const { paths: out } = generatedToMapPaths( + typed.filter((p) => known.has(p.typeName)), + store.routeContext(map), + { styleFor: store.pathStyleFor(map), taken: taken ?? store.paths(mapName).map((p) => p.name) }, + ); + return { paths: out, missing }; +} + +/** + * Add generated paths to a map through the map store (its note is + * written). With `replaceTypes`, the map's paths of those types go first + * (regenerating redraws the generator's own path types). + */ +export function addGeneratedPaths(plugin: HexmakerPlugin, mapName: string, paths: MapPath[], replaceTypes?: ReadonlySet): void { + const current = plugin.mapStore.paths(mapName); + const kept = replaceTypes ? current.filter((p) => !replaceTypes.has(p.typeName)) : [...current]; + if (!paths.length && kept.length === current.length) return; + plugin.mapStore.setPaths(mapName, [...kept, ...paths]); } /** The map path type a generated path is drawn as: its route's "as", else its learned type. */ @@ -283,7 +309,8 @@ function learnFromMaps( name, orientation: plugin.settings.hexOrientation, stagger: mapStagger(plugin, mapName), - paths: (map.pathChains ?? []).map((c) => ({ type: c.typeName, hexes: c.hexes })), + // The map's paths as drawn: anchored paths resolved to hex chains. + paths: plugin.paths.resolvedPathChains(mapName).map((c) => ({ type: c.typeName, hexes: c.hexes })), meta, })); } @@ -526,8 +553,10 @@ export async function fillMap( // other path types, and every path when only filling, are left alone. if (mode === "regenerate" && model.paths?.length) { const learned = new Set(model.paths.map((p) => drawnPathType(model, { type: p.type, route: pathRouteKey(p) }))); - const { chains, missing } = toPathChains(plugin, result.paths, model, plugin.mapPaletteName(mapName)); - map.pathChains = [...(map.pathChains ?? []).filter((c) => !learned.has(c.typeName)), ...chains]; + // Whole paths of those types go; the new ones are named around the rest. + const kept = plugin.mapStore.paths(mapName).filter((p) => !learned.has(p.typeName)).map((p) => p.name); + const { paths, missing } = toMapPaths(plugin, result.paths, model, mapName, kept); + addGeneratedPaths(plugin, mapName, paths, learned); if (missing.length) warnings.push(`No path type named ${missing.join(", ")}, so those paths were skipped`); await plugin.saveSettings(); } diff --git a/src/worldgen/neighbours.ts b/src/worldgen/neighbours.ts index f7926cab..c90902e8 100644 --- a/src/worldgen/neighbours.ts +++ b/src/worldgen/neighbours.ts @@ -8,7 +8,7 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import type { MapData, RegionBiome } from "../types"; import { getTerrainFromFile } from "../frontmatter"; -import { generateTerrain, readMapTerrain, toPathChains, type GeneratorFile, type GridSpec } from "./generators"; +import { addGeneratedPaths, generateTerrain, readMapTerrain, toMapPaths, type GeneratorFile, type GridSpec } from "./generators"; import { learnModel, mergeModels, type Compass, type HexWfcModel, type SolveResult } from "../../packages/hex-wfc/src"; import { link, @@ -353,11 +353,15 @@ export async function createWalkRegion( ); if ("error" in made) return made; const map = plugin.getMap(made.name); + if (map) map.biome = { ...plan.biome }; + await placeNewRegion(plugin, made.name, region); + // Paths after placing (it sets the stagger they're routed with). if (map) { - const { chains } = toPathChains(plugin, r.paths, plan.model, plugin.mapPaletteName(made.name)); - if (chains.length) map.pathChains = [...map.pathChains, ...chains]; - map.biome = { ...plan.biome }; + const { paths } = toMapPaths(plugin, r.paths, plan.model, made.name); + if (paths.length) { + addGeneratedPaths(plugin, made.name, paths); + await plugin.saveSettings(); + } } - await placeNewRegion(plugin, made.name, region); return made; } diff --git a/src/worldgen/procedural/starScatter.ts b/src/worldgen/procedural/starScatter.ts index 693667a2..763810cc 100644 --- a/src/worldgen/procedural/starScatter.ts +++ b/src/worldgen/procedural/starScatter.ts @@ -197,7 +197,7 @@ export function starScatter( const warnings: string[] = []; if (range > 0 && systems.length > 1) { if (!jumpRouteType) { - warnings.push('No "Jump route" path type — routes skipped. Install the Space - Sector preset to add it.'); + warnings.push("No path type for routes, so none were drawn. Pick one under Path type for routes (or add a path type to the palette)."); } else { const seen = new Set(); for (const a of systems) { diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index 6a55c572..1b209954 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -1,13 +1,21 @@ import type HexmakerPlugin from "../HexmakerPlugin"; -import type { TerrainColor } from "../types"; +import type { MapPath, PathType, TerrainColor } from "../types"; import { drawnPathType, generateTerrain, generatorFitsPalette, listGenerators, - toPathChains, + toMapPaths, type GridSpec, } from "./generators"; +import { + NO_PATHS, + ORBIT_TYPE_KEY, + ROUTE_TYPE_KEY, + chosenPathType, + pathTypeOption, + staticPathTypeOption, +} from "./generatorPathTypes"; import { ofType, SIDES, type GenerationContext, type ProcGrid, type ProcOption, type Side } from "./procedural/common"; import { STAR_SCATTER_ID, STAR_SCATTER_OPTIONS, starScatter, starScatterOffered } from "./procedural/starScatter"; import { ORBITS_ID, ORBITS_OPTIONS, orbits, orbitsFits, orbitsOptions } from "./procedural/orbits"; @@ -57,6 +65,9 @@ export interface GenerateRequest { grid: GridSpec; seed: number; options: Record; + /** The target palette's path types (options that pick one, e.g. Star + * scatter's "Path type for routes", choose among these). */ + pathTypes?: readonly PathType[]; /** Where the map sits in the bigger map (parent hex, neighbours). */ context?: GenerationContext; /** A new region placed next to existing ones: learned generators solve @@ -84,17 +95,18 @@ export interface TerrainGeneratorKind { continuesNeighbours?: boolean; options: ProcOption[]; /** The options as shown for one palette, when a choice lists that - * palette's own terrains (Orbits' Star). Same keys and defaults as - * `options`; see kindOptions. */ - optionsFor?(terrains: TerrainColor[]): ProcOption[]; + * palette's own terrains (Orbits' Star) or path types (Star scatter's + * and Orbits' path type). Same keys as `options`; see kindOptions. */ + optionsFor?(terrains: TerrainColor[], pathTypes?: readonly PathType[]): ProcOption[]; /** Can this generator produce terrain for a palette with these terrains? */ fits(terrains: TerrainColor[]): boolean; generate(req: GenerateRequest): GenerateOutcome; /** For learned generators: the generator note (for "Open generator"). */ generatorPath?: string; - /** Turn generated paths into path chains for a map on `paletteName` - * (drops path types that palette doesn't have). */ - toChains(paths: GeneratedPath[], paletteName: string | undefined): { chains: { typeName: string; hexes: string[] }[]; missing: string[] }; + /** Turn generated paths into anchored paths for the map `mapName` + * (already created, with its terrain): drops path types its palette + * doesn't have (named in `missing`); see generators.ts toMapPaths. */ + toPaths(paths: GeneratedPath[], mapName: string, taken?: Iterable): { paths: MapPath[]; missing: string[] }; } export const BLANK_ID = "blank"; @@ -177,13 +189,7 @@ function procGrid(plugin: HexmakerPlugin, grid: GridSpec): ProcGrid { } export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise { - const toChains = (paths: GeneratedPath[], paletteName: string | undefined) => toPathChains(plugin, paths, undefined, paletteName); - // Path types for generated routes/orbits: a palette's own spelling if one - // has it, else the Space presets' names (their palettes carry them). - const pathTypeNamed = (re: RegExp, fallback: string) => - (plugin.settings.terrainPalettes ?? []).flatMap((p) => p.pathTypes ?? []).find((t) => re.test(t.name))?.name ?? fallback; - const jumpRoute = pathTypeNamed(/jump route/i, "Jump route"); - const orbitPath = pathTypeNamed(/^orbit$/i, "Orbit"); + const toPaths = (paths: GeneratedPath[], mapName: string, taken?: Iterable) => toMapPaths(plugin, paths, undefined, mapName, taken); const builtIn: TerrainGeneratorKind[] = [ { @@ -194,7 +200,7 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise true, generate: () => ({ ok: true, cells: new Map(), paths: [], warnings: [] }), - toChains, + toPaths, }, { id: STAR_SCATTER_ID, @@ -202,13 +208,17 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise [...STAR_SCATTER_OPTIONS, pathTypeOption(ROUTE_TYPE_KEY, "routes", pathTypes)], fits: starScatterOffered, generate: (req) => { - const r = starScatter(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, jumpRoute); + const routeType = chosenPathType(req.options[ROUTE_TYPE_KEY], "routes", req.pathTypes); + // None picked on purpose: no routes, and nothing to warn about. + const options = !routeType && req.options[ROUTE_TYPE_KEY] === NO_PATHS ? { ...req.options, routes: "none" } : req.options; + const r = starScatter(req.terrains, procGrid(plugin, req.grid), req.seed, options, routeType); return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; }, - toChains, + toPaths, }, { id: ORBITS_ID, @@ -216,14 +226,18 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise [...orbitsOptions(terrains), pathTypeOption(ORBIT_TYPE_KEY, "orbits", pathTypes)], fits: orbitsFits, generate: (req) => { - const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitPath, req.context); + const orbitType = chosenPathType(req.options[ORBIT_TYPE_KEY], "orbits", req.pathTypes); + const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitType, req.context); + // No type and not None on purpose: say why there are no rings. + if (!orbitType && req.options[ORBIT_TYPE_KEY] !== NO_PATHS && r.cells.size) + r.warnings.push("No path type for orbits, so the rings weren't drawn. Pick one under Path type for orbits (or add a path type to the palette)."); return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; }, - toChains, + toPaths, }, { id: REGION_DETAIL_ID, @@ -238,7 +252,7 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise toPathChains(plugin, paths, g.model, paletteName), + toPaths: (paths, mapName, taken) => toMapPaths(plugin, paths, g.model, mapName, taken), }); } return kinds; @@ -351,10 +365,10 @@ export function builtinKind( if (!res.ok) return { ok: false, message: res.message }; return { ok: true, cells: res.cells, paths: res.paths, featureCells: res.featureCells, warnings: res.warnings }; }, - toChains: (paths, paletteName) => { + toPaths: (paths, mapName, taken) => { // Streams and trails draw as the palette's type that behaves like them when it has no such type. - const known = plugin.getPathTypes(paletteName); - return toPathChains(plugin, paths.map((p) => ({ type: builtinPathType(drawnPathType(fitted, p), known), hexes: p.hexes })), undefined, paletteName); + const known = plugin.getMapPathTypes(mapName); + return toMapPaths(plugin, paths.map((p) => ({ type: builtinPathType(drawnPathType(fitted, p), known), hexes: p.hexes })), undefined, mapName, taken); }, }; } @@ -379,8 +393,12 @@ export function runGenerator( } /** A generator's options as shown for a palette (see optionsFor). */ -export function kindOptions(kind: Pick, terrains: TerrainColor[]): ProcOption[] { - return kind.optionsFor?.(terrains) ?? kind.options; +export function kindOptions( + kind: Pick, + terrains: TerrainColor[], + pathTypes?: readonly PathType[], +): ProcOption[] { + return kind.optionsFor?.(terrains, pathTypes) ?? kind.options; } /** A generator's options at their defaults, overridden by `chosen`. */ diff --git a/tests/contextPaths.test.ts b/tests/contextPaths.test.ts index 555371c1..c676f940 100644 --- a/tests/contextPaths.test.ts +++ b/tests/contextPaths.test.ts @@ -2,7 +2,11 @@ import { describe, it } from "node:test"; import expect from "expect"; import { edgeHex, pairCrossings, routeContextPaths } from "../src/worldgen/procedural/contextPaths"; import { centerHex, distance, type ProcGrid } from "../src/worldgen/procedural/common"; -import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { DEFAULT_PATH_TYPES, DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { generatedToMapPaths, routedBranches } from "../src/paths/fromGenerated"; +import { mapRouteContext, pathTypeStyleFor } from "../src/paths/mapContext"; +import { stepsOf } from "../src/paths/fromHexes"; +import { impassableNames } from "../src/impassable"; const flat: ProcGrid = { cols: 13, rows: 9, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; const pointy: ProcGrid = { ...flat, orientation: "pointy" }; @@ -149,3 +153,70 @@ describe("pairCrossings (neighbour regions' paths crossing into a new map)", () expect(road.hexes[road.hexes.length - 1]).toBe("12_7"); }); }); + +// Phase 6: generated paths are stored as anchors; what the map draws (the +// editor router between those anchors, under the map's own routing context) +// must be exactly the hexes the generator produced. +describe("context paths become anchored map paths", () => { + const styleFor = pathTypeStyleFor(DEFAULT_PATH_TYPES); + const ctxFor = (grid: ProcGrid, c: Map) => mapRouteContext({ + orientation: grid.orientation, stagger: grid.stagger, + gridSize: { cols: grid.cols, rows: grid.rows }, gridOffset: grid.offset, + terrainOf: [...c].map(([k, terrain]): [string, { terrain: string }] => [k, { terrain }]), + impassable: impassableNames(DEFAULT_TERRAIN_PALETTE), + }); + const sameSteps = (a: readonly (readonly string[])[], b: readonly (readonly string[])[]) => { + const x = stepsOf(a), y = stepsOf(b); + return x.size === y.size && [...x].every((k) => y.has(k)); + }; + + for (const orientation of ["flat", "pointy"] as const) { + for (const stagger of ["odd", "even"] as const) { + it(`resolved chains equal the generated hexes (${orientation}, ${stagger})`, () => { + const grid: ProcGrid = { ...flat, orientation, stagger }; + const c = cells(grid, [6]); // a sea channel the road has to bridge + for (let seed = 1; seed <= 8; seed++) { + const routed = routeContextPaths(c, DEFAULT_TERRAIN_PALETTE, grid, [ + { type: "Road", avoidImpassable: true, autoRoute: "direct", from: "W", to: "E" }, + { type: "River", avoidImpassable: false, autoRoute: "winding", from: "N", to: "S" }, + ], seed); + expect(routed).toHaveLength(2); + const ctx = ctxFor(grid, c); + const { paths, inexact } = generatedToMapPaths(routed.map((p) => ({ typeName: p.type, hexes: p.hexes })), ctx, { styleFor }); + expect(inexact).toEqual([]); + expect(paths.map((p) => [p.name, p.typeName, p.branches.length])).toEqual([["Road", "Road", 1], ["River", "River", 1]]); + for (const p of paths) { + const gen = routed.find((r) => r.type === p.typeName)!.hexes; + expect(routedBranches(p, ctx, styleFor)).toEqual([gen]); + expect(p.branches[0].anchors[0]).toBe(gen[0]); + expect(p.branches[0].anchors[p.branches[0].anchors.length - 1]).toBe(gen[gen.length - 1]); + expect(p.branches[0].anchors.length).toBeLessThanOrEqual(gen.length); + } + } + }); + } + } + + it("roads that meet at the centre become one road with branches, drawing the same steps", () => { + const c = cells(flat); + const routed = routeContextPaths(c, DEFAULT_TERRAIN_PALETTE, flat, [ + { type: "Road", from: "W" }, + { type: "Road", from: "E" }, + { type: "Road", from: "N" }, + ], 3); + expect(routed).toHaveLength(3); + const ctx = ctxFor(flat, c); + const { paths } = generatedToMapPaths(routed.map((p) => ({ typeName: p.type, hexes: p.hexes })), ctx, { styleFor }); + expect(paths).toHaveLength(1); + expect(paths[0].name).toBe("Road"); + expect(paths[0].branches.length).toBeGreaterThan(1); + expect(sameSteps(routedBranches(paths[0], ctx, styleFor), routed.map((r) => r.hexes))).toBe(true); + }); + + it("names new paths around the map's existing ones", () => { + const c = cells(flat); + const routed = routeContextPaths(c, DEFAULT_TERRAIN_PALETTE, flat, [{ type: "Road", from: "W", to: "E" }], 1); + const { paths } = generatedToMapPaths(routed.map((p) => ({ typeName: p.type, hexes: p.hexes })), ctxFor(flat, c), { styleFor, taken: ["road", "Road 2"] }); + expect(paths.map((p) => p.name)).toEqual(["Road 3"]); + }); +}); diff --git a/tests/freshEyesR5Setup.test.ts b/tests/freshEyesR5Setup.test.ts index 08cd03d4..8f9ed8c5 100644 --- a/tests/freshEyesR5Setup.test.ts +++ b/tests/freshEyesR5Setup.test.ts @@ -44,7 +44,7 @@ const kind = (id: string, extra: Partial = {}): TerrainGen options: [], fits: () => true, generate: () => ({ ok: true, cells: new Map(), paths: [], warnings: [] }), - toChains: () => ({ chains: [], missing: [] }), + toPaths: () => ({ paths: [], missing: [] }), ...extra, }); diff --git a/tests/generatorPaths.test.ts b/tests/generatorPaths.test.ts new file mode 100644 index 00000000..cfda398a --- /dev/null +++ b/tests/generatorPaths.test.ts @@ -0,0 +1,131 @@ +/** + * Phase 6 (plan-path-anchors §7): generators write anchored paths through + * the map store. What the map draws (its paths resolved under its own + * routing context) is exactly what the generator produced, it survives a + * restart (read back from the note), and regenerating replaces only the + * generator's own path types. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { MapStore } from "../src/maps/MapStore"; +import { MemVault } from "./helpers/memVault"; +import type { MapData } from "../src/types"; +import { DEFAULT_PATH_TYPES, DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { addGeneratedPaths, toMapPaths } from "../src/worldgen/generators"; +import { routeContextPaths } from "../src/worldgen/procedural/contextPaths"; +import type { ProcGrid } from "../src/worldgen/procedural/common"; +import { parseMapNote } from "../src/maps/mapNote"; +import { stepsOf } from "../src/paths/fromHexes"; + +(globalThis as Record).window ??= globalThis; + +const NOTE = "world/hexes/m/_m.md"; +const grid: ProcGrid = { cols: 14, rows: 10, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; + +const newMap = (): MapData => ({ + name: "m", paletteName: "Default", gridSize: { cols: grid.cols, rows: grid.rows }, gridOffset: { x: 0, y: 0 }, + staggerOffset: "odd", baseTerrain: "grass", pathChains: [], +} as MapData); + +function plugin(vault: MemVault, maps: MapData[]) { + const p = { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", maps, hexOrientation: "flat" as const, staggerOffset: "odd" as const }, + getMap: (n: string) => maps.find((m) => m.name === n), + getMapPalette: () => DEFAULT_TERRAIN_PALETTE, + getMapPathTypes: () => DEFAULT_PATH_TYPES, + saveData: async () => {}, + refreshHexMap: () => {}, + mapStore: undefined as unknown as MapStore, + }; + p.mapStore = new MapStore(p as never); + return p; +} + +async function boot(vault: MemVault, maps: MapData[]) { + const p = plugin(vault, maps); + await p.mapStore.init(); + return p; +} + +/** Grass with a sea channel down column 6 (the road has to bridge it). */ +function terrain(): Map { + const m = new Map(); + for (let x = 0; x < grid.cols; x++) for (let y = 0; y < grid.rows; y++) m.set(`${x}_${y}`, x === 6 ? "ocean" : "grass"); + return m; +} + +const sameSteps = (a: readonly (readonly string[])[], b: readonly (readonly string[])[]) => { + const x = stepsOf(a), y = stepsOf(b); + return x.size === y.size && [...x].every((k) => y.has(k)); +}; + +describe("generated paths through the map store", () => { + it("a new map's generated roads and rivers draw exactly the generated hexes, and again after a restart", async () => { + const v = new MemVault(); + const maps = [newMap()]; + const p = await boot(v, maps); + const cells = terrain(); + p.mapStore.setMany("m", [...cells].filter(([, t]) => t !== "grass").map(([k, t]) => [k, { terrain: t }])); + const generated = routeContextPaths(cells, DEFAULT_TERRAIN_PALETTE, grid, [ + { type: "Road", avoidImpassable: true, autoRoute: "direct", from: "W", to: "E" }, + { type: "River", avoidImpassable: false, autoRoute: "winding", from: "N", to: "S" }, + { type: "Trail", from: "S" }, + ], 7); + const { paths, missing } = toMapPaths(p as never, generated, undefined, "m"); + expect(missing).toEqual(["Trail"]); + addGeneratedPaths(p as never, "m", paths); + await p.mapStore.flush(); + + const want = (t: string) => generated.find((g) => g.type === t)!.hexes; + const drawn = p.mapStore.resolved("m")!; + expect(drawn.map((r) => [r.typeName, r.hexes])).toEqual([["Road", want("Road")], ["River", want("River")]]); + // The compatibility view holds the same chains. + expect(maps[0].pathChains.map((c) => c.hexes)).toEqual([want("Road"), want("River")]); + + // The note stores anchors (fewer than the hexes), not every hex. + const note = parseMapNote(v.files.get(NOTE)!)!; + expect(note.paths.map((x) => x.name)).toEqual(["Road", "River"]); + expect(note.paths[0].branches[0].anchors.length).toBeLessThan(want("Road").length); + + // Restart: a fresh store reads the note and draws the same hexes; nothing is rewritten. + v.writes = []; + const again = await boot(v, [newMap()]); + expect(again.mapStore.resolved("m")!.map((r) => r.hexes)).toEqual([want("Road"), want("River")]); + expect(v.writes).toEqual([]); + }); + + it("roads that meet become one road with branches; new paths are named around existing ones", async () => { + const v = new MemVault(); + const maps = [newMap()]; + const p = await boot(v, maps); + const cells = terrain(); + p.mapStore.setMany("m", [...cells].filter(([, t]) => t !== "grass").map(([k, t]) => [k, { terrain: t }])); + p.mapStore.setPaths("m", [{ name: "Road", typeName: "Road", branches: [{ anchors: ["0_0", "3_0"] }] }]); + const generated = routeContextPaths(cells, DEFAULT_TERRAIN_PALETTE, grid, [ + { type: "Road", from: "W" }, { type: "Road", from: "E" }, { type: "Road", from: "S" }, + ], 2); + const { paths } = toMapPaths(p as never, generated, undefined, "m"); + expect(paths.map((x) => x.name)).toEqual(["Road 2"]); + expect(paths[0].branches.length).toBeGreaterThan(1); + addGeneratedPaths(p as never, "m", paths); + const drawn = p.mapStore.resolved("m")!.filter((r) => r.path === "Road 2").map((r) => r.hexes); + expect(sameSteps(drawn, generated.map((g) => g.hexes))).toBe(true); + }); + + it("regenerating replaces whole paths of the generator's types and keeps the rest", async () => { + const v = new MemVault(); + const maps = [newMap()]; + const p = await boot(v, maps); + p.mapStore.setPaths("m", [ + { name: "King's road", typeName: "Road", notes: "old", branches: [{ anchors: ["0_0", "5_0"] }] }, + { name: "Glass river", typeName: "River", branches: [{ anchors: ["2_0", "2_9"] }] }, + ]); + const generated = routeContextPaths(terrain(), DEFAULT_TERRAIN_PALETTE, grid, [{ type: "Road", from: "W", to: "E" }], 4); + const kept = p.mapStore.paths("m").filter((x) => x.typeName !== "Road").map((x) => x.name); + const { paths } = toMapPaths(p as never, generated, undefined, "m", kept); + addGeneratedPaths(p as never, "m", paths, new Set(["Road"])); + expect(p.mapStore.paths("m").map((x) => [x.name, x.typeName])).toEqual([["Glass river", "River"], ["Road", "Road"]]); + }); +}); diff --git a/tests/neighbourGenerators.test.ts b/tests/neighbourGenerators.test.ts index 05f0c6aa..1d537e28 100644 --- a/tests/neighbourGenerators.test.ts +++ b/tests/neighbourGenerators.test.ts @@ -1,6 +1,10 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { DEFAULT_PATH_TYPES, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { pairCrossings, routeContextPaths } from "../src/worldgen/procedural/contextPaths"; +import { generatedToMapPaths, routedBranches } from "../src/paths/fromGenerated"; +import { mapRouteContext, pathTypeStyleFor } from "../src/paths/mapContext"; +import { impassableNames } from "../src/impassable"; import { edgePulls, planetSurface } from "../src/worldgen/procedural/planetSurface"; import { BLANK_ID, defaultGeneratorFor, kindsForPalette, neighbourFirst, type TerrainGeneratorKind } from "../src/worldgen/registry"; import type { ContextTerrain, ProcGrid } from "../src/worldgen/procedural/common"; @@ -102,7 +106,7 @@ describe("generators offered for a new map", () => { options: [], fits: () => true, generate: () => ({ ok: true, cells: new Map(), paths: [], warnings: [] }), - toChains: () => ({ chains: [], missing: [] }), + toPaths: () => ({ paths: [], missing: [] }), ...extra, }); const blank = kind(BLANK_ID, { source: "blank" }); @@ -134,3 +138,37 @@ describe("generators offered for a new map", () => { expect(defaultGeneratorFor([blank, stars, overlandK], {})).toBe("star-scatter"); }); }); + +describe("paths carried across the seam from a neighbour (phase 6)", () => { + const styleFor = pathTypeStyleFor(DEFAULT_PATH_TYPES); + + for (const seed of [1, 2, 3, 4, 5]) { + it(`a road crossing the border starts on the seam hex and draws exactly the generated hexes (seed ${seed})`, () => { + const edge = westBorder("grass", "grassland"); + const cells = overland(seed, { water: "20", sea: "east" }, edge); + // The neighbour's road crosses into the first column at row 4; one + // river comes in from the north edge. + const carry = pairCrossings([ + { type: "Road", avoidImpassable: true, autoRoute: "direct", hex: `${grid.offset.x}_4` }, + { type: "Road", avoidImpassable: true, autoRoute: "direct", hex: `${grid.offset.x + grid.cols - 1}_6` }, + { type: "River", avoidImpassable: false, autoRoute: "winding", hex: `${grid.offset.x + 5}_0` }, + ], grid); + const routed = routeContextPaths(cells, LIMITED_TERRAIN_PALETTE, grid, carry, seed); + const ctx = mapRouteContext({ + orientation: grid.orientation, stagger: grid.stagger, + gridSize: { cols: grid.cols, rows: grid.rows }, gridOffset: grid.offset, + terrainOf: [...cells].map(([k, terrain]): [string, { terrain: string }] => [k, { terrain }]), + impassable: impassableNames(LIMITED_TERRAIN_PALETTE), + }); + const { paths, inexact } = generatedToMapPaths(routed.map((p) => ({ typeName: p.type, hexes: p.hexes })), ctx, { styleFor }); + expect(inexact).toEqual([]); + const road = paths.find((p) => p.typeName === "Road")!; + const genRoad = routed.find((p) => p.type === "Road")!.hexes; + expect(genRoad[0]).toBe(`${grid.offset.x}_4`); + expect(road.branches[0].anchors[0]).toBe(`${grid.offset.x}_4`); + expect(routedBranches(road, ctx, styleFor)).toEqual([genRoad]); + const river = paths.find((p) => p.typeName === "River")!; + expect(routedBranches(river, ctx, styleFor)).toEqual([routed.find((p) => p.type === "River")!.hexes]); + }); + } +}); diff --git a/tests/proceduralGenerators.test.ts b/tests/proceduralGenerators.test.ts index c64f067f..bcaa5f41 100644 --- a/tests/proceduralGenerators.test.ts +++ b/tests/proceduralGenerators.test.ts @@ -102,7 +102,7 @@ describe("star scatter", () => { const g = grid(16, 16); const without = starScatter(SPACE_SECTOR_TERRAINS, g, 9, { routes: "2" }); expect(without.paths).toEqual([]); - expect(without.warnings.join(" ")).toMatch(/Jump route/); + expect(without.warnings.join(" ")).toMatch(/Path type for routes/); const r = starScatter(SPACE_SECTOR_TERRAINS, g, 9, { routes: "2" }, "Jump route"); expect(r.paths.length).toBeGreaterThan(0); diff --git a/tests/worldgenFirstMap.test.ts b/tests/worldgenFirstMap.test.ts index f72bf48d..3991f990 100644 --- a/tests/worldgenFirstMap.test.ts +++ b/tests/worldgenFirstMap.test.ts @@ -1,7 +1,7 @@ import { describe, it } from "node:test"; import expect from "expect"; import { DEFAULT_SETTINGS, DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; -import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; +import { SPACE_PATH_TYPES, SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS, SYSTEM_PATH_TYPES } from "../src/palettes/presets"; import { OVERLAND_OPTIONS, maxLakeSize, @@ -15,13 +15,17 @@ import { OVERLAND_ID, } from "../src/worldgen/procedural/planetSurface"; import { STAR_SCATTER_ID } from "../src/worldgen/procedural/starScatter"; -import { BLANK_ID, firstMapGenerator, generationKey } from "../src/worldgen/registry"; +import { BLANK_ID, firstMapGenerator, generationKey, kindOptions, listGeneratorKinds, optionsWithDefaults } from "../src/worldgen/registry"; +import { ORBITS_ID } from "../src/worldgen/procedural/orbits"; +import { NO_PATHS, ORBIT_TYPE_KEY, PRESET_PATH_TYPE, ROUTE_TYPE_KEY, chosenPathType, defaultPathTypeFor } from "../src/worldgen/generatorPathTypes"; +import { generatedToMapPaths, routedBranches } from "../src/paths/fromGenerated"; +import { mapRouteContext, pathTypeStyleFor } from "../src/paths/mapContext"; import { defaultPaletteFor, paletteHint, repointPaletteName, resolveDefaultPalette, resolveExpandedDefault } from "../src/palettes/paletteOptions"; import { isUnusedPlaceholderMap } from "../src/setupPlaceholder"; import { neighbourSeaText } from "../src/worldgen/NewMapSetupModal"; import type { ProcGrid } from "../src/worldgen/procedural/common"; import { hexNeighbors } from "../packages/hex-wfc/src"; -import type { TerrainColor } from "../src/types"; +import type { PathType, TerrainColor } from "../src/types"; /** Fresh-eyes 2026-10-09 (#36): first-run wizard, Overland, Frozen, palette defaults. */ @@ -550,3 +554,124 @@ describe("Overland Sea default next to a neighbour (fresh-eyes r4)", () => { expect(neighbourSeaText({ side: "none", why: "dry" }, "ashby-vale")).toMatch(/no water/); }); }); + +// ── Phase 6: generator path types are explicit options, never names ────────── + +describe("Star scatter and Orbits: the path type is an option from the palette", () => { + const fakePlugin = { + settings: { worldFolder: "world", hexOrientation: "flat", staggerOffset: "odd", terrainPalettes: [] }, + app: { vault: { getMarkdownFiles: () => [] } }, + }; + const kindsP = listGeneratorKinds(fakePlugin as never); + const kindOf = async (id: string) => (await kindsP).find((k) => k.id === id)!; + const sector: ProcGrid = { cols: 16, rows: 16, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; + const system: ProcGrid = { ...sector, cols: 13, rows: 13 }; + const gridSpec = (g: ProcGrid) => ({ cols: g.cols, rows: g.rows, offset: g.offset, stagger: g.stagger }); + const renamedSector: PathType[] = SPACE_PATH_TYPES.map((t, i) => ({ ...t, name: ["Hyperlane", "Spice run"][i] })); + const renamedSystem: PathType[] = SYSTEM_PATH_TYPES.map((t) => ({ ...t, name: "Ring" })); + const run = async (id: string, terrains: TerrainColor[], g: ProcGrid, pathTypes: PathType[] | undefined, options: Record = {}) => { + const kind = await kindOf(id); + const out = kind.generate({ terrains, grid: gridSpec(g), seed: 9, options: optionsWithDefaults(kind, options), pathTypes }); + if (!out.ok) throw new Error(out.message); + return out; + }; + const optionOf = async (id: string, terrains: TerrainColor[], pathTypes: PathType[] | undefined, key: string) => + kindOptions(await kindOf(id), terrains, pathTypes).find((o) => o.key === key)!; + + it("the Space presets say, as data, which of their types draws routes and orbits", () => { + expect(defaultPathTypeFor("routes", SPACE_PATH_TYPES)).toBe("Jump route"); + expect(defaultPathTypeFor("orbits", SYSTEM_PATH_TYPES)).toBe("Orbit"); + // Only a preset's own designation counts: a type that merely sounds right doesn't. + expect(defaultPathTypeFor("routes", [{ name: "Orbit" }])).toBeUndefined(); + expect(defaultPathTypeFor("routes", [{ name: "Jump route" }], [{ pathRoles: { routes: "Lane" } }])).toBeUndefined(); + expect(defaultPathTypeFor("routes", [{ name: "Lane" }], [{ pathRoles: { routes: "Lane" } }])).toBe("Lane"); + }); + + it("Star scatter: the preset's route type by default, listed among the palette's types", async () => { + const opt = await optionOf(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, SPACE_PATH_TYPES, ROUTE_TYPE_KEY); + expect(opt.label).toBe("Path type for routes"); + expect(opt.choices.map((c) => c.value)).toEqual(["Jump route", "Trade route", NO_PATHS]); + expect(opt.default).toBe("Jump route"); + const r = await run(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, sector, SPACE_PATH_TYPES); + expect(r.paths.length).toBeGreaterThan(0); + expect(new Set(r.paths.map((p) => p.type))).toEqual(new Set(["Jump route"])); + const trade = await run(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, sector, SPACE_PATH_TYPES, { [ROUTE_TYPE_KEY]: "Trade route" }); + expect(new Set(trade.paths.map((p) => p.type))).toEqual(new Set(["Trade route"])); + }); + + it("Star scatter on a palette whose types are renamed: no guessing, and the option works", async () => { + const opt = await optionOf(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, renamedSector, ROUTE_TYPE_KEY); + expect(opt.choices.map((c) => c.value)).toEqual(["Hyperlane", "Spice run", NO_PATHS]); + expect(opt.default).toBe(NO_PATHS); + const byDefault = await run(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, sector, renamedSector); + expect(byDefault.paths).toEqual([]); + expect(byDefault.warnings.join(" ")).toContain("Path type for routes"); + const chosen = await run(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, sector, renamedSector, { [ROUTE_TYPE_KEY]: "Hyperlane" }); + expect(chosen.paths.length).toBeGreaterThan(0); + expect(new Set(chosen.paths.map((p) => p.type))).toEqual(new Set(["Hyperlane"])); + // The same routes as under the preset's names: the name changes nothing else. + const preset = await run(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, sector, SPACE_PATH_TYPES); + expect(chosen.paths.map((p) => p.hexes)).toEqual(preset.paths.map((p) => p.hexes)); + }); + + it("Star scatter: None on purpose draws no routes quietly; a palette without types offers only None and says so", async () => { + const none = await run(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, sector, SPACE_PATH_TYPES, { [ROUTE_TYPE_KEY]: NO_PATHS }); + expect(none.paths).toEqual([]); + expect(none.warnings.join(" ")).not.toContain("Path type for routes"); + const opt = await optionOf(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, [], ROUTE_TYPE_KEY); + expect(opt.choices).toEqual([{ value: NO_PATHS, label: "None (this palette has no path types)" }]); + const bare = await run(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, sector, []); + expect(bare.paths).toEqual([]); + expect(bare.warnings.join(" ")).toContain("Path type for routes"); + }); + + it("Orbits: the preset's orbit type by default; a renamed type works through the option", async () => { + const opt = await optionOf(ORBITS_ID, SPACE_SYSTEM_TERRAINS, SYSTEM_PATH_TYPES, ORBIT_TYPE_KEY); + expect(opt.label).toBe("Path type for orbits"); + expect(opt.default).toBe("Orbit"); + const r = await run(ORBITS_ID, SPACE_SYSTEM_TERRAINS, system, SYSTEM_PATH_TYPES, { bodies: "crowded" }); + expect(r.paths.length).toBeGreaterThan(0); + expect(new Set(r.paths.map((p) => p.type))).toEqual(new Set(["Orbit"])); + + expect((await optionOf(ORBITS_ID, SPACE_SYSTEM_TERRAINS, renamedSystem, ORBIT_TYPE_KEY)).default).toBe(NO_PATHS); + const byDefault = await run(ORBITS_ID, SPACE_SYSTEM_TERRAINS, system, renamedSystem, { bodies: "crowded" }); + expect(byDefault.paths).toEqual([]); + expect(byDefault.warnings.join(" ")).toContain("Path type for orbits"); + const ring = await run(ORBITS_ID, SPACE_SYSTEM_TERRAINS, system, renamedSystem, { bodies: "crowded", [ORBIT_TYPE_KEY]: "Ring" }); + expect(new Set(ring.paths.map((p) => p.type))).toEqual(new Set(["Ring"])); + expect(ring.paths.map((p) => p.hexes)).toEqual(r.paths.map((p) => p.hexes)); + const none = await run(ORBITS_ID, SPACE_SYSTEM_TERRAINS, system, SYSTEM_PATH_TYPES, { bodies: "crowded", [ORBIT_TYPE_KEY]: NO_PATHS }); + expect(none.paths).toEqual([]); + expect(none.warnings.join(" ")).not.toContain("Path type for orbits"); + }); + + it("a choice saved on another palette falls back to this palette's default", () => { + expect(chosenPathType("Hyperlane", "routes", SPACE_PATH_TYPES)).toBe("Jump route"); + expect(chosenPathType(PRESET_PATH_TYPE, "routes", SPACE_PATH_TYPES)).toBe("Jump route"); + expect(chosenPathType(NO_PATHS, "routes", SPACE_PATH_TYPES)).toBeUndefined(); + expect(chosenPathType("Trade route", "routes", SPACE_PATH_TYPES)).toBe("Trade route"); + }); + + it("orbit rings come out as anchored paths that draw exactly the ring hexes", async () => { + const r = await run(ORBITS_ID, SPACE_SYSTEM_TERRAINS, system, SYSTEM_PATH_TYPES, { bodies: "crowded" }); + const ctx = mapRouteContext({ orientation: "flat", stagger: "odd", gridSize: { cols: 13, rows: 13 }, gridOffset: { x: 0, y: 0 }, terrainOf: [], impassable: [] }); + const styleFor = pathTypeStyleFor(SYSTEM_PATH_TYPES); + const { paths, inexact } = generatedToMapPaths(r.paths.map((p) => ({ typeName: p.type, hexes: p.hexes })), ctx, { styleFor }); + expect(inexact).toEqual([]); + expect(paths.map((p) => p.name)).toEqual(r.paths.map((_, i) => (i ? `Orbit ${i + 1}` : "Orbit"))); + paths.forEach((p, i) => { + expect(routedBranches(p, ctx, styleFor)).toEqual([r.paths[i].hexes]); + expect(p.branches[0].anchors.length).toBeLessThan(r.paths[i].hexes.length); + }); + }); + + it("jump routes draw through every system they link (one network per joined set)", async () => { + const r = await run(STAR_SCATTER_ID, SPACE_SECTOR_TERRAINS, sector, SPACE_PATH_TYPES); + const ctx = mapRouteContext({ orientation: "flat", stagger: "odd", gridSize: { cols: 16, rows: 16 }, gridOffset: { x: 0, y: 0 }, terrainOf: [], impassable: [] }); + const { paths } = generatedToMapPaths(r.paths.map((p) => ({ typeName: p.type, hexes: p.hexes })), ctx, { styleFor: pathTypeStyleFor(SPACE_PATH_TYPES) }); + expect(paths.length).toBeLessThan(r.paths.length); + // Systems a step apart may sit on a route between two anchors; every one is drawn. + const drawn = new Set(paths.flatMap((p) => routedBranches(p, ctx, pathTypeStyleFor(SPACE_PATH_TYPES)).flat())); + for (const p of r.paths) for (const h of p.hexes) expect(drawn.has(h)).toBe(true); + }); +}); diff --git a/tests/worldgenGenerators.test.ts b/tests/worldgenGenerators.test.ts index 80660fd1..8f71b640 100644 --- a/tests/worldgenGenerators.test.ts +++ b/tests/worldgenGenerators.test.ts @@ -24,7 +24,7 @@ import type { TerrainColor } from "../src/types"; * In-memory vault + plugin stub. Hex notes are represented only by their * frontmatter (terrain, locked); other written files are kept as text. */ -function makePlugin(painted: Record, locked: string[] = []) { +function makePlugin(painted: Record, locked: string[] = [], drawnPaths: { typeName: string; hexes: string[] }[] = []) { const files = new Map(); const folders = new Set(); const fileObj = (path: string) => { @@ -105,6 +105,8 @@ function makePlugin(painted: Record, locked: string[] = []) { }, hasTerrainEncounterTable: () => false, syncHexEncounterTableLink: async () => {}, + // The map's anchored paths, resolved (what the map draws). + paths: { resolvedPathChains: () => drawnPaths }, } as unknown as HexmakerPlugin; const terrainAt = (k: string) => { const [x, y] = k.split("_").map(Number); @@ -171,6 +173,15 @@ describe("worldgen generators", () => { expect(listed[0].model.adjacency).toEqual(saved.model.adjacency); }); + it("learns paths from the map's resolved chains (anchored paths as drawn)", async () => { + const road = ["0_9", "1_9", "2_9", "3_9", "4_9", "5_9", "6_9", "7_9", "8_9", "9_9", "10_9", "11_9"]; + const { plugin } = makePlugin(lakeSample(), [], [{ typeName: "Road", hexes: road }]); + const saved = await saveGeneratorFromMap(plugin, "sample", "with-road"); + expect("error" in saved).toBe(false); + if ("error" in saved) return; + expect(saved.model.paths?.map((p) => p.type)).toEqual(["Road"]); + }); + it("refuses to learn from an unpainted map", async () => { const { plugin } = makePlugin({}); const r = await saveGeneratorFromMap(plugin, "sample", "x"); From 8249552d435065fa225899866dffe4ee19c95023 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 19:51:52 -0400 Subject: [PATCH 234/558] feat(paths): path tool revamp (phase 5) and keep-the-route pins with "Reroute instead" (phase 7) Phase 5, src/hex-map/pathTool.ts (controller; HexMapView only delegates): - far clicks auto-route from the active end and add an anchor; keep clicking to add more. Hex-by-hex is still there (a click away from the end is routed, with a mode-bar note, instead of leaving a lonely restart dot). - click a path to select it (anchor handles, ends bigger); click an end to continue it, anywhere else on it to fork; drag any point of its line to move an anchor or insert one there, with a live reroute preview (PathsService.setPreview, nothing saved until release, one undo step). - right-click a handle / Backspace deletes an anchor; erase mode splits; context menu: split, delete fork/path, rename, change type, reverse. - New path button and Alt-click start a new path even on another one. - one choke point for every path write: src/paths/editGate.ts canEditPaths (always allows for now; the per-map Play/Build/God mode will answer there). Undo items hold MapPath[] snapshots. - picker: "Paths on this map" list and new hints; mode-bar labels; help. Phase 7, src/paths/routePins.ts: RoutePins takes over MapStore.onRouteContextChange (returns true), pins with pinChanged and shows one batched notice "Kept the route of ... (n anchors added)" with "Reroute instead". PathsService calls routesChanging(map) before resolving whenever the context signature or the types' styles changed, so palette flags, resizes and avoidImpassable/autoRoute edits pin before anything draws. Terrain-stroke undo drops the pins it caused. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 7 + src/hex-map/HexMapView.ts | 550 +++++++---------- src/hex-map/PathNameModal.ts | 63 ++ src/hex-map/PathPickerModal.ts | 43 +- src/hex-map/autoRoute.ts | 50 +- src/hex-map/help.md | 16 +- src/hex-map/pathTool.ts | 1006 ++++++++++++++++++++++++++++++++ src/hex-map/toolMode.ts | 59 +- src/paths/PathsService.ts | 63 +- src/paths/editGate.ts | 31 + src/paths/pathGeometry.ts | 3 + src/paths/routePins.ts | 242 ++++++++ styles.css | 58 ++ tests/autoRoute.test.ts | 68 ++- tests/pathTool.test.ts | 148 +++++ tests/routePins.test.ts | 148 +++++ tests/toolMode.test.ts | 112 ++-- 18 files changed, 2151 insertions(+), 520 deletions(-) create mode 100644 src/hex-map/PathNameModal.ts create mode 100644 src/hex-map/pathTool.ts create mode 100644 src/paths/editGate.ts create mode 100644 src/paths/routePins.ts create mode 100644 tests/pathTool.test.ts create mode 100644 tests/routePins.test.ts diff --git a/package.json b/package.json index 376c0515..59dab49b 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathTool.test.ts tests/routePins.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathMigrate.test.ts tests/mapNotePaths.test.ts tests/r3Labels.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathTool.test.ts tests/routePins.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index be951dff..32f9d3b8 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -32,6 +32,7 @@ import { import { SetupWizardView } from "./SetupWizardView"; import { PaletteStore } from "./palettes/PaletteStore"; import { PathsService } from "./paths/PathsService"; +import { RoutePins } from "./paths/routePins"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; import { enabledKinds, isIconHiddenByKind, isSpacePalette, newTerrains, resolveMapKinds, sectionKindFor, sectionWordsFor, terrainsForTables, type SectionWordsFn } from "./mapKinds"; import { enableFeature, hasFeature, resolveFeatureLevel, shouldNudge, type AdvancedFeature, type FeatureLevel } from "./featureLevel"; @@ -114,10 +115,15 @@ export default class HexmakerPlugin extends Plugin { pathTypes: (map) => this.getMapPathTypes(map), palette: (map) => this.getMapPalette(map), hexData: (map) => this.mapStore.all(map), + // Keep routes where they were when their inputs change (phase 7). + routesChanging: (map) => this.pathPins.sync(map), }); + /** Keeps routes in place when terrain, the palette, the size or a type's routing changes (Decision 3). */ + pathPins = new RoutePins(this); async onload() { await this.loadSettings(); + this.pathPins.attach(); // Terrains known now (data.json's copy of the palettes). Any a palette // note adds while Obsidian was closed get their tables once the notes // are read (HG5). @@ -581,6 +587,7 @@ export default class HexmakerPlugin extends Plugin { } onunload() { + this.pathPins.detach(); clearPendingTerrain(); } diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 39cdeb31..d95f3063 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -29,7 +29,10 @@ import { import { MapModal } from "./MapModal"; import { mapAncestors } from "./submapNav"; import { ancestorNeighbourCrumbs, neighbourCrumbs } from "../maps/mapTree"; -import { pathClickOutcome, toolModeLabel } from "./toolMode"; +import { toolModeLabel } from "./toolMode"; +import { PathTool } from "./pathTool"; +import type { PinRecord } from "../paths/routePins"; +import { pathSummary } from "./pathTool"; import { openNoteFocused } from "../openNote"; import { coordHaloColor } from "../coordStyle"; import { ghostPathRuns, ghostRunPoints, seamJoinKey, seamJoins, seamPoint, type ShadowRef } from "./ghostPaths"; @@ -43,14 +46,14 @@ import { whenSized } from "./whenSized"; import { getHexNameFromFile } from "../frontmatter"; import { nearestHex } from "./hitTest"; import { PathPickerModal } from "./PathPickerModal"; -import { addRoutedLeg, findRoute } from "./autoRoute"; -import { impassableNames, noRouteMessage, pathAvoidsImpassable, pathMeanders } from "../impassable"; -import type { MapData, PathChain, TokenEntry } from "../types"; +import { impassableNames } from "../impassable"; +import type { MapData, MapPath, TokenEntry } from "../types"; import { hexNeighbors, smoothPath, sharpPath } from "./hexGeometry"; import { applyAffine, calibrateAffine, END_DOT_PX, + HANDLE_PX, fmt, latticeCenter, pxToLattice, @@ -120,7 +123,8 @@ interface CalibrateSnapshot { } type UndoItem = - | { kind: "terrain"; entries: TerrainUndoEntry[] } + /** `pins`: anchors the stroke made paths gain to keep their routes (undone with it). */ + | { kind: "terrain"; entries: TerrainUndoEntry[]; pins?: PinRecord[] } | { kind: "icon"; entries: IconUndoEntry[] } | { kind: "faction"; entries: FactionUndoEntry[] } | { kind: "region"; entries: RegionUndoEntry[] } @@ -128,8 +132,8 @@ type UndoItem = | { kind: "path"; mapName: string; - before: PathChain[]; - after: PathChain[]; + before: MapPath[]; + after: MapPath[]; } | { kind: "calibrate"; @@ -296,15 +300,11 @@ export class HexMapView extends ItemView { private toolsPanel: DrawingToolPanel | null = null; private swapSource: { x: number; y: number } | null = null; private swapDest: { x: number; y: number } | null = null; - // The last-clicked hex key and the specific chain being extended - private activePathTypeName: string | null = null; - private activePathEnd: string | null = null; - private activePathChain: PathChain | null = null; - /** Path tool: route between two clicked hexes instead of hex by hex. */ - private pathAutoRoute = false; - /** Auto-route: go through impassable terrain this time (bar checkbox). */ - private routeCrossImpassable = false; - /** Auto-route controls in the mode bar (shown while drawing a path). */ + /** The path tool: drawing, selecting, reshaping (src/hex-map/pathTool.ts). */ + private pathTool: PathTool; + /** Pins made while a terrain stroke is painted or its writes land (see routePins.ts). */ + private strokePins: PinRecord[] | null = null; + /** Path tool controls in the mode bar (shown while drawing a path). */ private modeBarRouteEl: HTMLElement | null = null; private paintTerrainName: string | null = null; private paintIconName: string | null = null; @@ -380,6 +380,20 @@ export class HexMapView extends ItemView { constructor(leaf: WorkspaceLeaf, plugin: HexmakerPlugin) { super(leaf); this.plugin = plugin; + this.pathTool = new PathTool({ + plugin: this.plugin, + mapName: () => this.activeMapName, + pointerLattice: (e) => this.pointerLattice(e), + hexAtPoint: (x, y) => { + const hexEl = this.hexElAt(this.contentEl.ownerDocument.elementFromPoint(x, y), x, y); + return hexEl ? `${hexEl.dataset.x}_${hexEl.dataset.y}` : null; + }, + ownerDocument: () => this.contentEl.ownerDocument, + pushUndo: (map, before, after) => this.pushPathUndo(map, before, after), + redraw: () => this.updatePathOverlay(), + refreshBar: () => this.updateModeBar(), + setGrabCursor: (on) => this.viewportEl?.toggleClass("duckmage-path-grab", on), + }); } getViewType(): string { @@ -805,9 +819,18 @@ export class HexMapView extends ItemView { return false; } if (this.drawingMode === null) return true; + // The path tool steps out one level at a time (finish → deselect → leave). + if (this.drawingMode === "path" && !this.isErasingMode && this.pathTool.escape()) return false; this.exitCurrentMode(); return false; }); + // Path tool: Backspace / Delete removes the hovered anchor, else the active end's. + for (const key of ["Backspace", "Delete"]) { + this.scope.register([], key, () => { + if (this.drawingMode !== "path" || this.isErasingMode) return true; + return !this.pathTool.deleteKey(); + }); + } this.factionTooltipEl = contentEl.createDiv({ cls: "duckmage-faction-tooltip" }); this.factionTooltipEl.hide(); @@ -930,8 +953,10 @@ export class HexMapView extends ItemView { if (this.drawingMode === "terrain" || this.drawingMode === "icon" || this.drawingMode === "factionLink" || this.drawingMode === "regionLink") { isTerrainPainting = true; lastPaintedKey = null; - if (this.drawingMode === "terrain") + if (this.drawingMode === "terrain") { this.currentTerrainStroke = new Map(); + this.strokePins = []; + } else if (this.drawingMode === "icon") this.currentIconStroke = new Map(); else if (this.drawingMode === "factionLink") @@ -954,6 +979,8 @@ export class HexMapView extends ItemView { beginDrag(); return; // skip pan setup } + // The path tool takes a press on the selected path (drag to reshape). + if (this.drawingMode === "path" && this.pathTool.pointerDown(e, this.isErasingMode)) return; // Any other active tool (road, river, tableLink, swap): // let the click event handle it — don't set up drag/pan so hasDragged // never swallows the click. @@ -973,6 +1000,7 @@ export class HexMapView extends ItemView { // document (issue #32). Stroke-time highlight is owned by onDragMove. this.registerDomEvent(contentEl, "mousemove", (e: MouseEvent) => { if (isTerrainPainting) return; + if (this.drawingMode === "path" && e.buttons === 0) this.pathTool.pointerMove(e); if (this.drawingMode === "terrain" || this.drawingMode === "icon") { const hexEl = (e.target as HTMLElement | null)?.closest( ".duckmage-hex", @@ -1110,18 +1138,15 @@ export class HexMapView extends ItemView { this.removeOneGmIconFromHex(hexEl, hexX, hexY, this.paintIconName); return; } - // Path tool: right-click a hex of the path type being drawn removes - // it from its chain, as the help says (fresh-eyes T2). Anywhere else - // still opens the tool menu. - if ( - this.drawingMode === "path" && - hexX !== null && hexY !== null && - this.pathChainWithHex(`${hexX}_${hexY}`, this.activePathTypeName) - ) { - void this.onHexPathDeleteClick(hexX, hexY, this.activePathTypeName); - return; + // Path tool: right-click an anchor handle of the selected path + // deletes it; on a path, the menu adds that path's actions. + let pathItems: { label: string; onClick: () => void }[] = []; + if (this.drawingMode === "path" && !this.isErasingMode) { + const r = this.pathTool.contextMenu(e); + if (r && "handled" in r) return; + if (r) pathItems = r.items; } - this.showPainterContextMenu(e.clientX, e.clientY, hexX, hexY); + this.showPainterContextMenu(e.clientX, e.clientY, hexX, hexY, pathItems); }, { capture: true }, ); @@ -1389,6 +1414,12 @@ export class HexMapView extends ItemView { if (hexKeyFromBasename(file.basename)) this.scheduleLinkBadges(); }), ); + // Paths that kept their route because of a terrain stroke: undone with it. + this.register( + this.plugin.pathPins.onPinned((r) => { + if (r.map === this.activeMapName && this.strokePins) this.strokePins.push(r); + }), + ); // Terrain painted / generated → the legend lists what the map now uses. this.register( this.plugin.mapStore.onChange((map) => { @@ -1807,6 +1838,7 @@ export class HexMapView extends ItemView { clientY: number, hexX: number | null, hexY: number | null, + pathItems: { label: string; onClick: () => void }[] = [], ): void { const mode = this.drawingMode; let onSwitch: (() => void) | null = null; @@ -1847,6 +1879,8 @@ export class HexMapView extends ItemView { onSwitch = () => this.handlePathButton(); switchLabel = "Switch path type"; extra.push({ label: erasing ? "Draw mode" : "Erase mode", onClick: toggleEraseMode }); + if (!erasing) extra.push({ label: "New path", onClick: () => this.pathTool.startNewPath() }); + extra.push(...pathItems); } else if (mode === "placeToken") { onSwitch = () => this.handleTokenButton(true); switchLabel = "Switch token"; @@ -1886,8 +1920,7 @@ export class HexMapView extends ItemView { } private exitPathMode(): void { - this.activePathEnd = null; - this.activePathChain = null; + this.pathTool.reset(); } openTerrainPicker(): void { @@ -2217,12 +2250,9 @@ export class HexMapView extends ItemView { } // Double-click on the destination confirms the swap - private onHexDblClick(x: number, y: number): void { - if (this.drawingMode === "path") { - this.exitPathMode(); - this.updatePathOverlay(); - return; - } + private onHexDblClick(_x: number, _y: number): void { + // Path tool: a double-click is two clicks on one hex, and the second + // one (on the active end) already finishes the branch. } /** Right-click → "Create token here": same TokenModal as the toolbar @@ -2389,10 +2419,9 @@ export class HexMapView extends ItemView { this.pathToolbarBtn?.toggleClass("is-erase", erasing && this.drawingMode === "path"); // Update path button swatch color to show active type if (this.pathBtnSwatch) { - const activeType = this.activePathTypeName - ? this.mapPathTypes().find( - (p) => p.name === this.activePathTypeName, - ) + const current = this.pathTool.currentType(); + const activeType = current + ? this.mapPathTypes().find((p) => p.name === current) : this.mapPathTypes()[0]; if (activeType) { this.pathBtnSwatch.setCssProps({ @@ -2553,9 +2582,13 @@ export class HexMapView extends ItemView { terrainPick: this.terrainPickMode, iconName: this.paintIconName, iconGmOnly: this.paintIconGmOnly, - pathTypeName: this.activePathTypeName, - pathAuto: this.pathAutoRoute, - pathHasStart: this.activePathEnd !== null, + pathTypeName: this.pathTool.currentType(), + pathAuto: this.pathTool.autoRoute, + pathDrawing: this.pathTool.labelState().drawing, + pathSelected: this.pathTool.labelState().selected, + pathSummary: this.pathTool.labelState().summary, + pathNew: this.pathTool.labelState().forceNew, + pathNote: this.pathTool.labelState().note, tablePath: this.paintTablePath, submapName: this.paintSubmapName, factionPath: this.paintFactionPath, @@ -4433,9 +4466,7 @@ export class HexMapView extends ItemView { private async onHexClick(x: number, y: number, e?: MouseEvent): Promise { if (this.drawingMode === "path") { - if (this.isErasingMode) { await this.onHexPathDeleteClick(x, y); return; } - if (this.pathAutoRoute) { await this.onHexPathRouteClick(x, y); return; } - await this.onHexPathDrawClick(x, y); + this.pathTool.click(x, y, e, this.isErasingMode); return; } if (this.drawingMode === "terrain") { @@ -4953,11 +4984,15 @@ export class HexMapView extends ItemView { return; } const entries = [...this.currentTerrainStroke.values()]; - this.undoStack.push({ kind: "terrain", entries }); + // Pins made by this stroke's writes (some land after the mouse is up). + const pins = this.strokePins ?? []; + this.strokePins = pins; + this.undoStack.push({ kind: "terrain", entries, pins }); if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); this.redoStack = []; this.currentTerrainStroke = null; this.updateUndoButton(); + void this.releaseStrokePins(pins); } private commitIconStroke(): void { @@ -5004,7 +5039,14 @@ export class HexMapView extends ItemView { if (!item) return; this.redoStack.push(item); if (item.kind === "terrain") { + this.strokePins = null; this.applyStroke(item.entries, "old"); + // Once the old terrain is back, the anchors the stroke pinned go too. + if (item.pins?.length) { + const pins = item.pins; + await this.terrainWritesSettled(); + this.plugin.pathPins.rerouteInstead(pins); + } } else if (item.kind === "icon") { await this.applyIconStroke(item.entries, "old"); } else if (item.kind === "faction") { @@ -5026,7 +5068,11 @@ export class HexMapView extends ItemView { if (!item) return; this.undoStack.push(item); if (item.kind === "terrain") { + // Repainting pins the routes again (and they're recorded afresh). + item.pins = []; + this.strokePins = item.pins; this.applyStroke(item.entries, "new"); + void this.releaseStrokePins(item.pins); } else if (item.kind === "icon") { await this.applyIconStroke(item.entries, "new"); } else if (item.kind === "faction") { @@ -5043,17 +5089,22 @@ export class HexMapView extends ItemView { this.updateUndoButton(); } - private async applyPathSnapshot( - mapName: string, - chains: PathChain[], - ): Promise { - const region = this.plugin.getMap(mapName); - if (!region) return; - region.pathChains = this.cloneChains(chains); - // Clear active chain tracking — the restored state may not match - this.exitPathMode(); - await this.plugin.saveSettings(); - this.updatePathOverlay(); + private applyPathSnapshot(mapName: string, paths: MapPath[]): Promise { + if (!this.plugin.getMap(mapName)) return Promise.resolve(); + this.pathTool.applySnapshot(mapName, paths); + return Promise.resolve(); + } + + /** Wait (briefly) until every queued terrain write has landed in the map store. */ + private async terrainWritesSettled(): Promise { + const busy = () => this.pendingTerrainWrites.size > 0 || [...this.flushing].some((k) => k.startsWith("t:")); + for (let i = 0; i < 100 && busy(); i++) await new Promise((r) => window.setTimeout(r, 50)); + } + + /** Stop collecting pins into `pins` once the stroke's writes have landed. */ + private async releaseStrokePins(pins: PinRecord[]): Promise { + await this.terrainWritesSettled(); + if (this.strokePins === pins) this.strokePins = null; } private applyStroke(stroke: TerrainUndoEntry[], which: "old" | "new"): void { @@ -5397,13 +5448,12 @@ export class HexMapView extends ItemView { this.app, this.plugin, this.plugin.mapPaletteName(this.activeMapName), - this.activePathTypeName, + this.pathTool.typeName, (typeName) => { this.leaveOtherToolFor("path"); - // A new type starts a new chain rather than continuing the old one; - // re-picking the type being drawn keeps the chain going. - if (this.drawingMode !== "path" || typeName !== this.activePathTypeName) this.exitPathMode(); - this.activePathTypeName = typeName; + // A new type ends the branch being drawn; re-picking the type keeps it going. + if (this.drawingMode !== "path") this.exitPathMode(); + this.pathTool.setType(typeName); this.drawingMode = "path"; this.isErasingMode = false; this.updateToolbarButtonStates(); @@ -5419,295 +5469,62 @@ export class HexMapView extends ItemView { this.updatePathOverlay(); }, { - value: this.pathAutoRoute, - onChange: (on) => this.setPathAutoRoute(on), + value: this.pathTool.autoRoute, + onChange: (on) => this.pathTool.setAutoRoute(on), noImpassable: impassableNames(this.plugin.getMapPalette(this.activeMapName)).length === 0, }, + { + list: this.plugin.mapStore.paths(this.activeMapName).map((p) => ({ name: p.name, typeName: p.typeName, summary: pathSummary(p) })), + selected: this.pathTool.selected, + onPick: (name) => { + this.leaveOtherToolFor("path"); + this.drawingMode = "path"; + this.isErasingMode = false; + this.pathTool.selectPath(name); + this.updateToolbarButtonStates(); + this.updatePathOverlay(); + }, + }, ).open(); } - /** Switch the path tool between hex-by-hex drawing and auto-route. */ - private setPathAutoRoute(on: boolean): void { - if (this.pathAutoRoute === on) return; - this.pathAutoRoute = on; - // A start picked for a route isn't a path yet: hex-by-hex drawing - // can't extend it, so drop it. A drawn path keeps going either way. - if (!on && this.activePathChain === null) this.activePathEnd = null; - this.updateModeBar(); - } - - /** Auto-route toggle, "Cross impassable" and the setup hint, in the mode bar. */ + /** The path tool's controls in the mode bar (src/hex-map/pathTool.ts). */ private renderRouteControls(): void { const el = this.modeBarRouteEl; if (!el) return; el.empty(); const show = this.drawingMode === "path" && !this.isErasingMode; el.toggle(show); - if (!show) return; - const auto = el.createEl("button", { - cls: "duckmage-mode-bar-route-toggle", - text: "Auto-route", - attr: { - "aria-pressed": String(this.pathAutoRoute), - title: this.pathAutoRoute - ? "On: click a start and an end, the path finds its way. Click to draw hex by hex." - : "Off: drawing hex by hex. Click to route between two hexes instead.", - }, - }); - auto.toggleClass("is-active", this.pathAutoRoute); - auto.addEventListener("click", () => this.setPathAutoRoute(!this.pathAutoRoute)); - if (!this.pathAutoRoute) return; - const type = this.mapPathTypes().find((p) => p.name === this.activePathTypeName); - if (type && !pathAvoidsImpassable(type)) return; // e.g. rivers: they go anywhere - const blocked = impassableNames(this.plugin.getMapPalette(this.activeMapName)); - if (!blocked.length) { - el.createSpan({ - cls: "duckmage-mode-bar-route-note", - text: "No impassable terrain", - attr: { title: "Nothing in this map's palette is impassable, so routes go straight through anything. Mark terrains (e.g. water) impassable in the palette editor or the terrain editor." }, - }); - return; - } - const label = el.createEl("label", { - cls: "duckmage-mode-bar-route-cross", - attr: { title: `Let the route go through ${blocked.join(", ")}` }, - }); - const box = label.createEl("input", { type: "checkbox" }); - box.checked = this.routeCrossImpassable; - box.addEventListener("change", () => { this.routeCrossImpassable = box.checked; }); - label.createSpan({ text: "Cross impassable" }); - } - - /** Terrain shown on a hex (its own, else the map's base terrain). */ - private terrainShownAt(x: number, y: number): string | null { - return getTerrainFromFile(this.app, this.plugin.hexPath(x, y, this.activeMapName)) - ?? this.getActiveMap().baseTerrain - ?? null; - } - - /** - * Auto-route click: the first click picks the start, the next one routes - * there from the start (or from the end of the last route, so a path can - * be routed leg by leg). The route is an ordinary chain: edit it like any - * drawn path. - */ - private async onHexPathRouteClick(x: number, y: number): Promise { - if (!this.activePathTypeName) return; - const key = `${x}_${y}`; - if (this.activePathEnd === null) { - this.activePathEnd = key; - this.activePathChain = null; - this.flashHex(x, y); - this.updateModeBar(); - return; - } - if (key === this.activePathEnd) return; - const map = this.getActiveMap(); - const type = this.mapPathTypes().find((p) => p.name === this.activePathTypeName); - const avoid = (type ? pathAvoidsImpassable(type) : true) && !this.routeCrossImpassable; - const blockedNames = avoid ? impassableNames(this.plugin.getMapPalette(this.activeMapName)) : []; - const blockedSet = new Set(blockedNames); - const result = findRoute(this.activePathEnd, key, { - orientation: this.plugin.settings.hexOrientation, - stagger: this.getActiveStagger(), - bounds: { - minX: map.gridOffset.x, - minY: map.gridOffset.y, - maxX: map.gridOffset.x + map.gridSize.cols - 1, - maxY: map.gridOffset.y + map.gridSize.rows - 1, - }, - blocked: blockedSet.size - ? (hx, hy) => { - const t = this.terrainShownAt(hx, hy); - return t !== null && blockedSet.has(t); - } - : undefined, - // Rivers wind; roads keep to the straight line (round 7 U17). - meander: type ? pathMeanders(type) : false, - }); - if (!result.ok) { - new Notice(result.reason === "no-route" ? noRouteMessage(blockedNames) : "Both ends must be on the map."); - return; - } - const before = this.cloneChains(map.pathChains); - // Continues a path only when it starts on that path's end; otherwise a - // new path. Existing hexes are never changed (round 7 R11). - const target = addRoutedLeg( - map.pathChains, - this.activePathTypeName, - result.hexes, - this.activePathChain, - (typeName, hexes): PathChain => ({ typeName, hexes }), - ); - this.activePathEnd = key; - this.activePathChain = target; - this.pushPathUndo(map.name, before, this.cloneChains(map.pathChains)); - await this.plugin.saveSettings(); - this.updatePathOverlay(); - this.updateModeBar(); - } - - /** Deep-clone a pathChains array for undo/redo snapshot. */ - private cloneChains(chains: PathChain[]): PathChain[] { - // Keep unknown map-note columns (extra) through undo/redo snapshots. - return chains.map((c) => ({ ...c, hexes: [...c.hexes], ...(c.extra ? { extra: { ...c.extra } } : {}) })); + if (show) this.pathTool.renderBarControls(el); } - private pushPathUndo( - mapName: string, - before: PathChain[], - after: PathChain[], - ): void { + private pushPathUndo(mapName: string, before: MapPath[], after: MapPath[]): void { this.undoStack.push({ kind: "path", mapName, before, after }); if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); this.redoStack = []; this.updateUndoButton(); } - private async onHexPathDrawClick(x: number, y: number): Promise { - if (!this.activePathTypeName) return; - const key = `${x}_${y}`; - const region = this.getActiveMap(); - const chains = region.pathChains.filter( - (c) => c.typeName === this.activePathTypeName, - ); - const before = this.cloneChains(region.pathChains); - - let neighbourKeys: string[] = []; - if (this.activePathEnd !== null) { - const [ax, ay] = this.activePathEnd.split("_").map(Number); - neighbourKeys = hexNeighbors( - ax, - ay, - this.plugin.settings.hexOrientation, - this.getActiveStagger(), - ).map(([nx, ny]) => `${nx}_${ny}`); - } - const outcome = pathClickOutcome(this.activePathEnd, key, neighbourKeys); - // Clicking the end again would stack a second one-hex chain on it. - if (outcome === "same") return; - if (outcome === "restart") { - // Paths don't auto-route between distant hexes; say so instead of - // silently leaving a lone dot (fresh-eyes T7). - new Notice("Paths go hex by hex: click a hex next to the end of the path. Started a new path here. To join distant hexes, turn on auto-route in the tool bar."); - // A one-hex chain is never drawn (a line needs two hexes), so the - // abandoned start would linger invisibly in the map data: drop it. - const abandoned = this.activePathChain; - if (abandoned && abandoned.hexes.length === 1) { - const i = region.pathChains.indexOf(abandoned); - if (i !== -1) region.pathChains.splice(i, 1); - this.activePathChain = null; - } - } - - // ── If adjacent to active end, extend that chain ───────────────────── - if (this.activePathEnd !== null) { - if (outcome === "extend") { - let target: PathChain | undefined; - if ( - this.activePathChain !== null && - this.activePathChain.hexes[this.activePathChain.hexes.length - 1] === - this.activePathEnd - ) { - target = this.activePathChain; - } else { - target = chains.find( - (c) => c.hexes[c.hexes.length - 1] === this.activePathEnd, - ); - } - if (target) { - target.hexes.push(key); - this.activePathEnd = key; - this.activePathChain = target; - this.pushPathUndo( - region.name, - before, - this.cloneChains(region.pathChains), - ); - await this.plugin.saveSettings(); - this.updatePathOverlay(); - return; - } - } - } - - // ── Not adjacent (or no active chain) — start a new chain ──────────── - const newChain: PathChain = { - typeName: this.activePathTypeName, - hexes: [key], - }; - region.pathChains.push(newChain); - this.activePathEnd = key; - this.activePathChain = newChain; - this.pushPathUndo(region.name, before, this.cloneChains(region.pathChains)); - await this.plugin.saveSettings(); - this.updatePathOverlay(); - } - - /** First path chain (of `typeName`, or any type when null) through hex `key`. */ - private pathChainWithHex(key: string, typeName: string | null): PathChain | undefined { - return this.getActiveMap().pathChains.find( - (c) => (typeName === null || c.typeName === typeName) && c.hexes.includes(key), - ); - } - - /** Remove hex (x, y) from the first chain through it — only chains of - * `typeName` when given (right-click while drawing that type). */ - private async onHexPathDeleteClick(x: number, y: number, typeName: string | null = null): Promise { - const key = `${x}_${y}`; - const region = this.getActiveMap(); - const chains = region.pathChains; - const before = this.cloneChains(region.pathChains); - - for (let ci = 0; ci < chains.length; ci++) { - if (typeName !== null && chains[ci].typeName !== typeName) continue; - const pos = chains[ci].hexes.indexOf(key); - if (pos === -1) continue; - - const chain = chains[ci]; - const isActiveChain = chain === this.activePathChain; - - if (chain.hexes.length === 1) { - // Remove entire chain from region.pathChains - const idx = region.pathChains.indexOf(chain); - if (idx !== -1) region.pathChains.splice(idx, 1); - if (isActiveChain) this.activePathChain = null; - } else if (pos === 0) { - chain.hexes.splice(0, 1); - } else if (pos === chain.hexes.length - 1) { - chain.hexes.splice(pos, 1); - } else { - // Split: replace with two chains - const left: PathChain = { - typeName: chain.typeName, - hexes: chain.hexes.slice(0, pos), - }; - const right: PathChain = { - typeName: chain.typeName, - hexes: chain.hexes.slice(pos + 1), - }; - const idx = region.pathChains.indexOf(chain); - if (idx !== -1) region.pathChains.splice(idx, 1, left, right); - if (isActiveChain) this.activePathChain = null; - } - - if (this.activePathEnd === key) { - // Removing the end of the path being drawn steps it back one hex, - // so drawing carries on from there. - const stepBack = pos === chain.hexes.length && chain.hexes.length > 0; - this.activePathEnd = stepBack ? chain.hexes[chain.hexes.length - 1] : null; - this.activePathChain = stepBack ? chain : null; - } - - this.pushPathUndo( - region.name, - before, - this.cloneChains(region.pathChains), - ); - await this.plugin.saveSettings(); - this.updatePathOverlay(); - return; - } + /** + * A pointer position in the path layer's lattice units (for hit-testing + * paths): one read of the grid's box and font size per event, no writes, + * inverted through the layer's calibration. Null before it's calibrated. + */ + private pointerLattice(e: { clientX: number; clientY: number }): { cx: number; cy: number } | null { + const calib = this.pathCalib; + const grid = calib?.grid; + if (!calib || !grid || !grid.isConnected) return null; + const style = getComputedStyle(grid); + const em = parseFloat(style.fontSize) || 16; + const g = grid.getBoundingClientRect(); + const layoutW = parseFloat(style.width) || grid.offsetWidth; + const layoutH = parseFloat(style.height) || grid.offsetHeight; + const sx = layoutW ? g.width / layoutW : 1; + const sy = layoutH ? g.height / layoutH : 1; + const ex = (e.clientX - g.left) / sx / em; + const ey = (e.clientY - g.top) / sy / em; + const a = calib.affine; + return { cx: (ex - a.tx) / a.sx, cy: (ey - a.ty) / a.sy }; } /** @@ -5802,27 +5619,43 @@ export class HexMapView extends ItemView { dash: s.dash.map((d) => fmt(d * scale)).join(" "), }; }); - // Small circle to mark the active endpoint (only in path mode) + // The path tool: the selected path highlighted, its anchor handles + // (ends bigger: continue from there) and the dot where clicks add. + const tool = calib && this.drawingMode === "path" ? this.pathTool.overlay() : null; let dot: { cx: string; cy: string; r: string; sw: string; color: string } | null = null; - if (calib && this.drawingMode === "path" && this.activePathEnd) { - const activeType = this.activePathTypeName ? this.mapPathTypes().find((p) => p.name === this.activePathTypeName) : undefined; - const [c] = em([latticeCenter(this.activePathEnd, calib.lattice)]); - dot = { - cx: fmt(c.cx), - cy: fmt(c.cy), - r: fmt(pxToLattice(END_DOT_PX.r) * scale), - sw: fmt(pxToLattice(END_DOT_PX.stroke) * scale), - color: activeType?.color ?? "#888888", - }; + const handles: { cx: string; cy: string; r: string; sw: string; hover: boolean }[] = []; + if (calib && tool) { + const activeType = this.mapPathTypes().find((p) => p.name === this.pathTool.currentType()); + if (tool.active) { + const [c] = em([latticeCenter(tool.active, calib.lattice)]); + dot = { + cx: fmt(c.cx), + cy: fmt(c.cy), + r: fmt(pxToLattice(END_DOT_PX.r) * scale), + sw: fmt(pxToLattice(END_DOT_PX.stroke) * scale), + color: activeType?.color ?? "#888888", + }; + } + for (const h of tool.handles) { + const [c] = em([latticeCenter(h.hex, calib.lattice)]); + handles.push({ + cx: fmt(c.cx), + cy: fmt(c.cy), + r: fmt(pxToLattice(h.end ? HANDLE_PX.end : HANDLE_PX.r) * scale), + sw: fmt(pxToLattice(HANDLE_PX.stroke) * scale), + hover: h.hover, + }); + } } - const key = JSON.stringify([lines.map((l) => [l.s.path, l.s.branch, l.d, l.width, l.dash, l.s.color]), dot]); + const selected = tool?.selected ?? null; + const key = JSON.stringify([lines.map((l) => [l.s.path, l.s.branch, l.d, l.width, l.dash, l.s.color]), dot, handles, selected]); const existing = gridContainer.querySelector("svg.duckmage-path-svg"); // ── Writes ── if (!existing || key !== this.pathLayerKey) { existing?.remove(); this.pathLayerKey = key; - if (lines.length || dot) { + if (lines.length || dot || handles.length) { const svgNS = "http://www.w3.org/2000/svg"; const svg = activeDocument.createElementNS(svgNS, "svg"); svg.classList.add("duckmage-path-svg"); @@ -5830,6 +5663,20 @@ export class HexMapView extends ItemView { svg.setAttribute("width", "1em"); svg.setAttribute("height", "1em"); svg.setAttribute("viewBox", "0 0 1 1"); + // The selected path's halo, under every line. + for (const l of lines) { + if (l.s.path !== selected) continue; + const halo = activeDocument.createElementNS(svgNS, "path"); + halo.setAttribute("class", "duckmage-svg-path-line duckmage-svg-path-selected"); + halo.setAttribute("d", l.d); + halo.setAttribute("stroke", l.s.color); + halo.setAttribute("stroke-width", fmt(Number(l.width) * 2.6)); + halo.setAttribute("stroke-linecap", "round"); + halo.setAttribute("stroke-linejoin", "round"); + halo.setAttribute("fill", "none"); + halo.setAttribute("opacity", "0.3"); + svg.appendChild(halo); + } for (const l of lines) { const path = activeDocument.createElementNS(svgNS, "path"); path.setAttribute("class", "duckmage-svg-path-line"); @@ -5844,6 +5691,17 @@ export class HexMapView extends ItemView { path.setAttribute("data-branch", String(l.s.branch)); svg.appendChild(path); } + for (const h of handles) { + const handle = activeDocument.createElementNS(svgNS, "circle"); + handle.setAttribute("class", "duckmage-svg-path-line duckmage-svg-path-handle"); + handle.setAttribute("cx", h.cx); + handle.setAttribute("cy", h.cy); + handle.setAttribute("r", h.r); + handle.setAttribute("fill", h.hover ? "#ffd84d" : "white"); + handle.setAttribute("stroke", "#222222"); + handle.setAttribute("stroke-width", h.sw); + svg.appendChild(handle); + } if (dot) { const circle = activeDocument.createElementNS(svgNS, "circle"); circle.setAttribute("class", "duckmage-svg-path-line"); diff --git a/src/hex-map/PathNameModal.ts b/src/hex-map/PathNameModal.ts new file mode 100644 index 00000000..d805a76e --- /dev/null +++ b/src/hex-map/PathNameModal.ts @@ -0,0 +1,63 @@ +import { App } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; + +/** + * Rename a path: one text field. `check` returns a problem to show (e.g. + * the name is taken) or null; Save is refused while there is one. + */ +export class PathNameModal extends HexmakerModal { + constructor( + app: App, + private current: string, + private check: (name: string) => string | null, + private onSave: (name: string) => void, + ) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + const { contentEl } = this; + contentEl.empty(); + contentEl.addClass("duckmage-path-name-modal"); + contentEl.createEl("h2", { text: "Rename path" }); + contentEl.createEl("p", { + cls: "setting-item-description", + text: "The map note lists the path under this name in both of its path tables; both are updated.", + }); + const input = contentEl.createEl("input", { type: "text", value: this.current, cls: "duckmage-path-name-input" }); + const problem = contentEl.createDiv({ cls: "duckmage-path-name-problem mod-warning" }); + const row = contentEl.createDiv({ cls: "modal-button-container" }); + const save = row.createEl("button", { text: "Save", cls: "mod-cta" }); + const cancel = row.createEl("button", { text: "Cancel" }); + const validate = (): string | null => { + const name = input.value.trim().replace(/\s+/g, " "); + const msg = !name ? "A path needs a name." : name === this.current ? null : this.check(name); + problem.setText(msg ?? ""); + save.disabled = !!msg; + return msg ? null : name; + }; + const submit = () => { + const name = validate(); + if (name === null) return; + this.close(); + if (name !== this.current) this.onSave(name); + }; + input.addEventListener("input", () => validate()); + input.addEventListener("keydown", (e) => { + if (e.key === "Enter") { + e.preventDefault(); + submit(); + } + }); + save.addEventListener("click", submit); + cancel.addEventListener("click", () => this.close()); + validate(); + input.focus(); + input.select(); + } + + onClose(): void { + this.contentEl.empty(); + } +} diff --git a/src/hex-map/PathPickerModal.ts b/src/hex-map/PathPickerModal.ts index 339d4d8a..1ddf5c91 100644 --- a/src/hex-map/PathPickerModal.ts +++ b/src/hex-map/PathPickerModal.ts @@ -61,6 +61,13 @@ export function buildPathPreviewSvg(pt: PathType): SVGElement { return svg; } +/** The open map's paths, listed in the picker. */ +export interface PathsOnMap { + list: { name: string; typeName: string; summary: string }[]; + selected: string | null; + onPick: (name: string) => void; +} + // ── Modal ───────────────────────────────────────────────────────────────────── export class PathPickerModal extends HexmakerModal { @@ -79,6 +86,8 @@ export class PathPickerModal extends HexmakerModal { private onErase?: () => void, /** Hex-by-hex vs auto-route switch, shown above the types. */ private autoRoute?: { value: boolean; onChange: (on: boolean) => void; noImpassable: boolean }, + /** "Paths on this map": click one to select it (for paths too small to hit on the map). */ + private pathsOnMap?: PathsOnMap, ) { super(app); } @@ -105,10 +114,11 @@ export class PathPickerModal extends HexmakerModal { }); } hint.setText( - ar.value - ? "Click a start hex, then an end hex: the path finds its own way and stays editable." + + (ar.value + ? "Click a start, then click far away: the path finds its own way there. Keep clicking to add more." + (ar.noImpassable ? " This palette has no impassable terrain yet: mark the terrains paths can't cross (e.g. water) in the palette editor." : "") - : "Click neighbouring hexes one by one.", + : "Click neighbouring hexes one by one (a click further away is routed for you).") + + " Click a path to select it, then drag its line to reshape it.", ); hint.createSpan({ text: " You can switch this while drawing, from the bar at the top." }); }; @@ -204,6 +214,33 @@ export class PathPickerModal extends HexmakerModal { if (pathTypes.length === 0) { grid.createEl("p", { text: "No path types defined. Switch to edit mode to add one.", cls: "duckmage-tpe-empty" }); } + this.renderPathsOnMap(section, pathTypes); + } + + /** "Paths on this map": each path (type colour, name, what it is); click to select it on the map. */ + private renderPathsOnMap(container: HTMLElement, types: PathType[]): void { + const pm = this.pathsOnMap; + if (!pm) return; + container.createDiv({ cls: "duckmage-path-draw-mode-label duckmage-path-type-step", text: "Paths on this map" }); + if (!pm.list.length) { + container.createDiv({ cls: "setting-item-description", text: "None yet: pick a type above and click on the map to start one." }); + return; + } + const list = container.createDiv({ cls: "duckmage-path-list" }); + for (const p of pm.list) { + const row = list.createEl("button", { cls: "duckmage-path-list-row", attr: { title: `Select ${p.name} on the map` } }); + row.toggleClass("is-selected", p.name === pm.selected); + const swatch = row.createSpan({ cls: "duckmage-path-list-swatch" }); + const color = types.find((t) => t.name === p.typeName)?.color; + if (color) swatch.setCssProps({ "--duckmage-path-swatch": color }); + row.createSpan({ cls: "duckmage-path-list-name", text: p.name }); + row.createSpan({ cls: "duckmage-path-list-summary", text: p.summary }); + row.addEventListener("click", () => { + this.selectionMade = true; + pm.onPick(p.name); + this.close(); + }); + } } private renderEditMode(): void { diff --git a/src/hex-map/autoRoute.ts b/src/hex-map/autoRoute.ts index cd6ca747..53f6376c 100644 --- a/src/hex-map/autoRoute.ts +++ b/src/hex-map/autoRoute.ts @@ -1,9 +1,8 @@ /** * Auto-route for the path tool. The router itself (A*, the winding route, * hex distance) lives in src/paths/router.ts (ROUTER v1, frozen by golden - * tests) and is re-exported here; this file keeps the tool's chain helpers. - * Pure — no Obsidian imports — so it's unit-tested directly - * (tests/autoRoute.test.ts). + * tests) and is re-exported here. The path tool itself (what a click does, + * dragging, forks) is src/hex-map/pathTool.ts. * * Hex keys are "x_y" offset coordinates, the same as path chains use. */ @@ -17,48 +16,3 @@ export { type RouteOptions, type RouteResult, } from "../paths/router"; - -/** The bits of a path chain auto-route needs. */ -export interface RouteChain { - typeName: string; - hexes: string[]; -} - -/** - * The chain an auto-route starting at `start` continues: one of the same - * type whose LAST hex is `start` (the active chain first). Anything else, - * including a start on a chain's first hex or in its middle, starts a new - * path (round 7 R11: a second road from the keep must not join the first). - */ -export function routeExtendTarget( - chains: readonly T[], - typeName: string, - start: string, - active: T | null, -): T | null { - const endsAtStart = (c: T) => c.typeName === typeName && c.hexes[c.hexes.length - 1] === start; - if (active && endsAtStart(active)) return active; - return chains.find(endsAtStart) ?? null; -} - -/** - * Add a routed leg to `chains`: appended to the chain it continues (only new - * hexes are added; existing ones are never changed), else as a new chain. - * Returns the chain the leg is now part of. - */ -export function addRoutedLeg( - chains: T[], - typeName: string, - route: readonly string[], - active: T | null, - make: (typeName: string, hexes: string[]) => T, -): T { - const target = routeExtendTarget(chains, typeName, route[0], active); - if (target) { - target.hexes.push(...route.slice(1)); - return target; - } - const chain = make(typeName, [...route]); - chains.push(chain); - return chain; -} diff --git a/src/hex-map/help.md b/src/hex-map/help.md index ee84ce0f..ad1597f7 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -59,10 +59,18 @@ The **+** buttons at the edges of the map grow the grid one column or row in tha ## Drawing tools -### Road / River -Paint a connected chain of road or river hexes. Left-click hexes to extend the chain; right-click a hex already in the chain to remove it. Each chain is drawn as a colored line connecting adjacent hexes. - -**Auto-route** (in the path picker, or the bar at the top while drawing): click a start hex, then an end hex, and the path finds its own way around impassable terrain, keeping close to the straight line. In the picker, choose how to draw first, then the path type; you can switch either way later from the bar. Mark terrains impassable in the palette editor (every water-type terrain, in any palette, is impassable by default). Each path type chooses whether it avoids them (roads do, rivers don't); tick **Cross impassable** in the bar to go through once. Rivers wind gently; roads keep straight. Starting on the end of a path of the same type continues it; starting anywhere else makes a new path. +### Paths +Pick a path type in the path picker (choose **Hex by hex** or **Auto-route** first; switch either way later from the bar at the top). Every path has a name and shows up under **Paths on this map** in the picker; click one there to select it. + +- **Draw:** click a hex to start, then keep clicking. Each click adds a point and the path finds its way there from the end, around impassable terrain, so you can click far away. In hex-by-hex mode, click neighbouring hexes; a click further away is routed too, and the bar says so. Click the end again, press **Esc** or **Done** to finish. +- **Select:** click a path. Its points show as handles; the bigger ones are its ends. +- **Continue or fork:** with a path selected, click an end to carry on from it, or click anywhere else on it to start a fork there. A path and its forks are one path in the map note. +- **Reshape:** drag any part of the selected path. Grabbing a point moves it; grabbing the line adds a point there. The new route shows as you drag; let go to keep it, or drop it back where it was to cancel. +- **New path:** **Alt-click**, or **New path** in the bar, starts a new path even on top of another one (a crossroads of two roads). +- **Delete:** right-click a handle, or hover one and press **Backspace**. Backspace while drawing removes the last point. Right-click a path for **Split here**, **Delete this fork**, **Delete path**, **Rename…**, **Change type…** and **Reverse**. In erase mode (the picker's ✕), click a path to split it there. +- **Esc** steps out one level: finish the branch, then deselect, then leave the tool. **Ctrl/Cmd+Z** undoes each change. + +Mark terrains impassable in the palette editor (every water-type terrain is impassable by default). Each path type chooses whether it goes around them (roads do, rivers don't) and whether it winds. Tick **Cross impassable** in the bar to let the next legs go through. If painting terrain, changing the palette, resizing the map or changing a type's routing would move an existing path, it keeps its route (points are added to hold it) and a notice offers **Reroute instead**; undoing the paint stroke undoes that too. ### Terrain Opens the terrain palette. Select a color/icon to enter paint mode, then left-click hexes to apply that terrain. Use **Pick** (⌖) to sample terrain from an existing hex. Use **Clear** to erase terrain from hexes. Right-click the terrain button to open the palette editor where you can reorder, rename, recolor, and add terrain types. diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts new file mode 100644 index 00000000..0ee002d4 --- /dev/null +++ b/src/hex-map/pathTool.ts @@ -0,0 +1,1006 @@ +/** + * The path tool (plan-path-anchors section 4): draw, select, continue, + * fork, reshape by dragging, delete anchors, split, erase. A controller + * the map view owns; it edits the map's anchored paths (MapData.paths) + * with the pure ops in src/paths/edit.ts and saves through the map store + * (mapStore.setPaths). Every edit goes through `commit`, which asks the + * path edit gate (src/paths/editGate.ts) first. + * + * Hit-testing is pure math in lattice units: the pointer is turned into + * lattice coordinates by the view (one read of the grid's box per event, + * never per hex) and compared with the same polylines the map draws. + * + * The top part of this file is pure (tests/pathTool.test.ts). + */ + +import { Notice } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { HexKey, MapPath } from "../types"; +import { latticeCenter, type LatticeGrid, type PathStroke, type Pt } from "../paths/pathGeometry"; +import type { ResolvedBranch } from "../paths/resolve"; +import type { RouteCache } from "../paths/routeCache"; +import { + appendAnchor, + clonePath, + clonePaths, + deleteAnchor, + deleteBranch, + forkAt, + insertAnchorAt, + moveAnchor, + newPath, + pathNameKey, + reverseBranch, + splitBranchAt, +} from "../paths/edit"; +import { anchorsFor, routeFnFor } from "../paths/fromHexes"; +import { canEditPaths, type PathEditAction } from "../paths/editGate"; +import { impassableNames, noRouteMessage } from "../impassable"; +import { hexNeighbors } from "./hexGeometry"; +import { PathPickerModal } from "./PathPickerModal"; +import { PathNameModal } from "./PathNameModal"; + +// ── Pure: hit-testing ──────────────────────────────────────────────────────── + +/** Anchor handle radius, lattice units (a hex's centre-to-corner is 1). */ +export const HANDLE_R = 0.24; +/** End handles ("+": continue from here) are drawn a little bigger. */ +export const END_HANDLE_R = 0.32; +/** Slack added to half the stroke width when hitting a line (lattice units). */ +export const LINE_SLACK = 0.25; + +export function distToSegment(p: Pt, a: Pt, b: Pt): number { + const dx = b.cx - a.cx; + const dy = b.cy - a.cy; + const len2 = dx * dx + dy * dy; + const t = len2 ? Math.max(0, Math.min(1, ((p.cx - a.cx) * dx + (p.cy - a.cy) * dy) / len2)) : 0; + return Math.hypot(p.cx - (a.cx + t * dx), p.cy - (a.cy + t * dy)); +} + +export function distToPolyline(p: Pt, pts: readonly Pt[]): number { + if (!pts.length) return Infinity; + if (pts.length === 1) return Math.hypot(p.cx - pts[0].cx, p.cy - pts[0].cy); + let best = Infinity; + for (let i = 1; i < pts.length; i++) best = Math.min(best, distToSegment(p, pts[i - 1], pts[i])); + return best; +} + +/** Index of the hex of `hexes` whose centre is nearest `p` (ties: the lower index). */ +export function nearestHexIdx(p: Pt, hexes: readonly HexKey[], grid: LatticeGrid): number { + let best = -1; + let bestD = Infinity; + hexes.forEach((h, i) => { + const c = latticeCenter(h, grid); + const d = Math.hypot(p.cx - c.cx, p.cy - c.cy); + if (d < bestD - 1e-9) { + bestD = d; + best = i; + } + }); + return best; +} + +/** Which end of its branch an anchor is: head (first, not a fork's start), tail (last), or neither. */ +export function anchorEnd(rb: Pick, anchor: number): "head" | "tail" | null { + const n = rb.anchorIdx.length; + if (n > 1 && anchor === n - 1) return "tail"; + if (anchor === 0 && !rb.forkFrom) return n > 1 ? "head" : "tail"; + return null; +} + +export interface PathHit { + path: string; + branch: number; + /** The branch's routed hex nearest the pointer. */ + hexIdx: number; + /** The anchor whose handle is under the pointer (selected path only), else null. */ + anchor: number | null; + /** When `anchor` is a branch end. */ + end: "head" | "tail" | null; +} + +/** + * What's under lattice point `p`: an anchor handle of the selected path + * first (the nearest within its radius), else the nearest path line within + * half its stroke plus LINE_SLACK (the selected path wins where lines + * overlap). Null when nothing is. + */ +export function hitTestPaths( + p: Pt, + strokes: readonly PathStroke[], + resolved: readonly ResolvedBranch[], + grid: LatticeGrid, + selected: string | null, +): PathHit | null { + if (selected !== null) { + let best: PathHit | null = null; + let bestD = Infinity; + for (const rb of resolved) { + if (rb.path !== selected) continue; + rb.anchorIdx.forEach((hexIdx, a) => { + const end = anchorEnd(rb, a); + const c = latticeCenter(rb.hexes[hexIdx], grid); + const d = Math.hypot(p.cx - c.cx, p.cy - c.cy); + if (d <= (end ? END_HANDLE_R : HANDLE_R) && d < bestD - 1e-9) { + bestD = d; + best = { path: rb.path, branch: rb.branch, hexIdx, anchor: a, end }; + } + }); + } + if (best) return best; + } + let pick: PathStroke | null = null; + let pickD = Infinity; + let pickSel = false; + for (const s of strokes) { + const d = distToPolyline(p, s.pts); + if (d > s.width / 2 + LINE_SLACK) continue; + const sel = s.path === selected; + if ((sel && !pickSel) || (sel === pickSel && d < pickD - 1e-9)) { + pick = s; + pickD = d; + pickSel = sel; + } + } + if (!pick) return null; + const rb = resolved.find((r) => r.path === pick.path && r.branch === pick.branch); + if (!rb) return null; + return { path: rb.path, branch: rb.branch, hexIdx: nearestHexIdx(p, rb.hexes, grid), anchor: null, end: null }; +} + +// ── Pure: what a click does ────────────────────────────────────────────────── + +export type PathClick = + | { kind: "none" } + /** Start a new path here (it's created by the next click). */ + | { kind: "start" } + /** Add an anchor at the clicked hex, from the active end. */ + | { kind: "append" } + /** The active end clicked again: finish the branch (the path stays selected). */ + | { kind: "finish" } + | { kind: "select"; path: string } + | { kind: "deselect" } + /** Continue the selected path from this end. */ + | { kind: "continue"; path: string; branch: number; end: "head" | "tail" } + /** Start a fork of the selected path at this hex of it. */ + | { kind: "fork"; path: string; branch: number; hexIdx: number } + /** Erase mode: split the branch at this hex. */ + | { kind: "split"; path: string; branch: number; hexIdx: number }; + +export interface PathClickState { + erasing: boolean; + /** Alt held, or "New path" pressed: start a new path whatever is under the pointer. */ + forceNew: boolean; + /** The hex clicks add to (an active end, or a path/fork just started), if any. */ + activeHex: HexKey | null; + selected: string | null; +} + +/** + * The click table (replaces the old hex-by-hex pathClickOutcome): + * erase splits; Alt / New path starts a new path; while drawing, every + * click adds an anchor (the active end again finishes); on the selected + * path an end continues it and anywhere else forks; another path is + * selected; empty map deselects, or starts a path when nothing is selected. + */ +export function pathClickOutcome(s: PathClickState, key: HexKey, hit: PathHit | null): PathClick { + if (s.erasing) return hit ? { kind: "split", path: hit.path, branch: hit.branch, hexIdx: hit.hexIdx } : { kind: "none" }; + if (s.forceNew) return { kind: "start" }; + if (s.activeHex !== null) return key === s.activeHex ? { kind: "finish" } : { kind: "append" }; + if (hit && hit.path === s.selected) { + if (hit.end) return { kind: "continue", path: hit.path, branch: hit.branch, end: hit.end }; + return { kind: "fork", path: hit.path, branch: hit.branch, hexIdx: hit.hexIdx }; + } + if (hit) return { kind: "select", path: hit.path }; + return s.selected !== null ? { kind: "deselect" } : { kind: "start" }; +} + +/** "Road, 2 forks" for the mode bar. */ +export function pathSummary(p: MapPath): string { + const forks = p.branches.length - 1; + return forks ? `${p.typeName}, ${forks} fork${forks === 1 ? "" : "s"}` : p.typeName; +} + +// ── The controller ─────────────────────────────────────────────────────────── + +/** What the tool needs from the map view. */ +export interface PathToolHost { + plugin: HexmakerPlugin; + mapName(): string; + /** The pointer in lattice units, from one read of the grid's box (null before the path layer is calibrated). */ + pointerLattice(e: { clientX: number; clientY: number }): Pt | null; + /** The hex under a screen point. */ + hexAtPoint(clientX: number, clientY: number): HexKey | null; + /** The document listeners for a drag go on (the view's own window). */ + ownerDocument(): Document; + /** Record one undo step. */ + pushUndo(mapName: string, before: MapPath[], after: MapPath[]): void; + /** Redraw the path layer (and its handles). */ + redraw(): void; + /** Refresh the mode bar. */ + refreshBar(): void; + /** Show (or clear) the "grab" cursor over the selected path. */ + setGrabCursor(on: boolean): void; +} + +/** A path or fork started by one click: it's created when the second anchor comes. */ +type Pending = { kind: "new"; hex: HexKey } | { kind: "fork"; path: string; hex: HexKey }; + +interface Drag { + path: string; + branch: number; + hit: PathHit; + route: Pick; + before: MapPath[]; + startHex: HexKey; + lastHex: HexKey; + startX: number; + startY: number; + started: boolean; + preview: MapPath[] | null; + frame: number | null; + cleanup: () => void; +} + +/** Decorations the path layer draws for the tool. */ +export interface PathToolOverlay { + /** The selected path (drawn highlighted). */ + selected: string | null; + /** Anchor handles of the selected path. */ + handles: { hex: HexKey; end: boolean; hover: boolean }[]; + /** The hex clicks add to. */ + active: HexKey | null; +} + +export class PathTool { + /** The type for new paths. */ + typeName: string | null = null; + autoRoute = false; + /** Let the next routes go through impassable terrain (pinned with anchors, so it's kept). */ + crossImpassable = false; + selected: string | null = null; + /** Where clicks add anchors on the selected path. */ + active: { branch: number; end: "head" | "tail" } | null = null; + private pending: Pending | null = null; + /** "New path" was pressed: the next click starts one whatever is under it. */ + private forceNew = false; + /** A short note for the mode bar about the last click. */ + hint: string | null = null; + private hover: { branch: number; anchor: number } | null = null; + private drag: Drag | null = null; + private suppressClick = false; + private strokeMemo: { resolved: readonly ResolvedBranch[]; strokes: PathStroke[] } | null = null; + + constructor(private host: PathToolHost) {} + + private get plugin(): HexmakerPlugin { + return this.host.plugin; + } + + private get map(): string { + return this.host.mapName(); + } + + // ── reads ── + + /** The map's stored paths. */ + paths(): readonly MapPath[] { + return this.plugin.mapStore.paths(this.map); + } + + private pathNamed(name: string | null): MapPath | undefined { + return name === null ? undefined : this.paths().find((p) => p.name === name); + } + + private resolved(): ResolvedBranch[] { + return this.plugin.paths.resolved(this.map); + } + + private branchRoute(path: string, branch: number): ResolvedBranch | undefined { + return this.resolved().find((r) => r.path === path && r.branch === branch); + } + + private grid(): LatticeGrid | null { + return this.plugin.paths.lattice(this.map); + } + + private strokes(): PathStroke[] { + const resolved = this.resolved(); + if (this.strokeMemo?.resolved !== resolved) this.strokeMemo = { resolved, strokes: this.plugin.paths.strokes(this.map) }; + return this.strokeMemo.strokes; + } + + private hitAt(e: { clientX: number; clientY: number }): PathHit | null { + const p = this.host.pointerLattice(e); + const grid = this.grid(); + if (!p || !grid) return null; + return hitTestPaths(p, this.strokes(), this.resolved(), grid, this.selected); + } + + /** The hex clicks add to, if any. */ + activeHex(): HexKey | null { + if (this.pending) return this.pending.hex; + const p = this.pathNamed(this.selected); + if (!p || !this.active) return null; + const a = p.branches[this.active.branch]?.anchors; + if (!a?.length) return null; + return this.active.end === "head" ? a[0] : a[a.length - 1]; + } + + /** Is a branch being drawn (an active end or a fresh start)? */ + isDrawing(): boolean { + return this.activeHex() !== null; + } + + /** The type of what's being drawn or edited: the selected path's, else the one picked for new paths. */ + currentType(): string | null { + if (this.pending?.kind === "fork") return this.pathNamed(this.pending.path)?.typeName ?? this.typeName; + if (this.pending?.kind === "new") return this.typeName; + return this.pathNamed(this.selected)?.typeName ?? this.typeName; + } + + /** For the mode bar label. */ + labelState(): { selected: string | null; summary: string | null; drawing: boolean; note: string | null; forceNew: boolean } { + const p = this.pathNamed(this.selected); + return { + selected: p?.name ?? null, + summary: p ? pathSummary(p) : null, + drawing: this.isDrawing(), + note: this.hint, + forceNew: this.forceNew, + }; + } + + overlay(): PathToolOverlay { + const handles: PathToolOverlay["handles"] = []; + if (this.selected !== null) { + for (const rb of this.resolved()) { + if (rb.path !== this.selected) continue; + rb.anchorIdx.forEach((hexIdx, a) => { + handles.push({ + hex: rb.hexes[hexIdx], + end: anchorEnd(rb, a) !== null, + hover: this.hover?.branch === rb.branch && this.hover.anchor === a, + }); + }); + } + } + return { selected: this.selected, handles, active: this.activeHex() }; + } + + // ── the one place paths are written ── + + /** + * THE choke point for the tool's path edits: asks the gate + * (canEditPaths), saves through the map store, records one undo step. + */ + private commit(next: MapPath[], action: PathEditAction = "draw"): boolean { + const map = this.map; + if (!canEditPaths(map, action)) { + new Notice("Paths can't be changed on this map right now."); + return false; + } + const before = clonePaths(this.paths()); + if (JSON.stringify(before) === JSON.stringify(next)) return false; + // Settle any pending routing change against the paths as they were, so + // the new ones are never pinned to an out-of-date route. + this.plugin.pathPins.sync(map); + this.plugin.mapStore.setPaths(map, next); + void this.plugin.saveSettings(); + if (action !== "history") this.host.pushUndo(map, before, clonePaths(next)); + this.strokeMemo = null; + this.host.redraw(); + this.host.refreshBar(); + return true; + } + + /** Undo / redo of a path step: restore a snapshot (through the gate). */ + applySnapshot(mapName: string, paths: MapPath[]): void { + if (!canEditPaths(mapName, "history")) { + new Notice("Paths can't be changed on this map right now."); + return; + } + this.plugin.pathPins.sync(mapName); + this.plugin.mapStore.setPaths(mapName, clonePaths(paths)); + void this.plugin.saveSettings(); + this.pending = null; + this.active = null; + this.hover = null; + if (mapName === this.map && !this.pathNamed(this.selected)) this.selected = null; + this.strokeMemo = null; + this.host.redraw(); + this.host.refreshBar(); + } + + private replacePath(name: string, next: MapPath | null): MapPath[] { + const out: MapPath[] = []; + for (const p of this.paths()) { + if (p.name !== name) out.push(clonePath(p)); + else if (next) out.push(next); + } + return out; + } + + private ready(): boolean { + if (this.plugin.paths.isReady(this.map)) return true; + new Notice("This map's paths are still loading."); + return false; + } + + // ── tool state ── + + /** Leave the tool (or switch map): forget everything but the picked type and switches. */ + reset(): void { + this.cancelDrag(); + this.selected = null; + this.active = null; + this.pending = null; + this.forceNew = false; + this.hint = null; + this.hover = null; + this.host.setGrabCursor(false); + } + + /** Pick the type for new paths. A new type ends the branch being drawn. */ + setType(typeName: string): void { + if (typeName !== this.typeName) { + this.pending = null; + this.active = null; + } + this.typeName = typeName; + } + + setAutoRoute(on: boolean): void { + this.autoRoute = on; + this.hint = null; + this.host.refreshBar(); + } + + /** Select a path by name (the picker's "Paths on this map"). */ + selectPath(name: string): void { + const p = this.pathNamed(name); + if (!p) return; + this.selected = p.name; + this.active = null; + this.pending = null; + this.forceNew = false; + this.hint = null; + this.host.redraw(); + this.host.refreshBar(); + } + + /** "New path" (mode bar): the next click starts a new path, even on top of another. */ + startNewPath(): void { + this.selected = null; + this.active = null; + this.pending = null; + this.forceNew = true; + this.hint = null; + this.host.redraw(); + this.host.refreshBar(); + } + + /** Finish the branch being drawn; with nothing being drawn, deselect. ("Done" in the mode bar.) */ + done(): void { + if (this.isDrawing() || this.forceNew) { + this.pending = null; + this.active = null; + this.forceNew = false; + } else { + this.selected = null; + } + this.hint = null; + this.host.redraw(); + this.host.refreshBar(); + } + + /** Esc: cancel a drag, else finish the branch, else deselect. False when there was nothing to step out of. */ + escape(): boolean { + if (this.drag) { + this.cancelDrag(); + return true; + } + if (this.isDrawing() || this.forceNew || this.selected !== null) { + this.done(); + return true; + } + return false; + } + + // ── clicks ── + + /** A left-click on hex (x, y). */ + click(x: number, y: number, e: { clientX: number; clientY: number; altKey?: boolean } | undefined, erasing: boolean): void { + if (this.suppressClick) { + this.suppressClick = false; + return; + } + if (!this.ready()) return; + const key = `${x}_${y}`; + const forceNew = this.forceNew || !!e?.altKey; + const activeHex = this.activeHex(); + const hit = e && (erasing || (!forceNew && activeHex === null)) ? this.hitAt(e) : null; + const outcome = pathClickOutcome({ erasing, forceNew, activeHex, selected: this.selected }, key, hit); + this.hint = null; + switch (outcome.kind) { + case "none": + break; + case "start": + if (!this.typeName) { + new Notice("Pick a path type first: click the path button."); + return; + } + this.forceNew = false; + this.selected = null; + this.active = null; + this.pending = { kind: "new", hex: key }; + break; + case "append": + this.append(key); + break; + case "finish": + this.pending = null; + this.active = null; + break; + case "select": + this.selected = outcome.path; + this.active = null; + break; + case "deselect": + this.selected = null; + break; + case "continue": + this.selected = outcome.path; + this.active = { branch: outcome.branch, end: outcome.end }; + break; + case "fork": { + const rb = this.branchRoute(outcome.path, outcome.branch); + if (rb) this.pending = { kind: "fork", path: outcome.path, hex: rb.hexes[outcome.hexIdx] }; + break; + } + case "split": + this.split(outcome.path, outcome.branch, outcome.hexIdx); + break; + } + this.host.redraw(); + this.host.refreshBar(); + } + + /** + * The anchors that take a branch from `from` to `to` (excluding `from`): + * just [to] normally. With Cross impassable on, a route through + * impassable terrain is pinned with whatever anchors make the normal + * router reproduce it. Null (with a notice) when there's no route. + */ + private legAnchors(from: HexKey, to: HexKey, typeName: string): HexKey[] | null { + const router: RouteCache | null = this.plugin.paths.router(this.map); + if (!router) return null; + const style = this.plugin.paths.styleOf(this.map, typeName); + const seg = router.route(from, to, style); + if (this.crossImpassable && style.avoid) { + const through = router.route(from, to, { ...style, avoid: false }); + if (through.fallback) { + new Notice("Both ends must be on the map."); + return null; + } + const same = !seg.fallback && seg.hexes.length === through.hexes.length && seg.hexes.every((k, i) => k === through.hexes[i]); + if (same) return [to]; + return anchorsFor(through.hexes, routeFnFor(router, style), router.context ?? undefined).slice(1); + } + if (seg.fallback === "out-of-bounds") { + new Notice("Both ends must be on the map."); + return null; + } + if (seg.fallback === "no-route") { + new Notice(noRouteMessage(style.avoid ? impassableNames(this.plugin.getMapPalette(this.map)) : [])); + return null; + } + return [to]; + } + + /** Hex-by-hex mode: say when a click wasn't next to the end (the router filled the gap). */ + private noteGap(from: HexKey, to: HexKey): void { + if (this.autoRoute) return; + const [x, y] = from.split("_").map(Number); + const grid = this.grid(); + if (!grid) return; + const near = hexNeighbors(x, y, grid.orientation, grid.stagger).some(([nx, ny]) => `${nx}_${ny}` === to); + if (!near) this.hint = "not next to the end, so the gap was routed"; + } + + /** Add an anchor at `key` from the active end (creating a started path or fork). */ + private append(key: HexKey): void { + const pending = this.pending; + if (pending?.kind === "new") { + const type = this.typeName; + if (!type) return; + const leg = this.legAnchors(pending.hex, key, type); + if (!leg) return; + const p = newPath(type, pending.hex, this.paths().map((q) => q.name)); + p.branches[0].anchors.push(...leg); + this.noteGap(pending.hex, key); + if (this.commit([...clonePaths(this.paths()), p])) { + this.pending = null; + this.selected = p.name; + this.active = { branch: 0, end: "tail" }; + } + return; + } + if (pending?.kind === "fork") { + const base = this.pathNamed(pending.path); + if (!base) { + this.pending = null; + return; + } + const leg = this.legAnchors(pending.hex, key, base.typeName); + if (!leg) return; + const { path, branch } = forkAt(base, pending.hex); + path.branches[branch].anchors.push(...leg); + this.noteGap(pending.hex, key); + if (this.commit(this.replacePath(base.name, path))) { + this.pending = null; + this.selected = path.name; + this.active = { branch, end: "tail" }; + } + return; + } + const p = this.pathNamed(this.selected); + const act = this.active; + if (!p || !act) return; + const anchors = p.branches[act.branch].anchors; + if (act.end === "tail") { + const from = anchors[anchors.length - 1]; + const leg = this.legAnchors(from, key, p.typeName); + if (!leg) return; + this.noteGap(from, key); + this.commit(this.replacePath(p.name, leg.reduce((q, k) => appendAnchor(q, act.branch, k), p))); + } else { + // The branch runs head → tail, so the new leg is routed key → head. + const from = anchors[0]; + const leg = this.legAnchors(key, from, p.typeName); + if (!leg) return; + this.noteGap(from, key); + const q = clonePath(p); + q.branches[act.branch].anchors = [key, ...leg.slice(0, -1), ...anchors]; + this.commit(this.replacePath(p.name, q)); + } + } + + // ── edits on a path ── + + private routeFn(typeName: string) { + const router = this.plugin.paths.router(this.map); + if (!router) return null; + return { fn: routeFnFor(router, this.plugin.paths.styleOf(this.map, typeName)), grid: router.context ?? undefined }; + } + + /** Split a branch at one of its routed hexes (the hex's two steps go; nothing else moves). */ + split(path: string, branch: number, hexIdx: number): void { + const p = this.pathNamed(path); + const rb = this.branchRoute(path, branch); + const r = p && this.routeFn(p.typeName); + if (!p || !rb || !r) return; + const next = splitBranchAt(p, rb, hexIdx, r.fn, r.grid); + this.afterPathEdit(p.name, next); + } + + deleteBranch(path: string, branch: number): void { + const p = this.pathNamed(path); + if (!p) return; + this.afterPathEdit(p.name, deleteBranch(p, branch)); + } + + deletePath(path: string): void { + if (!this.pathNamed(path)) return; + this.afterPathEdit(path, null); + } + + deleteAnchor(path: string, branch: number, anchor: number): void { + const p = this.pathNamed(path); + if (!p) return; + const next = deleteAnchor(p, branch, anchor); + // The active end steps back with its anchor; a branch that went takes it along. + this.afterPathEdit(p.name, next, (q) => { + if (!q || q.branches.length < p.branches.length) this.active = null; + }); + } + + reverse(path: string, branch: number): void { + const p = this.pathNamed(path); + const rb = this.branchRoute(path, branch); + const r = p && this.routeFn(p.typeName); + if (!p || !rb || !r) return; + this.afterPathEdit(p.name, reverseBranch(p, rb, r.fn, r.grid)); + } + + rename(path: string): void { + const p = this.pathNamed(path); + if (!p) return; + const others = this.paths().filter((q) => q.name !== p.name).map((q) => pathNameKey(q.name)); + new PathNameModal(this.plugin.app, p.name, (name) => (others.includes(pathNameKey(name)) ? `There's already a path called ${name} on this map.` : null), (name) => { + const q = clonePath(p); + q.name = name; + if (this.commit(this.replacePath(p.name, q)) && this.selected === p.name) this.selected = name; + this.host.refreshBar(); + }).open(); + } + + changeType(path: string): void { + const p = this.pathNamed(path); + if (!p) return; + new PathPickerModal(this.plugin.app, this.plugin, this.plugin.mapPaletteName(this.map), p.typeName, (typeName) => { + const cur = this.pathNamed(path); + if (!cur || cur.typeName === typeName) return; + const q = clonePath(cur); + q.typeName = typeName; + this.commit(this.replacePath(cur.name, q)); + }).open(); + } + + /** Commit one path's replacement (null removes it), keeping the tool state valid. */ + private afterPathEdit(name: string, next: MapPath | null, adjust?: (next: MapPath | null) => void): void { + if (!this.commit(this.replacePath(name, next))) return; + adjust?.(next); + if (!next && this.selected === name) { + this.selected = null; + this.active = null; + } + if (next && this.active && this.active.branch >= next.branches.length) this.active = null; + this.hover = null; + this.host.redraw(); + this.host.refreshBar(); + } + + /** Backspace / Delete: the hovered anchor, else the active end's anchor; cancels a fresh start. */ + deleteKey(): boolean { + if (this.pending) { + this.pending = null; + this.host.redraw(); + this.host.refreshBar(); + return true; + } + const p = this.pathNamed(this.selected); + if (!p) return false; + if (this.hover) { + const { branch, anchor } = this.hover; + this.deleteAnchor(p.name, branch, anchor); + return true; + } + if (this.active) { + const a = p.branches[this.active.branch].anchors; + this.deleteAnchor(p.name, this.active.branch, this.active.end === "head" ? 0 : a.length - 1); + return true; + } + return false; + } + + // ── right-click ── + + /** + * Right-click in the path tool: on an anchor handle of the selected path + * it deletes that anchor ("handled"); on a path it selects it and returns + * the path's menu items; elsewhere null (the usual tool menu). + */ + contextMenu(e: { clientX: number; clientY: number }): { handled: true } | { items: { label: string; onClick: () => void }[] } | null { + if (!this.plugin.paths.isReady(this.map)) return null; + const hit = this.hitAt(e); + if (!hit) return null; + if (hit.path === this.selected && hit.anchor !== null) { + this.deleteAnchor(hit.path, hit.branch, hit.anchor); + return { handled: true }; + } + if (this.selected !== hit.path) { + this.selected = hit.path; + this.active = null; + this.pending = null; + this.host.redraw(); + this.host.refreshBar(); + } + const p = this.pathNamed(hit.path); + if (!p) return null; + const { path, branch, hexIdx } = hit; + const items: { label: string; onClick: () => void }[] = [ + { label: "Split here", onClick: () => this.split(path, branch, hexIdx) }, + ]; + if (p.branches.length > 1) items.push({ label: branch === 0 ? "Delete main line" : "Delete this fork", onClick: () => this.deleteBranch(path, branch) }); + items.push( + { label: `Delete path: ${p.name}`, onClick: () => this.deletePath(path) }, + { label: "Rename…", onClick: () => this.rename(path) }, + { label: "Change type…", onClick: () => this.changeType(path) }, + { label: "Reverse", onClick: () => this.reverse(path, branch) }, + ); + return { items }; + } + + // ── pointer: hover and drag ── + + /** Pointer moved (no button): hover an anchor handle, show "grab" over the selected path. */ + pointerMove(e: { clientX: number; clientY: number }): void { + if (this.drag || this.selected === null || this.isDrawing()) { + if (this.hover) { this.hover = null; this.host.redraw(); } + this.host.setGrabCursor(false); + return; + } + const hit = this.hitAt(e); + const over = hit && hit.path === this.selected ? hit : null; + const hover = over && over.anchor !== null ? { branch: over.branch, anchor: over.anchor } : null; + const changed = (hover?.branch ?? -1) !== (this.hover?.branch ?? -1) || (hover?.anchor ?? -1) !== (this.hover?.anchor ?? -1); + this.hover = hover; + this.host.setGrabCursor(!!over); + if (changed) this.host.redraw(); + } + + /** + * Left button down: on the selected path (not while drawing, erasing or + * with Alt), get ready to drag. Returns true when it took the press. + */ + pointerDown(e: MouseEvent, erasing: boolean): boolean { + if (e.button !== 0 || erasing || e.altKey || this.forceNew || this.isDrawing() || this.selected === null) return false; + if (!this.plugin.paths.isReady(this.map)) return false; + const hit = this.hitAt(e); + if (!hit || hit.path !== this.selected) return false; + const rb = this.branchRoute(hit.path, hit.branch); + if (!rb) return false; + const startHex = rb.hexes[hit.anchor !== null ? rb.anchorIdx[hit.anchor] : hit.hexIdx]; + const doc = this.host.ownerDocument(); + const onMove = (ev: MouseEvent) => this.dragMove(ev); + const onUp = () => this.dragEnd(); + doc.addEventListener("mousemove", onMove); + doc.addEventListener("mouseup", onUp); + this.drag = { + path: hit.path, + branch: hit.branch, + hit, + route: { branch: rb.branch, hexes: [...rb.hexes], anchorIdx: [...rb.anchorIdx] }, + before: clonePaths(this.paths()), + startHex, + lastHex: startHex, + startX: e.clientX, + startY: e.clientY, + started: false, + preview: null, + frame: null, + cleanup: () => { + doc.removeEventListener("mousemove", onMove); + doc.removeEventListener("mouseup", onUp); + }, + }; + return true; + } + + private dragMove(e: MouseEvent): void { + const d = this.drag; + if (!d) return; + if (!d.started && Math.hypot(e.clientX - d.startX, e.clientY - d.startY) <= 4) return; + d.started = true; + const hex = this.host.hexAtPoint(e.clientX, e.clientY); + if (!hex || hex === d.lastHex) return; + d.lastHex = hex; + // One reroute per animation frame, only when the pointer enters a new hex. + if (d.frame === null) { + d.frame = window.requestAnimationFrame(() => { + d.frame = null; + if (this.drag === d) this.updatePreview(d); + }); + } + } + + /** The dragged anchor (inserted into its segment if the drag began on the line) moved to the hex under the pointer. */ + private updatePreview(d: Drag): void { + const base = d.before.find((p) => p.name === d.path); + if (!base) return; + let p = base; + let anchor = d.hit.anchor; + if (anchor === null) { + const ins = insertAnchorAt(base, d.route, d.hit.hexIdx); + p = ins.path; + anchor = ins.anchor; + } + const moved = moveAnchor(p, d.branch, anchor, d.lastHex); + d.preview = d.before.map((q) => (q.name === d.path ? moved : q)); + this.plugin.paths.setPreview(this.map, d.preview); + this.strokeMemo = null; + this.host.redraw(); + } + + private dragEnd(): void { + const d = this.drag; + if (!d) return; + d.cleanup(); + if (d.frame !== null) window.cancelAnimationFrame(d.frame); + this.drag = null; + if (!d.started) return; // a click: the click handler takes it + // The click that ends a drag isn't a click on the map. + this.suppressClick = true; + window.setTimeout(() => { this.suppressClick = false; }, 0); + if (d.lastHex !== d.startHex) this.updatePreview(d); + this.plugin.paths.setPreview(this.map, null); + this.strokeMemo = null; + // Dropped back where it started: nothing changes. + if (d.lastHex !== d.startHex && d.preview) this.commit(d.preview); + else this.host.redraw(); + } + + private cancelDrag(): void { + const d = this.drag; + if (!d) return; + d.cleanup(); + if (d.frame !== null) window.cancelAnimationFrame(d.frame); + this.drag = null; + this.plugin.paths.setPreview(this.map, null); + this.strokeMemo = null; + this.host.redraw(); + } + + /** Is a drag under way (its click must not count)? */ + isDragging(): boolean { + return !!this.drag?.started; + } + + // ── mode bar controls ── + + /** Draw-mode switch, Cross impassable, the selected path's name (rename), New path, Done. */ + renderBarControls(el: HTMLElement): void { + const auto = el.createEl("button", { + cls: "duckmage-mode-bar-route-toggle", + text: "Auto-route", + attr: { + "aria-pressed": String(this.autoRoute), + title: this.autoRoute + ? "On: click far away and the path finds its way there. Click to draw hex by hex." + : "Off: drawing hex by hex (a click away from the end is routed too). Click to auto-route.", + }, + }); + auto.toggleClass("is-active", this.autoRoute); + auto.addEventListener("click", () => this.setAutoRoute(!this.autoRoute)); + + const type = this.currentType(); + const avoids = type ? this.plugin.paths.styleOf(this.map, type).avoid : true; + if (avoids) { + const blocked = impassableNames(this.plugin.getMapPalette(this.map)); + if (!blocked.length) { + if (this.autoRoute) { + el.createSpan({ + cls: "duckmage-mode-bar-route-note", + text: "No impassable terrain", + attr: { title: "Nothing in this map's palette is impassable, so routes go straight through anything. Mark terrains (e.g. water) impassable in the palette editor or the terrain editor." }, + }); + } + } else { + const label = el.createEl("label", { + cls: "duckmage-mode-bar-route-cross", + attr: { title: `Let new legs go through ${blocked.join(", ")} (anchors are added so the line stays put)` }, + }); + const box = label.createEl("input", { type: "checkbox" }); + box.checked = this.crossImpassable; + box.addEventListener("change", () => { this.crossImpassable = box.checked; }); + label.createSpan({ text: "Cross impassable" }); + } + } + + const p = this.pathNamed(this.selected); + if (p) { + const chip = el.createEl("button", { + cls: "duckmage-mode-bar-route-toggle duckmage-mode-bar-path-name", + text: p.name, + attr: { title: "Rename this path" }, + }); + chip.addEventListener("click", () => this.rename(p.name)); + } + const fresh = el.createEl("button", { + cls: "duckmage-mode-bar-route-toggle", + text: "New path", + attr: { title: "Start a new path with the next click, even on top of another path. Holding alt while clicking does the same." }, + }); + fresh.toggleClass("is-active", this.forceNew); + fresh.addEventListener("click", () => this.startNewPath()); + if (p || this.isDrawing() || this.forceNew) { + const done = el.createEl("button", { + cls: "duckmage-mode-bar-route-toggle", + text: "Done", + attr: { title: this.isDrawing() ? "Finish this branch (Esc)" : "Deselect the path (Esc)" }, + }); + done.addEventListener("click", () => this.done()); + } + } +} diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts index f34cf051..80b32f68 100644 --- a/src/hex-map/toolMode.ts +++ b/src/hex-map/toolMode.ts @@ -1,6 +1,7 @@ /** - * Pure helpers for the map's drawing tools (path clicks, the on-map mode - * indicator). Kept free of Obsidian imports so they're unit-testable. + * Pure helpers for the map's drawing tools (the on-map mode indicator). + * Kept free of Obsidian imports so they're unit-testable. What a path-tool + * click does is pathClickOutcome in pathTool.ts. */ export type DrawingMode = @@ -14,25 +15,6 @@ export type DrawingMode = | "swap" | "placeToken"; -/** - * What a left-click on hex `key` does while drawing a path: - * - "start": no path in progress, so start one here; - * - "extend": `key` neighbours the end of the path in progress; - * - "same": `key` IS the end of the path (ignore — don't stack a dot); - * - "restart": `key` isn't next to the end, so a new path starts there. - * Paths go hex by hex, so the caller should say so (fresh-eyes T7: two - * distant clicks silently gave a single dot). - */ -export function pathClickOutcome( - activeEnd: string | null, - key: string, - neighbourKeysOfEnd: readonly string[], -): "start" | "extend" | "same" | "restart" { - if (activeEnd === null) return "start"; - if (key === activeEnd) return "same"; - return neighbourKeysOfEnd.includes(key) ? "extend" : "restart"; -} - export interface ToolModeState { mode: DrawingMode | null; erasing: boolean; @@ -41,10 +23,17 @@ export interface ToolModeState { iconName?: string | null; iconGmOnly?: boolean; pathTypeName?: string | null; - /** Path tool in auto-route mode (click a start, then an end). */ + /** Path tool in auto-route mode (far clicks are routed). */ pathAuto?: boolean; - /** Auto-route: a start (or the end of the last route) is set. */ - pathHasStart?: boolean; + /** A branch is being drawn (clicks add anchors). */ + pathDrawing?: boolean; + /** The selected path's name, and "Road, 2 forks". */ + pathSelected?: string | null; + pathSummary?: string | null; + /** "New path" pressed: the next click starts one. */ + pathNew?: boolean; + /** A short note about the last click. */ + pathNote?: string | null; tablePath?: string | null; submapName?: string | null; factionPath?: string | null; @@ -76,14 +65,22 @@ export function toolModeLabel(s: ToolModeState): string | null { if (erasing || !s.iconName) return `Erasing ${what}s`; return `Painting ${what}: ${baseName(s.iconName)}`; } - case "path": - if (erasing) return "Erasing paths: click a path hex to remove it"; - if (s.pathAuto) { - return s.pathHasStart - ? `Auto-routing ${s.pathTypeName ?? "path"}: click where it goes` - : `Auto-routing ${s.pathTypeName ?? "path"}: click the start hex`; + case "path": { + if (erasing) return "Erasing paths: click a path to split it there"; + const type = s.pathTypeName ?? "Path"; + const how = s.pathAuto ? "auto-routes" : "hex by hex"; + const note = s.pathNote ? ` · ${s.pathNote}` : ""; + if (s.pathNew) return `New ${type}: click where it starts`; + if (s.pathDrawing) { + const name = s.pathSelected ?? `New ${type}`; + return `${name}: click to add (${how}) · Esc to finish${note}`; + } + if (s.pathSelected) { + const what = s.pathSummary ? ` (${s.pathSummary})` : ""; + return `${s.pathSelected}${what}: drag the line to reshape · click an end to continue · click the line to fork${note}`; } - return `Drawing ${s.pathTypeName ?? "path"}: click neighbouring hexes`; + return `${type}: click to start a path · click a path to edit it${note}`; + } case "tableLink": return erasing ? "Unlinking tables" : `Linking table: ${baseName(s.tablePath) || "…"}`; case "submapLink": diff --git a/src/paths/PathsService.ts b/src/paths/PathsService.ts index 347aa727..dbd663fc 100644 --- a/src/paths/PathsService.ts +++ b/src/paths/PathsService.ts @@ -19,7 +19,7 @@ import type { MapData, MapPath, PathChain, PathType, TerrainColor } from "../types"; import { impassableNames } from "../impassable"; import type { RouteContext, SegmentStyle } from "./router"; -import { contextSignature } from "./router"; +import { contextSignature, DEFAULT_SEGMENT_STYLE } from "./router"; import { RouteCache } from "./routeCache"; import { resolvePaths, resolvedToChains, type ResolvedBranch, type StyleFor } from "./resolve"; import { storedMapPaths } from "./mapPaths"; @@ -66,6 +66,13 @@ export interface PathsHost { palette(map: string): readonly TerrainColor[]; /** The map's hexes with data (own terrain). */ hexData(map: string): ReadonlyMap; + /** + * Called before a map's paths are resolved whenever its routing context + * or its types' routing styles differ from the last resolve (and on the + * first one): the plugin's chance to keep existing routes where they + * were (phase 7 pins) before anything draws the new ones. + */ + routesChanging?(map: string): void; } interface Memo { @@ -77,6 +84,10 @@ interface Memo { export class PathsService { private caches = new Map(); private memo = new Map(); + /** Per map: the context signature and styles of the last resolve (see PathsHost.routesChanging). */ + private seen = new Map(); + /** Per map: paths drawn instead of the stored ones (the path tool's live drag preview). */ + private previews = new Map(); constructor(private host: PathsHost) {} @@ -85,6 +96,36 @@ export class PathsService { return storedMapPaths(map); } + /** + * Draw `paths` for this map instead of its stored ones until cleared + * (null). Nothing is saved: the path tool shows a drag's reroute live and + * commits once on release. + */ + setPreview(mapName: string, paths: MapPath[] | null): void { + if (paths) this.previews.set(mapName, paths); + else this.previews.delete(mapName); + } + + /** The paths being drawn for the map: the preview if any, else the stored ones. */ + shownPaths(map: MapData): MapPath[] { + return this.previews.get(map.name) ?? storedMapPaths(map); + } + + /** + * The map's router under its current context (cached segments), or null + * when the map isn't ready. Resolves first, so a pending context change + * has been dealt with. + */ + router(mapName: string): RouteCache | null { + if (!this.compute(mapName)) return null; + return this.cacheFor(mapName); + } + + /** The routing style of a type on this map (DEFAULT_SEGMENT_STYLE's when unknown). */ + styleOf(mapName: string, typeName: string): SegmentStyle { + return styleForTypes(this.host.pathTypes(mapName))(typeName) ?? DEFAULT_SEGMENT_STYLE; + } + /** Can this map's paths be resolved yet (terrain and palette loaded)? */ isReady(mapName: string): boolean { return !!this.host.getMap(mapName) && this.host.isMapReady(mapName); @@ -155,18 +196,32 @@ export class PathsService { forget(mapName: string): void { this.caches.delete(mapName); this.memo.delete(mapName); + this.seen.delete(mapName); + this.previews.delete(mapName); } private compute(mapName: string): Memo | null { const map = this.host.getMap(mapName); - const ctx = this.context(mapName); + let ctx = this.context(mapName); if (!map || !ctx) return null; - const paths = storedMapPaths(map); const types = this.host.pathTypes(mapName); const styleFor = styleForTypes(types); - const styles = [...new Set(paths.map((p) => p.typeName))] + const stylesOf = (ps: readonly MapPath[]) => [...new Set(ps.map((p) => p.typeName))] .map((n) => { const s = styleFor(n); return `${n}=${s ? `${+s.avoid}${+s.winding}` : "?"}`; }) .join(","); + // Routing inputs changed since the last resolve: let the host keep the + // old routes (pins add anchors) before the new ones are drawn. + const inputs = `${contextSignature(ctx)}|${stylesOf(storedMapPaths(map))}`; + if (this.seen.get(mapName) !== inputs) { + this.seen.set(mapName, inputs); + if (this.host.routesChanging) { + this.host.routesChanging(mapName); + ctx = this.context(mapName); + if (!ctx) return null; + } + } + const paths = this.shownPaths(map); + const styles = stylesOf(paths); const key = `${contextSignature(ctx)}|${styles}|${JSON.stringify(paths.map((p) => [p.name, p.typeName, p.branches.map((b) => b.anchors)]))}`; const hit = this.memo.get(mapName); if (hit && hit.key === key) return hit; diff --git a/src/paths/editGate.ts b/src/paths/editGate.ts new file mode 100644 index 00000000..9b7152b3 --- /dev/null +++ b/src/paths/editGate.ts @@ -0,0 +1,31 @@ +/** + * THE GATE for path edits. Every change to a map's stored paths made by + * the plugin at runtime goes through `canEditPaths` first: the path tool's + * edits (pathTool.ts applyEdit, including undo/redo of path steps), the + * keep-the-route pins when terrain, the palette, the map's size or a type's + * routing changes (routePins.ts), and "Reroute instead". + * + * Today it always allows. It is the one place a per-map mode (Play / Build / + * God, being added on fix/ow-playtest) will answer "is this allowed in this + * map's mode?": drawing and reshaping paths count as Build. Whether pins + * over regenerated terrain are allowed outside Build is still undecided. + * Pure, no Obsidian imports. + */ + +/** What kind of path edit is being asked for. */ +export type PathEditAction = + /** The path tool: draw, extend, fork, drag, delete, split, rename, retype, reverse. */ + | "draw" + /** Undo or redo of a path step. */ + | "history" + /** Keep a route where it was after its routing inputs changed (Decision 3). */ + | "pin" + /** "Reroute instead": drop the anchors a pin added. */ + | "reroute"; + +/** May `action` change the stored paths of map `mapName`? (Always yes, for now.) */ +export function canEditPaths(mapName: string, action: PathEditAction): boolean { + void mapName; + void action; + return true; +} diff --git a/src/paths/pathGeometry.ts b/src/paths/pathGeometry.ts index 95506a17..e586d729 100644 --- a/src/paths/pathGeometry.ts +++ b/src/paths/pathGeometry.ts @@ -281,6 +281,9 @@ const DASH_PX: Record = { dashed: [8, 4], dotted: [2, 4] }; /** The end dot of the path being drawn: radius and outline, px at the default zoom. */ export const END_DOT_PX = { r: 5, stroke: 1.5 }; +/** The path tool's anchor handles on the selected path: radius (ends bigger) and outline, px at the default zoom. */ +export const HANDLE_PX = { r: 4, end: 6, stroke: 1.5 }; + export interface PathStroke { /** MapPath.name and branch index (data-path / data-branch on screen). */ path: string; diff --git a/src/paths/routePins.ts b/src/paths/routePins.ts new file mode 100644 index 00000000..e0299b24 --- /dev/null +++ b/src/paths/routePins.ts @@ -0,0 +1,242 @@ +/** + * Phase 7 (Decision 3): keep a route where it was when its routing inputs + * change, and offer "Reroute instead". + * + * Routing inputs are the map's context (terrain shown as impassable, the + * palette's impassable flags, the map's bounds, the stagger) and each path + * type's explicit routing fields (avoidImpassable, autoRoute). When one of + * them would move a segment, `pinChanged` adds just enough anchors that the + * segment keeps its old hexes, and a notice says so with a "Reroute + * instead" button that drops those anchors again. + * + * Hooks: + * - context changes come from MapStore.onRouteContextChange (terrain painted + * or imported, and any change MapStore sees when it next routes the map). + * This class TAKES OVER the store's own silent pin (returns true): it + * pins the same way and also knows what it added, for the notice; + * - palette flags, resizes and type style edits are caught before the next + * draw: PathsService calls `sync(map)` whenever the map's context + * signature or its types' styles differ from its last resolve. `sync` + * asks MapStore to route under the current context (which fires the + * context hook above when it changed) and compares the types' styles with + * the last ones it saw. + * + * Every write goes through the path edit gate (editGate.ts). + */ + +import { Notice } from "obsidian"; +import type { HexKey, MapData, MapPath } from "../types"; +import type { SegmentStyle } from "./router"; +import type { RouteCache } from "./routeCache"; +import type { StyleFor } from "./resolve"; +import { clonePath, pinChanged, segmentFn } from "./edit"; +import { canEditPaths } from "./editGate"; +import type { RouteContextChange } from "../maps/MapStore"; + +/** What the pins need of the map store. */ +export interface PinStore { + isReady(map?: string): boolean; + paths(name: string): readonly MapPath[]; + setPaths(name: string, paths: MapPath[]): void; + routeCache(map: MapData): RouteCache; + pathStyleFor(map: MapData): StyleFor; + onRouteContextChange(fn: (e: RouteContextChange) => boolean | void): () => void; +} + +export interface PinHost { + getMap(name: string): MapData | undefined; + mapStore: PinStore; + /** Persist settings (maps whose paths still live in data.json). */ + saveSettings?(): Promise; +} + +/** One map's pin: the pinned paths as they were before, and how many anchors each gained. */ +export interface PinRecord { + map: string; + before: MapPath[]; + added: { path: string; added: number }[]; +} + +/** Is `sub` a subsequence of `seq`? */ +function isSubsequence(sub: readonly HexKey[], seq: readonly HexKey[]): boolean { + let i = 0; + for (const k of seq) if (i < sub.length && k === sub[i]) i++; + return i === sub.length; +} + +/** + * `current` with the anchors a pin added taken out again: each branch whose + * anchors before the pin are still all there, in order, goes back to them. + * Anything else (a branch edited since in other ways, a branch added or + * removed) is left as it is now. + */ +export function dropAddedAnchors(current: MapPath, before: MapPath): MapPath { + if (current.branches.length !== before.branches.length) return current; + let changed = false; + const out = clonePath(current); + out.branches.forEach((b, i) => { + const old = before.branches[i].anchors; + if (old.length < b.anchors.length && isSubsequence(old, b.anchors)) { + b.anchors = [...old]; + changed = true; + } + }); + return changed ? out : current; +} + +/** The styles of a map's types as a plain snapshot (type name → style). */ +function styleSnapshot(paths: readonly MapPath[], styleFor: StyleFor): Map { + const out = new Map(); + for (const p of paths) if (!out.has(p.typeName)) out.set(p.typeName, styleFor(p.typeName)); + return out; +} + +const sameStyle = (a: SegmentStyle | undefined, b: SegmentStyle | undefined) => + (!a && !b) || (!!a && !!b && a.avoid === b.avoid && a.winding === b.winding); + +/** How long pins are collected into one notice (a palette change pins many maps at once). */ +const BATCH_MS = 60; + +export class RoutePins { + private styles = new Map>(); + private batch: PinRecord[] = []; + private batchTimer: number | undefined; + private listeners = new Set<(r: PinRecord) => void>(); + private off: (() => void) | null = null; + + constructor(private host: PinHost) {} + + /** Start listening to the store's context changes. */ + attach(): void { + this.off?.(); + this.off = this.host.mapStore.onRouteContextChange((e) => this.onContextChange(e)); + } + + detach(): void { + this.off?.(); + this.off = null; + if (this.batchTimer !== undefined) window.clearTimeout(this.batchTimer); + this.batchTimer = undefined; + } + + /** Hear about each pin (the map view folds a pin into the undo step that caused it). */ + onPinned(fn: (r: PinRecord) => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + /** The store saw a context change: pin with a notice. Always handled here. */ + onContextChange(e: RouteContextChange): boolean { + if (!canEditPaths(e.map, "pin")) return true; // not allowed: the route moves + const paths = this.host.mapStore.paths(e.map); + if (!paths.length) return true; + const r = pinChanged(paths, segmentFn(e.previous, e.styleFor), segmentFn(e.current, e.styleFor), e.after); + if (r.pinned.length) this.apply(e.map, paths, r.paths, r.pinned); + return true; + } + + /** + * Before a map's paths are drawn after its routing inputs changed: route + * it under the current context (the store then reports a context change + * to onContextChange), and pin against any type whose routing style + * changed since the last look. + */ + sync(mapName: string): void { + const map = this.host.getMap(mapName); + const store = this.host.mapStore; + if (!map || !store.isReady(mapName)) return; + const cache = store.routeCache(map); + if (!map.paths) return; + const paths = store.paths(mapName); + const styleFor = store.pathStyleFor(map); + const now = styleSnapshot(paths, styleFor); + const prev = this.styles.get(mapName); + this.styles.set(mapName, now); + if (!prev || !paths.length || !cache.context) return; + const changed = [...now].some(([t, s]) => prev.has(t) && !sameStyle(prev.get(t), s)); + if (!changed || !canEditPaths(mapName, "pin")) return; + const oldStyleFor: StyleFor = (t) => (prev.has(t) ? prev.get(t) : styleFor(t)); + const r = pinChanged(paths, segmentFn(cache, oldStyleFor), segmentFn(cache, styleFor), cache.context); + if (r.pinned.length) this.apply(mapName, paths, r.paths, r.pinned); + } + + /** Forget what was seen for a map (deleted or renamed). */ + forget(mapName: string): void { + this.styles.delete(mapName); + } + + private apply(mapName: string, before: readonly MapPath[], after: MapPath[], added: { path: string; added: number }[]): void { + const names = new Set(added.map((a) => a.path)); + const rec: PinRecord = { map: mapName, before: before.filter((p) => names.has(p.name)).map(clonePath), added }; + this.host.mapStore.setPaths(mapName, after); + void this.host.saveSettings?.(); + for (const fn of this.listeners) { + try { fn(rec); } catch (e) { console.error("Hexmaker: pin listener failed", e); } + } + this.batch.push(rec); + if (this.batchTimer === undefined) this.batchTimer = window.setTimeout(() => this.showNotice(), BATCH_MS); + } + + /** The pending pins, shown as one notice now (tests call this directly). */ + flushNotice(): PinRecord[] { + if (this.batchTimer !== undefined) window.clearTimeout(this.batchTimer); + this.batchTimer = undefined; + const recs = this.batch; + this.batch = []; + return recs; + } + + private showNotice(): void { + const recs = this.flushNotice(); + if (!recs.length) return; + const msg = pinNoticeText(recs); + const notice = new Notice(msg, 15000); + const el = (notice as unknown as { noticeEl?: HTMLElement }).noticeEl; + if (el) { + const btn = el.createEl("button", { text: "Reroute instead", cls: "duckmage-notice-btn" }); + btn.addEventListener("click", (ev) => { + ev.stopPropagation(); + this.rerouteInstead(recs); + notice.hide(); + }); + } + } + + /** "Reroute instead": take the pinned anchors out again (only those still there). */ + rerouteInstead(recs: readonly PinRecord[]): void { + const byMap = new Map(); + for (const r of recs) byMap.set(r.map, [...(byMap.get(r.map) ?? []), r]); + for (const [mapName, rs] of byMap) { + if (!this.host.getMap(mapName) || !canEditPaths(mapName, "reroute")) continue; + const current = this.host.mapStore.paths(mapName); + let changed = false; + const next = current.map((p) => { + let q = p; + for (const r of rs) { + const b = r.before.find((x) => x.name === p.name); + if (b) q = dropAddedAnchors(q, b); + } + if (q !== p) changed = true; + return q; + }); + if (changed) this.host.mapStore.setPaths(mapName, next); + } + void this.host.saveSettings?.(); + } +} + +/** "Kept the route of King's Road, Glass River (3 anchors added)." */ +export function pinNoticeText(recs: readonly PinRecord[]): string { + const names: string[] = []; + let added = 0; + for (const r of recs) { + for (const a of r.added) { + if (!names.includes(a.path)) names.push(a.path); + added += a.added; + } + } + const shown = names.length > 4 ? `${names.slice(0, 4).join(", ")} and ${names.length - 4} more` : names.join(", "); + const maps = new Set(recs.map((r) => r.map)).size; + return `Kept the route of ${shown}${maps > 1 ? ` on ${maps} maps` : ""} (${added} anchor${added === 1 ? "" : "s"} added).`; +} + diff --git a/styles.css b/styles.css index 00f51d5b..325e77d5 100644 --- a/styles.css +++ b/styles.css @@ -8063,3 +8063,61 @@ button.duckmage-terrain-legend-chip { width: 1.8em; height: 1.8em; } + +/* Path tool (anchored paths): grab cursor over the selected path, the + "Reroute instead" notice button, and "Paths on this map" in the picker. */ +.duckmage-hex-map-viewport.duckmage-draw-mode.duckmage-path-grab .duckmage-hex { + cursor: grab; +} +.duckmage-hex-map-viewport.duckmage-draw-mode.duckmage-path-grab:active .duckmage-hex { + cursor: grabbing; +} +.duckmage-notice-btn { + margin-left: 0.6em; +} +.duckmage-mode-bar-path-name { + font-style: italic; +} +.duckmage-path-list { + display: flex; + flex-direction: column; + gap: 2px; + max-height: 14em; + overflow-y: auto; + margin-top: 0.3em; +} +.duckmage-path-list-row { + display: flex; + align-items: center; + gap: 0.5em; + justify-content: flex-start; + height: auto; + padding: 0.25em 0.5em; + box-shadow: none; + background: transparent; + text-align: left; +} +.duckmage-path-list-row.is-selected { + background: var(--background-modifier-hover); + font-weight: 600; +} +.duckmage-path-list-swatch { + flex: none; + width: 1.4em; + height: 0.3em; + border-radius: 999px; + background: var(--duckmage-path-swatch, var(--text-faint)); +} +.duckmage-path-list-summary { + margin-left: auto; + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} +.duckmage-path-name-input { + width: 100%; +} +.duckmage-path-name-problem { + min-height: 1.4em; + margin-top: 0.3em; + color: var(--text-error); +} diff --git a/tests/autoRoute.test.ts b/tests/autoRoute.test.ts index 2c2004c0..2f412435 100644 --- a/tests/autoRoute.test.ts +++ b/tests/autoRoute.test.ts @@ -160,7 +160,10 @@ describe("findRoute keeps to the straight line on open ground (round 6 R5)", () }); // ── Round 7: rivers meander (U17); a new route never joins or reshapes (R11) ── -import { addRoutedLeg, routeExtendTarget, type RouteChain } from "../src/hex-map/autoRoute"; +import { pathClickOutcome, type PathHit } from "../src/hex-map/pathTool"; +import { appendAnchor, newPath } from "../src/paths/edit"; +import { resolvePaths } from "../src/paths/resolve"; +import type { MapPath } from "../src/types"; import { pathMeanders } from "../src/impassable"; describe("auto-routed rivers wind (round 7 U17)", () => { @@ -228,41 +231,48 @@ describe("auto-routed rivers wind (round 7 U17)", () => { }); }); -describe("a second auto-route starts a new path (round 7 R11)", () => { +describe("a new path never joins or reshapes another (round 7 R11, anchored paths)", () => { // The region tester's map: road keep (12_8) → Gullmouth (7_5), then a - // second road from the keep to the east edge. - const make = (typeName: string, hexes: string[]): RouteChain => ({ typeName, hexes }); - const first = () => [make("Road", ["12_8", "11_7", "10_7", "9_6", "8_6", "7_5"]), make("River", ["11_13", "10_14", "9_13"])]; + // second road from the keep to the east edge. With anchored paths a + // click on a path selects it; Alt-click or "New path" starts a new one. + const ctx = { orientation: "flat" as const, stagger: "odd" as const, bounds: bounds(20, 16), blocked: new Set() }; + const first = (): MapPath[] => [ + { name: "Road", typeName: "Road", branches: [{ anchors: ["12_8", "7_5"] }] }, + { name: "River", typeName: "River", branches: [{ anchors: ["11_13", "9_13"] }] }, + ]; + const onRoad = (hexIdx: number, o: Partial = {}): PathHit => ({ path: "Road", branch: 0, hexIdx, anchor: null, end: null, ...o }); + const idle = { erasing: false, forceNew: false, activeHex: null, selected: null }; - it("starting on the first road's first hex makes a new road and leaves the first untouched", () => { - const chains = first(); - const before = JSON.parse(JSON.stringify(chains)); - const leg = addRoutedLeg(chains, "Road", ["12_8", "13_8", "14_8", "15_8"], null, make); - expect(chains).toHaveLength(3); - expect(chains.slice(0, 2)).toEqual(before); - expect(leg).toBe(chains[2]); - expect(leg.hexes).toEqual(["12_8", "13_8", "14_8", "15_8"]); + it("clicking the first road's first hex selects that road; it doesn't start a road joined to it", () => { + expect(pathClickOutcome(idle, "12_8", onRoad(0))).toEqual({ kind: "select", path: "Road" }); }); - it("starting in the middle of a road makes a new road", () => { - const chains = first(); - expect(routeExtendTarget(chains, "Road", "10_7", null)).toBeNull(); - addRoutedLeg(chains, "Road", ["10_7", "10_8"], chains[0], make); - expect(chains[0].hexes).toEqual(["12_8", "11_7", "10_7", "9_6", "8_6", "7_5"]); - expect(chains).toHaveLength(3); + it("Alt-click (or New path) on the keep starts a new road; the first is untouched", () => { + const paths = first(); + const before = JSON.stringify(paths); + expect(pathClickOutcome({ ...idle, forceNew: true }, "12_8", onRoad(0))).toEqual({ kind: "start" }); + // the next click creates it: a separate path with its own name + const road2 = appendAnchor(newPath("Road", "12_8", paths.map((p) => p.name)), 0, "15_8"); + const after = [...paths, road2]; + expect(road2.name).toBe("Road 2"); + expect(JSON.stringify(after.slice(0, 2))).toBe(before); + const resolved = resolvePaths(after, ctx); + expect(resolved.find((r) => r.path === "Road")!.hexes).toEqual(resolvePaths(first(), ctx).find((r) => r.path === "Road")!.hexes); + expect(resolved.find((r) => r.path === "Road 2")!.hexes[0]).toBe("12_8"); }); - it("starting exactly on a road's end continues it, adding only new hexes", () => { - const chains = first(); - const leg = addRoutedLeg(chains, "Road", ["7_5", "7_4", "7_3"], null, make); - expect(leg).toBe(chains[0]); - expect(chains).toHaveLength(2); - expect(chains[0].hexes).toEqual(["12_8", "11_7", "10_7", "9_6", "8_6", "7_5", "7_4", "7_3"]); + it("on the selected road, the middle forks and an end continues; only new anchors are added", () => { + const sel = { ...idle, selected: "Road" }; + expect(pathClickOutcome(sel, "10_7", onRoad(2))).toEqual({ kind: "fork", path: "Road", branch: 0, hexIdx: 2 }); + expect(pathClickOutcome(sel, "7_5", onRoad(5, { anchor: 1, end: "tail" }))).toEqual({ kind: "continue", path: "Road", branch: 0, end: "tail" }); + const [road] = first(); + const longer = appendAnchor(road, 0, "7_3"); + expect(longer.branches[0].anchors).toEqual(["12_8", "7_5", "7_3"]); + const was = resolvePaths([road], ctx)[0].hexes; + expect(resolvePaths([longer], ctx)[0].hexes.slice(0, was.length)).toEqual(was); }); - it("a river's end doesn't continue a road", () => { - const chains = first(); - expect(routeExtendTarget(chains, "Road", "9_13", null)).toBeNull(); - expect(routeExtendTarget(chains, "River", "9_13", null)).toBe(chains[1]); + it("while drawing a road, a click on the river adds an anchor to the road and leaves the river alone", () => { + expect(pathClickOutcome({ ...idle, selected: "Road", activeHex: "7_5" }, "9_13", { ...onRoad(1), path: "River" })).toEqual({ kind: "append" }); }); }); diff --git a/tests/pathTool.test.ts b/tests/pathTool.test.ts new file mode 100644 index 00000000..64c26b42 --- /dev/null +++ b/tests/pathTool.test.ts @@ -0,0 +1,148 @@ +/** + * The path tool's pure parts (plan-path-anchors section 4, phase 5): + * hit-testing a pointer against the drawn polylines and anchor handles, + * the click table (replacing the old hex-by-hex pathClickOutcome), and + * where a drag on the line inserts its anchor. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import type { MapPath, PathType } from "../src/types"; +import { + anchorEnd, + distToPolyline, + hitTestPaths, + nearestHexIdx, + pathClickOutcome, + pathSummary, + type PathClickState, + type PathHit, +} from "../src/hex-map/pathTool"; +import { buildPathStrokes, latticeCenter, type LatticeGrid } from "../src/paths/pathGeometry"; +import { resolvePaths } from "../src/paths/resolve"; +import type { RouteContext } from "../src/paths/router"; +import { insertAnchorAt, moveAnchor } from "../src/paths/edit"; +import { UNKNOWN_PATH_TYPE } from "../src/constants"; + +const ROAD: PathType = { name: "Road", color: "#a33", width: 4, lineStyle: "solid", routing: "through", avoidImpassable: true, autoRoute: "direct" }; +const RIVER: PathType = { name: "River", color: "#33a", width: 3, lineStyle: "solid", routing: "meander", avoidImpassable: false, autoRoute: "winding" }; +const grid: LatticeGrid = { orientation: "flat", stagger: "odd" }; +const ctx: RouteContext = { orientation: "flat", stagger: "odd", bounds: { minX: 0, minY: 0, maxX: 19, maxY: 15 }, blocked: new Set() }; + +const KINGS: MapPath = { name: "King's Road", typeName: "Road", branches: [{ anchors: ["1_5", "9_5"] }, { anchors: ["5_5", "5_10"] }] }; +const GLASS: MapPath = { name: "Glass River", typeName: "River", branches: [{ anchors: ["12_1", "12_9"] }] }; + +function scene(paths: MapPath[] = [KINGS, GLASS]) { + const resolved = resolvePaths(paths, ctx); + const strokes = buildPathStrokes(resolved, [ROAD, RIVER], grid, { unknownType: UNKNOWN_PATH_TYPE }); + return { resolved, strokes }; +} + +const at = (hex: string, dx = 0, dy = 0) => { + const c = latticeCenter(hex, grid); + return { cx: c.cx + dx, cy: c.cy + dy }; +}; + +describe("hit-testing paths (pure, lattice units)", () => { + it("a point on a line hits it; the hex index is the branch's nearest routed hex", () => { + const { resolved, strokes } = scene(); + const main = resolved.find((r) => r.path === "King's Road" && r.branch === 0)!; + const hit = hitTestPaths(at("4_5", 0, 0.05), strokes, resolved, grid, null); + expect(hit).toMatchObject({ path: "King's Road", branch: 0, anchor: null, end: null }); + expect(main.hexes[hit!.hexIdx]).toBe("4_5"); + }); + + it("misses beyond half the stroke plus the slack", () => { + const { resolved, strokes } = scene(); + expect(hitTestPaths(at("4_8"), strokes, resolved, grid, null)).toBeNull(); + expect(distToPolyline({ cx: 0, cy: 1 }, [{ cx: -1, cy: 0 }, { cx: 1, cy: 0 }])).toBeCloseTo(1); + }); + + it("anchor handles count only on the selected path; ends are marked head / tail, a fork's start isn't an end", () => { + const { resolved, strokes } = scene(); + expect(hitTestPaths(at("9_5"), strokes, resolved, grid, null)?.anchor).toBeNull(); + expect(hitTestPaths(at("9_5"), strokes, resolved, grid, "King's Road")).toMatchObject({ branch: 0, anchor: 1, end: "tail" }); + expect(hitTestPaths(at("1_5"), strokes, resolved, grid, "King's Road")).toMatchObject({ branch: 0, anchor: 0, end: "head" }); + const fork = resolved.find((r) => r.path === "King's Road" && r.branch === 1)!; + expect(fork.forkFrom).toBeDefined(); + expect(anchorEnd(fork, 0)).toBeNull(); + expect(anchorEnd(fork, 1)).toBe("tail"); + }); + + it("where lines overlap, the selected path wins", () => { + // Old Track runs along part of the King's Road (every hex an anchor: exact). + const kings = resolvePaths([KINGS], ctx).find((r) => r.branch === 0)!.hexes; + const over: MapPath = { name: "Old Track", typeName: "Road", branches: [{ anchors: kings.slice(2, 6) }] }; + const { resolved, strokes } = scene([over, KINGS]); + for (const sel of ["Old Track", "King's Road"]) expect(hitTestPaths(at(kings[3]), strokes, resolved, grid, sel)?.path).toBe(sel); + }); + + it("nearestHexIdx breaks ties toward the lower index", () => { + const a = latticeCenter("0_0", grid); + const b = latticeCenter("1_0", grid); + expect(nearestHexIdx({ cx: (a.cx + b.cx) / 2, cy: (a.cy + b.cy) / 2 }, ["0_0", "1_0"], grid)).toBe(0); + }); +}); + +describe("dragging the line inserts an anchor in the segment under the pointer", () => { + it("between the anchors around that hex, then moves it (only that branch changes)", () => { + const p: MapPath = { name: "R", typeName: "Road", branches: [{ anchors: ["0_5", "6_5", "12_5"] }] }; + const [rb] = resolvePaths([p], ctx); + const idx = rb.anchorIdx[1] + 3; // inside the second segment + const hex = rb.hexes[idx]; + const ins = insertAnchorAt(p, rb, idx); + expect(ins.inserted).toBe(true); + expect(ins.anchor).toBe(2); + expect(ins.path.branches[0].anchors).toEqual(["0_5", "6_5", hex, "12_5"]); + // the shape is unchanged until it moves + expect(resolvePaths([ins.path], ctx)[0].hexes).toEqual(rb.hexes); + const moved = moveAnchor(ins.path, 0, ins.anchor, "9_9"); + expect(moved.branches[0].anchors).toEqual(["0_5", "6_5", "9_9", "12_5"]); + // only the two segments around the moved anchor change + const now = resolvePaths([moved], ctx)[0]; + expect(now.hexes.slice(0, now.anchorIdx[1] + 1)).toEqual(rb.hexes.slice(0, rb.anchorIdx[1] + 1)); + // the route now passes the dragged-to hex + expect(resolvePaths([moved], ctx)[0].hexes).toContain("9_9"); + // grabbing an anchor itself inserts nothing + expect(insertAnchorAt(p, rb, rb.anchorIdx[1])).toMatchObject({ anchor: 1, inserted: false }); + }); +}); + +describe("pathClickOutcome: the click table", () => { + const S = (o: Partial = {}): PathClickState => ({ erasing: false, forceNew: false, activeHex: null, selected: null, ...o }); + const hit = (o: Partial = {}): PathHit => ({ path: "King's Road", branch: 0, hexIdx: 3, anchor: null, end: null, ...o }); + + it("nothing selected: an empty hex starts a path, a path is selected", () => { + expect(pathClickOutcome(S(), "4_4", null)).toEqual({ kind: "start" }); + expect(pathClickOutcome(S(), "4_5", hit())).toEqual({ kind: "select", path: "King's Road" }); + }); + + it("drawing: every click adds an anchor (far or near); the active end again finishes", () => { + expect(pathClickOutcome(S({ activeHex: "9_5" }), "15_2", null)).toEqual({ kind: "append" }); + expect(pathClickOutcome(S({ activeHex: "9_5" }), "10_5", hit({ path: "Glass River" }))).toEqual({ kind: "append" }); + expect(pathClickOutcome(S({ activeHex: "9_5" }), "9_5", hit())).toEqual({ kind: "finish" }); + }); + + it("selected: an end continues it, anywhere else on it forks, another path is selected, empty map deselects", () => { + const sel = S({ selected: "King's Road" }); + expect(pathClickOutcome(sel, "9_5", hit({ anchor: 1, end: "tail" }))).toEqual({ kind: "continue", path: "King's Road", branch: 0, end: "tail" }); + expect(pathClickOutcome(sel, "1_5", hit({ anchor: 0, end: "head" }))).toEqual({ kind: "continue", path: "King's Road", branch: 0, end: "head" }); + expect(pathClickOutcome(sel, "4_5", hit())).toEqual({ kind: "fork", path: "King's Road", branch: 0, hexIdx: 3 }); + expect(pathClickOutcome(sel, "12_3", hit({ path: "Glass River" }))).toEqual({ kind: "select", path: "Glass River" }); + expect(pathClickOutcome(sel, "3_12", null)).toEqual({ kind: "deselect" }); + }); + + it("Alt-click / New path always starts a new path, even on another path", () => { + expect(pathClickOutcome(S({ forceNew: true, selected: "King's Road" }), "4_5", hit())).toEqual({ kind: "start" }); + expect(pathClickOutcome(S({ forceNew: true, activeHex: "9_5" }), "4_5", null)).toEqual({ kind: "start" }); + }); + + it("erase mode splits the path under the pointer, and does nothing elsewhere", () => { + expect(pathClickOutcome(S({ erasing: true }), "4_5", hit())).toEqual({ kind: "split", path: "King's Road", branch: 0, hexIdx: 3 }); + expect(pathClickOutcome(S({ erasing: true }), "4_4", null)).toEqual({ kind: "none" }); + }); + + it("the mode bar summary names the type and forks", () => { + expect(pathSummary(KINGS)).toBe("Road, 1 fork"); + expect(pathSummary(GLASS)).toBe("River"); + }); +}); diff --git a/tests/routePins.test.ts b/tests/routePins.test.ts new file mode 100644 index 00000000..c730db46 --- /dev/null +++ b/tests/routePins.test.ts @@ -0,0 +1,148 @@ +/** + * Phase 7 (Decision 3): when terrain, the palette, the size or a type's + * routing would move a route, it's kept by adding anchors, with a notice + * offering "Reroute instead". RoutePins takes over MapStore's context + * hook; PathsService asks it to check before drawing. + */ +import { describe, it, beforeEach } from "node:test"; +import expect from "expect"; +import { Notice } from "obsidian"; +import { MapStore } from "../src/maps/MapStore"; +import { MemVault } from "./helpers/memVault"; +import type { MapData, PathChain, PathType, TerrainColor } from "../src/types"; +import { DEFAULT_PATH_TYPES, DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { dropAddedAnchors, pinNoticeText, RoutePins } from "../src/paths/routePins"; +import { PathsService } from "../src/paths/PathsService"; + +(globalThis as Record).window ??= globalThis; + +const ROAD_HEXES = ["0_5", "1_5", "2_5", "3_5", "4_5", "5_5", "6_5"]; + +async function boot(chains: PathChain[], over: Partial = {}) { + const v = new MemVault(); + const maps = [{ name: "m", paletteName: "Default", gridSize: { cols: 14, rows: 10 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", baseTerrain: "grass", pathChains: chains, ...over } as MapData]; + const state = { + palette: DEFAULT_TERRAIN_PALETTE.map((t) => ({ ...t })) as TerrainColor[], + types: DEFAULT_PATH_TYPES.map((t) => ({ ...t })) as PathType[], + }; + const p = { + app: v.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", maps, hexOrientation: "flat" as const, staggerOffset: "odd" as const }, + getMap: (n: string) => maps.find((m) => m.name === n), + getMapPalette: () => state.palette, + getMapPathTypes: () => state.types, + saveData: async () => {}, + refreshHexMap: () => {}, + }; + const store = new MapStore(p as never); + const pins = new RoutePins({ getMap: p.getMap, mapStore: store }); + pins.attach(); + await store.init(); + const svc = new PathsService({ + isMapReady: (n) => store.isReady(n), + getMap: p.getMap, + orientation: () => "flat", + stagger: () => "odd", + pathTypes: () => state.types, + palette: () => state.palette, + hexData: (n) => store.all(n), + routesChanging: (n) => pins.sync(n), + }); + return { v, maps, state, store, pins, svc }; +} + +const anchors = (maps: MapData[]) => maps[0].paths![0].branches[0].anchors; + +describe("keep the route when terrain changes under it (phase 7)", () => { + beforeEach(() => { Notice.shown = []; }); + + it("painting water under a road keeps its hexes and adds anchors, with a 'Kept the route' notice", async () => { + const { maps, store, pins } = await boot([{ typeName: "Road", hexes: ROAD_HEXES }]); + const before = store.resolved("m")![0].hexes; + expect(before).toEqual(ROAD_HEXES); + const was = [...anchors(maps)]; + store.set("m", "3_5", { terrain: "shallows" }); // water: impassable by its type + expect(store.resolved("m")![0].hexes).toEqual(before); + expect(anchors(maps).length).toBeGreaterThan(was.length); + const recs = pins.flushNotice(); + expect(recs).toHaveLength(1); + expect(recs[0].before[0].branches[0].anchors).toEqual(was); + expect(pinNoticeText(recs)).toMatch(/^Kept the route of Road \(\d+ anchors? added\)\.$/); + }); + + it("'Reroute instead' drops those anchors again, so the road goes round the water", async () => { + const { maps, store, pins } = await boot([{ typeName: "Road", hexes: ROAD_HEXES }]); + const was = [...anchors(maps)]; + store.set("m", "3_5", { terrain: "shallows" }); + pins.rerouteInstead(pins.flushNotice()); + expect(anchors(maps)).toEqual(was); + const now = store.resolved("m")![0].hexes; + expect(now).not.toContain("3_5"); + expect(now[0]).toBe("0_5"); + expect(now[now.length - 1]).toBe("6_5"); + }); + + it("painting forest under a road adds nothing", async () => { + const { maps, store, pins } = await boot([{ typeName: "Road", hexes: ROAD_HEXES }]); + const was = JSON.stringify(maps[0].paths); + store.set("m", "3_5", { terrain: "forest" }); + store.resolved("m"); + expect(JSON.stringify(maps[0].paths)).toBe(was); + expect(pins.flushNotice()).toEqual([]); + }); + + it("toggling a terrain impassable in the palette pins before the next draw", async () => { + const { maps, store, state, pins, svc } = await boot([{ typeName: "Road", hexes: ROAD_HEXES }]); + store.set("m", "3_5", { terrain: "forest" }); + expect(svc.resolvedPathChains("m")[0].hexes).toEqual(ROAD_HEXES); + const was = anchors(maps).length; + state.palette.find((t) => t.name === "forest")!.impassable = true; + expect(svc.resolvedPathChains("m")[0].hexes).toEqual(ROAD_HEXES); // the service asked first + expect(anchors(maps).length).toBeGreaterThan(was); + expect(pins.flushNotice()).toHaveLength(1); + }); + + it("growing the map pins a route that would now take the new room", async () => { + // A wall of water down column 2 with a gap at the bottom: a road from + // 1, 0 to 3, 0 goes all the way round. With a row added above the map, + // the short way over the top opens up. + const { maps, store, pins, svc } = await boot([]); + store.setMany("m", Array.from({ length: 9 }, (_, y) => [`2_${y}`, { terrain: "shallows" }] as [string, { terrain: string }])); + svc.resolvedPathChains("m"); // as the map view does before the tool draws + store.setPaths("m", [{ name: "Road", typeName: "Road", branches: [{ anchors: ["1_0", "3_0"] }] }]); + const before = svc.resolvedPathChains("m")[0].hexes; + expect(before.length).toBeGreaterThan(15); + maps[0].gridOffset = { x: 0, y: -1 }; + maps[0].gridSize = { cols: 14, rows: 11 }; + expect(svc.resolvedPathChains("m")[0].hexes).toEqual(before); + expect(anchors(maps).length).toBeGreaterThan(2); + expect(pins.flushNotice()).toHaveLength(1); + }); + + it("switching a type's avoidImpassable keeps its roads' routes (pinned), and Reroute instead takes it", async () => { + const { maps, store, state, pins, svc } = await boot([{ typeName: "Road", hexes: ROAD_HEXES }]); + const road = state.types.find((t) => t.name === "Road")!; + road.avoidImpassable = false; + svc.resolvedPathChains("m"); // the service has seen this style + store.set("m", "3_5", { terrain: "shallows" }); // no reroute: the road ignores water + expect(pins.flushNotice()).toEqual([]); + const was = [...anchors(maps)]; + road.avoidImpassable = true; + expect(svc.resolvedPathChains("m")[0].hexes).toEqual(ROAD_HEXES); + expect(anchors(maps).length).toBeGreaterThan(was.length); + const recs = pins.flushNotice(); + expect(recs).toHaveLength(1); + pins.rerouteInstead(recs); + expect(anchors(maps)).toEqual(was); + expect(svc.resolvedPathChains("m")[0].hexes).not.toContain("3_5"); + }); + + it("dropAddedAnchors restores a branch only while its old anchors are all still there", () => { + const before = { name: "R", typeName: "Road", branches: [{ anchors: ["0_0", "5_0"] }, { anchors: ["2_0", "2_4"] }] }; + const pinned = { ...before, branches: [{ anchors: ["0_0", "2_1", "5_0"] }, { anchors: ["2_0", "2_4", "4_4"] }] }; + expect(dropAddedAnchors(pinned, before).branches.map((b) => b.anchors)).toEqual([["0_0", "5_0"], ["2_0", "2_4"]]); + const edited = { ...before, branches: [{ anchors: ["0_0", "9_9"] }, { anchors: ["2_0", "2_4"] }] }; + expect(dropAddedAnchors(edited, before)).toBe(edited); + }); +}); diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 4322065a..66dd1140 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -2,9 +2,18 @@ import { describe, it } from "node:test"; import expect from "expect"; import { readFileSync } from "node:fs"; import * as path from "node:path"; -import { pathClickOutcome, toolModeLabel, type DrawingMode } from "../src/hex-map/toolMode"; +import { toolModeLabel, type DrawingMode } from "../src/hex-map/toolMode"; const viewSrc = readFileSync(path.join(process.cwd(), "src", "hex-map", "HexMapView.ts"), "utf8").replace(/\r\n/g, "\n"); +const toolSrc = readFileSync(path.join(process.cwd(), "src", "hex-map", "pathTool.ts"), "utf8").replace(/\r\n/g, "\n"); + +/** Source of the PathTool method `name`. */ +function toolMethod(name: string): string { + const m = new RegExp(`\\n (?:private )?(?:async )?${name}\\(`).exec(toolSrc); + const start = m ? m.index + 1 : -1; + expect(start).toBeGreaterThan(-1); + return toolSrc.slice(start, toolSrc.indexOf("\n }\n", start)); +} /** Source of the HexMapView method `name` (up to its closing brace at two-space indent). */ function method(name: string): string { @@ -14,26 +23,6 @@ function method(name: string): string { return viewSrc.slice(start, viewSrc.indexOf("\n }\n", start)); } -describe("pathClickOutcome (fresh-eyes T7)", () => { - const around = ["2_1", "3_2", "3_3", "2_3", "1_3", "1_2"]; // neighbours of 2_2 - - it("starts a path when none is in progress", () => { - expect(pathClickOutcome(null, "5_5", [])).toBe("start"); - }); - - it("extends the path on a neighbour of its end", () => { - expect(pathClickOutcome("2_2", "3_2", around)).toBe("extend"); - }); - - it("ignores a click on the end itself (no stacked dot)", () => { - expect(pathClickOutcome("2_2", "2_2", around)).toBe("same"); - }); - - it("reports a restart for a distant hex so the caller can explain it", () => { - expect(pathClickOutcome("2_2", "6_6", around)).toBe("restart"); - }); -}); - describe("Path tool button (fresh-eyes T7)", () => { it("clicking Path while drawing reopens the picker instead of exiting", () => { const body = method("handlePathButton"); @@ -41,42 +30,44 @@ describe("Path tool button (fresh-eyes T7)", () => { expect(body).not.toMatch(/exitPathMode\(\);\s*this\.drawingMode = null/); }); - it("a restart on a non-adjacent hex shows a hint", () => { - const body = method("onHexPathDrawClick"); - expect(body).toMatch(/outcome === "restart"[\s\S]*new Notice\(/); + it("a hex-by-hex click away from the end is routed, and the bar says so (no lonely restart dots)", () => { + expect(toolMethod("noteGap")).toMatch(/if \(this\.autoRoute\) return;[\s\S]*hexNeighbors\([\s\S]*this\.hint = /); }); }); -describe("Path tool auto-route (P1)", () => { - it("a click in auto-route mode routes instead of drawing hex by hex", () => { - expect(viewSrc).toMatch(/if \(this\.pathAutoRoute\) \{ await this\.onHexPathRouteClick\(x, y\); return; \}\s*await this\.onHexPathDrawClick\(x, y\);/); +describe("Path tool auto-route (P1, anchored paths)", () => { + it("a click in path mode goes to the path tool (auto-route or hex by hex is its switch)", () => { + expect(viewSrc).toMatch(/if \(this\.drawingMode === "path"\) \{\s*this\.pathTool\.click\(x, y, e, this\.isErasingMode\);\s*return;\s*\}/); }); - it("the route avoids impassable terrain unless the path type or the override says otherwise", () => { - const body = method("onHexPathRouteClick"); - expect(body).toMatch(/pathAvoidsImpassable\(type\)[\s\S]*!this\.routeCrossImpassable/); - expect(body).toMatch(/findRoute\(/); - expect(body).toMatch(/noRouteMessage\(blockedNames\)/); - // Saved as an ordinary chain with undo, so it stays editable. - expect(body).toMatch(/pushPathUndo\([\s\S]*saveSettings\(\)/); + it("a leg avoids impassable terrain unless the type's explicit field or Cross impassable says otherwise", () => { + const body = toolMethod("legAnchors"); + expect(body).toMatch(/this\.plugin\.paths\.styleOf\(this\.map, typeName\)/); + expect(body).toMatch(/this\.crossImpassable && style\.avoid/); + // a crossing is kept by pinning it with anchors the normal router reproduces + expect(body).toMatch(/anchorsFor\(through\.hexes, routeFnFor\(router, style\)/); + expect(body).toMatch(/noRouteMessage\(/); }); - it("bounds come from the map's grid", () => { - const body = method("onHexPathRouteClick"); - expect(body).toMatch(/maxX: map\.gridOffset\.x \+ map\.gridSize\.cols - 1/); - expect(body).toMatch(/maxY: map\.gridOffset\.y \+ map\.gridSize\.rows - 1/); + it("edits are saved through the map store with one undo step, behind the edit gate", () => { + const body = toolMethod("commit"); + expect(body).toMatch(/canEditPaths\(map, action\)/); + expect(body).toMatch(/this\.plugin\.mapStore\.setPaths\(map, next\)/); + expect(body).toMatch(/this\.host\.pushUndo\(map, before, clonePaths\(next\)\)/); + // nothing else in the tool writes paths + expect(toolSrc.match(/mapStore\.setPaths\(/g)!.length).toBe(2); // commit + applySnapshot + expect(toolMethod("applySnapshot")).toMatch(/canEditPaths\(mapName, "history"\)/); }); }); describe("Path tool right-click and tokens (fresh-eyes T2)", () => { - it("right-click on a hex of the path being drawn removes it instead of opening the menu", () => { + it("right-click on an anchor handle deletes it; on a path the menu gets that path's actions", () => { const start = viewSrc.indexOf('"contextmenu",'); const handler = viewSrc.slice(start, viewSrc.indexOf("{ capture: true }", start)); - expect(handler).toMatch(/this\.drawingMode === "path"[\s\S]*pathChainWithHex\([\s\S]*onHexPathDeleteClick\(hexX, hexY, this\.activePathTypeName\)[\s\S]*return;[\s\S]*showPainterContextMenu/); - }); - - it("the delete only touches chains of the given path type", () => { - expect(method("onHexPathDeleteClick")).toMatch(/typeName !== null && chains\[ci\]\.typeName !== typeName\) continue/); + expect(handler).toMatch(/this\.drawingMode === "path"[\s\S]*this\.pathTool\.contextMenu\(e\)[\s\S]*"handled" in r\) return;[\s\S]*showPainterContextMenu\(e\.clientX, e\.clientY, hexX, hexY, pathItems\)/); + const menu = toolMethod("contextMenu"); + for (const label of ["Split here", "Delete path: ", "Rename…", "Change type…", "Reverse"]) expect(menu).toContain(label); + expect(menu).toMatch(/hit\.anchor !== null\) \{\s*this\.deleteAnchor\(/); }); it("tokens let clicks through while a drawing tool is active", () => { @@ -96,10 +87,12 @@ describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => expect(toolModeLabel({ mode: "terrain", erasing: false, terrainPick: true })).toMatch(/^Picking terrain/); expect(toolModeLabel({ mode: "icon", erasing: false, iconName: "bw-castle.svg" })).toBe("Painting icon: bw-castle"); expect(toolModeLabel({ mode: "icon", erasing: false, iconName: "x.png", iconGmOnly: true })).toBe("Painting GM icon: x"); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road" })).toBe("Drawing Road: click neighbouring hexes"); - expect(toolModeLabel({ mode: "path", erasing: true })).toMatch(/^Erasing paths/); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathAuto: true })).toBe("Auto-routing Road: click the start hex"); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathAuto: true, pathHasStart: true })).toBe("Auto-routing Road: click where it goes"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road" })).toBe("Road: click to start a path · click a path to edit it"); + expect(toolModeLabel({ mode: "path", erasing: true })).toMatch(/^Erasing paths: click a path to split it/); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathAuto: true, pathDrawing: true, pathSelected: "King's Road" })).toBe("King's Road: click to add (auto-routes) · Esc to finish"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathDrawing: true, pathNote: "not next to the end, so the gap was routed" })).toBe("New Road: click to add (hex by hex) · Esc to finish · not next to the end, so the gap was routed"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathSelected: "King's Road", pathSummary: "Road, 2 forks" })).toBe("King's Road (Road, 2 forks): drag the line to reshape · click an end to continue · click the line to fork"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathNew: true })).toBe("New Road: click where it starts"); expect(toolModeLabel({ mode: "regionLink", erasing: false, regionPath: "world/regions/Kerrigan.md" })).toBe("Painting region: Kerrigan"); expect(toolModeLabel({ mode: "factionLink", erasing: true })).toBe("Erasing factions"); expect(toolModeLabel({ mode: "tableLink", erasing: false, tablePath: "world/tables/ocean.md" })).toBe("Linking table: ocean"); @@ -138,13 +131,26 @@ describe("Hex right-click menu offers Enter submap (fresh-eyes N3)", () => { }); }); -describe("Path chain upkeep (fresh-eyes T7/T2 follow-up)", () => { - it("a restart drops the abandoned one-hex start (never drawn, would linger in the data)", () => { - expect(method("onHexPathDrawClick")).toMatch(/abandoned && abandoned\.hexes\.length === 1[\s\S]*pathChains\.splice\(i, 1\)/); +describe("Path tool upkeep (anchored paths)", () => { + it("a path or fork started by one click isn't stored until its second anchor (no one-hex leftovers)", () => { + const click = toolMethod("click"); + expect(click).toMatch(/this\.pending = \{ kind: "new", hex: key \}/); + expect(click).not.toMatch(/commit\(/); + expect(toolMethod("append")).toMatch(/p\.branches\[0\]\.anchors\.push\(\.\.\.leg\)[\s\S]*this\.commit\(/); + }); + + it("Esc steps out one level (drag → branch → selection) before leaving the tool; Backspace deletes an anchor", () => { + expect(viewSrc).toMatch(/this\.drawingMode === "path" && !this\.isErasingMode && this\.pathTool\.escape\(\)\) return false;\s*this\.exitCurrentMode\(\);/); + expect(toolMethod("escape")).toMatch(/this\.drag[\s\S]*cancelDrag[\s\S]*this\.done\(\)/); + expect(viewSrc).toMatch(/for \(const key of \["Backspace", "Delete"\]\)[\s\S]{0,200}this\.pathTool\.deleteKey\(\)/); }); - it("removing the end of the path being drawn steps the end back one hex", () => { - expect(method("onHexPathDeleteClick")).toMatch(/const stepBack = pos === chain\.hexes\.length && chain\.hexes\.length > 0;/); + it("a drag previews without saving and commits once on release; dropping it back cancels", () => { + expect(toolMethod("updatePreview")).toMatch(/this\.plugin\.paths\.setPreview\(this\.map, d\.preview\)/); + expect(toolMethod("updatePreview")).not.toMatch(/commit\(/); + expect(toolMethod("dragEnd")).toMatch(/if \(d\.lastHex !== d\.startHex && d\.preview\) this\.commit\(d\.preview\);/); + // one reroute per animation frame, only on entering a new hex + expect(toolMethod("dragMove")).toMatch(/hex === d\.lastHex\) return;[\s\S]*requestAnimationFrame/); }); }); From a7bcd5205bc7277cbc9ac1c0511d9011456f0d85 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 19:58:51 -0400 Subject: [PATCH 235/558] =?UTF-8?q?fix(overworld):=20owner=20playtest=20fi?= =?UTF-8?q?xes=20=E2=80=94=20blank=20bricks,=20work=20modes,=20refresh,=20?= =?UTF-8?q?arrow=20nav?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Regions (bricks) view draws only the regions plus blank brick outlines for slots with no region; the overworld's own hexes, coordinates, names and badges are hidden there. Hover names the region (grid tooltip). 2. Minimal per-map work mode (Play / Build / God), stored as `mode:` in the map note, default Build, always shown on the toolbar. One rule: reshaping a placed region (biome swap, Reroll, Settings apply) needs God (reshapeGate / canReshape). Confirm dialogs removed; locked buttons are disabled with "Switch to God to change a placed biome." 3. A change to any region map (paint, generate, reroll, hand edit of its map note) drops its cached bitmap in every view, whatever map the view shows; empty bitmaps built before map data/palettes load never stick. 4. Biome changes redraw both views and the minimap/flower; the view switch says which view is on. 5. Map nav is glyphs only, fixed order ← ↑ → (with a new Forward + Alt+→ + command); region neighbours are a small hex flower, world-grid neighbours a ◀ ▲ ▼ ▶ pad, names in tooltips. "Next to (n)" is gone. 6. The mode bar names region-hex painting in the Regions view. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +- package.json | 4 +- src/HexmakerPlugin.ts | 10 + src/hex-map/BiomeModals.ts | 69 ++++--- src/hex-map/HexMapView.ts | 318 ++++++++++++++++++++---------- src/hex-map/help.md | 16 +- src/hex-map/overworldLayer.ts | 56 +++++- src/hex-map/overworldMinimap.ts | 8 +- src/hex-map/toolMode.ts | 6 +- src/maps/mapNav.ts | 121 ++++++++++++ src/maps/mapNote.ts | 2 + src/overworld/overworldChanges.ts | 41 ++++ src/overworld/overworldRender.ts | 6 +- src/overworld/regionsVault.ts | 22 ++- src/types.ts | 3 + src/workMode.ts | 49 +++++ styles.css | 157 ++++++++++++++- tests/mapNav.test.ts | 71 +++++++ tests/overworldChanges.test.ts | 55 ++++++ tests/toolMode.test.ts | 26 ++- tests/workMode.test.ts | 84 ++++++++ 21 files changed, 955 insertions(+), 180 deletions(-) create mode 100644 src/maps/mapNav.ts create mode 100644 src/overworld/overworldChanges.ts create mode 100644 src/workMode.ts create mode 100644 tests/mapNav.test.ts create mode 100644 tests/overworldChanges.test.ts create mode 100644 tests/workMode.test.ts diff --git a/README.md b/README.md index f7121deb..6574b8f1 100644 --- a/README.md +++ b/README.md @@ -118,12 +118,14 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which. The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. -**Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and the crumbs next to the map button name all six neighbours by direction ("North-east: Fenmarch"). A new region is made from a short form: biome (the hex's terrain is its biome), blend, how wiggly the borders are, and a seed, with a live preview of the region against its neighbours. It blends with the overworld around it, and the hexes along its edges are pinned to the regions already made, so seams line up whatever order you make them in. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. +**Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and a small hex flower on the toolbar shows all six neighbours in their directions (hover a petal for its name, click to go there; empty petals have no region yet). A new region is made from a short form: biome (the hex's terrain is its biome), blend, how wiggly the borders are, and a seed, with a live preview of the region against its neighbours. It blends with the overworld around it, and the hexes along its edges are pinned to the regions already made, so seams line up whatever order you make them in. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: -- **Regions** (the full view): every region's own hexes, drawn small and stitched together over the overworld. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Painted hexes are locked, so remaking a region keeps them. -- **Biomes**: one biome per hex, labelled, with transitions outlined. Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, after asking, since that replaces its generated terrain; **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. +- **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Painted hexes are locked, so remaking a region keeps them. +- **Biomes**: one biome per hex, labelled, with transitions outlined. Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. + +**Work modes: Play, Build, God.** Each map has a work mode, always shown on the toolbar next to the map button; click it to switch. It's saved in the map note as a plain `mode:` property (`play`, `build` or `god`), so each map opens in its own mode; new maps are in Build. For now one rule is enforced: changing what's already placed on an overworld (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs God. In Build and Play those buttons are greyed out with "Switch to God to change a placed biome." There are no confirm boxes for these any more: the mode is the safety catch. Placing a biome on an empty hex isn't locked, note text is never locked, and settings and palettes aren't either. Which biome a hex is comes from its terrain's **Type**, never its name: forest-type terrains are temperate forest, wetland swamp, and so on. Where a type has variants, the **last** terrains of that type in the palette stand for them, in this order: forest → taiga, deep forest; grassland → savanna; hills → karst; wetland → river delta. Reorder the palette to choose (on Expanded: evergreen, evergreen heavy, savanna, jungle hills, river delta). A terrain with no type has no biome. @@ -131,7 +133,7 @@ A small **minimap** of the overworld (bottom right) shows on the overworld and o **Neighbouring maps.** In **Maps → New map…**, **Next to** makes the new map a region beside an existing one (same size and palette, lined up hex for hex); **Properties → New region here…** opens the form already placed. The generators marked *Continues … edge* (Overland and learned generators) carry the neighbour's terrain on across the shared border, and the preview shows the neighbour's edge faded around the new map. Region detail is only offered for submaps, since it zooms into a parent hex. -**Shared coordinates.** Neighbouring regions number their hexes on one grid, so a hex number is unique across the world: the map east of a 20-column map that starts at 0 starts at column 20. The placement note shows the range ("Hexes 20, 0 to 39, 13"). Maps joined before this, or two existing maps linked in **Properties → Neighbouring regions**, keep their own numbers; nothing is renamed. Next to the map button, the neighbouring regions show as crumbs named by side ("Thornwood ▾ East: Cole's Ford"); click one to go there. Inside a submap, the crumbs offer its parent's neighbours ("beside Thornwood: South: Cole's Ford"), one click away. A road or river that ends on a region's edge, next to the end of the neighbour's path of the same type, is drawn on to the shared edge on both maps so they join. +**Shared coordinates.** Neighbouring regions number their hexes on one grid, so a hex number is unique across the world: the map east of a 20-column map that starts at 0 starts at column 20. The placement note shows the range ("Hexes 20, 0 to 39, 13"). Maps joined before this, or two existing maps linked in **Properties → Neighbouring regions**, keep their own numbers; nothing is renamed. After the map button and the ← ↑ → arrows (back, parent, forward: always in that order, hover for the map each goes to), the neighbouring regions show as a small ◀ ▲ ▼ ▶ pad, one button per side, greyed out where there's no neighbour; hover for the name, click to go there. Inside a submap, the pad goes to its parent's neighbours, one click away. A road or river that ends on a region's edge, next to the end of the neighbour's path of the same type, is drawn on to the shared edge on both maps so they join. Generators only change hexes when a map is created or regenerated; you can always repaint by hand afterwards. @@ -289,6 +291,7 @@ Every command, as it appears in the command palette: | **Hexmap World Creator: New overworld…** | A map of biomes (World biomes) whose hexes open into regions that join up; can make every region at once. Advanced: Regions and overworlds. | | **Hexmap World Creator: Go up to parent map** | From a submap, back to the map it belongs to. | | **Hexmap World Creator: Go back to previous map** | Returns to the map you were on before. | +| **Hexmap World Creator: Go forward to the next map** | After going back, forward again (like a browser). | | **Hexmap World Creator: Add map data to this map's hex notes** | Adds a Map data box (terrain, region, name, from the map) under the title of every hex note of the open map, kept up to date when you open a hex. New hex notes from the built-in template already have one. | | **Hexmap World Creator: Update map data in region and faction notes** | Adds or updates a Map data box under the title of every region and faction note: the maps that use it (with hex counts) and, for regions, the encounter table. Kept up to date when you open the note. | | **Hexmap World Creator: Export current map…** | Opens the map export form (PNG, PDF, hexcrawl manual). | diff --git a/package.json b/package.json index c9537bbc..7085670d 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index d7caa043..3ec64853 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -277,6 +277,16 @@ export default class HexmakerPlugin extends Plugin { return true; }, }); + this.addCommand({ + id: "map-go-forward", + name: "Go forward to the next map", + checkCallback: (checking) => { + const view = this.app.workspace.getActiveViewOfType(HexMapView); + if (!view?.canNavigateForward()) return false; + if (!checking) view.navigateForward(); + return true; + }, + }); this.addCommand({ id: "open-random-tables", name: "Open random tables", diff --git a/src/hex-map/BiomeModals.ts b/src/hex-map/BiomeModals.ts index ea9c7ece..1601b7e8 100644 --- a/src/hex-map/BiomeModals.ts +++ b/src/hex-map/BiomeModals.ts @@ -3,10 +3,10 @@ * hex's BIOME, one hex at a time, and its region is made or remade from it. * * - BiomePickerModal: click an overworld hex (biomes view) → pick a biome. - * On a hex with no region yet that makes the region (always allowed). On - * a hex whose region exists it remakes it, after a confirm (canReshape: - * the one gate work modes / God mode will plug into). Reroll and - * Settings… live here too. + * On a hex with no region yet that makes the region (Build and God). On + * a hex whose region exists it remakes it: God mode only (reshapeGate, + * src/workMode.ts), with no confirm; in Build/Play those buttons are + * disabled and say how to unlock them. Reroll and Settings… live here too. * - RegionGenModal: a small generator editor for one region (biome, blend, * variation, seed) with a live preview drawn like the overworld preview * page; Apply makes or remakes the region. @@ -15,7 +15,6 @@ import { App, Notice } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; -import { ConfirmModal } from "../worldgen/ConfirmModal"; import { regionMapAt } from "../maps/submaps"; import { BIOMES, biomeForTerrain, representableBiomes, representativeTerrain, type BiomeId } from "../overworld/biomes"; import { REGION_WARP, type BlendWidth } from "../overworld/blendField"; @@ -23,14 +22,15 @@ import { regionCells } from "../overworld/layout"; import { composeAffine, drawRegionCells, cellsBox, type RegionCell } from "../overworld/overworldRender"; import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; import { - canReshape, createRegion, overworldOf, planRegionAt, regenerateRegion, + reshapeGate, setBiomeAt, type RegionGenOptions, } from "../overworld/regionsVault"; +import { RESHAPE_LOCKED_HINT } from "../workMode"; export interface BiomeHost { app: App; @@ -43,13 +43,17 @@ export interface BiomeHost { made?(name: string): void; } -const RESHAPE_TEXT = - "This replaces the region's generated terrain. Hexes you painted by hand in that region stay (they're locked); anything else you changed there is lost."; +/** Whether hex (px, py)'s region may be remade now (no region yet, or the map is in God mode). */ +export function mayReshape(host: BiomeHost, parentName: string, px: number, py: number): boolean { + return reshapeGate(host.plugin, parentName, px, py) === "allowed"; +} -/** Run `go` if reshaping hex (px, py)'s region is allowed, asking first when it would replace one. */ -export function withReshape(host: BiomeHost, parentName: string, px: number, py: number, what: string, go: () => void): void { - if (canReshape(host.plugin, parentName, px, py) === "allowed") { go(); return; } - new ConfirmModal(host.app, what, RESHAPE_TEXT, "Replace", go).open(); +/** Mark a button as locked by the work mode: disabled, with the hint as its tooltip. */ +function lockButton(btn: HTMLButtonElement): void { + btn.disabled = true; + btn.addClass("is-locked"); + btn.setAttr("title", RESHAPE_LOCKED_HINT); + btn.setAttr("aria-label", `${btn.getText()} (${RESHAPE_LOCKED_HINT})`); } /** The biomes this overworld's palette can paint, with the terrain each paints. */ @@ -80,33 +84,36 @@ export class BiomePickerModal extends HexmakerModal { const region = regionMapAt(plugin.settings.maps, this.parentName, hex); this.titleEl.setText(`Hex ${this.px}, ${this.py}`); const { contentEl } = this; + const locked = !mayReshape(this.host, this.parentName, this.px, this.py); contentEl.createEl("p", { cls: "setting-item-description", - text: region - ? `Region: ${plugin.mapLabel(region.name)}. Picking another biome remakes it.` - : "No region yet. Pick a biome and its region is made, blending with its neighbours.", + text: !region ? "No region yet. Pick a biome and its region is made, blending with its neighbours." + : locked ? `Region: ${plugin.mapLabel(region.name)}.` + : `Region: ${plugin.mapLabel(region.name)}. Picking another biome remakes it (hand-painted hexes stay).`, }); + if (locked) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: RESHAPE_LOCKED_HINT }); const grid = contentEl.createDiv({ cls: "duckmage-biome-grid" }); for (const b of paintableBiomes(plugin, this.parentName)) { const btn = grid.createEl("button", { cls: "duckmage-biome-option" + (b.id === current ? " is-active" : ""), attr: { title: `Paints ${b.terrain}` } }); btn.createSpan({ cls: "duckmage-biome-swatch" }).setCssProps({ "--duckmage-biome-color": b.color }); btn.createSpan({ text: b.label }); + if (locked && b.id !== current) lockButton(btn); btn.addEventListener("click", () => { if (b.id === current && region) return; - withReshape(this.host, this.parentName, this.px, this.py, `Make ${plugin.mapLabel(region?.name ?? "this region")} ${b.label.toLowerCase()}?`, () => { - this.close(); - void this.apply(b.id); - }); + if (!mayReshape(this.host, this.parentName, this.px, this.py)) return; + this.close(); + void this.apply(b.id); }); } const row = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); if (region) { row.createEl("button", { text: "Enter region" }).addEventListener("click", () => { this.close(); this.host.enter(region.name); }); - row.createEl("button", { text: "Reroll" }).addEventListener("click", () => { - withReshape(this.host, this.parentName, this.px, this.py, `Reroll ${plugin.mapLabel(region.name)}?`, () => { - this.close(); - void regenerateRegion(plugin, region.name, { seed: newSeed() }).then(() => this.host.changed()); - }); + const reroll = row.createEl("button", { text: "Reroll" }); + if (locked) lockButton(reroll); + reroll.addEventListener("click", () => { + if (!mayReshape(this.host, this.parentName, this.px, this.py)) return; + this.close(); + void regenerateRegion(plugin, region.name, { seed: newSeed() }).then(() => this.host.changed()); }); } row.createEl("button", { text: "Settings…" }).addEventListener("click", () => { @@ -198,11 +205,15 @@ export class RegionGenModal extends HexmakerModal { const row = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); row.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); - row.createEl("button", { text: region ? "Apply" : "Make region", cls: "mod-cta" }).addEventListener("click", () => { - withReshape(this.host, this.parentName, this.px, this.py, `Remake ${plugin.mapLabel(region?.name ?? "this region")}?`, () => { - this.close(); - void this.apply(); - }); + const apply = row.createEl("button", { text: region ? "Apply" : "Make region", cls: "mod-cta" }); + if (!mayReshape(this.host, this.parentName, this.px, this.py)) { + lockButton(apply); + row.createSpan({ cls: "duckmage-locked-hint", text: RESHAPE_LOCKED_HINT }); + } + apply.addEventListener("click", () => { + if (!mayReshape(this.host, this.parentName, this.px, this.py)) return; + this.close(); + void this.apply(); }); this.redraw(); } diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 7a063b9a..5129ef4e 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -29,6 +29,8 @@ import { import { MapModal } from "./MapModal"; import { mapAncestors } from "./submapNav"; import { ancestorNeighbourCrumbs, neighbourCrumbs } from "../maps/mapTree"; +import { flowerPetals, MapHistory, navArrows, PAD_SIDES } from "../maps/mapNav"; +import { WORK_MODES, WORK_MODE_TEXT, workModeOf, type WorkMode } from "../workMode"; import { pathClickOutcome, toolModeLabel } from "./toolMode"; import { openNoteFocused } from "../openNote"; import { coordHaloColor } from "../coordStyle"; @@ -74,8 +76,8 @@ import { OverworldLayer } from "./overworldLayer"; import { OverworldMinimap } from "./overworldMinimap"; import { BiomePickerModal, type BiomeHost } from "./BiomeModals"; import { regionHome } from "../overworld/regionsVault"; +import { overworldRefreshFor } from "../overworld/overworldChanges"; import { parentOf as parentOfCell } from "../overworld/layout"; -import { regionNeighbourMaps } from "../overworld/regionWorld"; import { RegionNavigateModal } from "./RegionNavigateModal"; import { neighbourShadow } from "../worldgen/neighbours"; import { TokenInfoModal } from "./TokenInfoModal"; @@ -383,10 +385,13 @@ export class HexMapView extends ItemView { /** Set when another view/window mutated shared state while this view was * inactive; consumed by a re-render on next activation (issue #32). */ private needsRerender = false; - private mapHistory: string[] = []; + /** Back / Forward between maps, like a browser. */ + private history = new MapHistory(); private mapBtn: HTMLButtonElement | null = null; - private backBtn: HTMLButtonElement | null = null; - private upBtn: HTMLButtonElement | null = null; + /** ← ↑ →: always in that order, glyphs only (see mapNav.ts). */ + private navArrowsEl: HTMLElement | null = null; + /** The map's work mode (Play / Build / God), always shown. */ + private workModeBtn: HTMLButtonElement | null = null; private crumbsEl: HTMLElement | null = null; /** Sideways crumbs: the neighbouring regions of the open map. */ private sideCrumbsEl: HTMLElement | null = null; @@ -534,23 +539,34 @@ export class HexMapView extends ItemView { this.undoStack = []; this.redoStack = []; this.updateUndoButton(); - if (opts.recordHistory !== false) { - this.mapHistory.push(this.activeMapName); - if (this.mapHistory.length > 50) this.mapHistory.shift(); - } + if (opts.recordHistory !== false) this.history.visit(this.activeMapName); this.switchToMap(name); } /** Back to the previously viewed map (skips maps deleted since). */ navigateBack(): boolean { - while (this.mapHistory.length > 0) { - const prev = this.mapHistory.pop()!; - if (!this.plugin.getMap(prev) || prev === this.activeMapName) continue; - this.navigateToMap(prev, { recordHistory: false }); - return true; + const prev = this.history.goBack(this.activeMapName, (m) => !!this.plugin.getMap(m)); + if (!prev) { + this.refreshMapNav(); + return false; } - this.refreshMapNav(); - return false; + this.navigateToMap(prev, { recordHistory: false }); + return true; + } + + /** Forward again after Back. */ + navigateForward(): boolean { + const next = this.history.goForward(this.activeMapName, (m) => !!this.plugin.getMap(m)); + if (!next) { + this.refreshMapNav(); + return false; + } + this.navigateToMap(next, { recordHistory: false }); + return true; + } + + canNavigateForward(): boolean { + return this.history.peekForward(this.activeMapName, (m) => !!this.plugin.getMap(m)) !== undefined; } /** Up to the map this one is a submap of, flashing the hex we came from. */ @@ -629,11 +645,7 @@ export class HexMapView extends ItemView { /** The map Back would go to (skips maps deleted since and the current one). */ private previousMapName(): string | undefined { - for (let i = this.mapHistory.length - 1; i >= 0; i--) { - const m = this.mapHistory[i]; - if (m !== this.activeMapName && this.plugin.getMap(m)) return m; - } - return undefined; + return this.history.peekBack(this.activeMapName, (m) => !!this.plugin.getMap(m)); } canNavigateUp(): boolean { @@ -668,35 +680,10 @@ export class HexMapView extends ItemView { this.applyTransform(); } - /** Breadcrumb (ancestors), Up and Back buttons for the active map. */ + /** Breadcrumb (ancestors), the ← ↑ → arrows and the neighbour widget for the active map. */ private refreshMapNav(): void { - // Both buttons name the map they go to (fresh-eyes T4: "↑ up" vs - // "← back" wasn't self-explanatory): Parent = the map this one is a - // submap of; Previous = the map viewed before this one (like a browser). - const prev = this.previousMapName(); - if (this.backBtn) { - if (prev) { - this.backBtn.show(); - const label = `Back to the previous map: ${this.plugin.mapLabel(prev)} (Alt+←)`; - this.backBtn.title = label; - this.backBtn.setAttr("aria-label", label); - } else { - this.backBtn.hide(); - } - } - - const parent = this.plugin.parentOf(this.activeMapName); - if (this.upBtn) { - if (parent) { - this.upBtn.show(); - const label = `Up to the parent map: ${this.plugin.mapLabel(parent.map)}, hex ${hexKeyCoords(parent.hex)} (Alt+↑)`; - this.upBtn.title = label; - this.upBtn.setAttr("aria-label", label); - } else { - this.upBtn.hide(); - } - } - + this.refreshNavArrows(); + this.refreshWorkModeBtn(); this.refreshSideCrumbs(); const crumbs = this.crumbsEl; if (!crumbs) return; @@ -715,68 +702,149 @@ export class HexMapView extends ItemView { crumbs.toggle(ancestors.length > 0); } - /** Sideways crumbs (X3): the regions next to the open map, one click away. */ + /** + * ← back, ↑ parent, → forward: glyphs only, always in that order. When + * any applies all three show (the others disabled) so they never shift; + * the target map is in the tooltip. + */ + private refreshNavArrows(): void { + const el = this.navArrowsEl; + if (!el) return; + el.empty(); + const parent = this.plugin.parentOf(this.activeMapName); + const arrows = navArrows({ + back: this.previousMapName(), + up: parent?.map, + forward: this.history.peekForward(this.activeMapName, (m) => !!this.plugin.getMap(m)), + }); + el.toggle(arrows.length > 0); + for (const a of arrows) { + const label = !a.target + ? { back: "Back (no previous map)", up: "Up (no parent map)", forward: "Forward (nothing to go forward to)" }[a.id] + : a.id === "back" ? `Back to ${this.plugin.mapLabel(a.target)} (Alt+←)` + : a.id === "up" ? `Up to ${this.plugin.mapLabel(a.target)}, hex ${hexKeyCoords(parent!.hex)} (Alt+↑)` + : `Forward to ${this.plugin.mapLabel(a.target)} (Alt+→)`; + const btn = el.createEl("button", { + cls: `duckmage-map-nav-arrow duckmage-map-${a.id}-btn`, + text: a.glyph, + attr: { title: label, "aria-label": label, "data-nav": a.id }, + }); + btn.disabled = !a.target; + btn.addEventListener("click", () => { + if (a.id === "back") this.navigateBack(); + else if (a.id === "up") this.navigateUp(); + else this.navigateForward(); + }); + } + } + + /** The work-mode switch: names the map's mode; click to pick another. */ + private refreshWorkModeBtn(): void { + const btn = this.workModeBtn; + if (!btn) return; + const mode = workModeOf(this.plugin.getMap(this.activeMapName)); + const text = WORK_MODE_TEXT[mode]; + btn.setText(text.label); + btn.removeClass("is-play", "is-build", "is-god"); + btn.addClass(`is-${mode}`); + const tip = `Mode: ${text.label}. ${text.desc} Click to change.`; + btn.setAttr("title", tip); + btn.setAttr("aria-label", tip); + } + + private openWorkModeMenu(e: MouseEvent): void { + const map = this.plugin.getMap(this.activeMapName); + if (!map) return; + const cur = workModeOf(map); + const menu = new Menu(); + for (const m of WORK_MODES) { + menu.addItem((item) => + item + .setTitle(`${WORK_MODE_TEXT[m].label}: ${WORK_MODE_TEXT[m].desc}`) + .setChecked(m === cur) + .onClick(() => this.setWorkMode(m)), + ); + } + menu.showAtMouseEvent(e); + } + + /** Switch the open map's work mode (saved in its map note as `mode:`). */ + setWorkMode(mode: WorkMode): void { + const map = this.plugin.getMap(this.activeMapName); + if (!map || workModeOf(map) === mode) return; + map.workMode = mode; + void this.plugin.saveSettings(); + this.refreshWorkModeBtn(); + } + + /** + * The neighbours of the open map, one click away, always in the same + * places: a hex flower for a region of an overworld (its six neighbouring + * regions, empty petals where there's none yet), a d-pad for maps on a + * world grid. Names are in the tooltips, not on the bar. + */ private refreshSideCrumbs(): void { const el = this.sideCrumbsEl; if (!el) return; el.empty(); const maps = this.plugin.settings.maps; - // A region of an overworld: its neighbours are the regions of its parent - // hex's six neighbours, named by true bearing ("North-east: Fenmarch"). const home = regionHome(this.plugin, this.activeMapName); if (home) { - const near = regionNeighbourMaps(maps, home.overworld.name, home.layout, home.px, home.py); - const word = (b: string) => b[0].toUpperCase() + b.slice(1); - if (near.length <= 2) { - for (const n of near) { - const title = `Neighbouring region to the ${n.bearing}: ${this.plugin.mapLabel(n.map.name)}`; - el.createEl("button", { - cls: "duckmage-map-crumb duckmage-map-side-crumb", - text: `${word(n.bearing)}: ${this.plugin.mapLabel(n.map.name)}`, - attr: { title, "aria-label": title, "data-side": n.bearing }, - }).addEventListener("click", () => this.navigateToMap(n.map.name)); - } - } else { - // Up to six neighbours: one crumb that lists them, so the bar stays short. - const btn = el.createEl("button", { - cls: "duckmage-map-crumb duckmage-map-side-crumb", - text: `Next to (${near.length}) ▾`, - attr: { title: "The regions around this one", "aria-label": "The regions around this one" }, - }); - btn.addEventListener("click", (e) => { - const menu = new Menu(); - for (const n of near) { - menu.addItem((item) => item.setTitle(`${word(n.bearing)}: ${this.plugin.mapLabel(n.map.name)}`).onClick(() => this.navigateToMap(n.map.name))); - } - menu.showAtMouseEvent(e); + const petals = flowerPetals(home.layout.orientation, home.layout.parentStagger, home.px, home.py); + const palette = this.plugin.getMapPalette(home.overworld.name); + const flower = el.createDiv({ cls: "duckmage-region-flower", attr: { role: "group", "aria-label": "Neighbouring regions" } }); + const R = 12; // px from the middle to a petal's centre + const here = flower.createSpan({ cls: "duckmage-region-flower-petal is-here", attr: { title: `Here: ${this.plugin.mapLabel(this.activeMapName)}` } }); + here.setCssProps({ "--duckmage-petal-x": "0px", "--duckmage-petal-y": "0px" }); + for (const p of petals) { + const key = `${p.hex[0]}_${p.hex[1]}`; + const region = regionMapAt(maps, home.overworld.name, key); + const terrain = this.plugin.mapStore.get(home.overworld.name, key)?.terrain; + const colour = terrain ? palette.find((t) => t.name === terrain)?.color : undefined; + const word = p.bearing[0].toUpperCase() + p.bearing.slice(1); + const title = region ? `${word}: ${this.plugin.mapLabel(region.name)}` : `${word}: no region yet`; + const petal = flower.createEl("button", { + cls: "duckmage-region-flower-petal" + (region ? "" : " is-empty"), + attr: { title, "aria-label": title, "data-side": p.bearing }, }); + petal.setCssProps({ "--duckmage-petal-x": `${(p.dx * R).toFixed(1)}px`, "--duckmage-petal-y": `${(p.dy * R).toFixed(1)}px` }); + if (colour && region) petal.setCssProps({ "--duckmage-petal-bg": colour }); + if (region) petal.addEventListener("click", () => this.navigateToMap(region.name)); + else petal.disabled = true; } - el.toggle(near.length > 0); + el.show(); return; } let side = neighbourCrumbs(this.plugin.getMap(this.activeMapName), maps); let via: string | null = null; if (side.length === 0) { - // A submap: offer its parent's neighbours too ("beside Thornwood: South: Cole's Ford"). + // A submap: its parent's neighbours (round 6: one click, not two). const up = ancestorNeighbourCrumbs(this.activeMapName, maps, (m) => this.plugin.parentOf(m)?.map); if (up) { via = up.via; side = up.crumbs; - el.createSpan({ cls: "duckmage-map-side-via", text: `beside ${this.plugin.mapLabel(via)}:` }); } } - for (const c of side) { - const title = via - ? `Neighbouring region to the ${c.side} of ${this.plugin.mapLabel(via)}: ${this.plugin.mapLabel(c.name)}` - : `Neighbouring region to the ${c.side}: ${this.plugin.mapLabel(c.name)}`; - const crumb = el.createEl("button", { - cls: "duckmage-map-crumb duckmage-map-side-crumb", - text: c.text, - attr: { title, "aria-label": title, "data-side": c.side }, + if (!side.length) { + el.hide(); + return; + } + const pad = el.createDiv({ cls: "duckmage-map-pad", attr: { role: "group", "aria-label": "Neighbouring maps" } }); + for (const { side: s, glyph } of PAD_SIDES) { + const c = side.find((x) => x.side === s); + const word = s[0].toUpperCase() + s.slice(1); + const title = !c ? `${word}: nothing there` + : via ? `${word} of ${this.plugin.mapLabel(via)}: ${this.plugin.mapLabel(c.name)}` + : `${word}: ${this.plugin.mapLabel(c.name)}`; + const btn = pad.createEl("button", { + cls: `duckmage-map-pad-btn is-${s}`, + text: glyph, + attr: { title, "aria-label": title, "data-side": s }, }); - crumb.addEventListener("click", () => this.navigateToMap(c.name)); + if (c) btn.addEventListener("click", () => this.navigateToMap(c.name)); + else btn.disabled = true; } - el.toggle(side.length > 0); + el.show(); } public switchMapFromModal(name: string): void { @@ -829,6 +897,11 @@ export class HexMapView extends ItemView { e.preventDefault(); return false; }); + this.scope.register(["Alt"], "ArrowRight", (e: KeyboardEvent) => { + if (!this.navigateForward()) return; + e.preventDefault(); + return false; + }); // clipEl clips the panning viewport; controlsEl overlays buttons without clipping const clipEl = contentEl.createDiv({ cls: "duckmage-hex-map-clip" }); @@ -907,7 +980,8 @@ export class HexMapView extends ItemView { // current terrain (painting doesn't re-render the grid). this.registerDomEvent(clipEl, "mouseover", (e: MouseEvent) => { const hexEl = (e.target as HTMLElement | null)?.closest(".duckmage-hex[data-x]"); - if (hexEl) this.labelHex(hexEl); + // Regions view: the grid's own tooltip names the region under the pointer. + if (hexEl && !hexEl.closest(".duckmage-ow-regions")) this.labelHex(hexEl); }); // ── Zoom (scroll wheel, no modifier required) ────────────────────────── @@ -1304,7 +1378,9 @@ export class HexMapView extends ItemView { title: "Manage maps", }); this.updateMapBtnLabel(); - // Neighbouring regions sit right after the map button: "map ▾ ← west east →". + // ← ↑ → right after the map button, then the neighbours (flower / d-pad). + this.navArrowsEl = mapNavGroup.createDiv({ cls: "duckmage-map-nav-arrows" }); + this.navArrowsEl.hide(); this.sideCrumbsEl = mapNavGroup.createDiv({ cls: "duckmage-map-crumbs duckmage-map-side-crumbs" }); this.sideCrumbsEl.hide(); this.mapBtn.addEventListener("click", () => @@ -1321,19 +1397,8 @@ export class HexMapView extends ItemView { }).open(), ); - this.upBtn = mapNavGroup.createEl("button", { - cls: "duckmage-map-up-btn", - text: "↑ parent map", - }); - this.upBtn.hide(); - this.upBtn.addEventListener("click", () => this.navigateUp()); - - this.backBtn = mapNavGroup.createEl("button", { - cls: "duckmage-map-back-btn", - text: "← previous map", - }); - this.backBtn.hide(); - this.backBtn.addEventListener("click", () => this.navigateBack()); + this.workModeBtn = mapNavGroup.createEl("button", { cls: "duckmage-work-mode-btn" }); + this.workModeBtn.addEventListener("click", (e) => this.openWorkModeMenu(e)); this.refreshMapNav(); this.undoBtn = controlsEl.createEl("button", { @@ -2633,6 +2698,7 @@ export class HexMapView extends ItemView { erasing: this.isErasingMode, terrainName: this.paintTerrainName, terrainPick: this.terrainPickMode, + regionHexes: OverworldLayer.viewOf(this.plugin, this.getActiveMap()) === "regions", iconName: this.paintIconName, iconGmOnly: this.paintIconGmOnly, pathTypeName: this.activePathTypeName, @@ -3907,6 +3973,28 @@ export class HexMapView extends ItemView { const gridContainer = this.viewportEl.createDiv({ cls: `duckmage-hex-map-grid${isFlat ? " duckmage-grid-flat" : ""}`, }); + // An overworld's Regions view shows only the regions (and blank bricks + // where there's none yet): its own hexes stay as invisible click + // targets, and their coordinates, names and badges are hidden (owner + // playtest: "just show blank bricks rather than the hex one behind"). + const regionsView = owView === "regions"; + if (regionsView) { + gridContainer.addClass("duckmage-ow-regions"); + // The region's name on hover, nothing drawn on the map. + let pending = false; + gridContainer.addEventListener("mousemove", (e) => { + if (pending) return; + pending = true; + window.requestAnimationFrame(() => { + pending = false; + const cell = this.overworldLayer.cellAt(gridContainer, e.clientX, e.clientY); + const tip = !cell ? "" + : cell.region ? `${this.plugin.mapLabel(cell.region)}: click to go there` + : `No region yet (hex ${cell.parentHex.replace("_", ", ")}): click to set its biome`; + if (gridContainer.title !== tip) gridContainer.title = tip; + }); + }); + } else if (owView === "biomes") gridContainer.addClass("duckmage-ow-biomes"); // Apply optional independent grid transform (used for bg-image calibration). // Custom-property values default to identity in CSS when unset, so we @@ -3960,6 +4048,14 @@ export class HexMapView extends ItemView { }); hexEl.tabIndex = -1; + if (regionsView) { + hexEl.addEventListener("click", (e) => { + void this.onHexClick(x, y, e); + }); + hexEl.addEventListener("contextmenu", (evt) => this.onHexContextMenu(evt, x, y)); + return; + } + this.setHexColor(hexEl, terrainEntry?.color); const iconOverride = iconOverrides?.has(path) @@ -4027,7 +4123,7 @@ export class HexMapView extends ItemView { hexEl.addClass("duckmage-hex-has-region-map"); hexEl.createSpan({ cls: "duckmage-hex-region-outline", - attr: { title: `Region: ${this.plugin.mapLabel(regionMap)} (${owView === "regions" ? "click to enter at that spot" : owView ? "click to set its biome, Ctrl+click to enter" : "Ctrl+click hex to enter"})` }, + attr: { title: `Region: ${this.plugin.mapLabel(regionMap)} (${owView ? "click to set its biome, Ctrl+click to enter" : "Ctrl+click hex to enter"})` }, }); } if (locations.length) { @@ -4136,6 +4232,9 @@ export class HexMapView extends ItemView { this.renderNeighbourShadow(gridContainer, region); this.overworldLayer.render(gridContainer, region); this.minimap.render(this.contentEl, region); + // The view switch or a hand-edited `mode:` may have changed what the bars say. + this.updateModeBar(); + this.refreshWorkModeBtn(); this.renderPathOverlay(gridContainer); this.renderRegionOverlay(gridContainer); this.renderFactionOverlay(gridContainer); @@ -5143,15 +5242,18 @@ export class HexMapView extends ItemView { */ private onOverworldDataChange(map: string): void { const active = this.getActiveMap(); - const changed = this.plugin.getMap(map); - if (changed?.submapKind === "region" && changed.parent?.map === active.name) this.overworldLayer.invalidate(map); - if (map === active.name) this.overworldLayer.scheduleRedraw(); const home = regionHome(this.plugin, active.name); - if (map === active.name || map === home?.overworld.name) { + const r = overworldRefreshFor(this.plugin.getMap(map) ?? { name: map }, active.name, home?.overworld.name); + // Any region, whatever this view shows: its bitmap is cached here too. + if (r.invalidate) this.overworldLayer.invalidate(r.invalidate); + if (r.redrawLayer) this.overworldLayer.scheduleRedraw(); + if (r.refreshMinimap) { if (this.minimapTimer !== null) window.clearTimeout(this.minimapTimer); this.minimapTimer = window.setTimeout(() => { this.minimapTimer = null; this.minimap.render(this.contentEl, this.getActiveMap()); + // The region flower's petals are coloured by the overworld's biomes. + this.refreshSideCrumbs(); }, 300); } } diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 51873a7a..213b28d1 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -28,14 +28,18 @@ Hexes with locations show a small ring at the top, with a count once there are t | **Click the ring**, or **Ctrl/Cmd+click** the hex | Enter the hex's region, or its location (the list when there are several) | | **Ctrl/Cmd+Shift+click** the hex | Open it in a new tab | | Hex editor **Maps** strip | The region chip (outlined) and one chip per location; **+** for a new map, linking one, or the locations list | -| **↑ up** button / **Alt+↑** | Back up to the parent map; the hex you came from flashes | -| **← back** button / **Alt+←** | Return to the previously viewed map | +| **←** / **Alt+←** | Back to the map you were on before | +| **↑** / **Alt+↑** | Up to the parent map; the hex you came from flashes | +| **→** / **Alt+→** | Forward again after going back | | Breadcrumb (top left) | Jump to any map above this one | -| Crumbs after the map button ("East: Cole's Ford") | Jump to a neighbouring region. Inside a submap they show its parent's neighbours ("beside Thornwood: South: Cole's Ford") | +| Small hex flower after the arrows (a region of an overworld) | The six regions around this one, each in its direction. Hover a petal for its name, click to go there. Empty petals have no region yet | +| **◀ ▲ ▼ ▶** after the arrows (neighbouring maps) | Go to the map on that side; hover for its name. Inside a submap they go to its parent's neighbours | + +The arrows are always ← ↑ → in that order; one that doesn't apply right now is greyed out. Hover any of them for the map it goes to. **Region settings.** The first region you make on a map asks once how its regions cover its hexes: **Hex flower** (a hex of 7, 19, 37, 61 or 91 hexes) or **Rectangle** (6×6, 8×8, 10×10 or your own size), the palette, and how far neighbouring regions blend. They stay in the map menu's **Regions** tab, which also lists the regions. Shape, size and palette are fixed once a region exists, so every region lines up; delete the regions to change them. Blend stays editable and applies to regions made afterwards. -"Go up to parent map" and "Go back to previous map" are also commands, so you can bind your own hotkeys. A palette can suggest the palette for its submaps with a `child-palette:` line in its note's frontmatter. *Space - Sector* suggests *Space - System*. +"Go up to parent map", "Go back to previous map" and "Go forward to the next map" are also commands, so you can bind your own hotkeys. A palette can suggest the palette for its submaps with a `child-palette:` line in its note's frontmatter. *Space - Sector* suggests *Space - System*. --- @@ -119,7 +123,9 @@ Tokens show their name underneath. The layers panel's **Labels** group turns coo Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. -**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view: **Regions** shows every region's hexes stitched together (click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (click to set one: an empty hex gets its region, a hex with one has it remade after asking). The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. +**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (click to set one: an empty hex gets its region). The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. + +**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards one thing: changing what's already placed on an overworld (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**. In Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex isn't locked (Play will lock more later). Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. diff --git a/src/hex-map/overworldLayer.ts b/src/hex-map/overworldLayer.ts index 56493197..eb943fbe 100644 --- a/src/hex-map/overworldLayer.ts +++ b/src/hex-map/overworldLayer.ts @@ -6,6 +6,9 @@ * that region's map changes or the zoom moves a lot), and the layer is just * those bitmaps copied into place. * + * Slots with no region yet are drawn as blank bricks (outline only): the + * overworld's own hexes aren't shown in this view at all. + * * In the "biomes" view the same canvas carries the preview's minimap marks * over the overworld's own hexes instead: biome labels, white outlines on * transition hexes, the river. @@ -58,10 +61,26 @@ interface RegionBitmap { box: { x: number; y: number; w: number; h: number }; } +/** Cache name of the one bitmap holding every empty slot ("blank bricks"). */ +const BLANK = "*blank slots*"; +/** Empty slots: a faint fill and a light outline, so they read on light and dark themes. */ +const BLANK_FILL = "rgba(128, 128, 128, 0.10)"; +const BLANK_EDGE = "rgba(128, 128, 128, 0.55)"; + /** Largest composite canvas side and area (device px): beyond it the layer drops resolution. */ const MAX_SIDE = 8192; const MAX_AREA = 24e6; +/** The overworld hexes (its whole grid) that have no region yet, in reading order. */ +export function blankSlots(map: Pick, taken: ReadonlySet): [number, number][] { + const out: [number, number][] = []; + const { x: ox, y: oy } = map.gridOffset, { cols, rows } = map.gridSize; + for (let y = oy; y < oy + rows; y++) { + for (let x = ox; x < ox + cols; x++) if (!taken.has(`${x}_${y}`)) out.push([x, y]); + } + return out; +} + export class OverworldLayer { readonly cache = new RegionBitmapCache(); private geom: Geometry | null = null; @@ -128,10 +147,9 @@ export class OverworldLayer { this.draw(); } - /** A region's map changed: rebuild its bitmap on the next draw. */ + /** A region's map changed: rebuild its bitmap on the next draw (callers redraw when it's on screen). */ invalidate(regionName: string): void { this.cache.invalidate(regionName); - this.scheduleRedraw(); } /** The overworld itself changed (biomes view): redraw. */ @@ -194,14 +212,27 @@ export class OverworldLayer { private drawRegions(canvas: HTMLCanvasElement, geom: Geometry, map: MapData): void { const regions = regionsOf(this.plugin.settings.maps, map.name); - this.cache.retain(new Set(regions.map((r) => r.name))); + this.cache.retain(new Set([...regions.map((r) => r.name), BLANK])); const k0 = geom.pxScale; const bitmaps: RegionBitmap[] = []; let cells = 0; + const geoKey = `${k0.toFixed(3)}|${geom.c2g.map((v) => v.toFixed(2)).join(",")}`; + // Built before the map data and palettes were loaded (startup, plugin + // reload), a region bitmap is empty: never let that one stick. + const loaded = this.plugin.mapStore.isReady() && this.plugin.paletteStore.isReady() ? "ready" : "loading"; + // Slots with no region yet: blank bricks (just their outline), one + // bitmap for all of them, rebuilt when a region is made or removed. + const taken = new Set(regions.map((r) => r.parent!.hex)); + const empty = blankSlots(map, taken); + if (empty.length) { + const blankKey = `${geoKey}|${empty.map(([x, y]) => `${x}_${y}`).join(",")}`; + const blank = this.cache.get(BLANK, blankKey, () => this.buildBlank(empty, geom, k0)); + if (blank.canvas) bitmaps.push(blank); + } for (const r of regions) { const [px, py] = r.parent!.hex.split("_").map(Number); const palette = this.plugin.getMapPalette(r.name); - const key = `${k0.toFixed(3)}|${geom.c2g.map((v) => v.toFixed(2)).join(",")}|${palette.map((t) => t.color).join("")}`; + const key = `${geoKey}|${loaded}|${r.baseTerrain ?? ""}|${palette.map((t) => t.color).join("")}`; const bmp = this.cache.get(r.name, key, () => this.buildRegion(r, px, py, geom, k0)); cells += regionCells(geom.layout, px, py).length; if (bmp.canvas) bitmaps.push(bmp); @@ -243,6 +274,23 @@ export class OverworldLayer { return { canvas, box }; } + /** Every empty slot's outline in one bitmap. */ + private buildBlank(slots: [number, number][], geom: Geometry, k: number): RegionBitmap { + const all = slots.flatMap(([px, py]) => regionCells(geom.layout, px, py).map(([x, y]) => ({ x, y }))); + const box = cellsBox(geom.layout, all, geom.c2g); + const canvas = createEl("canvas"); + canvas.width = Math.max(1, Math.ceil(box.w * k)); + canvas.height = Math.max(1, Math.ceil(box.h * k)); + const ctx = canvas.getContext("2d"); + if (!ctx) return { canvas: null, box }; + const toBitmap = composeAffine(geom.c2g, [k, 0, 0, k, -box.x * k, -box.y * k]); + for (const [px, py] of slots) { + const cells = regionCells(geom.layout, px, py).map(([x, y]) => ({ x, y, color: BLANK_FILL })); + drawRegionCells(ctx, geom.layout, cells, toBitmap, { seamColour: BLANK_EDGE, seamWidth: 0.12 }); + } + return { canvas, box }; + } + /** The biomes view: the preview minimap's marks over the overworld's own hexes. */ private drawBiomes(canvas: HTMLCanvasElement, geom: Geometry, map: MapData): void { const { x: ox, y: oy } = map.gridOffset, { cols, rows } = map.gridSize; diff --git a/src/hex-map/overworldMinimap.ts b/src/hex-map/overworldMinimap.ts index 7ae83f9d..1498e5d9 100644 --- a/src/hex-map/overworldMinimap.ts +++ b/src/hex-map/overworldMinimap.ts @@ -51,11 +51,13 @@ export class OverworldMinimap { this.el = box; if (t.isOverworld) { const sw = box.createDiv({ cls: "duckmage-ow-view-toggle", attr: { role: "group", "aria-label": "Overworld view" } }); + sw.createSpan({ cls: "duckmage-ow-view-label", text: "View:" }); for (const [id, label, tip] of [ - ["regions", "Regions", "Every region's hexes, stitched together. Click to enter a region; the terrain tool paints its hexes."], - ["biomes", "Biomes", "One biome per hex. Click a hex to set its biome; its region is made or remade from it."], + ["regions", "Regions", "Every region's hexes, stitched together (blank bricks where there's none yet). Click to enter a region; the terrain tool paints its hexes."], + ["biomes", "Biomes", "One biome per hex. Click a hex to set its biome: a hex with no region gets one; changing a placed one needs God mode."], ] as const) { - const b = sw.createEl("button", { text: label, cls: view === id ? "is-active" : "", attr: { title: tip } }); + const on = view === id; + const b = sw.createEl("button", { text: label, cls: on ? "is-active" : "", attr: { title: on ? `${tip} (showing now)` : tip, "aria-pressed": on ? "true" : "false" } }); b.addEventListener("click", () => { if (view === id) return; map.overworldView = id; diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts index f34cf051..f29623e7 100644 --- a/src/hex-map/toolMode.ts +++ b/src/hex-map/toolMode.ts @@ -38,6 +38,8 @@ export interface ToolModeState { erasing: boolean; terrainName?: string | null; terrainPick?: boolean; + /** An overworld's Regions view: the terrain tool paints the regions' own hexes. */ + regionHexes?: boolean; iconName?: string | null; iconGmOnly?: boolean; pathTypeName?: string | null; @@ -69,8 +71,8 @@ export function toolModeLabel(s: ToolModeState): string | null { return null; case "terrain": if (s.terrainPick) return "Picking terrain: click a hex to copy its terrain"; - if (erasing || !s.terrainName) return "Clearing terrain"; - return `Painting terrain: ${s.terrainName}`; + if (erasing || !s.terrainName) return s.regionHexes ? "Clearing region hexes" : "Clearing terrain"; + return s.regionHexes ? `Painting region hexes: ${s.terrainName}` : `Painting terrain: ${s.terrainName}`; case "icon": { const what = s.iconGmOnly ? "GM icon" : "icon"; if (erasing || !s.iconName) return `Erasing ${what}s`; diff --git a/src/maps/mapNav.ts b/src/maps/mapNav.ts new file mode 100644 index 00000000..e5ea0961 --- /dev/null +++ b/src/maps/mapNav.ts @@ -0,0 +1,121 @@ +/** + * Map navigation in the toolbar, the pure part (owner playtest 2026-10-10): + * + * - Back / Up / Forward are arrow glyphs only, always ← ↑ → in that order. + * When any of them applies all three show (the others disabled) so they + * never move around; the map each goes to is in its tooltip. + * - A region of an overworld gets a small hex flower: itself in the middle, + * the regions of its six neighbouring overworld hexes around it, each in + * its fixed direction (empty petals where there's no region yet). + * - Maps on a world grid get the same idea with four sides (a d-pad). + * + * Pure: no Obsidian imports. + */ + +import { hexCenter, hexNeighbors, type Orientation, type Stagger } from "../../packages/hex-wfc/src/grid"; +import { bearingWord } from "../overworld/regionWorld"; + +export type NavArrowId = "back" | "up" | "forward"; + +export interface NavArrow { + id: NavArrowId; + glyph: "←" | "↑" | "→"; + /** The map it goes to (undefined: not available now, shown disabled). */ + target?: string; +} + +const ARROWS: [NavArrowId, NavArrow["glyph"]][] = [["back", "←"], ["up", "↑"], ["forward", "→"]]; + +/** The three arrows in their fixed order, or [] when none applies. */ +export function navArrows(t: { back?: string; up?: string; forward?: string }): NavArrow[] { + if (!t.back && !t.up && !t.forward) return []; + return ARROWS.map(([id, glyph]) => ({ id, glyph, target: t[id] })); +} + +/** Browser-style map history: Back and Forward stacks. */ +export class MapHistory { + private back: string[] = []; + private fwd: string[] = []; + + constructor(private limit = 50) {} + + /** A normal move from `from`: remember it for Back; Forward is cleared. */ + visit(from: string): void { + this.back.push(from); + if (this.back.length > this.limit) this.back.shift(); + this.fwd = []; + } + + /** The map Back goes to (skipping `current` and maps that are gone), without moving. */ + peekBack(current: string, exists: (m: string) => boolean): string | undefined { + return peek(this.back, current, exists); + } + + peekForward(current: string, exists: (m: string) => boolean): string | undefined { + return peek(this.fwd, current, exists); + } + + /** Step back from `current`: returns the map to show, and puts `current` on Forward. */ + goBack(current: string, exists: (m: string) => boolean): string | undefined { + return step(this.back, this.fwd, current, exists, this.limit); + } + + goForward(current: string, exists: (m: string) => boolean): string | undefined { + return step(this.fwd, this.back, current, exists, this.limit); + } +} + +function peek(stack: string[], current: string, exists: (m: string) => boolean): string | undefined { + for (let i = stack.length - 1; i >= 0; i--) { + if (stack[i] !== current && exists(stack[i])) return stack[i]; + } + return undefined; +} + +function step(from: string[], to: string[], current: string, exists: (m: string) => boolean, limit: number): string | undefined { + while (from.length) { + const m = from.pop()!; + if (m === current || !exists(m)) continue; + to.push(current); + if (to.length > limit) to.shift(); + return m; + } + return undefined; +} + +export interface FlowerPetal { + /** Compass word for the direction ("north-east"). */ + bearing: string; + /** The neighbouring overworld hex. */ + hex: [number, number]; + /** Unit offset from the middle on screen (y down). */ + dx: number; + dy: number; +} + +/** + * The six petals around overworld hex (px, py), clockwise from the one + * nearest north. Same order and places for every hex of a map (the stagger + * changes which hex is which, not where its petal sits). + */ +export function flowerPetals(orientation: Orientation, stagger: Stagger, px: number, py: number): FlowerPetal[] { + const [cx, cy] = hexCenter(px, py, orientation, stagger); + const out = hexNeighbors(px, py, orientation, stagger).map(([qx, qy]) => { + const [x, y] = hexCenter(qx, qy, orientation, stagger); + const len = Math.hypot(x - cx, y - cy) || 1; + const dx = (x - cx) / len, dy = (y - cy) / len; + // Clockwise from north; a hair of slack so the petal at -30° sorts first. + const angle = (Math.atan2(dx, -dy) + 2 * Math.PI + 1e-6) % (2 * Math.PI); + return { bearing: bearingWord(dx, dy), hex: [qx, qy] as [number, number], dx, dy, angle }; + }); + out.sort((a, b) => a.angle - b.angle); + return out.map(({ bearing, hex, dx, dy }) => ({ bearing, hex, dx, dy })); +} + +/** The four sides of a world-grid map, always in this order (a d-pad: ◀ ▲ ▼ ▶). */ +export const PAD_SIDES = [ + { side: "west", glyph: "◀" }, + { side: "north", glyph: "▲" }, + { side: "south", glyph: "▼" }, + { side: "east", glyph: "▶" }, +] as const; diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index 11d7ecfb..42d4a0f0 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -335,6 +335,8 @@ const SIMPLE_KEYS: [keyof MapSettings, string, Kind, string[]?][] = [ ["regionSeed", "region-seed", "num"], ["overworldView", "overworld-view", "str"], ["showMinimap", "show-minimap", "bool"], + // Work mode: play, build or god (src/workMode.ts). + ["workMode", "mode", "str"], ["biomeRiver", "biome-river", "str"], ["showCoords", "show-coords", "bool"], ["showTerrainIcons", "show-terrain-icons", "bool"], diff --git a/src/overworld/overworldChanges.ts b/src/overworld/overworldChanges.ts new file mode 100644 index 00000000..55f8ad58 --- /dev/null +++ b/src/overworld/overworldChanges.ts @@ -0,0 +1,41 @@ +/** + * What an open map view must redraw when a map's data changes (owner + * playtest 2026-10-10: "the parent map doesn't refresh when you paint a + * child"). Pure: no Obsidian imports. + * + * A region's bitmap is cached by every view's overworld layer, whatever map + * that view shows right now, so a change to ANY region map drops its bitmap + * everywhere: painting it, generating or rerolling it, or editing its map + * note by hand. Otherwise going back up to the overworld showed the old one. + */ + +export interface ChangedMapInfo { + name: string; + submapKind?: string; + parent?: { map: string; hex: string }; +} + +export interface OverworldRefresh { + /** Region whose cached bitmap is stale (rebuilt on the next draw). */ + invalidate?: string; + /** Redraw the open map's overworld layer now (its regions or biome marks changed). */ + redrawLayer: boolean; + /** Redraw the minimap and the region flower (the overworld behind them changed). */ + refreshMinimap: boolean; +} + +export function overworldRefreshFor( + changed: ChangedMapInfo | undefined, + activeName: string, + /** The overworld the open map is a region of, if it is one. */ + homeOverworld: string | undefined, +): OverworldRefresh { + const parentMap = changed?.submapKind === "region" ? changed.parent?.map : undefined; + const isRegion = parentMap !== undefined; + const name = changed?.name; + return { + invalidate: isRegion ? name : undefined, + redrawLayer: name === activeName || parentMap === activeName, + refreshMinimap: !!name && (name === activeName || name === homeOverworld), + }; +} diff --git a/src/overworld/overworldRender.ts b/src/overworld/overworldRender.ts index fdd0ff9d..7256f52e 100644 --- a/src/overworld/overworldRender.ts +++ b/src/overworld/overworldRender.ts @@ -198,7 +198,7 @@ export function drawRegionCells( layout: RegionLayout, cells: RegionCell[], toCanvas: Affine, - opts: { seams?: boolean } = {}, + opts: { seams?: boolean; seamColour?: string; seamWidth?: number } = {}, ): void { const s = affineScale(toCanvas); const own = new Set(cells.map((c) => `${c.x}_${c.y}`)); @@ -210,8 +210,8 @@ export function drawRegionCells( ctx.fill(); } if (opts.seams === false) return; - ctx.strokeStyle = SEAM_COLOUR; - ctx.lineWidth = Math.max(1, s * 0.18); + ctx.strokeStyle = opts.seamColour ?? SEAM_COLOUR; + ctx.lineWidth = Math.max(1, s * (opts.seamWidth ?? 0.18)); for (const c of cells) { const [ax, ay] = childPoint(layout, c.x, c.y); for (const [nx, ny] of childNeighbours(layout, c.x, c.y)) { diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index ae9dd051..e414497e 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -17,6 +17,7 @@ import { regionMapAt } from "../maps/submaps"; import { biomeProfiles, representativeTerrain, type BiomeId, type BiomeProfile } from "./biomes"; import { regionCells, type RegionLayout } from "./layout"; import type { BlendWidth } from "./blendField"; +import { canReshape, RESHAPE_LOCKED_HINT } from "../workMode"; import { defaultRegionName, dominantTerrain, @@ -256,14 +257,15 @@ export function regionBlockKeys(layout: RegionLayout, px: number, py: number): s // ── reshaping: set a biome, regenerate, reroll ─────────────────────────── /** - * Whether reshaping a hex's region (repainting its biome, rerolling, - * regenerating) may go ahead, and how. The single gate for work modes - * (plan-work-modes: God mode) to plug into later. Today: making a region - * for the first time is always allowed; replacing an existing region's - * generated terrain asks first. + * Whether reshaping hex (px, py)'s region (swapping its biome, rerolling, + * regenerating, applying region settings) may go ahead. Making a region + * for the first time is allowed in Build and God; changing one that's + * already there needs the map in God mode (src/workMode.ts). No confirm: + * the mode is the safety catch. */ -export function canReshape(plugin: HexmakerPlugin, parentName: string, px: number, py: number): "allowed" | "confirm" { - return regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`) ? "confirm" : "allowed"; +export function reshapeGate(plugin: HexmakerPlugin, parentName: string, px: number, py: number): "allowed" | "locked" { + if (!regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`)) return "allowed"; + return canReshape(plugin.getMap(parentName)) ? "allowed" : "locked"; } /** @@ -274,6 +276,7 @@ export function canReshape(plugin: HexmakerPlugin, parentName: string, px: numbe export async function regenerateRegion(plugin: HexmakerPlugin, regionName: string, opts: RegionGenOptions = {}): Promise { const region = plugin.getMap(regionName); if (region?.submapKind !== "region" || !region.parent) return 0; + if (!canReshape(plugin.getMap(region.parent.map))) return 0; // see reshapeGate const [px, py] = region.parent.hex.split("_").map(Number); const plan = planRegionAt(plugin, region.parent.map, px, py, opts); if (!plan) return 0; @@ -291,8 +294,8 @@ export async function regenerateRegion(plugin: HexmakerPlugin, regionName: strin /** * Set an overworld hex's biome: paint it with the biome's terrain on the * overworld's palette (the terrain IS the biome signal), then make its - * region (first placement) or regenerate it (callers confirm first; see - * canReshape). Returns the region's name, or an error. + * region (first placement) or regenerate it (God mode only; see + * reshapeGate). Returns the region's name, or an error. */ export async function setBiomeAt( plugin: HexmakerPlugin, @@ -307,6 +310,7 @@ export async function setBiomeAt( const terrain = representativeTerrain(biome, plugin.getMapPalette(parentName)); if (!terrain) return { error: "This map's palette has no terrain for that biome." }; const hex = `${px}_${py}`; + if (reshapeGate(plugin, parentName, px, py) === "locked") return { error: RESHAPE_LOCKED_HINT }; if (plugin.mapStore.get(parentName, hex)?.terrain !== terrain) { plugin.mapStore.set(parentName, hex, { terrain }); await plugin.mapStore.flush(); diff --git a/src/types.ts b/src/types.ts index b2d1bf2d..4402ced4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -203,6 +203,9 @@ export interface MapData { overworldView?: "regions" | "biomes"; /** Overworlds and their regions: the small overworld panel. Unset = shown. */ showMinimap?: boolean; + /** Work mode (Play / Build / God, src/workMode.ts), as written in the + * map note (`mode: god`). Unset = Build. */ + workMode?: string; /** Overworlds made by World biomes: the river's hexes, source to mouth, * as "x,y > x,y > …" (biome data drawn on the overworld; not a path). */ biomeRiver?: string; diff --git a/src/workMode.ts b/src/workMode.ts new file mode 100644 index 00000000..c6028415 --- /dev/null +++ b/src/workMode.ts @@ -0,0 +1,49 @@ +/** + * Work modes, per map (owner round 4, WM1–WM4): Play · Build · God. + * + * Stored readably in the map note (`mode: build`); a map opens in the mode + * saved with it, default Build. This first pass enforces ONE rule: + * canReshape() — changing what's already placed on an overworld (swapping a + * placed biome, Reroll, regenerating, applying region settings to an + * existing region) needs God. Placing a biome on an empty hex is allowed in + * Build and God. Note text is never locked, and settings and palettes + * aren't either (WM2, WM4). The rest of the modes plan (per-mode undo, + * other locks) is still to come. + * + * Pure: no Obsidian imports. + */ + +export type WorkMode = "play" | "build" | "god"; + +export const WORK_MODES: readonly WorkMode[] = ["play", "build", "god"]; + +export const DEFAULT_WORK_MODE: WorkMode = "build"; + +export const WORK_MODE_TEXT: Record = { + play: { label: "Play", desc: "Run a game: look around and move. Notes stay editable." }, + build: { label: "Build", desc: "Add to the map. Things already placed stay as they are." }, + god: { label: "God", desc: "Change anything, including placed biomes, rerolls and regenerating." }, +}; + +/** The hint on a locked reshape action. */ +export const RESHAPE_LOCKED_HINT = "Switch to God to change a placed biome."; + +/** A map note's `mode:` value, read forgivingly ("God mode", "BUILD", "player"); unknown → undefined. */ +export function parseWorkMode(raw: unknown): WorkMode | undefined { + if (typeof raw !== "string") return undefined; + const t = raw.trim().toLowerCase(); + if (/^god/.test(t)) return "god"; + if (/^build/.test(t)) return "build"; + if (/^play/.test(t)) return "play"; + return undefined; +} + +/** The mode a map is in (its saved one, else Build). */ +export function workModeOf(map: { workMode?: string } | undefined): WorkMode { + return parseWorkMode(map?.workMode) ?? DEFAULT_WORK_MODE; +} + +/** May what's already placed on this map be changed (biome swap, reroll, regenerate)? */ +export function canReshape(map: { workMode?: string } | undefined): boolean { + return workModeOf(map) === "god"; +} diff --git a/styles.css b/styles.css index cfb848a9..7b88d1f9 100644 --- a/styles.css +++ b/styles.css @@ -8078,8 +8078,8 @@ button.duckmage-terrain-legend-chip { padding: 2px 8px; border-radius: 0; } -.duckmage-ow-view-toggle button:first-child { border-radius: 4px 0 0 4px; } -.duckmage-ow-view-toggle button:last-child { border-radius: 0 4px 4px 0; } +.duckmage-ow-view-toggle button:first-of-type { border-radius: 4px 0 0 4px; } +.duckmage-ow-view-toggle button:last-of-type { border-radius: 0 4px 4px 0; } .duckmage-ow-view-toggle button.is-active { background: var(--interactive-accent); color: var(--text-on-accent); @@ -8177,3 +8177,156 @@ button.duckmage-terrain-legend-chip { width: 1.8em; height: 1.8em; } + +/* ── Overworld playtest fixes (2026-10-10) ───────────────────────────────── */ + +/* Regions view: only the regions and blank bricks show. The overworld's own + hexes stay as invisible click targets; their coordinates, names and + badges are hidden (the region's name is the grid's tooltip on hover). */ +.duckmage-ow-regions .duckmage-hex { + background: transparent; +} +.duckmage-ow-regions .duckmage-hex:hover::after { + display: none; +} +.duckmage-ow-regions .duckmage-coord-labels-layer, +.duckmage-ow-regions .duckmage-hex-names-layer, +.duckmage-ow-regions .duckmage-link-badges-layer { + display: none; +} + +/* Map navigation: ← ↑ → as glyphs only, always in that order. */ +.duckmage-map-nav-arrows { + display: flex; + gap: 2px; +} +.duckmage-map-nav-arrows .duckmage-map-nav-arrow { + height: 26px; + min-width: 26px; + padding: 0 4px; + font-size: 0.95em; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-muted); + cursor: pointer; +} +.duckmage-map-nav-arrows .duckmage-map-nav-arrow:hover:not(:disabled) { + color: var(--text-normal); + border-color: var(--interactive-accent); +} +.duckmage-map-nav-arrows .duckmage-map-nav-arrow:disabled { + color: var(--text-faint); + opacity: 0.5; + cursor: default; +} + +/* A region's neighbours: a small hex flower, each petal in its direction. */ +.duckmage-region-flower { + position: relative; + width: 36px; + height: 34px; + flex-shrink: 0; +} +.duckmage-region-flower-petal { + position: absolute; + left: calc(50% - 5px + var(--duckmage-petal-x, 0px)); + top: calc(50% - 5px + var(--duckmage-petal-y, 0px)); + width: 10px; + height: 10px; + min-height: 0; + padding: 0; + border-radius: 50%; + box-shadow: none; + border: 1px solid var(--text-faint); + background: var(--duckmage-petal-bg, var(--background-secondary-alt)); + cursor: pointer; +} +.duckmage-region-flower-petal:hover:not(:disabled) { + border-color: var(--interactive-accent); + transform: scale(1.3); + z-index: 1; +} +.duckmage-region-flower-petal.is-here { + background: var(--interactive-accent); + border-color: var(--interactive-accent); + cursor: default; +} +.duckmage-region-flower-petal.is-empty { + background: transparent; + border-style: dashed; + opacity: 0.6; + cursor: default; +} + +/* Maps on a world grid: their four sides as a d-pad (◀ ▲ ▼ ▶), fixed order. */ +.duckmage-map-pad { + display: flex; + gap: 1px; +} +.duckmage-map-pad .duckmage-map-pad-btn { + height: 26px; + min-width: 20px; + padding: 0 3px; + font-size: 0.7em; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-muted); + cursor: pointer; +} +.duckmage-map-pad .duckmage-map-pad-btn:hover:not(:disabled) { + color: var(--text-normal); + border-color: var(--interactive-accent); +} +.duckmage-map-pad .duckmage-map-pad-btn:disabled { + opacity: 0.35; + cursor: default; +} + +/* Work mode (Play / Build / God): always on the toolbar. */ +.duckmage-map-nav-group .duckmage-work-mode-btn { + height: 26px; + padding: 0 8px; + font-size: 0.8em; + font-weight: 600; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-muted); + cursor: pointer; + white-space: nowrap; +} +.duckmage-map-nav-group .duckmage-work-mode-btn.is-play { + color: var(--color-green); + border-color: var(--color-green); +} +.duckmage-map-nav-group .duckmage-work-mode-btn.is-god { + color: var(--text-on-accent); + background: var(--color-orange); + border-color: var(--color-orange); +} + +/* A reshape action locked by the work mode, and the line saying how to unlock it. */ +.duckmage-biome-option.is-locked, +.duckmage-token-modal-buttons button.is-locked { + opacity: 0.45; + cursor: not-allowed; +} +.duckmage-locked-hint { + font-size: 0.85em; + color: var(--text-muted); + margin: 0 0 0.6em; +} +.duckmage-token-modal-buttons .duckmage-locked-hint { + margin: 0; + align-self: center; +} + +/* Overworld view switch: say which one is on. */ +.duckmage-ow-view-label { + font-size: 0.75em; + color: var(--text-muted); + align-self: center; + padding-right: 4px; +} diff --git a/tests/mapNav.test.ts b/tests/mapNav.test.ts new file mode 100644 index 00000000..4056b03c --- /dev/null +++ b/tests/mapNav.test.ts @@ -0,0 +1,71 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { flowerPetals, MapHistory, navArrows, PAD_SIDES } from "../src/maps/mapNav"; + +describe("map nav arrows", () => { + it("are always ← ↑ → in that order, glyphs only, when any applies", () => { + expect(navArrows({})).toEqual([]); + const only = navArrows({ up: "parent" }); + expect(only.map((a) => a.glyph)).toEqual(["←", "↑", "→"]); + expect(only.map((a) => a.target)).toEqual([undefined, "parent", undefined]); + const all = navArrows({ forward: "f", back: "b", up: "u" }); + expect(all.map((a) => a.id)).toEqual(["back", "up", "forward"]); + expect(all.map((a) => a.target)).toEqual(["b", "u", "f"]); + }); + + it("the d-pad's four sides keep one order", () => { + expect(PAD_SIDES.map((s) => s.side)).toEqual(["west", "north", "south", "east"]); + }); +}); + +describe("MapHistory (back and forward)", () => { + const all = () => true; + it("goes back, then forward again, and a new move clears forward", () => { + const h = new MapHistory(); + h.visit("a"); // a → b + h.visit("b"); // b → c + expect(h.peekBack("c", all)).toBe("b"); + expect(h.peekForward("c", all)).toBeUndefined(); + expect(h.goBack("c", all)).toBe("b"); + expect(h.peekForward("b", all)).toBe("c"); + expect(h.goBack("b", all)).toBe("a"); + expect(h.goForward("a", all)).toBe("b"); + expect(h.goForward("b", all)).toBe("c"); + expect(h.goForward("c", all)).toBeUndefined(); + h.goBack("c", all); + h.visit("b"); // b → d + expect(h.peekForward("d", all)).toBeUndefined(); + }); + + it("skips maps deleted since and the open map", () => { + const h = new MapHistory(); + h.visit("a"); + h.visit("gone"); + h.visit("c"); + const exists = (m: string) => m !== "gone"; + expect(h.peekBack("c", exists)).toBe("a"); + expect(h.goBack("c", exists)).toBe("a"); + }); +}); + +describe("region hex flower", () => { + const order = (o: "flat" | "pointy", px: number, py: number) => flowerPetals(o, "odd", px, py).map((p) => p.bearing); + + it("has six petals in fixed directions, clockwise from north, whatever the stagger", () => { + expect(order("flat", 2, 2)).toEqual(["north", "north-east", "south-east", "south", "south-west", "north-west"]); + expect(order("flat", 3, 2)).toEqual(order("flat", 2, 2)); + expect(order("pointy", 2, 2)).toEqual(order("pointy", 2, 3)); + expect(order("pointy", 2, 2)).toHaveLength(6); + expect(new Set(order("pointy", 2, 2)).size).toBe(6); + }); + + it("places each petal one unit from the middle in its direction", () => { + for (const p of flowerPetals("flat", "odd", 1, 1)) { + expect(Math.hypot(p.dx, p.dy)).toBeCloseTo(1, 6); + } + const north = flowerPetals("flat", "odd", 1, 1)[0]; + expect(north.hex).toEqual([1, 0]); + expect(north.dx).toBeCloseTo(0, 6); + expect(north.dy).toBeCloseTo(-1, 6); + }); +}); diff --git a/tests/overworldChanges.test.ts b/tests/overworldChanges.test.ts new file mode 100644 index 00000000..33a5465e --- /dev/null +++ b/tests/overworldChanges.test.ts @@ -0,0 +1,55 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { overworldRefreshFor } from "../src/overworld/overworldChanges"; +import { blankSlots } from "../src/hex-map/overworldLayer"; +import { RegionBitmapCache } from "../src/overworld/overworldRender"; + +const region = { name: "ow-2-2", submapKind: "region", parent: { map: "ow", hex: "2_2" } }; + +describe("overworld refresh when a map changes", () => { + it("a region painted while its overworld is open: drop its bitmap and redraw", () => { + expect(overworldRefreshFor(region, "ow", undefined)).toEqual({ invalidate: "ow-2-2", redrawLayer: true, refreshMinimap: false }); + }); + + it("a region painted while the region itself is open: still drop its bitmap (going back up shows it)", () => { + const r = overworldRefreshFor(region, "ow-2-2", "ow"); + expect(r.invalidate).toBe("ow-2-2"); + expect(r.redrawLayer).toBe(true); + }); + + it("a region painted while another map is open: the bitmap is still dropped", () => { + const r = overworldRefreshFor(region, "somewhere-else", undefined); + expect(r.invalidate).toBe("ow-2-2"); + expect(r.redrawLayer).toBe(false); + }); + + it("the overworld's own biomes changed: redraw it, and the minimap and flower of its regions", () => { + expect(overworldRefreshFor({ name: "ow" }, "ow", undefined)).toEqual({ invalidate: undefined, redrawLayer: true, refreshMinimap: true }); + expect(overworldRefreshFor({ name: "ow" }, "ow-2-2", "ow").refreshMinimap).toBe(true); + }); + + it("a location (not a region) never touches the region bitmaps", () => { + const r = overworldRefreshFor({ name: "town", submapKind: "location", parent: { map: "ow", hex: "1_1" } }, "ow", undefined); + expect(r.invalidate).toBeUndefined(); + }); + + it("an invalidated bitmap is rebuilt on the next draw, the others are reused", () => { + const cache = new RegionBitmapCache(); + let builds = 0; + const get = (n: string) => cache.get(n, "k", () => ++builds); + get("a"); + get("b"); + cache.invalidate("a"); + get("a"); + get("b"); + expect(builds).toBe(3); + }); +}); + +describe("blank bricks", () => { + it("are the overworld hexes with no region, in reading order", () => { + const map = { gridOffset: { x: 0, y: 0 }, gridSize: { cols: 3, rows: 2 } }; + expect(blankSlots(map, new Set(["1_0", "0_1"]))).toEqual([[0, 0], [2, 0], [1, 1], [2, 1]]); + expect(blankSlots(map, new Set(["0_0", "1_0", "2_0", "0_1", "1_1", "2_1"]))).toEqual([]); + }); +}); diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 4322065a..4d906be4 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -90,6 +90,11 @@ describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => expect(toolModeLabel({ mode: null, erasing: false })).toBeNull(); }); + it("names the regions' hexes when painting in an overworld's Regions view", () => { + expect(toolModeLabel({ mode: "terrain", erasing: false, terrainName: "forest", regionHexes: true })).toBe("Painting region hexes: forest"); + expect(toolModeLabel({ mode: "terrain", erasing: true, regionHexes: true })).toBe("Clearing region hexes"); + }); + it("names what each tool is doing", () => { expect(toolModeLabel({ mode: "terrain", erasing: false, terrainName: "forest" })).toBe("Painting terrain: forest"); expect(toolModeLabel({ mode: "terrain", erasing: false, terrainName: null })).toBe("Clearing terrain"); @@ -114,15 +119,18 @@ describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => }); }); -describe("Map navigation buttons say where they go (fresh-eyes T4)", () => { - it("labels Up/Back as parent/previous map and names the target map", () => { - expect(viewSrc).toContain('text: "↑ parent map"'); - expect(viewSrc).toContain('text: "← previous map"'); - const nav = method("refreshMapNav"); - expect(nav).toMatch(/backBtn\.setAttr\("aria-label", label\)/); - expect(nav).toMatch(/upBtn\.setAttr\("aria-label", label\)/); - expect(nav).toMatch(/previous map: \$\{this\.plugin\.mapLabel\(prev\)\}/); - expect(nav).toMatch(/parent map: \$\{this\.plugin\.mapLabel\(parent\.map\)\}/); +describe("Map navigation buttons say where they go (fresh-eyes T4, owner playtest 2026-10-10)", () => { + it("shows arrows only, and names the target map in the tooltip and aria-label", () => { + const nav = method("refreshNavArrows"); + expect(nav).toContain("text: a.glyph"); + expect(nav).toContain('attr: { title: label, "aria-label": label'); + expect(nav).toContain("Back to ${this.plugin.mapLabel(a.target)}"); + expect(nav).toContain("Up to ${this.plugin.mapLabel(a.target)}"); + expect(nav).toContain("Forward to ${this.plugin.mapLabel(a.target)}"); + // Neighbours: a hex flower / d-pad with names in tooltips, no "Next to (6)" text. + const side = method("refreshSideCrumbs"); + expect(side).not.toContain("Next to ("); + expect(side).toContain("flowerPetals("); }); }); diff --git a/tests/workMode.test.ts b/tests/workMode.test.ts new file mode 100644 index 00000000..c0f828ac --- /dev/null +++ b/tests/workMode.test.ts @@ -0,0 +1,84 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { canReshape, parseWorkMode, workModeOf } from "../src/workMode"; +import { reshapeGate, setBiomeAt, regenerateRegion } from "../src/overworld/regionsVault"; +import { buildMapNote, parseMapNote } from "../src/maps/mapNote"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import type { MapData } from "../src/types"; + +describe("work modes (Play / Build / God)", () => { + it("reads the map note's mode forgivingly; anything else is Build", () => { + expect(parseWorkMode("god")).toBe("god"); + expect(parseWorkMode(" God mode ")).toBe("god"); + expect(parseWorkMode("BUILD")).toBe("build"); + expect(parseWorkMode("player")).toBe("play"); + expect(parseWorkMode("chaos")).toBeUndefined(); + expect(parseWorkMode(3)).toBeUndefined(); + expect(workModeOf(undefined)).toBe("build"); + expect(workModeOf({ workMode: "nonsense" })).toBe("build"); + expect(workModeOf({ workMode: "Play" })).toBe("play"); + }); + + it("only God may reshape", () => { + expect(canReshape({ workMode: "god" })).toBe(true); + expect(canReshape({ workMode: "build" })).toBe(false); + expect(canReshape({ workMode: "play" })).toBe(false); + expect(canReshape({})).toBe(false); + }); + + it("is stored in the map note as a plain `mode:` key and read back", () => { + const note = buildMapNote("m", { settings: { paletteName: "Default", workMode: "god" }, hexes: new Map(), paths: [] }); + expect(note).toMatch(/^mode: god$/m); + expect(parseMapNote(note)!.settings.workMode).toBe("god"); + const plain = buildMapNote("m", { settings: { paletteName: "Default" }, hexes: new Map(), paths: [] }); + expect(plain).not.toMatch(/^mode:/m); + }); +}); + +describe("reshape gate on an overworld", () => { + function fakePlugin(mode: string | undefined) { + const overworld = { name: "ow", workMode: mode, gridSize: { cols: 3, rows: 3 }, gridOffset: { x: 0, y: 0 } } as unknown as MapData; + const region = { name: "ow-1-1", submapKind: "region", parent: { map: "ow", hex: "1_1" } } as unknown as MapData; + const writes: string[] = []; + const plugin = { + settings: { maps: [overworld, region] }, + getMap: (n: string) => [overworld, region].find((m) => m.name === n), + getMapPalette: () => DEFAULT_TERRAIN_PALETTE, + mapStore: { + get: () => undefined, + all: () => new Map(), + set: (map: string, key: string) => writes.push(`${map}|${key}`), + setMany: (map: string) => writes.push(map), + flush: async () => {}, + }, + saveSettings: async () => {}, + }; + return { plugin, writes }; + } + + it("first placement on an empty hex is allowed in every mode", () => { + for (const mode of [undefined, "play", "build", "god"]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(reshapeGate(fakePlugin(mode).plugin as any, "ow", 0, 0)).toBe("allowed"); + } + }); + + it("a hex that already has a region can only change in God", () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(reshapeGate(fakePlugin("build").plugin as any, "ow", 1, 1)).toBe("locked"); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(reshapeGate(fakePlugin(undefined).plugin as any, "ow", 1, 1)).toBe("locked"); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(reshapeGate(fakePlugin("god").plugin as any, "ow", 1, 1)).toBe("allowed"); + }); + + it("a locked biome swap or reroll changes nothing and says how to unlock it", async () => { + const { plugin, writes } = fakePlugin("build"); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const res = await setBiomeAt(plugin as any, "ow", 1, 1, "taiga"); + expect(res).toEqual({ error: "Switch to God to change a placed biome." }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(await regenerateRegion(plugin as any, "ow-1-1", { seed: 1 })).toBe(0); + expect(writes).toEqual([]); + }); +}); From 33daac83573f311fff715ffa10971e82273c4ee1 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:04:20 -0400 Subject: [PATCH 236/558] fix(path tool): fresh-eyes fixes: wrap the mode bar text, no 'Road (Road)', bigger handles, list picks centre the path and give new paths a type, stale hint cleared Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 6 ++++++ src/hex-map/pathTool.ts | 8 ++++++++ src/hex-map/toolMode.ts | 2 +- src/paths/pathGeometry.ts | 2 +- styles.css | 13 +++++++++++++ 5 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index d95f3063..8728fd4a 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -2598,6 +2598,9 @@ export class HexMapView extends ItemView { const changed = this.modeBarTextEl.getText() !== (label ?? ""); this.modeBarTextEl.setText(label ?? ""); this.modeBarEl.toggle(label !== null); + // The path tool says more and has more controls: its text wraps instead of being cut off. + this.modeBarEl.toggleClass("is-path", this.drawingMode === "path"); + this.modeBarTextEl.setAttr("title", label ?? ""); if (label === null || !changed) return; // A tool just started or changed: pulse the bar so it's noticed // (round 4: a tester never saw it). The map does NOT move here: a tool @@ -5481,6 +5484,9 @@ export class HexMapView extends ItemView { this.drawingMode = "path"; this.isErasingMode = false; this.pathTool.selectPath(name); + // Show it: the list is for paths that are hard to find on the map. + const first = this.plugin.mapStore.paths(this.activeMapName).find((q) => q.name === name)?.branches[0]?.anchors[0]; + if (first) { const [hx, hy] = first.split("_").map(Number); this.centerOnHex(hx, hy); } this.updateToolbarButtonStates(); this.updatePathOverlay(); }, diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index 0ee002d4..57b62fe9 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -460,6 +460,8 @@ export class PathTool { selectPath(name: string): void { const p = this.pathNamed(name); if (!p) return; + // Picked from the list before any type: new paths take this one. + if (!this.typeName) this.typeName = p.typeName; this.selected = p.name; this.active = null; this.pending = null; @@ -471,6 +473,9 @@ export class PathTool { /** "New path" (mode bar): the next click starts a new path, even on top of another. */ startNewPath(): void { + // No type picked yet (the tool was entered from "Paths on this map"): + // the new path takes the selected one's. + if (!this.typeName) this.typeName = this.currentType(); this.selected = null; this.active = null; this.pending = null; @@ -526,6 +531,8 @@ export class PathTool { case "none": break; case "start": + // No type picked yet: Alt-click beside a selected path takes its type. + if (!this.typeName) this.typeName = this.currentType(); if (!this.typeName) { new Notice("Pick a path type first: click the path button."); return; @@ -747,6 +754,7 @@ export class PathTool { } if (next && this.active && this.active.branch >= next.branches.length) this.active = null; this.hover = null; + this.hint = null; this.host.redraw(); this.host.refreshBar(); } diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts index 80b32f68..2b9b040b 100644 --- a/src/hex-map/toolMode.ts +++ b/src/hex-map/toolMode.ts @@ -76,7 +76,7 @@ export function toolModeLabel(s: ToolModeState): string | null { return `${name}: click to add (${how}) · Esc to finish${note}`; } if (s.pathSelected) { - const what = s.pathSummary ? ` (${s.pathSummary})` : ""; + const what = s.pathSummary && s.pathSummary !== s.pathSelected ? ` (${s.pathSummary})` : ""; return `${s.pathSelected}${what}: drag the line to reshape · click an end to continue · click the line to fork${note}`; } return `${type}: click to start a path · click a path to edit it${note}`; diff --git a/src/paths/pathGeometry.ts b/src/paths/pathGeometry.ts index e586d729..daca4800 100644 --- a/src/paths/pathGeometry.ts +++ b/src/paths/pathGeometry.ts @@ -282,7 +282,7 @@ const DASH_PX: Record = { dashed: [8, 4], dotted: [2, 4] }; export const END_DOT_PX = { r: 5, stroke: 1.5 }; /** The path tool's anchor handles on the selected path: radius (ends bigger) and outline, px at the default zoom. */ -export const HANDLE_PX = { r: 4, end: 6, stroke: 1.5 }; +export const HANDLE_PX = { r: 5, end: 7.5, stroke: 1.5 }; export interface PathStroke { /** MapPath.name and branch index (data-path / data-branch on screen). */ diff --git a/styles.css b/styles.css index 325e77d5..69941d44 100644 --- a/styles.css +++ b/styles.css @@ -8121,3 +8121,16 @@ button.duckmage-terrain-legend-chip { margin-top: 0.3em; color: var(--text-error); } + +/* Path tool: the mode bar text wraps (it has more to say and more controls). */ +.duckmage-hex-map-controls .duckmage-mode-bar.is-path { + border-radius: 0.9em; +} +.duckmage-hex-map-controls .duckmage-mode-bar.is-path .duckmage-mode-bar-text { + white-space: normal; + min-width: 14em; + line-height: 1.25; +} +.duckmage-hex-map-controls .duckmage-mode-bar.is-path .duckmage-mode-bar-hint { + display: none; +} From d0cfcd8b26290866c3ba090c827f5f7eaf7b678f Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:12:10 -0400 Subject: [PATCH 237/558] fix(overworld): Play locks first biome placement; "Region areas" tool; no region outlines in Biomes view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Work modes: canAdd() (Build and God, not Play). A first biome on an empty overworld hex, which makes its region, is locked in Play: the picker greys out with "Switch to Build to place a biome." Enforced underneath too: reshapeLock() gives the hint, setBiomeAt/createRegion/ generateMissingRegions refuse in Play; "Make the missing regions" is locked in Play. Note editing stays unlocked in every mode. - Drawing panel: the region-note tool is now "Region areas" (button, picker title, mode bar "Painting region area: …"), so it no longer clashes with the overworld "Regions" view. README + help updated. - Biomes view: no purple region outline on overworld hexes (every hex has a region); non-overworld maps keep it. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++-- src/hex-map/BiomeModals.ts | 47 +++++++++++++++++------------ src/hex-map/GeoRegionPickerModal.ts | 3 +- src/hex-map/HexMapView.ts | 16 +++++----- src/hex-map/OverworldModals.ts | 8 +++++ src/hex-map/help.md | 5 ++- src/hex-map/toolMode.ts | 5 ++- src/overworld/regionsVault.ts | 31 ++++++++++++------- src/workMode.ts | 28 ++++++++++++----- tests/toolMode.test.ts | 2 +- tests/workMode.test.ts | 34 ++++++++++++++++++--- 11 files changed, 129 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index e4f02bab..8757a659 100644 --- a/README.md +++ b/README.md @@ -123,9 +123,9 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: - **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Painted hexes are locked, so remaking a region keeps them. -- **Biomes**: one biome per hex, labelled, with transitions outlined. Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. +- **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one). Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. -**Work modes: Play, Build, God.** Each map has a work mode, always shown on the toolbar next to the map button; click it to switch. It's saved in the map note as a plain `mode:` property (`play`, `build` or `god`), so each map opens in its own mode; new maps are in Build. For now one rule is enforced: changing what's already placed on an overworld (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs God. In Build and Play those buttons are greyed out with "Switch to God to change a placed biome." There are no confirm boxes for these any more: the mode is the safety catch. Placing a biome on an empty hex isn't locked, note text is never locked, and settings and palettes aren't either. +**Work modes: Play, Build, God.** Each map has a work mode, always shown on the toolbar next to the map button; click it to switch. It's saved in the map note as a plain `mode:` property (`play`, `build` or `god`), so each map opens in its own mode; new maps are in Build. For now two rules are enforced on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs God; in Build and Play those buttons are greyed out with "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region), or making regions at all (**Make the missing regions…**), needs Build or God; in Play the biome picker is greyed out with "Switch to Build to place a biome." There are no confirm boxes for these any more: the mode is the safety catch. Note text is never locked in any mode, and settings and palettes aren't either. Which biome a hex is comes from its terrain's **Type**, never its name: forest-type terrains are temperate forest, wetland swamp, and so on. Where a type has variants, the **last** terrains of that type in the palette stand for them, in this order: forest → taiga, deep forest; grassland → savanna; hills → karst; wetland → river delta. Reorder the palette to choose (on Expanded: evergreen, evergreen heavy, savanna, jungle hills, river delta). A terrain with no type has no biome. @@ -198,7 +198,7 @@ Click the **pencil** icon on the right edge of the map to open the drawing tools | **Link table** | Add the selected random table to the hex's Encounters Table section | — | | **Link submap** | Add the selected map to the hex's locations | Remove that map from the hex (any map, if none is selected) | | **Factions** | Paint a faction colour (drag to paint multiple hexes) | Erase faction from hex | -| **Regions** | Paint a geographic region colour | Erase region from hex | +| **Region areas** | Paint a region note's colour (a geographic area, not a region map) | Erase region from hex | | **Token** | Open the token creator, then click a hex to place the new token | Cancel placement | **Terrain painter extras:** diff --git a/src/hex-map/BiomeModals.ts b/src/hex-map/BiomeModals.ts index 1601b7e8..1c2f32b4 100644 --- a/src/hex-map/BiomeModals.ts +++ b/src/hex-map/BiomeModals.ts @@ -3,10 +3,10 @@ * hex's BIOME, one hex at a time, and its region is made or remade from it. * * - BiomePickerModal: click an overworld hex (biomes view) → pick a biome. - * On a hex with no region yet that makes the region (Build and God). On - * a hex whose region exists it remakes it: God mode only (reshapeGate, - * src/workMode.ts), with no confirm; in Build/Play those buttons are - * disabled and say how to unlock them. Reroll and Settings… live here too. + * On a hex with no region yet that makes the region (Build and God; in + * Play the picker is greyed). On a hex whose region exists it remakes + * it: God mode only (reshapeLock, src/workMode.ts), with no confirm. + * Locked buttons are disabled and say how to unlock them. Reroll and Settings… live here too. * - RegionGenModal: a small generator editor for one region (biome, blend, * variation, seed) with a live preview drawn like the overworld preview * page; Apply makes or remakes the region. @@ -26,11 +26,10 @@ import { overworldOf, planRegionAt, regenerateRegion, - reshapeGate, + reshapeLock, setBiomeAt, type RegionGenOptions, } from "../overworld/regionsVault"; -import { RESHAPE_LOCKED_HINT } from "../workMode"; export interface BiomeHost { app: App; @@ -43,17 +42,22 @@ export interface BiomeHost { made?(name: string): void; } -/** Whether hex (px, py)'s region may be remade now (no region yet, or the map is in God mode). */ +/** Why hex (px, py)'s biome can't be set or its region remade now, or undefined when it can. */ +export function biomeLock(host: BiomeHost, parentName: string, px: number, py: number): string | undefined { + return reshapeLock(host.plugin, parentName, px, py); +} + +/** Whether hex (px, py)'s biome may be set now (first placement in Build/God, a change in God). */ export function mayReshape(host: BiomeHost, parentName: string, px: number, py: number): boolean { - return reshapeGate(host.plugin, parentName, px, py) === "allowed"; + return biomeLock(host, parentName, px, py) === undefined; } /** Mark a button as locked by the work mode: disabled, with the hint as its tooltip. */ -function lockButton(btn: HTMLButtonElement): void { +function lockButton(btn: HTMLButtonElement, hint: string): void { btn.disabled = true; btn.addClass("is-locked"); - btn.setAttr("title", RESHAPE_LOCKED_HINT); - btn.setAttr("aria-label", `${btn.getText()} (${RESHAPE_LOCKED_HINT})`); + btn.setAttr("title", hint); + btn.setAttr("aria-label", `${btn.getText()} (${hint})`); } /** The biomes this overworld's palette can paint, with the terrain each paints. */ @@ -84,20 +88,22 @@ export class BiomePickerModal extends HexmakerModal { const region = regionMapAt(plugin.settings.maps, this.parentName, hex); this.titleEl.setText(`Hex ${this.px}, ${this.py}`); const { contentEl } = this; - const locked = !mayReshape(this.host, this.parentName, this.px, this.py); + const lock = biomeLock(this.host, this.parentName, this.px, this.py); contentEl.createEl("p", { cls: "setting-item-description", - text: !region ? "No region yet. Pick a biome and its region is made, blending with its neighbours." - : locked ? `Region: ${plugin.mapLabel(region.name)}.` + text: !region ? (lock ? "No region yet." : "No region yet. Pick a biome and its region is made, blending with its neighbours.") + : lock ? `Region: ${plugin.mapLabel(region.name)}.` : `Region: ${plugin.mapLabel(region.name)}. Picking another biome remakes it (hand-painted hexes stay).`, }); - if (locked) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: RESHAPE_LOCKED_HINT }); + if (lock) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); const grid = contentEl.createDiv({ cls: "duckmage-biome-grid" }); for (const b of paintableBiomes(plugin, this.parentName)) { const btn = grid.createEl("button", { cls: "duckmage-biome-option" + (b.id === current ? " is-active" : ""), attr: { title: `Paints ${b.terrain}` } }); btn.createSpan({ cls: "duckmage-biome-swatch" }).setCssProps({ "--duckmage-biome-color": b.color }); btn.createSpan({ text: b.label }); - if (locked && b.id !== current) lockButton(btn); + // With a region, its current biome stays clickable (a no-op); with + // none yet, every biome would make one, so all are locked. + if (lock && (b.id !== current || !region)) lockButton(btn, lock); btn.addEventListener("click", () => { if (b.id === current && region) return; if (!mayReshape(this.host, this.parentName, this.px, this.py)) return; @@ -109,7 +115,7 @@ export class BiomePickerModal extends HexmakerModal { if (region) { row.createEl("button", { text: "Enter region" }).addEventListener("click", () => { this.close(); this.host.enter(region.name); }); const reroll = row.createEl("button", { text: "Reroll" }); - if (locked) lockButton(reroll); + if (lock) lockButton(reroll, lock); reroll.addEventListener("click", () => { if (!mayReshape(this.host, this.parentName, this.px, this.py)) return; this.close(); @@ -206,9 +212,10 @@ export class RegionGenModal extends HexmakerModal { const row = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); row.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); const apply = row.createEl("button", { text: region ? "Apply" : "Make region", cls: "mod-cta" }); - if (!mayReshape(this.host, this.parentName, this.px, this.py)) { - lockButton(apply); - row.createSpan({ cls: "duckmage-locked-hint", text: RESHAPE_LOCKED_HINT }); + const lock = biomeLock(this.host, this.parentName, this.px, this.py); + if (lock) { + lockButton(apply, lock); + row.createSpan({ cls: "duckmage-locked-hint", text: lock }); } apply.addEventListener("click", () => { if (!mayReshape(this.host, this.parentName, this.px, this.py)) return; diff --git a/src/hex-map/GeoRegionPickerModal.ts b/src/hex-map/GeoRegionPickerModal.ts index be60a429..f99ca590 100644 --- a/src/hex-map/GeoRegionPickerModal.ts +++ b/src/hex-map/GeoRegionPickerModal.ts @@ -10,6 +10,7 @@ import { type OverlayStyle, } from "../frontmatter"; import { addOverlayPatternControls, renderHexPreview } from "./overlayPatternControls"; +import { REGION_AREAS_TOOL } from "./toolMode"; // ── Region editor sub-modal ─────────────────────────────────────────────────── @@ -146,7 +147,7 @@ export class GeoRegionPickerModal extends HexmakerModal { } onOpen(): void { - this.titleEl.setText("Regions"); + this.titleEl.setText(REGION_AREAS_TOOL); this.makeDraggable(); this.buildPalette(); } diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 5129ef4e..32d1ffcf 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -31,7 +31,7 @@ import { mapAncestors } from "./submapNav"; import { ancestorNeighbourCrumbs, neighbourCrumbs } from "../maps/mapTree"; import { flowerPetals, MapHistory, navArrows, PAD_SIDES } from "../maps/mapNav"; import { WORK_MODES, WORK_MODE_TEXT, workModeOf, type WorkMode } from "../workMode"; -import { pathClickOutcome, toolModeLabel } from "./toolMode"; +import { pathClickOutcome, REGION_AREAS_TOOL, toolModeLabel } from "./toolMode"; import { openNoteFocused } from "../openNote"; import { coordHaloColor } from "../coordStyle"; import { ghostPathRuns, ghostRunPoints, seamJoinKey, seamJoins, seamPoint, type ShadowRef } from "./ghostPaths"; @@ -1936,7 +1936,7 @@ export class HexMapView extends ItemView { cls: "duckmage-draw-btn duckmage-draw-btn-tablelink", }); this.regionLinkBtnLabel = this.regionLinkBtn.createSpan({ - text: "Regions", + text: REGION_AREAS_TOOL, }); this.regionLinkBtn.addEventListener("click", () => this.handleRegionLinkButton(), @@ -2678,7 +2678,7 @@ export class HexMapView extends ItemView { const name = this.paintRegionPath.split("/").pop()?.replace(/.md$/, "") ?? "Region"; this.regionLinkBtnLabel.setText(erasing ? "Erase: " + name : "Paint: " + name); } else { - this.regionLinkBtnLabel.setText("Regions"); + this.regionLinkBtnLabel.setText(REGION_AREAS_TOOL); } } this.regionLinkBtn?.toggleClass("is-erase", erasing && this.drawingMode === "regionLink"); @@ -4113,17 +4113,19 @@ export class HexMapView extends ItemView { // Submap marker: shows which hexes drill down (a system in a sector, // a dungeon in a region). Clicking it enters the submap when no tool // is active; with a tool active the click falls through to the hex. - // A Region map: a thin inner hex outline. Locations: the badge, with - // a count from two on; its tooltip lists them. + // A Region map: a thin inner hex outline, except on an overworld + // (either view), where every hex has a region and the outline says + // nothing. Locations: the badge, with a count from two on; its + // tooltip lists them. const legacySubmap: unknown = fromStore ? undefined : fm?.["duckmage-submap"]; const regionMap = stored?.regionMap && this.plugin.getMap(stored.regionMap) ? stored.regionMap : undefined; const locations = (fromStore ? stored?.locations ?? [] : typeof legacySubmap === "string" && legacySubmap ? [legacySubmap] : []) .filter((m) => m !== regionMap && !!this.plugin.getMap(m)); if (regionMap) { hexEl.addClass("duckmage-hex-has-region-map"); - hexEl.createSpan({ + if (!owView) hexEl.createSpan({ cls: "duckmage-hex-region-outline", - attr: { title: `Region: ${this.plugin.mapLabel(regionMap)} (${owView ? "click to set its biome, Ctrl+click to enter" : "Ctrl+click hex to enter"})` }, + attr: { title: `Region: ${this.plugin.mapLabel(regionMap)} (Ctrl+click hex to enter)` }, }); } if (locations.length) { diff --git a/src/hex-map/OverworldModals.ts b/src/hex-map/OverworldModals.ts index 6c9f3b18..c1dd8745 100644 --- a/src/hex-map/OverworldModals.ts +++ b/src/hex-map/OverworldModals.ts @@ -22,6 +22,7 @@ import { RECT_SIDES } from "../maps/submaps"; import { newWorldId } from "../worldgen/world"; import { isSpacePalette } from "../mapKinds"; import { ecotoneHexes } from "../overworld/regionWorld"; +import { ADD_REGION_LOCKED_HINT, canAdd } from "../workMode"; export class GenerateRegionsModal extends HexmakerModal { private stop = false; @@ -43,6 +44,13 @@ export class GenerateRegionsModal extends HexmakerModal { const row = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); const cancel = row.createEl("button", { text: "Cancel" }); const go = row.createEl("button", { text: "Make them", cls: "mod-cta" }); + if (!canAdd(this.plugin.getMap(this.mapName))) { + go.disabled = true; + go.addClass("is-locked"); + go.setAttr("title", ADD_REGION_LOCKED_HINT); + status.setText(ADD_REGION_LOCKED_HINT); + status.addClass("duckmage-locked-hint"); + } cancel.addEventListener("click", () => { if (this.running) { this.stop = true; cancel.setText("Stopping…"); } else this.close(); }); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 8a3ffd47..fad76fb2 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -80,6 +80,9 @@ Opens a folder-tree picker scoped to your Tables folder. Select a random-encount ### Factions Opens a folder-tree picker scoped to your Factions folder. Select a faction note, then left-click hexes to link it into each hex's **Factions** section. +### Region areas +Opens a picker of your Regions folder's notes. Select a region note (a named area like a basin or a kingdom), then left-click hexes to paint its colour on them (pick **Remove** in the picker to erase instead). This is the region overlay. It's not the same as a hex's region map (the map you enter on an overworld). + ### Swap Swap the contents of two hex positions by renaming their files. @@ -127,7 +130,7 @@ Turn on any one of them from the hint (✦) where it would appear, or all of the **Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (click to set one: an empty hex gets its region). The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. -**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards one thing: changing what's already placed on an overworld (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**. In Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex isn't locked (Play will lock more later). Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. +**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards two things on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**; in Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region) needs **Build** or God; in Play the biome picker is greyed out and says "Switch to Build to place a biome." Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts index f29623e7..c63c124e 100644 --- a/src/hex-map/toolMode.ts +++ b/src/hex-map/toolMode.ts @@ -3,6 +3,9 @@ * indicator). Kept free of Obsidian imports so they're unit-testable. */ +/** The drawing-panel tool that paints region notes (the region overlay). Not "Regions": that's the overworld view. */ +export const REGION_AREAS_TOOL = "Region areas"; + export type DrawingMode = | "path" | "terrain" @@ -93,7 +96,7 @@ export function toolModeLabel(s: ToolModeState): string | null { case "factionLink": return erasing ? "Erasing factions" : `Painting faction: ${baseName(s.factionPath) || "…"}`; case "regionLink": - return erasing ? "Erasing regions" : `Painting region: ${baseName(s.regionPath) || "…"}`; + return erasing ? "Erasing region areas" : `Painting region area: ${baseName(s.regionPath) || "…"}`; case "swap": return "Swapping hexes: click two hexes"; case "placeToken": diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index e414497e..acd7ad1e 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -17,7 +17,7 @@ import { regionMapAt } from "../maps/submaps"; import { biomeProfiles, representativeTerrain, type BiomeId, type BiomeProfile } from "./biomes"; import { regionCells, type RegionLayout } from "./layout"; import type { BlendWidth } from "./blendField"; -import { canReshape, RESHAPE_LOCKED_HINT } from "../workMode"; +import { ADD_REGION_LOCKED_HINT, canAdd, canReshape, PLACE_LOCKED_HINT, RESHAPE_LOCKED_HINT } from "../workMode"; import { defaultRegionName, dominantTerrain, @@ -166,6 +166,7 @@ export interface CreateRegionOptions extends RegionGenOptions { */ export async function createRegion(plugin: HexmakerPlugin, parentName: string, px: number, py: number, opts: CreateRegionOptions): Promise<{ name: string } | { error: string }> { const parent = plugin.getMap(parentName); + if (!canAdd(parent)) return { error: ADD_REGION_LOCKED_HINT }; if (!parent?.regions) return { error: "Set up this map's regions first." }; if (!meshes(parent.regions)) return { error: "Hex-flower regions don't join up yet: make this one from the new-map form." }; const hex = `${px}_${py}`; @@ -234,6 +235,7 @@ export async function generateMissingRegions( parentName: string, hooks: { onProgress?: (done: number, total: number, name: string) => void; cancelled?: () => boolean } = {}, ): Promise<{ made: string[]; errors: string[] }> { + if (!canAdd(plugin.getMap(parentName))) return { made: [], errors: [ADD_REGION_LOCKED_HINT] }; const ow = overworldOf(plugin, parentName); if (!ow) return { made: [], errors: ["This map has no rectangle region settings."] }; const order = regionOrder(missingRegionHexes(plugin, parentName), ow.layout.orientation, ow.layout.parentStagger); @@ -257,15 +259,21 @@ export function regionBlockKeys(layout: RegionLayout, px: number, py: number): s // ── reshaping: set a biome, regenerate, reroll ─────────────────────────── /** - * Whether reshaping hex (px, py)'s region (swapping its biome, rerolling, - * regenerating, applying region settings) may go ahead. Making a region - * for the first time is allowed in Build and God; changing one that's - * already there needs the map in God mode (src/workMode.ts). No confirm: - * the mode is the safety catch. + * Why setting hex (px, py)'s biome (first placement, or swapping it, + * rerolling, regenerating, applying region settings) is locked right now, + * or undefined when it may go ahead. A first placement (no region yet) + * needs Build or God; changing a region that's already there needs God + * (src/workMode.ts). No confirm: the mode is the safety catch. */ +export function reshapeLock(plugin: HexmakerPlugin, parentName: string, px: number, py: number): string | undefined { + const map = plugin.getMap(parentName); + if (!regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`)) return canAdd(map) ? undefined : PLACE_LOCKED_HINT; + return canReshape(map) ? undefined : RESHAPE_LOCKED_HINT; +} + +/** reshapeLock as a yes/no. */ export function reshapeGate(plugin: HexmakerPlugin, parentName: string, px: number, py: number): "allowed" | "locked" { - if (!regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`)) return "allowed"; - return canReshape(plugin.getMap(parentName)) ? "allowed" : "locked"; + return reshapeLock(plugin, parentName, px, py) === undefined ? "allowed" : "locked"; } /** @@ -294,8 +302,8 @@ export async function regenerateRegion(plugin: HexmakerPlugin, regionName: strin /** * Set an overworld hex's biome: paint it with the biome's terrain on the * overworld's palette (the terrain IS the biome signal), then make its - * region (first placement) or regenerate it (God mode only; see - * reshapeGate). Returns the region's name, or an error. + * region (first placement: Build or God) or regenerate it (God only; see + * reshapeLock). Returns the region's name, or an error. */ export async function setBiomeAt( plugin: HexmakerPlugin, @@ -310,7 +318,8 @@ export async function setBiomeAt( const terrain = representativeTerrain(biome, plugin.getMapPalette(parentName)); if (!terrain) return { error: "This map's palette has no terrain for that biome." }; const hex = `${px}_${py}`; - if (reshapeGate(plugin, parentName, px, py) === "locked") return { error: RESHAPE_LOCKED_HINT }; + const lock = reshapeLock(plugin, parentName, px, py); + if (lock) return { error: lock }; if (plugin.mapStore.get(parentName, hex)?.terrain !== terrain) { plugin.mapStore.set(parentName, hex, { terrain }); await plugin.mapStore.flush(); diff --git a/src/workMode.ts b/src/workMode.ts index c6028415..48cea020 100644 --- a/src/workMode.ts +++ b/src/workMode.ts @@ -2,13 +2,16 @@ * Work modes, per map (owner round 4, WM1–WM4): Play · Build · God. * * Stored readably in the map note (`mode: build`); a map opens in the mode - * saved with it, default Build. This first pass enforces ONE rule: - * canReshape() — changing what's already placed on an overworld (swapping a - * placed biome, Reroll, regenerating, applying region settings to an - * existing region) needs God. Placing a biome on an empty hex is allowed in - * Build and God. Note text is never locked, and settings and palettes - * aren't either (WM2, WM4). The rest of the modes plan (per-mode undo, - * other locks) is still to come. + * saved with it, default Build. This first pass enforces two rules: + * - canReshape(): changing what's already placed on an overworld (swapping + * a placed biome, Reroll, regenerating, applying region settings to an + * existing region) needs God. + * - canAdd(): placing a biome on an empty overworld hex (which makes its + * region), or making regions at all, needs Build or God; Play only looks + * and moves. + * Note text is never locked, and settings and palettes aren't either (WM2, + * WM4). The rest of the modes plan (per-mode undo, other locks) is still + * to come. * * Pure: no Obsidian imports. */ @@ -28,6 +31,12 @@ export const WORK_MODE_TEXT: Record = /** The hint on a locked reshape action. */ export const RESHAPE_LOCKED_HINT = "Switch to God to change a placed biome."; +/** The hint on a locked first placement (Play mode). */ +export const PLACE_LOCKED_HINT = "Switch to Build to place a biome."; + +/** The hint when making a region is locked (Play mode). */ +export const ADD_REGION_LOCKED_HINT = "Switch to Build to make a region."; + /** A map note's `mode:` value, read forgivingly ("God mode", "BUILD", "player"); unknown → undefined. */ export function parseWorkMode(raw: unknown): WorkMode | undefined { if (typeof raw !== "string") return undefined; @@ -47,3 +56,8 @@ export function workModeOf(map: { workMode?: string } | undefined): WorkMode { export function canReshape(map: { workMode?: string } | undefined): boolean { return workModeOf(map) === "god"; } + +/** May new things be added to this map (a first biome, a new region)? Build and God; not Play. */ +export function canAdd(map: { workMode?: string } | undefined): boolean { + return workModeOf(map) !== "play"; +} diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 4d906be4..1d33a95d 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -105,7 +105,7 @@ describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => expect(toolModeLabel({ mode: "path", erasing: true })).toMatch(/^Erasing paths/); expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathAuto: true })).toBe("Auto-routing Road: click the start hex"); expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathAuto: true, pathHasStart: true })).toBe("Auto-routing Road: click where it goes"); - expect(toolModeLabel({ mode: "regionLink", erasing: false, regionPath: "world/regions/Kerrigan.md" })).toBe("Painting region: Kerrigan"); + expect(toolModeLabel({ mode: "regionLink", erasing: false, regionPath: "world/regions/Kerrigan.md" })).toBe("Painting region area: Kerrigan"); expect(toolModeLabel({ mode: "factionLink", erasing: true })).toBe("Erasing factions"); expect(toolModeLabel({ mode: "tableLink", erasing: false, tablePath: "world/tables/ocean.md" })).toBe("Linking table: ocean"); expect(toolModeLabel({ mode: "submapLink", erasing: false, submapName: "deep" })).toBe("Linking submap: deep"); diff --git a/tests/workMode.test.ts b/tests/workMode.test.ts index c0f828ac..9119e6a2 100644 --- a/tests/workMode.test.ts +++ b/tests/workMode.test.ts @@ -1,7 +1,7 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { canReshape, parseWorkMode, workModeOf } from "../src/workMode"; -import { reshapeGate, setBiomeAt, regenerateRegion } from "../src/overworld/regionsVault"; +import { canAdd, canReshape, parseWorkMode, workModeOf } from "../src/workMode"; +import { createRegion, generateMissingRegions, reshapeGate, reshapeLock, setBiomeAt, regenerateRegion } from "../src/overworld/regionsVault"; import { buildMapNote, parseMapNote } from "../src/maps/mapNote"; import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; import type { MapData } from "../src/types"; @@ -26,6 +26,13 @@ describe("work modes (Play / Build / God)", () => { expect(canReshape({})).toBe(false); }); + it("Build and God may add; Play may not", () => { + expect(canAdd({ workMode: "god" })).toBe(true); + expect(canAdd({ workMode: "build" })).toBe(true); + expect(canAdd({})).toBe(true); + expect(canAdd({ workMode: "play" })).toBe(false); + }); + it("is stored in the map note as a plain `mode:` key and read back", () => { const note = buildMapNote("m", { settings: { paletteName: "Default", workMode: "god" }, hexes: new Map(), paths: [] }); expect(note).toMatch(/^mode: god$/m); @@ -56,11 +63,30 @@ describe("reshape gate on an overworld", () => { return { plugin, writes }; } - it("first placement on an empty hex is allowed in every mode", () => { - for (const mode of [undefined, "play", "build", "god"]) { + it("first placement on an empty hex is allowed in Build and God, not Play", () => { + for (const mode of [undefined, "build", "god"]) { // eslint-disable-next-line @typescript-eslint/no-explicit-any expect(reshapeGate(fakePlugin(mode).plugin as any, "ow", 0, 0)).toBe("allowed"); } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(reshapeGate(fakePlugin("play").plugin as any, "ow", 0, 0)).toBe("locked"); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(reshapeLock(fakePlugin("play").plugin as any, "ow", 0, 0)).toBe("Switch to Build to place a biome."); + }); + + it("in Play, placing a first biome or making regions changes nothing", async () => { + const { plugin, writes } = fakePlugin("play"); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const p = plugin as any; + expect(await setBiomeAt(p, "ow", 0, 0, "taiga")).toEqual({ error: "Switch to Build to place a biome." }); + expect(await createRegion(p, "ow", 0, 0, { fill: "match" })).toEqual({ error: "Switch to Build to make a region." }); + expect(await generateMissingRegions(p, "ow")).toEqual({ made: [], errors: ["Switch to Build to make a region."] }); + expect(writes).toEqual([]); + }); + + it("in Play, a placed biome still says to switch to God", () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(reshapeLock(fakePlugin("play").plugin as any, "ow", 1, 1)).toBe("Switch to God to change a placed biome."); }); it("a hex that already has a region can only change in God", () => { From 917c8afe5ebeef3a3ee553bd4aefec075bb19cf9 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:23:33 -0400 Subject: [PATCH 238/558] fix(maps): paths no longer wiped by a data.json reload mid-save-burst Root cause: onExternalSettingsChange -> loadSettings swaps in fresh map objects read from data.json, which never holds the paths of maps whose note does (withoutNotePaths). loadSettings then awaited a second loadData, so a saveSettings in the burst could run MapStore.sync() on the fresh objects before reloadFromNotes was queued; syncPaths read the missing `paths` as "no paths" and the next write emptied every map note. A flush already queued for a dirty map (its world slot just changed) did the same to that map even when reloadFromNotes came first. Obsidian fires the hook for our own saves when several land together, which made it intermittent. Fix, in layers: - MapStore.adopt/adoptAll: a fresh map object without paths takes the store's; a note-backed map with missing paths is "not loaded", never empty (syncPaths leaves it alone). - loadSettings reads data.json once (no await between the swap and adoptAll) and hands the fresh maps to the store at once. - onExternalSettingsChange ignores data.json contents this session wrote. - Write guard: a write that would drop every path or hex a note holds is refused unless an edit removed them (setPaths, the path tool, clearing hexes); the note's are taken back, logged, and a notice says so. Also: stale routing context. setPaths/syncPaths settle the context against the OLD paths before new ones go in, and painting terrain refreshes the context even on a map with no paths, so a first path drawn after painting water is never pinned through it. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 40 ++++++++- src/maps/MapStore.ts | 97 ++++++++++++++++++++-- tests/mapNotePaths.test.ts | 32 ++++++++ tests/pathLossReload.test.ts | 154 +++++++++++++++++++++++++++++++++++ 5 files changed, 316 insertions(+), 11 deletions(-) create mode 100644 tests/pathLossReload.test.ts diff --git a/package.json b/package.json index 4ec2aa08..e4c1acfc 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 1cdd927a..2e6aef38 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -674,7 +674,13 @@ export default class HexmakerPlugin extends Plugin { async loadSettings() { // One-time migration: rename settings keys "regions" → "maps" and "defaultRegion" → "defaultMap" // Must run on raw data BEFORE Object.assign so the migrated key wins over DEFAULT_SETTINGS. - const data = ((await this.loadData()) ?? {}) as Record; + // One read only: nothing may await between swapping in the new + // settings and handing their maps to the map store (adoptAll below), or a + // save in between would see maps without their paths (incident + // 2026-10-10). rawData is an untouched copy for the "fresh install?" checks. + const loaded = (await this.loadData()) as Record | null; + const rawData = loaded ? (JSON.parse(JSON.stringify(loaded)) as Record) : null; + const data = loaded ?? {}; if (data["regions"] !== undefined && data["maps"] === undefined) { data["maps"] = data["regions"]; } @@ -697,6 +703,10 @@ export default class HexmakerPlugin extends Plugin { : []; this.settings.maps = this.settings.maps.map((r) => migrateMapData(r, DEFAULT_PALETTE_NAME)); + // Reloaded (onExternalSettingsChange): data.json doesn't hold the paths + // of maps whose note does, so the fresh map objects take the store's at + // once. Missing paths mean "not loaded", never "no paths". + this.mapStore.adoptAll(); // Ensure terrainPalettes is valid if ( !Array.isArray(this.settings.terrainPalettes) || @@ -744,7 +754,6 @@ export default class HexmakerPlugin extends Plugin { // settings (an update) gets Advanced so nothing it used disappears; a // fresh one starts Simple. Saved right away, so the next load doesn't // mistake a fresh install's first save for an update. - const rawData = (await this.loadData()) as Record | null; this.settings.featureLevel = resolveFeatureLevel(rawData); this.settings.advancedFeatures = Array.isArray(data["advancedFeatures"]) ? (data["advancedFeatures"] as unknown[]).filter((f): f is string => typeof f === "string") : []; this.settings.dismissedHints = Array.isArray(data["dismissedHints"]) ? (data["dismissedHints"] as unknown[]).filter((f): f is string => typeof f === "string") : []; @@ -766,8 +775,26 @@ export default class HexmakerPlugin extends Plugin { * note, which a person can read and edit. Maps not yet in a note keep them. */ async saveData(data: unknown): Promise { - if (data !== this.settings || !this.mapStore?.isReady()) return super.saveData(data); - return super.saveData(withoutNotePaths(this.settings, (name) => this.mapStore.holdsPaths(name))); + const out = data !== this.settings || !this.mapStore?.isReady() ? data : withoutNotePaths(this.settings, (name) => this.mapStore.holdsPaths(name)); + this.rememberWrite(out); + return super.saveData(out); + } + + /** What we wrote to data.json lately (compact JSON), to tell our own writes from outside changes. */ + private recentWrites: string[] = []; + + private rememberWrite(data: unknown): void { + try { + this.recentWrites.push(JSON.stringify(data)); + if (this.recentWrites.length > 20) this.recentWrites.shift(); + } catch { /* not JSON-able: never matches */ } + } + + /** data.json holds exactly something this session wrote (an echo of our own save). */ + private isOwnWrite(disk: unknown): boolean { + if (disk === null || disk === undefined) return false; + const text = JSON.stringify(disk); + return this.recentWrites.includes(text); } async saveSettings() { @@ -793,6 +820,11 @@ export default class HexmakerPlugin extends Plugin { // Reloads settings into memory and refreshes all open views so the user sees // the synced state without a manual Obsidian restart. async onExternalSettingsChange(): Promise { + // Obsidian also fires this for our own saves when several land close + // together (its watcher sees a write it hasn't recorded yet). Reloading + // our own data would at best do nothing and at worst roll back changes + // made since that save, so ignore anything we wrote ourselves. + if (this.isOwnWrite(await this.loadData())) return; await this.loadSettings(); // Map notes hold paths and map settings; the new data.json doesn't win. // Queued before any sync, so nothing writes the bare copy over a note. diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index 15eff6d4..a87b5e4d 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -113,6 +113,15 @@ export class MapStore { /** Old every-hex paths converted this session, per map (for the startup notice). */ private converted: { map: string; report: CompactReport }[] = []; private contextListeners = new Set<(e: RouteContextChange) => boolean | void>(); + /** + * Per map: the MapData object the store last worked with. When settings + * are reloaded (onExternalSettingsChange) the map objects are replaced by + * fresh ones without `paths` (data.json doesn't hold them); see adopt(). + */ + private known = new Map(); + /** Maps whose paths / hexes were all removed by an edit (not a reload): allowed to empty the note. */ + private clearedPaths = new Set(); + private clearedHexes = new Set(); constructor(private plugin: HexmakerPlugin) {} @@ -188,6 +197,7 @@ export class MapStore { else (h as Record)[k] = v; } if (Object.keys(h).length) t.set(key, h); else t.delete(key); + if (!t.size) this.clearedHexes.add(map); if ("terrain" in patch) this.terrainChanged(map); this.markDirty(map); this.emit(map); @@ -201,15 +211,46 @@ export class MapStore { for (const k of Object.keys(h) as (keyof HexData)[]) if (h[k] === undefined || h[k] === "") delete h[k]; if (Object.keys(h).length) t.set(key, h); else t.delete(key); } + if (!t.size) this.clearedHexes.add(map); this.terrainChanged(map); this.markDirty(map); this.emit(map); } - /** Terrain changed: if that moves the map's routing context, routes are pinned (see routeCache). */ + /** + * Terrain changed: if that moves the map's routing context, routes are + * pinned (see routeCache). Done whether or not the map has paths yet, so + * the context is never stale when the first path is drawn. + */ private terrainChanged(name: string): void { const map = this.plugin.getMap(name); - if (map && map.paths?.length && this.routeCaches.has(name) && this.isReady(name)) this.routeCache(map); + if (!map || !this.routeCaches.has(name) || !this.isReady(name)) return; + this.adopt(map); + this.routeCache(map); + } + + /** + * `map` replaces the object the store last held for its name (settings + * reloaded from data.json): if it came without paths — data.json never + * holds the paths of maps whose note does — it takes the store's. Missing + * paths mean "not loaded", never "no paths". + */ + private adopt(map: MapData): void { + const prev = this.known.get(map.name); + if (prev && prev !== map && map.paths === undefined && prev.paths !== undefined) { + map.paths = prev.paths; + // The same chain objects, so the compatibility view still matches them. + map.pathChains = prev.pathChains; + } + this.known.set(map.name, map); + } + + /** + * Settings were reloaded (HexmakerPlugin.loadSettings): put the paths the + * store holds onto the fresh map objects at once, before anything syncs. + */ + adoptAll(): void { + for (const m of this.uniqueMaps()) this.adopt(m); } onChange(fn: (map: string) => void): () => void { @@ -300,6 +341,12 @@ export class MapStore { setPaths(name: string, paths: MapPath[]): void { const map = this.plugin.getMap(name); if (!map) return; + this.adopt(map); + // Bring the routing context up to date first, so any pinning it causes + // applies to the OLD paths. The new ones were drawn on the map as it is + // now and must never be pinned to an older terrain or palette. + if (this.routeCaches.has(name) && this.isReady(name)) this.routeCache(map); + if (!paths.length) this.clearedPaths.add(name); map.paths = paths; this.rebuildView(map); this.markDirty(name); @@ -336,10 +383,19 @@ export class MapStore { */ private syncPaths(map: MapData): void { if (!this.ready || this.broken.has(map.name) || this.migrating.has(map.name)) return; + this.adopt(map); + // Paths missing on a map whose note holds them: not loaded (yet), never + // "no paths". Leave them missing; reloadFromNotes fills them in, and the + // write guard keeps the note's. + if (map.paths === undefined && this.holdsPaths(map.name)) return; + // Settle the routing context against the current paths before folding edits in. + if (this.routeCaches.has(map.name) && this.isReady(map.name)) this.routeCache(map); if (!map.pathChains) map.pathChains = []; const view = this.views.get(map.name) ?? emptyView(); - const r = reconcile(map.paths ?? [], map.pathChains, view, (t, h) => this.anchorsOf(map, t, h)); + const before = map.paths ?? []; + const r = reconcile(before, map.pathChains, view, (t, h) => this.anchorsOf(map, t, h)); this.views.set(map.name, r.view); + if (r.changed && before.length && !r.paths.length) this.clearedPaths.add(map.name); if (r.changed || !map.paths) map.paths = r.paths; } @@ -514,7 +570,8 @@ export class MapStore { this.backedUp.add(path); } await this.savePathReport(map.name); - const data = this.dataFor(map); + let data = this.dataFor(map); + if (this.keepsNoteData(map, path, data, r.data)) data = this.dataFor(map); const ctx = this.contextFor(map); const next = updateMapNote(current, map.name, data, ctx); this.lastDerived.set(map.name, JSON.stringify(ctx)); @@ -523,6 +580,8 @@ export class MapStore { this.lastContent.set(path, next); if (next !== current) await vault.modify(file, next); this.lastKey.set(map.name, mapNoteKey(data)); + this.clearedPaths.delete(map.name); + this.clearedHexes.delete(map.name); } else { const data = this.dataFor(map); const folder = this.mapFolder(map.name); @@ -538,6 +597,30 @@ export class MapStore { } } + /** + * Write guard (incident 2026-10-10): a write that would drop EVERY path, + * or every hex, the note holds is refused unless an edit removed them + * (setPaths / the path tool / clearing hexes). Anything else is a lost + * or not-yet-loaded copy in memory: the note's are taken back into + * memory, logged, and said with a notice. True if anything was kept. + */ + private keepsNoteData(map: MapData, path: string, data: MapNoteData, disk: MapNoteData): boolean { + const dropsPaths = disk.paths.length > 0 && data.paths.length === 0 && !this.clearedPaths.has(map.name); + const dropsHexes = disk.hexes.size > 0 && data.hexes.size === 0 && !this.clearedHexes.has(map.name); + if (!dropsPaths && !dropsHexes) return false; + const what = [dropsPaths ? `${disk.paths.length} path${disk.paths.length === 1 ? "" : "s"}` : "", dropsHexes ? `${disk.hexes.size} hex${disk.hexes.size === 1 ? "" : "es"}` : ""].filter(Boolean).join(" and "); + console.error(`Hexmap World Creator: a save of ${path} would have removed all its ${what} without them being deleted; the note's were kept.`, { map: map.name, paths: map.paths, hexes: data.hexes.size }); + new Notice(`Hexmap World Creator: a save would have removed all ${what} from ${path}. They weren't deleted, so the note's were kept. To remove them, delete them again.`, 15000); + if (dropsHexes) this.hexes.set(map.name, this.matchCase(map, disk.hexes)); + if (dropsPaths) { + this.views.delete(map.name); + this.applyPaths(map, disk); + } + this.known.set(map.name, map); + this.emit(map.name); + return true; + } + // ── load / hand edits ──────────────────────────────────────────────── /** Wikilinks in the note (background image, tables) resolve like Obsidian's. */ @@ -560,6 +643,7 @@ export class MapStore { } this.hexes.set(map.name, this.matchCase(map, data.hexes)); this.applyPaths(map, data); + this.known.set(map.name, map); this.lastKey.set(map.name, mapNoteKey(this.dataFor(map))); // Loaded or hand-edited: taken as written. Derived parts catch up on the next write. this.lastDerived.set(map.name, JSON.stringify(this.contextFor(map))); @@ -773,7 +857,7 @@ export class MapStore { const t = this.hexes.get(oldName); if (t) { this.hexes.delete(oldName); this.hexes.set(newName, t); } if (this.broken.delete(oldName)) this.broken.add(newName); - for (const m of [this.views, this.routeCaches] as Map[]) { + for (const m of [this.views, this.routeCaches, this.known] as Map[]) { if (m.has(oldName)) { m.set(newName, m.get(oldName)); m.delete(oldName); } } const { vault, fileManager } = this.plugin.app; @@ -805,6 +889,9 @@ export class MapStore { this.hexes.delete(name); this.views.delete(name); this.routeCaches.delete(name); + this.known.delete(name); + this.clearedPaths.delete(name); + this.clearedHexes.delete(name); this.lastKey.delete(name); this.lastDerived.delete(name); this.dirty.delete(name); diff --git a/tests/mapNotePaths.test.ts b/tests/mapNotePaths.test.ts index 7fd588f7..48e52003 100644 --- a/tests/mapNotePaths.test.ts +++ b/tests/mapNotePaths.test.ts @@ -473,6 +473,38 @@ describe("map store: path edits, hand edits and the three-way merge", () => { expect(JSON.stringify(m[0].paths)).toBe(pinned); }); + it("a path drawn after painting water on a map with no paths routes around it (never pinned to the old terrain)", async () => { + const v = new MemVault(); + const m = [fixtureMap()]; + const { store } = await boot(v, m); + expect(store.resolved("m")).toEqual([]); // the store has a routing context now + store.set("m", "3_5", { terrain: "shallows" }); // no paths yet + const seen: string[] = []; + store.onRouteContextChange((e) => { seen.push(e.map); }); + store.setPaths("m", [P("Road", "Road", ["0_5", "6_5"])]); + expect(m[0].paths![0].branches[0].anchors).toEqual(["0_5", "6_5"]); + expect(store.resolved("m")![0].hexes).not.toContain("3_5"); + expect(seen).toEqual([]); // the context was already current: nothing to pin + }); + + it("setPaths settles a stale routing context against the OLD paths, never the new ones", async () => { + const v = new MemVault(); + const m = [fixtureMap()]; + const { store } = await boot(v, m); + // Where a road from 0,5 to 6,5 goes on open ground. + store.setPaths("m", [P("Road", "Road", ["0_5", "6_5"])]); + const open = store.resolved("m")![0].hexes; + const mid = open[Math.floor(open.length / 2)]; + store.setPaths("m", []); + store.set("m", mid, { terrain: "forest" }); + // A context change the store hasn't seen yet (palette edit: forest becomes impassable). + const palette = DEFAULT_TERRAIN_PALETTE.map((t) => (t.name === "forest" ? { ...t, impassable: true } : t)); + (store as unknown as { plugin: { getMapPalette: () => unknown } }).plugin.getMapPalette = () => palette; + store.setPaths("m", [P("Road", "Road", ["0_5", "6_5"])]); + expect(m[0].paths![0].branches[0].anchors).toEqual(["0_5", "6_5"]); + expect(store.resolved("m")![0].hexes).not.toContain(mid); + }); + it("a format-6 note is broken with a notice that names the format and says to update", async () => { const v = new MemVault({ [NOTE]: buildMapNote("m", data([KINGS])).replace(`hexmaker-map: ${MAP_NOTE_FORMAT}`, "hexmaker-map: 6") }); const before = v.files.get(NOTE); diff --git a/tests/pathLossReload.test.ts b/tests/pathLossReload.test.ts new file mode 100644 index 00000000..5cf70571 --- /dev/null +++ b/tests/pathLossReload.test.ts @@ -0,0 +1,154 @@ +/** + * Incident 2026-10-10: a data.json reload (onExternalSettingsChange) in the + * middle of a burst of saveSettings calls wiped map notes' paths. loadSettings + * hands MapStore fresh map objects with no `paths` (data.json never holds the + * paths of maps whose note does); any sync/flush that reached them before + * reloadFromNotes read "missing" as "empty" and wrote that to the note. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { Notice } from "obsidian"; +import { MapStore, withoutNotePaths } from "../src/maps/MapStore"; +import { parseMapNote } from "../src/maps/mapNote"; +import { MemVault } from "./helpers/memVault"; +import type { MapData, MapPath } from "../src/types"; + +(globalThis as Record).window ??= globalThis; + +const NOTE = "world/hexes/coast/_coast.md"; +const NORTH = "world/hexes/north/_north.md"; + +const maps = (): MapData[] => [ + { name: "coast", gridSize: { cols: 8, rows: 8 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "Road", hexes: ["1_2", "2_2", "3_2"] }, { typeName: "River", hexes: ["5_0", "5_1", "5_2", "5_3"] }] } as MapData, + { name: "north", gridSize: { cols: 6, rows: 6 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "Road", hexes: ["0_0", "1_0", "2_0"] }] } as MapData, +]; + +function plugin(vault: MemVault, list: MapData[]) { + const p = { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", maps: list }, + getMap: (n: string) => p.settings.maps.find((m) => m.name === n), + saveData: async () => {}, + refreshHexMap: () => {}, + }; + return p; +} + +async function boot() { + const v = new MemVault(); + const p = plugin(v, maps()); + const store = new MapStore(p as never); + await store.init(); + return { v, p, store }; +} + +/** What loadSettings does on an external data.json change: fresh map objects, read from what we last saved. */ +function reloadDataJson(p: ReturnType, store: MapStore): MapData[] { + const disk = JSON.parse(JSON.stringify(withoutNotePaths(p.settings, (n) => store.holdsPaths(n)))) as { maps: MapData[] }; + p.settings = { ...p.settings, maps: disk.maps }; + return disk.maps; +} + +const notePaths = (v: MemVault, path = NOTE): MapPath[] => parseMapNote(v.files.get(path)!)!.paths; + +describe("incident 2026-10-10: paths survive a data.json reload mid-burst", () => { + it("setup: the notes hold the paths and data.json doesn't", async () => { + const { v, p, store } = await boot(); + expect(notePaths(v)).toHaveLength(2); + expect(notePaths(v, NORTH)).toHaveLength(1); + const fresh = reloadDataJson(p, store); + expect(fresh.every((m) => m.paths === undefined && m.pathChains === undefined)).toBe(true); + }); + + it("a saveSettings sync that reaches the fresh objects before reloadFromNotes keeps every map's paths", async () => { + const { v, p, store } = await boot(); + reloadDataJson(p, store); + await store.sync(); // the burst's next saveSettings + expect(notePaths(v)).toHaveLength(2); + expect(notePaths(v, NORTH)).toHaveLength(1); + expect(store.paths("coast")).toHaveLength(2); + await store.reloadFromNotes(); + expect(notePaths(v)).toHaveLength(2); + expect(store.paths("north")).toHaveLength(1); + }); + + it("a flush already queued for a dirty map (its world slot just changed) keeps its paths", async () => { + const { v, p, store } = await boot(); + p.getMap("coast")!.world = { id: "w1", cx: 1, cy: 0 }; + void store.sync(); // coast is dirty: the flush is queued + const fresh = reloadDataJson(p, store); // Obsidian's reload lands before the queue runs + const reload = store.reloadFromNotes(); + await reload; + expect(notePaths(v)).toHaveLength(2); + expect(fresh[0].paths).toHaveLength(2); + expect(fresh[0].pathChains!.length).toBeGreaterThan(0); + expect(parseMapNote(v.files.get(NOTE)!)!.settings).toMatchObject({ world: { id: "w1", cx: 1, cy: 0 } }); + }); + + it("the fresh map's hexes and settings are the note's too", async () => { + const { v, p, store } = await boot(); + store.set("coast", "4_4", { terrain: "forest", name: "Old Tower" }); + await store.flush(); + reloadDataJson(p, store); + await store.sync(); + expect(store.get("coast", "4_4")).toEqual({ terrain: "forest", name: "Old Tower" }); + const back = parseMapNote(v.files.get(NOTE)!)!; + expect(back.hexes.get("4_4")).toEqual({ terrain: "forest", name: "Old Tower" }); + expect(back.paths).toHaveLength(2); + }); +}); + +describe("map store: write guard against dropping every path or hex", () => { + it("refuses a write that would empty a note's paths without an explicit delete, and says so", async () => { + const { v, p, store } = await boot(); + Notice.shown.length = 0; + // Something hands the store a map object whose paths read as empty (not a delete). + const m = p.getMap("coast")!; + const replaced = { ...m, paths: [], pathChains: [] } as MapData; + p.settings = { ...p.settings, maps: p.settings.maps.map((x) => (x === m ? replaced : x)) }; + (store as unknown as { known: Map }).known?.delete("coast"); + (store as unknown as { dirty: Set }).dirty.add("coast"); + await store.flush(); + expect(notePaths(v)).toHaveLength(2); + expect(Notice.shown.some((n) => n.msg.includes("_coast.md") && n.msg.includes("kept"))).toBe(true); + // Memory takes the note's paths back, so the map shows them again. + expect(store.paths("coast")).toHaveLength(2); + }); + + it("an explicit delete of every path still empties the note (setPaths)", async () => { + const { v, store } = await boot(); + store.setPaths("coast", []); + await store.flush(); + expect(notePaths(v)).toEqual([]); + }); + + it("deleting every path through pathChains (the path tool) still empties the note", async () => { + const { v, p, store } = await boot(); + expect(store.paths("north")).toHaveLength(1); + p.getMap("north")!.pathChains!.splice(0); + await store.sync(); + expect(notePaths(v, NORTH)).toEqual([]); + }); + + it("clearing every hex by hand edits through the store still empties the note's hexes", async () => { + const { v, store } = await boot(); + store.set("coast", "4_4", { terrain: "forest" }); + await store.flush(); + store.set("coast", "4_4", { terrain: null }); + await store.flush(); + expect(parseMapNote(v.files.get(NOTE)!)!.hexes.size).toBe(0); + }); + + it("refuses a write that would drop every hex the note holds when nothing cleared them", async () => { + const { v, store } = await boot(); + store.set("coast", "4_4", { terrain: "forest" }); + await store.flush(); + // Lose the in-memory table (not a user clear). + (store as unknown as { hexes: Map }).hexes.delete("coast"); + (store as unknown as { dirty: Set }).dirty.add("coast"); + await store.flush(); + expect(parseMapNote(v.files.get(NOTE)!)!.hexes.get("4_4")).toEqual({ terrain: "forest" }); + expect(store.get("coast", "4_4")).toEqual({ terrain: "forest" }); + }); +}); From de5f25df217c48859f25346a3beae8252bf0c426 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:30:02 -0400 Subject: [PATCH 239/558] fix(path tool): #48 fresh-eyes polish MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Anchor handles and the active-end dot get their own layer (duckmage-path-handles-svg, z-index 6) over the elevated override and GM icon layer, so no icon hides a handle. A press the tool takes now stops the browser's image drag, so pressing on a hex icon still drags. - Right-click menu: the path's own items first (Split here, Delete this fork, Delete path, Rename..., Change type..., Reverse), a separator, then the tool's items (painterMenuEntries, pathMenuItems). - Rename box: Save looks disabled (mod-disabled + disabled + aria) with the reason under the field while the name is empty or taken (pathNameState). - "Paths on this map": each path shows its ends, forks and size from the resolved routes ("3, 4 -> 9, 2 · 2 forks · 18 hexes", pathListSummary). Names are untouched. - Hex by hex: press and drag adds an anchor for every hex entered (going back a hex takes it away again); the whole drag is one commit / one undo step, through canEditPaths. Auto-route keeps drag-to-reshape. append() now shares drawTarget/extendTo with the drag. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/hex-map/HexMapView.ts | 55 ++-- src/hex-map/PainterContextMenu.ts | 36 ++- src/hex-map/PathNameModal.ts | 28 +- src/hex-map/PathPickerModal.ts | 4 +- src/hex-map/help.md | 8 +- src/hex-map/pathTool.ts | 414 +++++++++++++++++++++++++----- styles.css | 28 ++ tests/pathToolPolish.test.ts | 263 +++++++++++++++++++ tests/toolMode.test.ts | 8 +- 10 files changed, 746 insertions(+), 102 deletions(-) create mode 100644 tests/pathToolPolish.test.ts diff --git a/package.json b/package.json index a2b151a5..84210f69 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/generatorPaths.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/generatorPaths.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathTool.test.ts tests/pathToolPolish.test.ts tests/routePins.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/generatorPaths.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathTool.test.ts tests/pathToolPolish.test.ts tests/routePins.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/generatorPaths.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 0a9ca96c..7eaa324b 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -32,7 +32,7 @@ import { ancestorNeighbourCrumbs, neighbourCrumbs } from "../maps/mapTree"; import { toolModeLabel } from "./toolMode"; import { PathTool } from "./pathTool"; import type { PinRecord } from "../paths/routePins"; -import { pathSummary } from "./pathTool"; +import { pathListSummary } from "./pathTool"; import { flowerPetals, MapHistory, navArrows, PAD_SIDES } from "../maps/mapNav"; import { WORK_MODES, WORK_MODE_TEXT, workModeOf, type WorkMode } from "../workMode"; import { openNoteFocused } from "../openNote"; @@ -2027,7 +2027,6 @@ export class HexMapView extends ItemView { switchLabel = "Switch path type"; extra.push({ label: erasing ? "Draw mode" : "Erase mode", onClick: toggleEraseMode }); if (!erasing) extra.push({ label: "New path", onClick: () => this.pathTool.startNewPath() }); - extra.push(...pathItems); } else if (mode === "placeToken") { onSwitch = () => this.handleTokenButton(true); switchLabel = "Switch token"; @@ -2035,7 +2034,8 @@ export class HexMapView extends ItemView { // swap: no picker → onSwitch stays null, menu shows only "Exit tool" this.painterMenu?.close(); - this.painterMenu = new PainterContextMenu(onSwitch, () => this.exitCurrentMode(), switchLabel, extra); + // The path under the pointer comes first, above a separator (#48). + this.painterMenu = new PainterContextMenu(onSwitch, () => this.exitCurrentMode(), switchLabel, extra, mode === "path" ? pathItems : []); this.painterMenu.open(clientX, clientY); } @@ -5803,7 +5803,12 @@ export class HexMapView extends ItemView { noImpassable: impassableNames(this.plugin.getMapPalette(this.activeMapName)).length === 0, }, { - list: this.plugin.mapStore.paths(this.activeMapName).map((p) => ({ name: p.name, typeName: p.typeName, summary: pathSummary(p) })), + list: (() => { + // Ends, forks and size from the resolved routes (#48), so similar + // names (Road 2 … Road 6) can be told apart. Names stay the user's. + const resolved = this.plugin.paths.resolved(this.activeMapName); + return this.plugin.mapStore.paths(this.activeMapName).map((p) => ({ name: p.name, typeName: p.typeName, summary: pathListSummary(p, resolved) })); + })(), selected: this.pathTool.selected, onPick: (name) => { this.leaveOtherToolFor("path"); @@ -5982,19 +5987,27 @@ export class HexMapView extends ItemView { const selected = tool?.selected ?? null; const key = JSON.stringify([lines.map((l) => [l.s.path, l.s.branch, l.d, l.width, l.dash, l.s.color]), dot, handles, selected]); const existing = gridContainer.querySelector("svg.duckmage-path-svg"); + const existingHandles = gridContainer.querySelector("svg.duckmage-path-handles-svg"); + const wantLines = lines.length > 0; + const wantHandles = !!dot || handles.length > 0; // ── Writes ── - if (!existing || key !== this.pathLayerKey) { + if (key !== this.pathLayerKey || wantLines !== !!existing || wantHandles !== !!existingHandles) { existing?.remove(); + existingHandles?.remove(); this.pathLayerKey = key; - if (lines.length || dot || handles.length) { - const svgNS = "http://www.w3.org/2000/svg"; - const svg = activeDocument.createElementNS(svgNS, "svg"); - svg.classList.add("duckmage-path-svg"); - // One user unit = 1em of the grid (it overflows for seam stubs). - svg.setAttribute("width", "1em"); - svg.setAttribute("height", "1em"); - svg.setAttribute("viewBox", "0 0 1 1"); + const svgNS = "http://www.w3.org/2000/svg"; + // One user unit = 1em of the grid (it overflows for seam stubs). + const emSvg = (cls: string): SVGSVGElement => { + const s = activeDocument.createElementNS(svgNS, "svg"); + s.classList.add(cls); + s.setAttribute("width", "1em"); + s.setAttribute("height", "1em"); + s.setAttribute("viewBox", "0 0 1 1"); + return s; + }; + if (wantLines) { + const svg = emSvg("duckmage-path-svg"); // The selected path's halo, under every line. for (const l of lines) { if (l.s.path !== selected) continue; @@ -6023,6 +6036,17 @@ export class HexMapView extends ItemView { path.setAttribute("data-branch", String(l.s.branch)); svg.appendChild(path); } + // Under the icon layer (elevated and GM icons sit above paths). + const icons = gridContainer.querySelector("svg.duckmage-path-icons-svg"); + if (icons) gridContainer.insertBefore(svg, icons); + else gridContainer.appendChild(svg); + } + // The tool's handles and active-end dot get their own layer, over + // the icon layer (terrain, elevated override and GM icons), so a + // handle is never hidden under an icon (#48). Hit-testing is pure + // math, so they stay grabbable whatever is drawn over the hex. + if (wantHandles) { + const svg = emSvg("duckmage-path-handles-svg"); for (const h of handles) { const handle = activeDocument.createElementNS(svgNS, "circle"); handle.setAttribute("class", "duckmage-svg-path-line duckmage-svg-path-handle"); @@ -6046,10 +6070,7 @@ export class HexMapView extends ItemView { circle.setAttribute("opacity", "0.9"); svg.appendChild(circle); } - // Under the icon layer (elevated and GM icons sit above paths). - const icons = gridContainer.querySelector("svg.duckmage-path-icons-svg"); - if (icons) gridContainer.insertBefore(svg, icons); - else gridContainer.appendChild(svg); + gridContainer.appendChild(svg); } } this.renderPathIconsLayer(gridContainer); diff --git a/src/hex-map/PainterContextMenu.ts b/src/hex-map/PainterContextMenu.ts index 7f76c8dc..41f4ed8a 100644 --- a/src/hex-map/PainterContextMenu.ts +++ b/src/hex-map/PainterContextMenu.ts @@ -3,6 +3,29 @@ export interface PainterContextMenuOption { onClick: () => void; } +/** A menu row: an option, or a separator line. */ +export type PainterContextMenuEntry = PainterContextMenuOption | { separator: true }; + +/** + * The rows of a painter menu, top to bottom (pure): the `leading` items + * (what's under the pointer, e.g. the path tool's path items) first, then + * a separator, then the tool's own items: Switch (when there's a picker), + * Exit tool, and the tool's extras. No separator without leading items. + */ +export function painterMenuEntries( + leading: readonly PainterContextMenuOption[], + onSwitch: (() => void) | null, + switchLabel: string, + onExit: () => void, + extra: readonly PainterContextMenuOption[], +): PainterContextMenuEntry[] { + const tool: PainterContextMenuOption[] = []; + if (onSwitch) tool.push({ label: switchLabel, onClick: onSwitch }); + tool.push({ label: "Exit tool", onClick: onExit }); + tool.push(...extra); + return leading.length ? [...leading, { separator: true }, ...tool] : tool; +} + /** * Lightweight right-click context menu for painter-type tools. * Shows "Switch" (if a picker exists for the tool) and "Exit tool" by default. @@ -17,6 +40,8 @@ export class PainterContextMenu { private readonly onExit: () => void, private readonly switchLabel = "Switch", private readonly extra: PainterContextMenuOption[] = [], + /** Items about what's under the pointer, listed first (above a separator). */ + private readonly leading: PainterContextMenuOption[] = [], ) {} open(x: number, y: number): void { @@ -26,12 +51,11 @@ export class PainterContextMenu { menu.style.left = `${x}px`; menu.style.top = `${y}px`; - const opts: PainterContextMenuOption[] = []; - if (this.onSwitch) opts.push({ label: this.switchLabel, onClick: this.onSwitch }); - opts.push({ label: "Exit tool", onClick: this.onExit }); - opts.push(...this.extra); - - for (const opt of opts) { + for (const opt of painterMenuEntries(this.leading, this.onSwitch, this.switchLabel, this.onExit, this.extra)) { + if ("separator" in opt) { + menu.createDiv({ cls: "duckmage-painter-ctx-separator" }); + continue; + } const item = menu.createDiv({ cls: "duckmage-painter-ctx-item", text: opt.label, diff --git a/src/hex-map/PathNameModal.ts b/src/hex-map/PathNameModal.ts index d805a76e..1544af49 100644 --- a/src/hex-map/PathNameModal.ts +++ b/src/hex-map/PathNameModal.ts @@ -1,9 +1,26 @@ import { App } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; +/** + * What the rename box's Save does with what's typed (pure): the cleaned + * name (trimmed, inner whitespace collapsed) when it can be saved, else + * null with a short reason. Empty is refused; the current name is fine + * (Save just closes); anything else asks `check` (e.g. the name is taken). + */ +export function pathNameState( + raw: string, + current: string, + check: (name: string) => string | null, +): { name: string | null; problem: string | null } { + const name = raw.trim().replace(/\s+/g, " "); + const problem = !name ? "A path needs a name." : name === current ? null : check(name); + return { name: problem ? null : name, problem }; +} + /** * Rename a path: one text field. `check` returns a problem to show (e.g. - * the name is taken) or null; Save is refused while there is one. + * the name is taken) or null. While there is one, Save looks and is + * disabled and the reason shows under the field (#48). */ export class PathNameModal extends HexmakerModal { constructor( @@ -31,11 +48,14 @@ export class PathNameModal extends HexmakerModal { const save = row.createEl("button", { text: "Save", cls: "mod-cta" }); const cancel = row.createEl("button", { text: "Cancel" }); const validate = (): string | null => { - const name = input.value.trim().replace(/\s+/g, " "); - const msg = !name ? "A path needs a name." : name === this.current ? null : this.check(name); + const { name, problem: msg } = pathNameState(input.value, this.current, this.check); problem.setText(msg ?? ""); save.disabled = !!msg; - return msg ? null : name; + save.toggleClass("mod-disabled", !!msg); + save.setAttribute("aria-disabled", String(!!msg)); + if (msg) save.setAttribute("title", msg); + else save.removeAttribute("title"); + return name; }; const submit = () => { const name = validate(); diff --git a/src/hex-map/PathPickerModal.ts b/src/hex-map/PathPickerModal.ts index 1ddf5c91..1f34f35a 100644 --- a/src/hex-map/PathPickerModal.ts +++ b/src/hex-map/PathPickerModal.ts @@ -217,7 +217,7 @@ export class PathPickerModal extends HexmakerModal { this.renderPathsOnMap(section, pathTypes); } - /** "Paths on this map": each path (type colour, name, what it is); click to select it on the map. */ + /** "Paths on this map": each path (type colour, name, its ends, forks and size); click to select it on the map. */ private renderPathsOnMap(container: HTMLElement, types: PathType[]): void { const pm = this.pathsOnMap; if (!pm) return; @@ -228,7 +228,7 @@ export class PathPickerModal extends HexmakerModal { } const list = container.createDiv({ cls: "duckmage-path-list" }); for (const p of pm.list) { - const row = list.createEl("button", { cls: "duckmage-path-list-row", attr: { title: `Select ${p.name} on the map` } }); + const row = list.createEl("button", { cls: "duckmage-path-list-row", attr: { title: `Select ${p.name} (${p.typeName}) on the map` } }); row.toggleClass("is-selected", p.name === pm.selected); const swatch = row.createSpan({ cls: "duckmage-path-list-swatch" }); const color = types.find((t) => t.name === p.typeName)?.color; diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 3af04b3f..0e820418 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -64,14 +64,14 @@ The **+** buttons at the edges of the map grow the grid one column or row in tha ## Drawing tools ### Paths -Pick a path type in the path picker (choose **Hex by hex** or **Auto-route** first; switch either way later from the bar at the top). Every path has a name and shows up under **Paths on this map** in the picker; click one there to select it. +Pick a path type in the path picker (choose **Hex by hex** or **Auto-route** first; switch either way later from the bar at the top). Every path has a name and shows up under **Paths on this map** in the picker, with its ends, forks and size; click one there to select it. -- **Draw:** click a hex to start, then keep clicking. Each click adds a point and the path finds its way there from the end, around impassable terrain, so you can click far away. In hex-by-hex mode, click neighbouring hexes; a click further away is routed too, and the bar says so. Click the end again, press **Esc** or **Done** to finish. +- **Draw:** click a hex to start, then keep clicking. Each click adds a point and the path finds its way there from the end, around impassable terrain, so you can click far away. In hex-by-hex mode, click neighbouring hexes (a click further away is routed too, and the bar says so), or press and drag: every hex you pass becomes a point, and going back a hex takes the last one away. The whole drag is one undo step. Click the end again, press **Esc** or **Done** to finish. - **Select:** click a path. Its points show as handles; the bigger ones are its ends. - **Continue or fork:** with a path selected, click an end to carry on from it, or click anywhere else on it to start a fork there. A path and its forks are one path in the map note. -- **Reshape:** drag any part of the selected path. Grabbing a point moves it; grabbing the line adds a point there. The new route shows as you drag; let go to keep it, or drop it back where it was to cancel. +- **Reshape:** drag any part of the selected path (in hex-by-hex mode, dragging from an end carries the path on instead). Grabbing a point moves it; grabbing the line adds a point there. The new route shows as you drag; let go to keep it, or drop it back where it was to cancel. - **New path:** **Alt-click**, or **New path** in the bar, starts a new path even on top of another one (a crossroads of two roads). -- **Delete:** right-click a handle, or hover one and press **Backspace**. Backspace while drawing removes the last point. Right-click a path for **Split here**, **Delete this fork**, **Delete path**, **Rename…**, **Change type…** and **Reverse**. In erase mode (the picker's ✕), click a path to split it there. +- **Delete:** right-click a handle, or hover one and press **Backspace**. Backspace while drawing removes the last point. Right-click a path: its own items come first (**Split here**, **Delete this fork**, **Delete path**, **Rename…**, **Change type…**, **Reverse**), then the tool's. In erase mode (the picker's ✕), click a path to split it there. - **Esc** steps out one level: finish the branch, then deselect, then leave the tool. **Ctrl/Cmd+Z** undoes each change. Mark terrains impassable in the palette editor (every water-type terrain is impassable by default). Each path type chooses whether it goes around them (roads do, rivers don't) and whether it winds. Tick **Cross impassable** in the bar to let the next legs go through. If painting terrain, changing the palette, resizing the map or changing a type's routing would move an existing path, it keeps its route (points are added to hold it) and a notice offers **Reroute instead**; undoing the paint stroke undoes that too. diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index 57b62fe9..2a95f5cf 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -201,6 +201,58 @@ export function pathSummary(p: MapPath): string { return forks ? `${p.typeName}, ${forks} fork${forks === 1 ? "" : "s"}` : p.typeName; } +/** What the path items of the right-click menu do. */ +export interface PathMenuActions { + split: () => void; + deleteBranch: () => void; + deletePath: () => void; + rename: () => void; + changeType: () => void; + reverse: () => void; +} + +/** + * The path's items in the right-click menu, in order (#48): Split here, + * Delete this fork (or main line; only with forks), Delete path, Rename…, + * Change type…, Reverse. The menu lists them above the tool's own items. + */ +export function pathMenuItems(p: MapPath, branch: number, act: PathMenuActions): { label: string; onClick: () => void }[] { + const items = [{ label: "Split here", onClick: act.split }]; + if (p.branches.length > 1) items.push({ label: branch === 0 ? "Delete main line" : "Delete this fork", onClick: act.deleteBranch }); + items.push( + { label: `Delete path: ${p.name}`, onClick: act.deletePath }, + { label: "Rename…", onClick: act.rename }, + { label: "Change type…", onClick: act.changeType }, + { label: "Reverse", onClick: act.reverse }, + ); + return items; +} + +const hexLabel = (k: HexKey): string => k.replace("_", ", "); + +/** + * "3, 4 → 9, 2 · 2 forks · 18 hexes": a path's ends (its main line's + * first and last routed hex), forks and size (distinct routed hexes over + * every branch), from the resolved routes, so paths with similar names + * (Road 2 … Road 6) can be told apart in "Paths on this map" (#48). + * Before the routes are resolved it falls back to the main line's anchors + * and leaves the size out. + */ +export function pathListSummary(p: MapPath, resolved: readonly ResolvedBranch[]): string { + const own = resolved.filter((r) => r.path === p.name); + const main = own.find((r) => r.branch === 0)?.hexes ?? p.branches[0]?.anchors ?? []; + const parts: string[] = []; + if (main.length) parts.push(main.length > 1 ? `${hexLabel(main[0])} → ${hexLabel(main[main.length - 1])}` : hexLabel(main[0])); + const forks = p.branches.length - 1; + if (forks) parts.push(`${forks} fork${forks === 1 ? "" : "s"}`); + if (own.length) { + const hexes = new Set(); + for (const r of own) for (const h of r.hexes) hexes.add(h); + parts.push(`${hexes.size} hex${hexes.size === 1 ? "" : "es"}`); + } + return parts.join(" · "); +} + // ── The controller ─────────────────────────────────────────────────────────── /** What the tool needs from the map view. */ @@ -242,6 +294,60 @@ interface Drag { cleanup: () => void; } +/** The branch end a draw adds to: a path (by name), its branch, which end. */ +interface DrawTarget { + name: string; + branch: number; + end: "head" | "tail"; +} + +/** Hex-by-hex press-and-drag: every hex the pointer enters becomes an anchor; one commit on release. */ +interface DrawDrag { + /** What a click at the press would have done (start, append, finish or continue). */ + outcome: PathClick; + pressHex: HexKey; + lastHex: HexKey; + startX: number; + startY: number; + started: boolean; + /** The paths as drawn so far (shown as the preview; committed on release). */ + work: MapPath[] | null; + target: DrawTarget | null; + /** The branch's anchor count before the drag: only anchors past it can be stepped back over. */ + baseLen: number; + /** Some entered hex couldn't be reached (impassable, off the map) and was skipped. */ + blocked: boolean; + frame: number | null; + cleanup: () => void; +} + +/** + * One anchor added to a branch end (pure): `leg` is what legAnchors gives + * from the end to `key` (tail) or from `key` to the end (head), the new + * anchor included last (tail) / the end included last (head). + */ +export function extendBranch(p: MapPath, branch: number, end: "head" | "tail", key: HexKey, leg: readonly HexKey[]): MapPath { + if (end === "tail") return leg.reduce((q, k) => appendAnchor(q, branch, k), p); + const q = clonePath(p); + q.branches[branch].anchors = [key, ...leg.slice(0, -1), ...p.branches[branch].anchors]; + return q; +} + +/** + * Drag-drawing stepped back into the hex before the end: drop the end + * anchor (pure). Only anchors the drag added (past `baseLen`) go; null + * when `key` isn't that hex or the end wasn't added by this drag. + */ +export function stepBack(p: MapPath, branch: number, end: "head" | "tail", key: HexKey, baseLen: number): MapPath | null { + const a = p.branches[branch]?.anchors; + if (!a || a.length <= baseLen || a.length < 2) return null; + const prev = end === "tail" ? a[a.length - 2] : a[1]; + if (prev !== key) return null; + const q = clonePath(p); + q.branches[branch].anchors = end === "tail" ? a.slice(0, -1) : a.slice(1); + return q; +} + /** Decorations the path layer draws for the tool. */ export interface PathToolOverlay { /** The selected path (drawn highlighted). */ @@ -268,6 +374,7 @@ export class PathTool { hint: string | null = null; private hover: { branch: number; anchor: number } | null = null; private drag: Drag | null = null; + private drawDrag: DrawDrag | null = null; private suppressClick = false; private strokeMemo: { resolved: readonly ResolvedBranch[]; strokes: PathStroke[] } | null = null; @@ -319,6 +426,12 @@ export class PathTool { /** The hex clicks add to, if any. */ activeHex(): HexKey | null { + const t = this.drawDrag?.target; + const work = this.drawDrag?.work; + if (work && t) { + const a = work.find((p) => p.name === t.name)?.branches[t.branch]?.anchors; + if (a?.length) return t.end === "head" ? a[0] : a[a.length - 1]; + } if (this.pending) return this.pending.hex; const p = this.pathNamed(this.selected); if (!p || !this.active) return null; @@ -432,6 +545,7 @@ export class PathTool { /** Leave the tool (or switch map): forget everything but the picked type and switches. */ reset(): void { this.cancelDrag(); + this.cancelDrawDrag(); this.selected = null; this.active = null; this.pending = null; @@ -505,6 +619,10 @@ export class PathTool { this.cancelDrag(); return true; } + if (this.drawDrag) { + this.cancelDrawDrag(); + return true; + } if (this.isDrawing() || this.forceNew || this.selected !== null) { this.done(); return true; @@ -579,15 +697,16 @@ export class PathTool { * impassable terrain is pinned with whatever anchors make the normal * router reproduce it. Null (with a notice) when there's no route. */ - private legAnchors(from: HexKey, to: HexKey, typeName: string): HexKey[] | null { + private legAnchors(from: HexKey, to: HexKey, typeName: string, quiet = false): HexKey[] | null { const router: RouteCache | null = this.plugin.paths.router(this.map); if (!router) return null; + const say = (msg: string) => { if (!quiet) new Notice(msg); }; const style = this.plugin.paths.styleOf(this.map, typeName); const seg = router.route(from, to, style); if (this.crossImpassable && style.avoid) { const through = router.route(from, to, { ...style, avoid: false }); if (through.fallback) { - new Notice("Both ends must be on the map."); + say("Both ends must be on the map."); return null; } const same = !seg.fallback && seg.hexes.length === through.hexes.length && seg.hexes.every((k, i) => k === through.hexes[i]); @@ -595,11 +714,11 @@ export class PathTool { return anchorsFor(through.hexes, routeFnFor(router, style), router.context ?? undefined).slice(1); } if (seg.fallback === "out-of-bounds") { - new Notice("Both ends must be on the map."); + say("Both ends must be on the map."); return null; } if (seg.fallback === "no-route") { - new Notice(noRouteMessage(style.avoid ? impassableNames(this.plugin.getMapPalette(this.map)) : [])); + say(noRouteMessage(style.avoid ? impassableNames(this.plugin.getMapPalette(this.map)) : [])); return null; } return [to]; @@ -615,61 +734,59 @@ export class PathTool { if (!near) this.hint = "not next to the end, so the gap was routed"; } - /** Add an anchor at `key` from the active end (creating a started path or fork). */ - private append(key: HexKey): void { + /** + * Where the next anchor goes, as paths + a branch end: a started path or + * fork is created here (with its one anchor) in a copy of the map's + * paths; an active end is used as it is. Null when nothing is being drawn. + */ + private drawTarget(): { paths: MapPath[]; target: DrawTarget } | null { const pending = this.pending; if (pending?.kind === "new") { const type = this.typeName; - if (!type) return; - const leg = this.legAnchors(pending.hex, key, type); - if (!leg) return; + if (!type) return null; const p = newPath(type, pending.hex, this.paths().map((q) => q.name)); - p.branches[0].anchors.push(...leg); - this.noteGap(pending.hex, key); - if (this.commit([...clonePaths(this.paths()), p])) { - this.pending = null; - this.selected = p.name; - this.active = { branch: 0, end: "tail" }; - } - return; + return { paths: [...clonePaths(this.paths()), p], target: { name: p.name, branch: 0, end: "tail" } }; } if (pending?.kind === "fork") { const base = this.pathNamed(pending.path); - if (!base) { - this.pending = null; - return; - } - const leg = this.legAnchors(pending.hex, key, base.typeName); - if (!leg) return; + if (!base) return null; const { path, branch } = forkAt(base, pending.hex); - path.branches[branch].anchors.push(...leg); - this.noteGap(pending.hex, key); - if (this.commit(this.replacePath(base.name, path))) { - this.pending = null; - this.selected = path.name; - this.active = { branch, end: "tail" }; - } - return; + return { paths: this.replacePath(base.name, path), target: { name: path.name, branch, end: "tail" } }; } const p = this.pathNamed(this.selected); - const act = this.active; - if (!p || !act) return; - const anchors = p.branches[act.branch].anchors; - if (act.end === "tail") { - const from = anchors[anchors.length - 1]; - const leg = this.legAnchors(from, key, p.typeName); - if (!leg) return; - this.noteGap(from, key); - this.commit(this.replacePath(p.name, leg.reduce((q, k) => appendAnchor(q, act.branch, k), p))); - } else { - // The branch runs head → tail, so the new leg is routed key → head. - const from = anchors[0]; - const leg = this.legAnchors(key, from, p.typeName); - if (!leg) return; - this.noteGap(from, key); - const q = clonePath(p); - q.branches[act.branch].anchors = [key, ...leg.slice(0, -1), ...anchors]; - this.commit(this.replacePath(p.name, q)); + if (!p || !this.active || !p.branches[this.active.branch]) return null; + return { paths: clonePaths(this.paths()), target: { name: p.name, ...this.active } }; + } + + /** `paths` with an anchor added at `key` on the target's end (routed from it); null when it can't be reached. */ + private extendTo(paths: readonly MapPath[], t: DrawTarget, key: HexKey, quiet = false): MapPath[] | null { + const p = paths.find((q) => q.name === t.name); + const anchors = p?.branches[t.branch]?.anchors; + if (!p || !anchors?.length) return null; + const endHex = t.end === "tail" ? anchors[anchors.length - 1] : anchors[0]; + if (endHex === key) return null; + // The branch runs head → tail, so a head leg is routed key → head. + const leg = t.end === "tail" ? this.legAnchors(endHex, key, p.typeName, quiet) : this.legAnchors(key, endHex, p.typeName, quiet); + if (!leg) return null; + const next = extendBranch(p, t.branch, t.end, key, leg); + return paths.map((q) => (q === p ? next : q)); + } + + /** Add an anchor at `key` from the active end (creating a started path or fork). */ + private append(key: HexKey): void { + const d = this.drawTarget(); + if (!d) { + if (this.pending?.kind === "fork") this.pending = null; + return; + } + const from = this.activeHex(); + const next = this.extendTo(d.paths, d.target, key); + if (!next) return; + if (from) this.noteGap(from, key); + if (this.commit(next)) { + this.pending = null; + this.selected = d.target.name; + this.active = { branch: d.target.branch, end: d.target.end }; } } @@ -807,24 +924,23 @@ export class PathTool { const p = this.pathNamed(hit.path); if (!p) return null; const { path, branch, hexIdx } = hit; - const items: { label: string; onClick: () => void }[] = [ - { label: "Split here", onClick: () => this.split(path, branch, hexIdx) }, - ]; - if (p.branches.length > 1) items.push({ label: branch === 0 ? "Delete main line" : "Delete this fork", onClick: () => this.deleteBranch(path, branch) }); - items.push( - { label: `Delete path: ${p.name}`, onClick: () => this.deletePath(path) }, - { label: "Rename…", onClick: () => this.rename(path) }, - { label: "Change type…", onClick: () => this.changeType(path) }, - { label: "Reverse", onClick: () => this.reverse(path, branch) }, - ); - return { items }; + return { + items: pathMenuItems(p, branch, { + split: () => this.split(path, branch, hexIdx), + deleteBranch: () => this.deleteBranch(path, branch), + deletePath: () => this.deletePath(path), + rename: () => this.rename(path), + changeType: () => this.changeType(path), + reverse: () => this.reverse(path, branch), + }), + }; } // ── pointer: hover and drag ── /** Pointer moved (no button): hover an anchor handle, show "grab" over the selected path. */ pointerMove(e: { clientX: number; clientY: number }): void { - if (this.drag || this.selected === null || this.isDrawing()) { + if (this.drag || this.drawDrag || this.selected === null || this.isDrawing()) { if (this.hover) { this.hover = null; this.host.redraw(); } this.host.setGrabCursor(false); return; @@ -839,12 +955,21 @@ export class PathTool { } /** - * Left button down: on the selected path (not while drawing, erasing or - * with Alt), get ready to drag. Returns true when it took the press. + * Left button down. Hex by hex: where a click would draw (start a path, + * add to the active end, or continue from an end handle), get ready to + * drag-draw. Otherwise, on the selected path (not while drawing, erasing + * or with Alt), get ready to drag it into a new shape. Returns true when + * it took the press (and stops the browser's own image drag, so a press + * on a hex icon works too). */ pointerDown(e: MouseEvent, erasing: boolean): boolean { - if (e.button !== 0 || erasing || e.altKey || this.forceNew || this.isDrawing() || this.selected === null) return false; + if (e.button !== 0 || erasing) return false; if (!this.plugin.paths.isReady(this.map)) return false; + if (!this.autoRoute && this.beginDrawDrag(e)) { + e.preventDefault(); + return true; + } + if (e.altKey || this.forceNew || this.isDrawing() || this.selected === null) return false; const hit = this.hitAt(e); if (!hit || hit.path !== this.selected) return false; const rb = this.branchRoute(hit.path, hit.branch); @@ -873,9 +998,168 @@ export class PathTool { doc.removeEventListener("mouseup", onUp); }, }; + e.preventDefault(); + return true; + } + + // ── hex-by-hex press-and-drag drawing ── + + /** Hex by hex: a press where a click would draw gets ready to drag-draw (nothing changes until the pointer leaves the hex). */ + private beginDrawDrag(e: MouseEvent): boolean { + const key = this.host.hexAtPoint(e.clientX, e.clientY); + if (!key) return false; + const forceNew = this.forceNew || e.altKey; + const activeHex = this.activeHex(); + const hit = !forceNew && activeHex === null ? this.hitAt(e) : null; + const outcome = pathClickOutcome({ erasing: false, forceNew, activeHex, selected: this.selected }, key, hit); + if (outcome.kind !== "start" && outcome.kind !== "append" && outcome.kind !== "finish" && outcome.kind !== "continue") return false; + if (outcome.kind === "start" && !(this.typeName ?? this.currentType())) return false; + if (!canEditPaths(this.map, "draw")) return false; + const doc = this.host.ownerDocument(); + const onMove = (ev: MouseEvent) => this.drawDragMove(ev); + const onUp = () => this.drawDragEnd(); + doc.addEventListener("mousemove", onMove); + doc.addEventListener("mouseup", onUp); + this.drawDrag = { + outcome, + pressHex: key, + lastHex: key, + startX: e.clientX, + startY: e.clientY, + started: false, + work: null, + target: null, + baseLen: 0, + blocked: false, + frame: null, + cleanup: () => { + doc.removeEventListener("mousemove", onMove); + doc.removeEventListener("mouseup", onUp); + }, + }; return true; } + /** + * The pointer left the pressed hex: do what the press would have done + * as a click (start the path, continue from the end, add the pressed + * hex), in a working copy. False when there's nothing to draw from. + */ + private startDrawDrag(d: DrawDrag): boolean { + const o = d.outcome; + if (o.kind === "start") { + if (!this.typeName) this.typeName = this.currentType(); + if (!this.typeName) return false; + this.forceNew = false; + this.selected = null; + this.active = null; + this.pending = { kind: "new", hex: d.pressHex }; + } else if (o.kind === "continue") { + this.selected = o.path; + this.active = { branch: o.branch, end: o.end }; + this.pending = null; + } + this.hint = null; + const t = this.drawTarget(); + if (!t) return false; + const len = (paths: readonly MapPath[]) => paths.find((p) => p.name === t.target.name)?.branches[t.target.branch]?.anchors.length ?? 0; + d.baseLen = this.pending?.kind === "new" ? 0 : len(t.paths); + d.target = t.target; + d.work = t.paths; + // A press away from the active end adds that hex first, as a click would. + if (o.kind === "append") { + const next = this.extendTo(d.work, d.target, d.pressHex, true); + if (next) d.work = next; + else d.blocked = true; + } + return true; + } + + /** One hex entered: it becomes an anchor (or, stepping back into the hex before the end, the end goes). */ + private drawStep(d: DrawDrag, key: HexKey): void { + const t = d.target; + if (!t || !d.work) return; + const p = d.work.find((q) => q.name === t.name); + if (!p) return; + const back = stepBack(p, t.branch, t.end, key, d.baseLen); + if (back) { + d.work = d.work.map((q) => (q === p ? back : q)); + return; + } + const next = this.extendTo(d.work, t, key, true); + if (next) d.work = next; + else d.blocked = true; + } + + private drawDragMove(e: MouseEvent): void { + const d = this.drawDrag; + if (!d) return; + if (!d.started && Math.hypot(e.clientX - d.startX, e.clientY - d.startY) <= 4) return; + const hex = this.host.hexAtPoint(e.clientX, e.clientY); + if (!hex || hex === d.lastHex) return; + if (!d.started) { + d.started = true; + if (!this.startDrawDrag(d)) { + this.cancelDrawDrag(); + return; + } + } + d.lastHex = hex; + // Every hex is taken now (none skipped); the preview redraws once per frame. + this.drawStep(d, hex); + if (d.frame === null) { + d.frame = window.requestAnimationFrame(() => { + d.frame = null; + if (this.drawDrag === d) this.showDrawPreview(d); + }); + } + } + + private showDrawPreview(d: DrawDrag): void { + this.plugin.paths.setPreview(this.map, d.work); + this.strokeMemo = null; + this.host.redraw(); + } + + /** Release: the whole drag is one commit (one undo step). */ + private drawDragEnd(): void { + const d = this.drawDrag; + if (!d) return; + d.cleanup(); + if (d.frame !== null) window.cancelAnimationFrame(d.frame); + this.drawDrag = null; + if (!d.started) return; // a click: the click handler takes it + this.suppressClick = true; + window.setTimeout(() => { this.suppressClick = false; }, 0); + this.plugin.paths.setPreview(this.map, null); + this.strokeMemo = null; + const t = d.target; + if (t && d.work && this.commit(d.work)) { + this.pending = null; + this.selected = t.name; + this.active = { branch: t.branch, end: t.end }; + } + this.hint = d.blocked ? "some hexes couldn't be reached and were skipped" : null; + this.host.redraw(); + this.host.refreshBar(); + } + + private cancelDrawDrag(): void { + const d = this.drawDrag; + if (!d) return; + d.cleanup(); + if (d.frame !== null) window.cancelAnimationFrame(d.frame); + this.drawDrag = null; + if (d.started) { + this.suppressClick = true; + window.setTimeout(() => { this.suppressClick = false; }, 0); + } + this.plugin.paths.setPreview(this.map, null); + this.strokeMemo = null; + this.host.redraw(); + this.host.refreshBar(); + } + private dragMove(e: MouseEvent): void { const d = this.drag; if (!d) return; @@ -942,7 +1226,7 @@ export class PathTool { /** Is a drag under way (its click must not count)? */ isDragging(): boolean { - return !!this.drag?.started; + return !!this.drag?.started || !!this.drawDrag?.started; } // ── mode bar controls ── diff --git a/styles.css b/styles.css index 024d3403..aa220511 100644 --- a/styles.css +++ b/styles.css @@ -377,6 +377,18 @@ z-index: 5; } +/* The path tool's anchor handles and active-end dot: over the paths AND + the icon layer (elevated override and GM icons), so no icon hides a + handle (#48). Placed in em like the paths. */ +.duckmage-path-handles-svg { + position: absolute; + top: 0; + left: 0; + overflow: visible; + pointer-events: none; + z-index: 6; +} + /* SVG overlay for faction color fills — sits below paths */ .duckmage-faction-svg { position: absolute; @@ -5654,6 +5666,13 @@ tr:hover .duckmage-rt-entry-copy-btn:hover { color: var(--text-accent); } +/* Between the items about what's under the pointer and the tool's own. */ +.duckmage-painter-ctx-separator { + height: 1px; + margin: 4px 0; + background: var(--background-modifier-border); +} + /* ── Stagger offset toggle button ────────────────────────────────────────── */ .duckmage-stagger-toggle { @@ -8234,6 +8253,15 @@ button.duckmage-terrain-legend-chip { min-height: 1.4em; margin-top: 0.3em; color: var(--text-error); + font-size: var(--font-ui-small); +} +/* Save while the name is empty or taken: Obsidian's disabled look, even + on a mod-cta button (#48). */ +.duckmage-path-name-modal button.mod-disabled, +.duckmage-path-name-modal button:disabled { + opacity: 0.5; + cursor: not-allowed; + box-shadow: none; } /* Path tool: the mode bar text wraps (it has more to say and more controls). */ diff --git a/tests/pathToolPolish.test.ts b/tests/pathToolPolish.test.ts new file mode 100644 index 00000000..2749a850 --- /dev/null +++ b/tests/pathToolPolish.test.ts @@ -0,0 +1,263 @@ +/** + * Path tool polish (#48): the "Paths on this map" summary, the right-click + * menu's order and separator, the rename box's Save state, and hex-by-hex + * press-and-drag drawing (every hex entered is an anchor; one undo step). + */ +import { describe, it, beforeEach } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { Notice } from "obsidian"; +import type { MapData, MapPath, PathType } from "../src/types"; +import { + extendBranch, + pathListSummary, + pathMenuItems, + PathTool, + stepBack, + type PathMenuActions, +} from "../src/hex-map/pathTool"; +import { painterMenuEntries } from "../src/hex-map/PainterContextMenu"; +import { pathNameState } from "../src/hex-map/PathNameModal"; +import { resolvePaths } from "../src/paths/resolve"; +import type { RouteContext } from "../src/paths/router"; +import { PathsService } from "../src/paths/PathsService"; + +const ROAD: PathType = { name: "Road", color: "#a33", width: 4, lineStyle: "solid", routing: "through", avoidImpassable: true, autoRoute: "direct" }; +const ctx: RouteContext = { orientation: "flat", stagger: "odd", bounds: { minX: 0, minY: 0, maxX: 19, maxY: 15 }, blocked: new Set() }; + +describe('"Paths on this map" summary (#48)', () => { + it("ends of the main line, forks and distinct routed hexes, from the resolved routes", () => { + const p: MapPath = { name: "Road 3", typeName: "Road", branches: [{ anchors: ["3_4", "9_4"] }, { anchors: ["6_4", "6_9"] }, { anchors: ["7_4", "7_1"] }] }; + const resolved = resolvePaths([p], ctx); + const hexes = new Set(resolved.flatMap((r) => r.hexes)); + expect(pathListSummary(p, resolved)).toBe(`3, 4 → 9, 4 · 2 forks · ${hexes.size} hexes`); + }); + + it("one fork, singular; no forks, none mentioned; other paths' routes don't count", () => { + const a: MapPath = { name: "Road 2", typeName: "Road", branches: [{ anchors: ["0_0", "3_0"] }, { anchors: ["1_0", "1_3"] }] }; + const b: MapPath = { name: "Road 4", typeName: "Road", branches: [{ anchors: ["0_8", "5_8"] }] }; + const resolved = resolvePaths([a, b], ctx); + expect(pathListSummary(a, resolved)).toMatch(/^0, 0 → 3, 0 · 1 fork · \d+ hexes$/); + expect(pathListSummary(b, resolved)).toBe("0, 8 → 5, 8 · 6 hexes"); + }); + + it("before the routes are resolved: the main line's anchors, no size", () => { + const p: MapPath = { name: "Road 5", typeName: "Road", branches: [{ anchors: ["2_2", "4_4", "8_1"] }] }; + expect(pathListSummary(p, [])).toBe("2, 2 → 8, 1"); + expect(pathListSummary({ name: "Lone", typeName: "Road", branches: [{ anchors: ["1_1"] }] }, [])).toBe("1, 1"); + }); + + it("never renames: the summary is beside the name, not part of it", () => { + const p: MapPath = { name: "Road 6", typeName: "Road", branches: [{ anchors: ["0_0", "2_0"] }] }; + expect(pathListSummary(p, resolvePaths([p], ctx))).not.toContain("Road 6"); + }); +}); + +describe("right-click menu: path items first, a separator, then the tool's (#48)", () => { + const noop = () => {}; + const acts: PathMenuActions = { split: noop, deleteBranch: noop, deletePath: noop, rename: noop, changeType: noop, reverse: noop }; + + it("path items in order: Split here, Delete this fork, Delete path, Rename…, Change type…, Reverse", () => { + const forked: MapPath = { name: "King's Road", typeName: "Road", branches: [{ anchors: ["0_0", "4_0"] }, { anchors: ["2_0", "2_4"] }] }; + expect(pathMenuItems(forked, 1, acts).map((i) => i.label)).toEqual([ + "Split here", "Delete this fork", "Delete path: King's Road", "Rename…", "Change type…", "Reverse", + ]); + expect(pathMenuItems(forked, 0, acts)[1].label).toBe("Delete main line"); + const single: MapPath = { name: "Road", typeName: "Road", branches: [{ anchors: ["0_0", "4_0"] }] }; + expect(pathMenuItems(single, 0, acts).map((i) => i.label)).toEqual(["Split here", "Delete path: Road", "Rename…", "Change type…", "Reverse"]); + }); + + it("the tool's items follow a separator; with no path under the pointer there's no separator", () => { + const lead = [{ label: "Split here", onClick: noop }, { label: "Reverse", onClick: noop }]; + const extra = [{ label: "Erase mode", onClick: noop }, { label: "New path", onClick: noop }]; + const rows = painterMenuEntries(lead, noop, "Switch path type", noop, extra); + expect(rows.map((r) => ("separator" in r ? "---" : r.label))).toEqual([ + "Split here", "Reverse", "---", "Switch path type", "Exit tool", "Erase mode", "New path", + ]); + const plain = painterMenuEntries([], null, "Switch", noop, extra); + expect(plain.map((r) => ("separator" in r ? "---" : r.label))).toEqual(["Exit tool", "Erase mode", "New path"]); + }); +}); + +describe("rename box: Save is disabled with a reason while the name is empty or taken (#48)", () => { + const taken = (n: string) => (n.toLowerCase() === "road 2" ? `There's already a path called ${n} on this map.` : null); + + it("taken or empty: no name, a reason", () => { + expect(pathNameState("Road 2", "Road 3", taken)).toEqual({ name: null, problem: "There's already a path called Road 2 on this map." }); + expect(pathNameState(" ", "Road 3", taken)).toEqual({ name: null, problem: "A path needs a name." }); + }); + + it("free, or unchanged: the cleaned name, no reason", () => { + expect(pathNameState(" King's Road ", "Road 3", taken)).toEqual({ name: "King's Road", problem: null }); + expect(pathNameState("Road 3", "Road 3", taken)).toEqual({ name: "Road 3", problem: null }); + }); +}); + +describe("drawing helpers (pure)", () => { + const p: MapPath = { name: "R", typeName: "Road", branches: [{ anchors: ["2_2", "3_2"] }] }; + + it("extendBranch adds at the tail, or before the head", () => { + expect(extendBranch(p, 0, "tail", "4_2", ["4_2"]).branches[0].anchors).toEqual(["2_2", "3_2", "4_2"]); + expect(extendBranch(p, 0, "head", "1_2", ["2_2"]).branches[0].anchors).toEqual(["1_2", "2_2", "3_2"]); + expect(p.branches[0].anchors).toEqual(["2_2", "3_2"]); + }); + + it("stepBack drops the end only when re-entering the hex before it, and only anchors the drag added", () => { + expect(stepBack(p, 0, "tail", "2_2", 1)?.branches[0].anchors).toEqual(["2_2"]); + expect(stepBack(p, 0, "tail", "2_2", 2)).toBeNull(); + expect(stepBack(p, 0, "tail", "5_5", 0)).toBeNull(); + expect(stepBack(p, 0, "head", "3_2", 1)?.branches[0].anchors).toEqual(["3_2"]); + }); +}); + +describe("anchor handles sit over the icon layers (#48)", () => { + const root = process.cwd(); + const css = readFileSync(path.join(root, "styles.css"), "utf8").replace(/\r\n/g, "\n"); + const view = readFileSync(path.join(root, "src", "hex-map", "HexMapView.ts"), "utf8").replace(/\r\n/g, "\n"); + const z = (cls: string) => Number(new RegExp(`\\.${cls} \\{[^}]*z-index: (\\d+)`).exec(css)?.[1]); + + it("their own layer stacks above the paths and the elevated override / GM icon layer", () => { + expect(z("duckmage-path-handles-svg")).toBeGreaterThan(z("duckmage-path-icons-svg")); + expect(z("duckmage-path-handles-svg")).toBeGreaterThan(z("duckmage-path-svg")); + expect(css).toMatch(/\.duckmage-path-handles-svg \{[^}]*pointer-events: none/); + }); + + it("the view draws handles and the active-end dot there, not in the path layer", () => { + const body = view.slice(view.indexOf(" private renderPathOverlay("), view.indexOf(" private updatePathIcons(")); + const handlesAt = body.indexOf('emSvg("duckmage-path-handles-svg")'); + expect(handlesAt).toBeGreaterThan(body.indexOf('emSvg("duckmage-path-svg")')); + expect(body.slice(handlesAt)).toMatch(/duckmage-svg-path-handle[\s\S]*if \(dot\)/); + }); + + it("a press the tool takes stops the browser's image drag (a press on a hex icon still drags)", () => { + const tool = readFileSync(path.join(root, "src", "hex-map", "pathTool.ts"), "utf8").replace(/\r\n/g, "\n"); + const down = tool.slice(tool.indexOf(" pointerDown(e: MouseEvent"), tool.indexOf(" // ── hex-by-hex press-and-drag drawing ──")); + expect(down.match(/e\.preventDefault\(\);\s*return true;/g)).toHaveLength(2); + }); +}); + +// ── The controller, against an in-memory map ──────────────────────────────── + +type Listener = (e: unknown) => void; + +function rig() { + const map = { name: "m", paletteName: "Default", gridSize: { cols: 20, rows: 16 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", paths: [] as MapPath[] } as unknown as MapData; + const svc = new PathsService({ + isMapReady: () => true, + getMap: (n) => (n === "m" ? map : undefined), + orientation: () => "flat", + stagger: () => "odd", + pathTypes: () => [ROAD], + palette: () => [], + hexData: () => new Map(), + }); + const plugin = { + app: {}, + mapStore: { paths: () => map.paths ?? [], setPaths: (_n: string, ps: MapPath[]) => { map.paths = ps; } }, + paths: svc, + pathPins: { sync: () => {} }, + saveSettings: async () => {}, + getMapPalette: () => [], + }; + const listeners = new Map>(); + const doc = { + addEventListener: (t: string, f: Listener) => { if (!listeners.has(t)) listeners.set(t, new Set()); listeners.get(t)!.add(f); }, + removeEventListener: (t: string, f: Listener) => { listeners.get(t)?.delete(f); }, + }; + const undo: { before: MapPath[]; after: MapPath[] }[] = []; + const tool = new PathTool({ + plugin: plugin as never, + mapName: () => "m", + pointerLattice: () => null, + // A hex is 100 px square here: (x, y) ↔ (100x, 100y). + hexAtPoint: (cx, cy) => `${Math.round(cx / 100)}_${Math.round(cy / 100)}`, + ownerDocument: () => doc as unknown as Document, + pushUndo: (_m, before, after) => { undo.push({ before, after }); }, + redraw: () => {}, + refreshBar: () => {}, + setGrabCursor: () => {}, + }); + tool.typeName = "Road"; + const at = (hex: string) => { const [x, y] = hex.split("_").map(Number); return { clientX: x * 100, clientY: y * 100 }; }; + const ev = (hex: string, o: Record = {}) => ({ button: 0, altKey: false, preventDefault: () => {}, ...at(hex), ...o }) as unknown as MouseEvent; + const fire = (t: string, e: unknown) => { for (const f of [...(listeners.get(t) ?? [])]) f(e); }; + /** Press at the first hex, move through the rest, release. */ + const drag = (hexes: string[]) => { + const took = tool.pointerDown(ev(hexes[0]), false); + for (const h of hexes.slice(1)) fire("mousemove", ev(h)); + fire("mouseup", ev(hexes[hexes.length - 1])); + flushFrames(); + return took; + }; + return { map, tool, undo, drag, ev, listeners }; +} + +const frames: (() => void)[] = []; +function flushFrames() { while (frames.length) frames.shift()!(); } +const g = globalThis as Record; +g.window ??= globalThis; +g.requestAnimationFrame = (cb: () => void) => { frames.push(cb); return frames.length; }; +g.cancelAnimationFrame = () => {}; + +describe("hex-by-hex press-and-drag (#48)", () => { + beforeEach(() => { Notice.shown = []; }); + + it("every hex entered becomes an anchor, and the whole drag is one undo step", () => { + const { map, tool, undo, drag } = rig(); + expect(drag(["2_2", "3_2", "4_2", "5_2", "6_2"])).toBe(true); + expect(map.paths).toEqual([{ name: "Road", typeName: "Road", branches: [{ anchors: ["2_2", "3_2", "4_2", "5_2", "6_2"] }] }]); + expect(undo).toHaveLength(1); + expect(undo[0].before).toEqual([]); + expect(undo[0].after).toEqual(map.paths); + expect(tool.selected).toBe("Road"); + expect(tool.active).toEqual({ branch: 0, end: "tail" }); + expect(Notice.shown).toEqual([]); + }); + + it("the click that ends a drag doesn't add another anchor", () => { + const { map, tool, undo, drag, ev } = rig(); + drag(["2_2", "3_2", "4_2"]); + tool.click(4, 2, ev("4_2"), false); + expect(map.paths![0].branches[0].anchors).toEqual(["2_2", "3_2", "4_2"]); + expect(undo).toHaveLength(1); + }); + + it("dragging on from the active end extends the branch, one more undo step", () => { + const { map, undo, drag } = rig(); + drag(["2_2", "3_2", "4_2"]); + drag(["4_2", "5_2", "6_2"]); + expect(map.paths![0].branches[0].anchors).toEqual(["2_2", "3_2", "4_2", "5_2", "6_2"]); + expect(undo).toHaveLength(2); + }); + + it("stepping back into the previous hex takes the last anchor away again", () => { + const { map, drag } = rig(); + drag(["2_2", "3_2", "4_2", "5_2", "4_2"]); + expect(map.paths![0].branches[0].anchors).toEqual(["2_2", "3_2", "4_2"]); + }); + + it("a press without leaving the hex is a click (nothing is committed by the drag)", () => { + const { map, undo, drag } = rig(); + drag(["2_2"]); + expect(map.paths).toEqual([]); + expect(undo).toHaveLength(0); + }); + + it("auto-route mode doesn't drag-draw (dragging reshapes a selected path, as before)", () => { + const { map, tool, undo, drag } = rig(); + tool.setAutoRoute(true); + expect(drag(["2_2", "3_2", "4_2"])).toBe(false); + expect(map.paths).toEqual([]); + expect(undo).toHaveLength(0); + }); + + it("Esc mid-drag cancels it: nothing is saved", () => { + const { map, tool, ev, listeners } = rig(); + tool.pointerDown(ev("2_2"), false); + for (const f of [...(listeners.get("mousemove") ?? [])]) f(ev("3_2")); + expect(tool.escape()).toBe(true); + expect(map.paths).toEqual([]); + expect(listeners.get("mousemove")?.size ?? 0).toBe(0); + }); +}); diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 516ed70c..f311fcbc 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -66,7 +66,8 @@ describe("Path tool right-click and tokens (fresh-eyes T2)", () => { const handler = viewSrc.slice(start, viewSrc.indexOf("{ capture: true }", start)); expect(handler).toMatch(/this\.drawingMode === "path"[\s\S]*this\.pathTool\.contextMenu\(e\)[\s\S]*"handled" in r\) return;[\s\S]*showPainterContextMenu\(e\.clientX, e\.clientY, hexX, hexY, pathItems\)/); const menu = toolMethod("contextMenu"); - for (const label of ["Split here", "Delete path: ", "Rename…", "Change type…", "Reverse"]) expect(menu).toContain(label); + expect(menu).toMatch(/pathMenuItems\(p, branch, \{/); + // The labels and their order: tests/pathToolPolish.test.ts (#48). expect(menu).toMatch(/hit\.anchor !== null\) \{\s*this\.deleteAnchor\(/); }); @@ -144,7 +145,10 @@ describe("Path tool upkeep (anchored paths)", () => { const click = toolMethod("click"); expect(click).toMatch(/this\.pending = \{ kind: "new", hex: key \}/); expect(click).not.toMatch(/commit\(/); - expect(toolMethod("append")).toMatch(/p\.branches\[0\]\.anchors\.push\(\.\.\.leg\)[\s\S]*this\.commit\(/); + // The started path is made (in a copy) only when the next anchor is added, then committed with it. + expect(toolMethod("append")).toMatch(/this\.drawTarget\(\)[\s\S]*this\.extendTo\([\s\S]*this\.commit\(/); + expect(toolMethod("drawTarget")).toMatch(/newPath\(type, pending\.hex/); + expect(toolMethod("drawTarget")).not.toMatch(/commit\(/); }); it("Esc steps out one level (drag → branch → selection) before leaving the tool; Backspace deletes an anchor", () => { From f13d875df1b1769ef0cce1c2c4aec629933837b4 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:35:07 -0400 Subject: [PATCH 240/558] fix(path tool): the paths list says what the map note's Route cell says pathListSummary reuses pathRouteText / pathRouteStats (read-only use of mapNote.ts and MapStore.ts), so the list and the note agree, type warnings included. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 3 ++- src/hex-map/pathTool.ts | 30 ++++++++++-------------------- tests/pathToolPolish.test.ts | 5 +++++ 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 7eaa324b..8a014241 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -5807,7 +5807,8 @@ export class HexMapView extends ItemView { // Ends, forks and size from the resolved routes (#48), so similar // names (Road 2 … Road 6) can be told apart. Names stay the user's. const resolved = this.plugin.paths.resolved(this.activeMapName); - return this.plugin.mapStore.paths(this.activeMapName).map((p) => ({ name: p.name, typeName: p.typeName, summary: pathListSummary(p, resolved) })); + const types = this.plugin.getMapPathTypes(this.activeMapName).map((t) => t.name); + return this.plugin.mapStore.paths(this.activeMapName).map((p) => ({ name: p.name, typeName: p.typeName, summary: pathListSummary(p, resolved, types) })); })(), selected: this.pathTool.selected, onPick: (name) => { diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index 2a95f5cf..695d6546 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -35,6 +35,8 @@ import { } from "../paths/edit"; import { anchorsFor, routeFnFor } from "../paths/fromHexes"; import { canEditPaths, type PathEditAction } from "../paths/editGate"; +import { pathRouteText } from "../maps/mapNote"; +import { pathRouteStats } from "../maps/MapStore"; import { impassableNames, noRouteMessage } from "../impassable"; import { hexNeighbors } from "./hexGeometry"; import { PathPickerModal } from "./PathPickerModal"; @@ -228,29 +230,17 @@ export function pathMenuItems(p: MapPath, branch: number, act: PathMenuActions): return items; } -const hexLabel = (k: HexKey): string => k.replace("_", ", "); - /** - * "3, 4 → 9, 2 · 2 forks · 18 hexes": a path's ends (its main line's - * first and last routed hex), forks and size (distinct routed hexes over - * every branch), from the resolved routes, so paths with similar names - * (Road 2 … Road 6) can be told apart in "Paths on this map" (#48). - * Before the routes are resolved it falls back to the main line's anchors - * and leaves the size out. + * "3, 4 → 9, 2 · 2 forks · 18 hexes": a path's ends, forks and size + * (distinct routed hexes over every branch, from the resolved routes), so + * paths with similar names (Road 2 … Road 6) can be told apart in "Paths + * on this map" (#48). It's the map note's own Route cell (pathRouteText, + * pathRouteStats), so the list and the note say the same thing, warnings + * included. Before the routes are resolved the size is left out. */ -export function pathListSummary(p: MapPath, resolved: readonly ResolvedBranch[]): string { +export function pathListSummary(p: MapPath, resolved: readonly ResolvedBranch[], pathTypes?: string[]): string { const own = resolved.filter((r) => r.path === p.name); - const main = own.find((r) => r.branch === 0)?.hexes ?? p.branches[0]?.anchors ?? []; - const parts: string[] = []; - if (main.length) parts.push(main.length > 1 ? `${hexLabel(main[0])} → ${hexLabel(main[main.length - 1])}` : hexLabel(main[0])); - const forks = p.branches.length - 1; - if (forks) parts.push(`${forks} fork${forks === 1 ? "" : "s"}`); - if (own.length) { - const hexes = new Set(); - for (const r of own) for (const h of r.hexes) hexes.add(h); - parts.push(`${hexes.size} hex${hexes.size === 1 ? "" : "es"}`); - } - return parts.join(" · "); + return pathRouteText(p, { pathRoutes: pathRouteStats([p], own), pathTypes }); } // ── The controller ─────────────────────────────────────────────────────────── diff --git a/tests/pathToolPolish.test.ts b/tests/pathToolPolish.test.ts index 2749a850..4a27054e 100644 --- a/tests/pathToolPolish.test.ts +++ b/tests/pathToolPolish.test.ts @@ -48,6 +48,11 @@ describe('"Paths on this map" summary (#48)', () => { expect(pathListSummary({ name: "Lone", typeName: "Road", branches: [{ anchors: ["1_1"] }] }, [])).toBe("1, 1"); }); + it("says what the map note's Route column says, warnings included", () => { + const p: MapPath = { name: "Old Way", typeName: "Causeway", branches: [{ anchors: ["0_0", "2_0"] }] }; + expect(pathListSummary(p, resolvePaths([p], ctx), ["Road", "River"])).toMatch(/^0, 0 → 2, 0 · 3 hexes · ⚠/); + }); + it("never renames: the summary is beside the name, not part of it", () => { const p: MapPath = { name: "Road 6", typeName: "Road", branches: [{ anchors: ["0_0", "2_0"] }] }; expect(pathListSummary(p, resolvePaths([p], ctx))).not.toContain("Road 6"); From a6d638e7928ecc3afc6bbb53e40c080b5baffdd1 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:41:34 -0400 Subject: [PATCH 241/558] fix(path tool): drag-draw refreshes the bar at its first hex; picker hint mentions press-and-drag Co-Authored-By: Claude Opus 5.5 --- src/hex-map/PathPickerModal.ts | 2 +- src/hex-map/pathTool.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/hex-map/PathPickerModal.ts b/src/hex-map/PathPickerModal.ts index 1f34f35a..89086bf6 100644 --- a/src/hex-map/PathPickerModal.ts +++ b/src/hex-map/PathPickerModal.ts @@ -117,7 +117,7 @@ export class PathPickerModal extends HexmakerModal { (ar.value ? "Click a start, then click far away: the path finds its own way there. Keep clicking to add more." + (ar.noImpassable ? " This palette has no impassable terrain yet: mark the terrains paths can't cross (e.g. water) in the palette editor." : "") - : "Click neighbouring hexes one by one (a click further away is routed for you).") + + : "Click neighbouring hexes one by one, or press and drag across them (a click further away is routed for you).") + " Click a path to select it, then drag its line to reshape it.", ); hint.createSpan({ text: " You can switch this while drawing, from the bar at the top." }); diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index 695d6546..48858bea 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -1093,6 +1093,8 @@ export class PathTool { this.cancelDrawDrag(); return; } + // The bar says "drawing" from the first hex, not only after release. + this.host.refreshBar(); } d.lastHex = hex; // Every hex is taken now (none skipped); the preview redraws once per frame. From c43e77c4f128435ada5d1d41ff384e8bfa1e5269 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:46:07 -0400 Subject: [PATCH 242/558] =?UTF-8?q?fix(overworld):=20Play=20greys=20out=20?= =?UTF-8?q?"New=20map=20from=20this=20hex=20=E2=86=92=20Region";=20Biomes?= =?UTF-8?q?=20tooltip=20names=20the=20region?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - In Play, the Region card of "New map from this hex…" is disabled with "Switch to Build to make a region." instead of opening a form whose Make region button is locked; startNewRegion refuses in Play too. - Biomes view: the hex tooltip ends with "Region: " (the purple outline that carried it is hidden on overworlds). README + help. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- src/hex-map/HexMapView.ts | 6 +++++- src/hex-map/help.md | 4 ++-- src/hex-map/hexHover.ts | 5 ++++- src/hex-map/newChildMap.ts | 6 +++++- tests/hexHover.test.ts | 5 +++++ 6 files changed, 23 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8757a659..3070c757 100644 --- a/README.md +++ b/README.md @@ -123,9 +123,9 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: - **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Painted hexes are locked, so remaking a region keeps them. -- **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one). Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. +- **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one; hover a hex for its region's name). Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. -**Work modes: Play, Build, God.** Each map has a work mode, always shown on the toolbar next to the map button; click it to switch. It's saved in the map note as a plain `mode:` property (`play`, `build` or `god`), so each map opens in its own mode; new maps are in Build. For now two rules are enforced on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs God; in Build and Play those buttons are greyed out with "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region), or making regions at all (**Make the missing regions…**), needs Build or God; in Play the biome picker is greyed out with "Switch to Build to place a biome." There are no confirm boxes for these any more: the mode is the safety catch. Note text is never locked in any mode, and settings and palettes aren't either. +**Work modes: Play, Build, God.** Each map has a work mode, always shown on the toolbar next to the map button; click it to switch. It's saved in the map note as a plain `mode:` property (`play`, `build` or `god`), so each map opens in its own mode; new maps are in Build. For now two rules are enforced on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs God; in Build and Play those buttons are greyed out with "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region), or making regions at all (**Make the missing regions…**), needs Build or God; in Play the biome picker is greyed out with "Switch to Build to place a biome.", and **New map from this hex… → Region** is greyed out with "Switch to Build to make a region." There are no confirm boxes for these any more: the mode is the safety catch. Note text is never locked in any mode, and settings and palettes aren't either. Which biome a hex is comes from its terrain's **Type**, never its name: forest-type terrains are temperate forest, wetland swamp, and so on. Where a type has variants, the **last** terrains of that type in the palette stand for them, in this order: forest → taiga, deep forest; grassland → savanna; hills → karst; wetland → river delta. Reorder the palette to choose (on Expanded: evergreen, evergreen heavy, savanna, jungle hills, river delta). A terrain with no type has no biome. diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 32d1ffcf..08e1ed43 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -5122,7 +5122,11 @@ export class HexMapView extends ItemView { // The notes it links (towns, dungeons…), from the metadata cache (S3). const note = this.app.vault.getAbstractFileByPath(hexPath); const linked = note instanceof TFile ? linkedNotesText(linksBySection(this.app.metadataCache.getFileCache(note)), this.plugin.sectionWordsFor(this.activeMapName)) : ""; - const label = hexHoverLabel(x, y, own, this.getActiveMap().baseTerrain ?? null, getHexNameFromFile(hexPath), linked); + // Biomes view: the region outline is hidden (every hex has one), so the + // tooltip names the hex's region instead. + const regionMap = OverworldLayer.viewOf(this.plugin, this.getActiveMap()) === "biomes" ? this.plugin.mapStore.get(this.activeMapName, `${x}_${y}`)?.regionMap : undefined; + const region = regionMap && this.plugin.getMap(regionMap) ? this.plugin.mapLabel(regionMap) : null; + const label = hexHoverLabel(x, y, own, this.getActiveMap().baseTerrain ?? null, getHexNameFromFile(hexPath), linked, region); if (hexEl.title !== label) { hexEl.title = label; hexEl.setAttr("aria-label", label); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index fad76fb2..c28b209c 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -128,9 +128,9 @@ Tokens show their name underneath. The layers panel's **Labels** group turns coo Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. -**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (click to set one: an empty hex gets its region). The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. +**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name; click to set one: an empty hex gets its region). The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. -**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards two things on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**; in Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region) needs **Build** or God; in Play the biome picker is greyed out and says "Switch to Build to place a biome." Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. +**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards two things on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**; in Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region) needs **Build** or God; in Play the biome picker is greyed out and says "Switch to Build to place a biome.", and **New map from this hex… → Region** says "Switch to Build to make a region." Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. diff --git a/src/hex-map/hexHover.ts b/src/hex-map/hexHover.ts index 20e6879f..f4c3aa04 100644 --- a/src/hex-map/hexHover.ts +++ b/src/hex-map/hexHover.ts @@ -10,6 +10,7 @@ export function hexHoverLabel( baseTerrain: string | null, name: string | null = null, linked = "", + region: string | null = null, ): string { const where = `hex ${x}, ${y}`; const label = ownTerrain @@ -18,7 +19,9 @@ export function hexHoverLabel( ? `${baseTerrain} (map base) · ${where}` : `Hex ${x}, ${y}`; // A named hex leads with its name (N1). - const full = name ? `${name} · ${label}` : label; + const named = name ? `${name} · ${label}` : label; + // An overworld hex in the Biomes view: its region (it has no outline there). + const full = region ? `${named} · Region: ${region}` : named; // Then what it links: "· Town: Gullmouth" (round 6 S3). return linked ? `${full} · ${linked}` : full; } diff --git a/src/hex-map/newChildMap.ts b/src/hex-map/newChildMap.ts index fd768d88..d20a5525 100644 --- a/src/hex-map/newChildMap.ts +++ b/src/hex-map/newChildMap.ts @@ -9,6 +9,7 @@ import { DEFAULT_REGION_SETTINGS, regionMapAt } from "../maps/submaps"; import { renderRegionSettingsForm } from "./regionSettingsForm"; import { meshes } from "../overworld/regionWorld"; import { RegionGenModal } from "./BiomeModals"; +import { ADD_REGION_LOCKED_HINT, canAdd } from "../workMode"; /** The two kinds of map a hex opens into, with the small line under each (K1). */ export const CHILD_KIND_TEXT: Record = { @@ -45,6 +46,8 @@ export function startNewLocation(host: NewChildMapHost, parentMap: string, x: nu export function startNewRegion(host: NewChildMapHost, parentMap: string, x: number, y: number): void { const parent = host.plugin.getMap(parentMap); if (!parent) return; + // Play mode: making a region is locked (the Region card says so too). + if (!canAdd(parent)) { new Notice(ADD_REGION_LOCKED_HINT); return; } const go = (settings: RegionSettings) => { // Rectangles join their neighbours: the region form (biome, blend, seed, // live preview) makes it in its slot of the shared grid. @@ -108,7 +111,8 @@ export class ChildKindModal extends HexmakerModal { const why = existing ? `This hex's region is ${plugin.mapLabel(existing.name)}.` - : !regionsOn ? "Advanced: needs Regions and overworlds." : undefined; + : !regionsOn ? "Advanced: needs Regions and overworlds." + : !canAdd(plugin.getMap(this.parentMap)) ? ADD_REGION_LOCKED_HINT : undefined; card("region", why); if (existing && this.host.onEnter) { const enter = contentEl.createEl("button", { cls: "duckmage-child-kind-enter", text: `Enter ${plugin.mapLabel(existing.name)}` }); diff --git a/tests/hexHover.test.ts b/tests/hexHover.test.ts index cf2915b2..7a72228d 100644 --- a/tests/hexHover.test.ts +++ b/tests/hexHover.test.ts @@ -19,6 +19,11 @@ describe("hexHoverLabel", () => { expect(hexHoverLabel(6, 6, "beach", null, null, "")).toBe("beach · hex 6, 6"); }); + it("names the hex's region after its coordinates (Biomes view, where the outline is hidden)", () => { + expect(hexHoverLabel(4, 2, "taiga", null, null, "", "Frostmarch")).toBe("taiga · hex 4, 2 · Region: Frostmarch"); + expect(hexHoverLabel(4, 2, "taiga", null, "Old Pass", "Town: Rime", "Frostmarch")).toBe("Old Pass · taiga · hex 4, 2 · Region: Frostmarch · Town: Rime"); + }); + it("falls back to the coordinates", () => { expect(hexHoverLabel(0, 0, null, null)).toBe("Hex 0, 0"); }); From 436499cc5a6fbd040912cdb02f843511904ad5c8 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:46:32 -0400 Subject: [PATCH 243/558] docs(CLAUDE.md): note-only map fields survive settings reloads; missing is not empty Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CLAUDE.md b/CLAUDE.md index 0d478f9e..20e631b1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -188,6 +188,7 @@ Renders an interactive hex-grid map for tabletop RPG world-building inside Obsid - `onChanged` callback from `HexEditorModal` defers `renderGrid()` 300 ms when no terrain/icon overrides are passed (link-only changes) to avoid a metadata-cache race after `vault.modify`. - Modals that preload file content accept an optional `preloaded` / `initialContent` parameter — callers that already hold the file content pass it in to avoid a redundant vault read. - **Map data lives in map notes, not hex notes.** Terrain, icon, GM icons, region, submap and locked are stored in `{hexFolder}/{map}/_{map}.md` (src/maps). Read/write them only through the `src/frontmatter.ts` getters/setters or `plugin.mapStore` — never `cache.frontmatter.terrain` etc., and never gate the read on the hex note existing (most hexes have no note; notes are created when a hex gets content). This mistake caused four separate regressions (submap rings, hex locks, editor terrain, exports) — see the KB plan note `plan-map-notes`. +- **Note-only fields survive a settings reload; missing ≠ empty.** data.json leaves out what only the map note holds (each map's `paths`/`pathChains`, via `withoutNotePaths`; hexes live only in `MapStore`). So `loadSettings` / `onExternalSettingsChange` hand out fresh `MapData` objects WITHOUT those fields, and Obsidian fires `onExternalSettingsChange` for our own saves during a save burst. Never read a missing note-only field as "empty" (`map.paths ?? []` feeding a write is the trap): `MapStore.adopt()` carries the store's copy onto fresh objects, `loadSettings` must not `await` between swapping `this.settings` and `mapStore.adoptAll()`, and `MapStore.writeNote` refuses to drop every path/hex a note holds unless an edit cleared them (`clearedPaths`/`clearedHexes`). Any new field stored only in the map note needs the same treatment. Incident: 2026-10-10 paths wiped when creating a region next to a map (KB `incident-2026-10-10-path-loss-on-external-reload`; regression tests `tests/pathLossReload.test.ts`). - Exclude notes whose `basename` starts with `"_"` whenever enumerating vault files for display, dropdowns, or linking. Pattern: `.filter(f => !f.basename.startsWith("_"))`. - **All modals must extend `DuckmageModal`** (`src/DuckmageModal.ts`) rather than Obsidian's `Modal` directly. `DuckmageModal` is the single place for shared modal behaviour. Any functionality needed by more than one modal belongs there, not in `utils.ts` or duplicated across files. - All modals call `this.makeDraggable()` in `onOpen` (inherited from `DuckmageModal`), which adds the `duckmage-editor-modal-drag` class and locks dragging to the title-bar area. (`FileLinkSuggestModal` is the sole exception — it extends `SuggestModal` and cannot inherit from `DuckmageModal`.) From 0b59653dbc6fa5bf11d2428ebf98f755d530ed6e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:52:42 -0400 Subject: [PATCH 244/558] fix(merge): drop duplicate toolModeLabel import Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 86a6f395..c7cd25eb 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -35,7 +35,7 @@ import type { PinRecord } from "../paths/routePins"; import { pathSummary } from "./pathTool"; import { flowerPetals, MapHistory, navArrows, PAD_SIDES } from "../maps/mapNav"; import { WORK_MODES, WORK_MODE_TEXT, workModeOf, type WorkMode } from "../workMode"; -import { REGION_AREAS_TOOL, toolModeLabel } from "./toolMode"; +import { REGION_AREAS_TOOL } from "./toolMode"; import { openNoteFocused } from "../openNote"; import { coordHaloColor } from "../coordStyle"; import { ghostPathRuns, ghostRunPoints, seamJoinKey, seamJoins, seamPoint, type ShadowRef } from "./ghostPaths"; From 1a03473382e074cc363413de32bd642bbbea675f Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 20:56:16 -0400 Subject: [PATCH 245/558] feat(paths): path edits follow the map's work mode (Play locks drawing, undo and reroute; pins always allowed) Co-Authored-By: Claude Opus 5.5 --- package.json | 4 ++-- src/HexmakerPlugin.ts | 2 ++ src/hex-map/pathTool.ts | 6 +++--- src/paths/editGate.ts | 31 ++++++++++++++++++++++--------- tests/pathEditGate.test.ts | 27 +++++++++++++++++++++++++++ 5 files changed, 56 insertions(+), 14 deletions(-) create mode 100644 tests/pathEditGate.test.ts diff --git a/package.json b/package.json index c95939c8..b11776bf 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 01191cf3..dc152880 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -35,6 +35,7 @@ import { SetupWizardView } from "./SetupWizardView"; import { PaletteStore } from "./palettes/PaletteStore"; import { PathsService } from "./paths/PathsService"; import { RoutePins } from "./paths/routePins"; +import { setPathEditMapLookup } from "./paths/editGate"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; import { enabledKinds, isIconHiddenByKind, isSpacePalette, newTerrains, resolveMapKinds, sectionKindFor, sectionWordsFor, terrainsForTables, type SectionWordsFn } from "./mapKinds"; import { enableFeature, hasFeature, resolveFeatureLevel, shouldNudge, type AdvancedFeature, type FeatureLevel } from "./featureLevel"; @@ -133,6 +134,7 @@ export default class HexmakerPlugin extends Plugin { // Icon pickers open on the Space tab for space-only setups. setIconPackDefault(() => defaultIconPack(this.settings)); setHexDataSource(this.mapStore); + setPathEditMapLookup((name) => this.getMap(name)); // Notes written by this plugin are read from memory until indexed (see frontmatter.ts). this.registerEvent(this.app.metadataCache.on("changed", (file) => clearPendingTerrain(file.path))); // Defer until vault metadata cache is ready; calling before layout-ready diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index 48858bea..6c42ba51 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -34,7 +34,7 @@ import { splitBranchAt, } from "../paths/edit"; import { anchorsFor, routeFnFor } from "../paths/fromHexes"; -import { canEditPaths, type PathEditAction } from "../paths/editGate"; +import { canEditPaths, PATH_EDIT_LOCKED_HINT, type PathEditAction } from "../paths/editGate"; import { pathRouteText } from "../maps/mapNote"; import { pathRouteStats } from "../maps/MapStore"; import { impassableNames, noRouteMessage } from "../impassable"; @@ -480,7 +480,7 @@ export class PathTool { private commit(next: MapPath[], action: PathEditAction = "draw"): boolean { const map = this.map; if (!canEditPaths(map, action)) { - new Notice("Paths can't be changed on this map right now."); + new Notice(PATH_EDIT_LOCKED_HINT); return false; } const before = clonePaths(this.paths()); @@ -500,7 +500,7 @@ export class PathTool { /** Undo / redo of a path step: restore a snapshot (through the gate). */ applySnapshot(mapName: string, paths: MapPath[]): void { if (!canEditPaths(mapName, "history")) { - new Notice("Paths can't be changed on this map right now."); + new Notice(PATH_EDIT_LOCKED_HINT); return; } this.plugin.pathPins.sync(mapName); diff --git a/src/paths/editGate.ts b/src/paths/editGate.ts index c4dc4a25..c279dc3b 100644 --- a/src/paths/editGate.ts +++ b/src/paths/editGate.ts @@ -5,13 +5,15 @@ * keep-the-route pins when terrain, the palette, the map's size or a type's * routing changes (routePins.ts), and "Reroute instead". * - * Today it always allows. It is the one place the per-map work mode - * (src/workMode.ts: Play / Build / God, `workModeOf(map)`) will answer "is - * this allowed in this map's mode?": drawing and reshaping paths count as - * Build. Whether pins over regenerated terrain are allowed outside Build is - * still undecided. + * It answers "is this allowed in this map's work mode?" (src/workMode.ts: + * Play / Build / God). Drawing, reshaping, undo/redo and "Reroute instead" + * count as Build, so they need Build or God. Keep-the-route pins only + * preserve what is already drawn, so they are allowed in every mode. + * The plugin registers how to look a map up (`setPathEditMapLookup`); with + * no lookup (tests, early load) everything is allowed. * Pure, no Obsidian imports. */ +import { canAdd } from "../workMode"; /** What kind of path edit is being asked for. */ export type PathEditAction = @@ -24,9 +26,20 @@ export type PathEditAction = /** "Reroute instead": drop the anchors a pin added. */ | "reroute"; -/** May `action` change the stored paths of map `mapName`? (Always yes, for now.) */ +type MapLookup = (mapName: string) => { workMode?: string } | undefined; +let lookup: MapLookup | null = null; + +/** Tell the gate how to find a map (and so its work mode). */ +export function setPathEditMapLookup(fn: MapLookup | null): void { + lookup = fn; +} + +/** Shown when a path edit is refused because of the map's mode. */ +export const PATH_EDIT_LOCKED_HINT = "Switch to Build to change paths on this map."; + +/** May `action` change the stored paths of map `mapName`? */ export function canEditPaths(mapName: string, action: PathEditAction): boolean { - void mapName; - void action; - return true; + if (action === "pin") return true; // keeps what is drawn; never a user change + if (!lookup) return true; + return canAdd(lookup(mapName)); } diff --git a/tests/pathEditGate.test.ts b/tests/pathEditGate.test.ts new file mode 100644 index 00000000..f8256955 --- /dev/null +++ b/tests/pathEditGate.test.ts @@ -0,0 +1,27 @@ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { canEditPaths, setPathEditMapLookup } from "../src/paths/editGate"; + +describe("path edit gate follows the map's work mode", () => { + afterEach(() => setPathEditMapLookup(null)); + + it("allows everything when no lookup is registered", () => { + expect(canEditPaths("any", "draw")).toBe(true); + }); + + it("Play locks drawing, undo and reroute; Build and God allow them", () => { + const maps: Record = { p: { workMode: "play" }, b: { workMode: "build" }, g: { workMode: "god" }, d: {} }; + setPathEditMapLookup((n) => maps[n]); + for (const a of ["draw", "history", "reroute"] as const) { + expect(canEditPaths("p", a)).toBe(false); + expect(canEditPaths("b", a)).toBe(true); + expect(canEditPaths("g", a)).toBe(true); + expect(canEditPaths("d", a)).toBe(true); // default mode is Build + } + }); + + it("keep-the-route pins are allowed in every mode (they only preserve what is drawn)", () => { + setPathEditMapLookup(() => ({ workMode: "play" })); + expect(canEditPaths("p", "pin")).toBe(true); + }); +}); From 5e3a68ca6aefb1072abe7842127a86129ceeea24 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 21:16:12 -0400 Subject: [PATCH 246/558] refactor(path tool): drop the routing-context settling workaround MapStore now settles the routing context itself (setPaths / syncPaths and on paint, 917c8af), so commit() and applySnapshot() no longer call pathPins.sync before setPaths. Tests: the path tool against the real MapStore, RoutePins and PathsService (no pathPins stub): a road drawn right after painting water on a path-less map routes round it with only its two anchors and no pin; after an unseen palette change the old road is kept (pinned) and the new one is routed under the new palette. The rig in pathToolPolish no longer stubs pathPins. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/pathTool.ts | 6 +-- tests/pathToolPolish.test.ts | 1 - tests/routePins.test.ts | 77 ++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 5 deletions(-) diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index 6c42ba51..1c742ec4 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -485,9 +485,8 @@ export class PathTool { } const before = clonePaths(this.paths()); if (JSON.stringify(before) === JSON.stringify(next)) return false; - // Settle any pending routing change against the paths as they were, so - // the new ones are never pinned to an out-of-date route. - this.plugin.pathPins.sync(map); + // setPaths settles any pending routing-context change against the paths + // as they were, so the new ones are never pinned to an out-of-date route. this.plugin.mapStore.setPaths(map, next); void this.plugin.saveSettings(); if (action !== "history") this.host.pushUndo(map, before, clonePaths(next)); @@ -503,7 +502,6 @@ export class PathTool { new Notice(PATH_EDIT_LOCKED_HINT); return; } - this.plugin.pathPins.sync(mapName); this.plugin.mapStore.setPaths(mapName, clonePaths(paths)); void this.plugin.saveSettings(); this.pending = null; diff --git a/tests/pathToolPolish.test.ts b/tests/pathToolPolish.test.ts index 4a27054e..390bfe81 100644 --- a/tests/pathToolPolish.test.ts +++ b/tests/pathToolPolish.test.ts @@ -161,7 +161,6 @@ function rig() { app: {}, mapStore: { paths: () => map.paths ?? [], setPaths: (_n: string, ps: MapPath[]) => { map.paths = ps; } }, paths: svc, - pathPins: { sync: () => {} }, saveSettings: async () => {}, getMapPalette: () => [], }; diff --git a/tests/routePins.test.ts b/tests/routePins.test.ts index c730db46..83f19c68 100644 --- a/tests/routePins.test.ts +++ b/tests/routePins.test.ts @@ -13,6 +13,7 @@ import type { MapData, PathChain, PathType, TerrainColor } from "../src/types"; import { DEFAULT_PATH_TYPES, DEFAULT_TERRAIN_PALETTE } from "../src/constants"; import { dropAddedAnchors, pinNoticeText, RoutePins } from "../src/paths/routePins"; import { PathsService } from "../src/paths/PathsService"; +import { PathTool } from "../src/hex-map/pathTool"; (globalThis as Record).window ??= globalThis; @@ -146,3 +147,79 @@ describe("keep the route when terrain changes under it (phase 7)", () => { expect(dropAddedAnchors(edited, before)).toBe(edited); }); }); + +/** + * The path tool against the real store, pins and path service. The tool + * doesn't settle the routing context itself: MapStore does, on paint and in + * setPaths, so a path drawn right after a change is routed under the map as + * it is now and never pinned to the old one. Clicks carry no pointer event, + * so nothing resolves the map between the change and the draw. + */ +describe("drawing with the path tool right after the routing context changed", () => { + beforeEach(() => { Notice.shown = []; }); + + function toolFor(env: Awaited>) { + const plugin = { + app: {}, + mapStore: env.store, + paths: env.svc, + saveSettings: async () => {}, + getMapPalette: () => env.state.palette, + }; + const tool = new PathTool({ + plugin: plugin as never, + mapName: () => "m", + pointerLattice: () => null, + hexAtPoint: () => null, + ownerDocument: () => ({ addEventListener: () => {}, removeEventListener: () => {} }) as unknown as Document, + pushUndo: () => {}, + redraw: () => {}, + refreshBar: () => {}, + setGrabCursor: () => {}, + }); + tool.typeName = "Road"; + const draw = (...hexes: string[]) => { + for (const h of hexes) { + const [x, y] = h.split("_").map(Number); + tool.click(x, y, undefined, false); + } + tool.done(); + }; + return { tool, draw }; + } + + it("water painted on a map with no paths: the new road goes round it, nothing is pinned", async () => { + const env = await boot([]); + env.svc.resolvedPathChains("m"); // the map view drew the map + env.store.set("m", "3_5", { terrain: "shallows" }); // water: impassable for roads + const { draw } = toolFor(env); + draw("0_5", "6_5"); + expect(env.maps[0].paths).toEqual([{ name: "Road", typeName: "Road", branches: [{ anchors: ["0_5", "6_5"] }] }]); + const hexes = env.svc.resolvedPathChains("m")[0].hexes; + expect(hexes).not.toContain("3_5"); + expect(hexes[0]).toBe("0_5"); + expect(hexes[hexes.length - 1]).toBe("6_5"); + expect(env.pins.flushNotice()).toEqual([]); + }); + + it("a palette change nobody has drawn yet: the old road is kept (pinned), the new one is routed under the new palette", async () => { + const OLD = ["0_8", "1_8", "2_8", "3_8", "4_8", "5_8", "6_8"]; + const env = await boot([{ typeName: "Road", hexes: OLD }]); + env.store.set("m", "3_5", { terrain: "forest" }); + env.store.set("m", "3_8", { terrain: "forest" }); + expect(env.svc.resolvedPathChains("m")[0].hexes).toEqual(OLD); // drawn, forest passable + env.state.palette.find((t) => t.name === "forest")!.impassable = true; // not seen by anyone yet + const { draw } = toolFor(env); + draw("0_5", "6_5"); + const paths = env.maps[0].paths!; + expect(paths).toHaveLength(2); + const added = paths.find((p) => p.branches[0].anchors[0] === "0_5")!; + expect(added.branches[0].anchors).toEqual(["0_5", "6_5"]); // not pinned + const chains = env.svc.resolvedPathChains("m"); + expect(chains.find((c) => c.hexes[0] === "0_8")!.hexes).toEqual(OLD); // kept where it was + expect(chains.find((c) => c.hexes[0] === "0_5")!.hexes).not.toContain("3_5"); + const recs = env.pins.flushNotice(); + expect(recs).toHaveLength(1); + expect(recs[0].added.map((a) => a.path)).toEqual([paths.find((p) => p !== added)!.name]); + }); +}); From 957724c2aa80f16ab63574e8eca54c1445e38244 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 21:16:13 -0400 Subject: [PATCH 247/558] test(#47): integration test for a data.json reload mid-save-burst Drives the real HexmakerPlugin (loadSettings, saveSettings, saveData's note-path stripping, onExternalSettingsChange's echo filter, reloadFromNotes) and MapStore's note writes against an in-memory vault: a neighbour map is dirty (world slot just changed) when an outside data.json change lands between saveSettings calls. Every map keeps its paths in its note and in memory, and the write guard never has to step in; same with our own echo let through; our own echo is ignored; a restart reads the same paths back. With the three MapStore fix layers disabled, it reproduces #47 (coast note 2 paths -> 0). Co-Authored-By: Claude Opus 5.5 --- .../integration/pathLossReload.integration.ts | 212 ++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 tests/integration/pathLossReload.integration.ts diff --git a/tests/integration/pathLossReload.integration.ts b/tests/integration/pathLossReload.integration.ts new file mode 100644 index 00000000..202151d4 --- /dev/null +++ b/tests/integration/pathLossReload.integration.ts @@ -0,0 +1,212 @@ +/** + * Issue #47 / incident 2026-10-10, end to end through the real plugin class: + * HexmakerPlugin.saveSettings (data.json without the notes' paths), + * onExternalSettingsChange (echo filter, loadSettings, reloadFromNotes) and + * MapStore's note writes, with a neighbour map dirty (its world slot just + * changed) while a data.json reload lands in the middle of a save burst. + * + * The unit tests (tests/pathLossReload.test.ts) drive MapStore with a + * simulated reload; this one runs the plugin's own load / save / reload + * code against an in-memory vault, so a change to any link in that chain + * that brings the loss back fails here. + */ +import { describe, it, beforeEach } from "node:test"; +import expect from "expect"; +import * as obsidian from "obsidian"; +import { MemVault } from "../helpers/memVault"; +import { parseMapNote } from "../../src/maps/mapNote"; +import type { MapData, MapPath } from "../../src/types"; + +const g = globalThis as Record; +g.window ??= globalThis; + +// The unit-test obsidian mock lacks the UI base classes the plugin module's +// views extend; stubs are enough here (no view is ever opened). +// The module object itself (an import namespace may be a copy). +const mock = require("obsidian") as Record; +for (const name of ["Component", "ItemView", "Menu", "PluginSettingTab", "Scope", "Setting", "MarkdownRenderer"]) { + if (!mock[name]) mock[name] = class {}; +} + +const DATA = ".obsidian/plugins/hexmaker/data.json"; +const COAST = "world/hexes/coast/_coast.md"; +const NORTH = "world/hexes/north/_north.md"; + +/** Obsidian's Plugin.loadData / saveData, against data.json in the in-memory vault. */ +function wireDataJson(v: MemVault): void { + const proto = (mock.Plugin as { prototype: Record }).prototype; + proto.loadData = async function () { + const text = v.files.get(DATA); + return text === undefined ? null : JSON.parse(text); + }; + proto.saveData = async function (data: unknown) { + v.files.set(DATA, JSON.stringify(data, null, 2)); + }; +} + +function initialData() { + return { + hexFolder: "world/hexes", + hexOrientation: "flat", + featureLevel: "advanced", + installedAt: "2026-01-01", + expandedByDefault: false, + defaultPalette: "Default", + maps: [ + { name: "coast", paletteName: "Default", gridSize: { cols: 8, rows: 8 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "Road", hexes: ["1_2", "2_2", "3_2"] }, { typeName: "River", hexes: ["5_0", "5_1", "5_2", "5_3"] }] }, + { name: "north", paletteName: "Default", gridSize: { cols: 8, rows: 8 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "Road", hexes: ["0_0", "1_0", "2_0"] }] }, + ], + }; +} + +interface Booted { + v: MemVault; + plugin: { + settings: { maps: MapData[]; dismissedHints?: string[] }; + getMap(name: string): MapData | undefined; + loadSettings(): Promise; + saveSettings(): Promise; + onExternalSettingsChange(): Promise; + paletteStore: { init(): Promise }; + mapStore: { init(): Promise; flush(): Promise; sync(): Promise; holdsPaths(name: string): boolean; paths(name: string): readonly MapPath[] }; + }; +} + +async function boot(): Promise { + const v = new MemVault(); + v.files.set(DATA, JSON.stringify(initialData(), null, 2)); + wireDataJson(v); + const app = { + ...v.app(), + workspace: { getLeavesOfType: () => [], on: () => ({}), onLayoutReady: (fn: () => void) => fn() }, + }; + (app.vault as Record).on = () => ({}); + (app.metadataCache as Record).on = () => ({}); + const { default: HexmakerPlugin } = await import("../../src/HexmakerPlugin"); + const plugin = new HexmakerPlugin(app as never, { id: "hexmaker", dir: ".obsidian/plugins/hexmaker", version: "0.0.0-test" } as never) as unknown as Booted["plugin"] & Record; + plugin.app = app; + plugin.manifest = { id: "hexmaker", dir: ".obsidian/plugins/hexmaker", version: "0.0.0-test" }; + // Nothing to show in a test (no views, no icons). + plugin.refreshHexMap = () => {}; + plugin.loadAvailableIcons = () => {}; + plugin.ensureTablesForNewTerrains = async () => {}; + await plugin.loadSettings(); + await plugin.paletteStore.init(); + await plugin.mapStore.init(); + await plugin.saveSettings(); + await plugin.mapStore.flush(); + return { v, plugin }; +} + +const notePaths = (v: MemVault, path: string): MapPath[] => parseMapNote(v.files.get(path)!)!.paths; +const diskMaps = (v: MemVault): Record[] => (JSON.parse(v.files.get(DATA)!) as { maps: Record[] }).maps; +const settle = async (b: Booted) => { + await b.plugin.mapStore.flush(); + await new Promise((r) => setTimeout(r, 0)); + await b.plugin.mapStore.flush(); +}; + +describe("#47: a data.json reload mid-save-burst keeps every map's paths (real plugin)", () => { + beforeEach(() => { (obsidian.Notice as unknown as { shown: unknown[] }).shown = []; }); + + it("setup: the notes hold the paths (format 5) and data.json doesn't", async () => { + const { v, plugin } = await boot(); + expect(notePaths(v, COAST)).toHaveLength(2); + expect(notePaths(v, NORTH)).toHaveLength(1); + expect(plugin.mapStore.holdsPaths("coast")).toBe(true); + for (const m of diskMaps(v)) { + expect(m.paths).toBeUndefined(); + expect(m.pathChains).toBeUndefined(); + } + }); + + it("an outside data.json change lands mid-burst while the neighbour map is dirty: notes and memory keep every path", async () => { + const b = await boot(); + const { v, plugin } = b; + const coastBefore = JSON.stringify(plugin.getMap("coast")!.paths); + const northBefore = JSON.stringify(plugin.getMap("north")!.paths); + // A new region was placed next to coast: its world slot changed, so its note write is queued. + plugin.getMap("coast")!.world = { id: "w1", cx: 0, cy: 0 }; + const maps = plugin.settings.maps; + let loads = 0; + const load = plugin.loadSettings.bind(plugin); + plugin.loadSettings = async () => { loads++; await load(); }; + const burst: Promise[] = [plugin.saveSettings(), plugin.saveSettings()]; + // Another device (or a hand edit) changes data.json: not one of our own writes. + const disk = JSON.parse(v.files.get(DATA)!) as { dismissedHints?: string[] }; + disk.dismissedHints = [...(disk.dismissedHints ?? []), "from-elsewhere"]; + v.files.set(DATA, JSON.stringify(disk, null, 2)); + burst.push(plugin.onExternalSettingsChange()); + // The burst goes on while the reload is in flight. + burst.push(plugin.saveSettings(), plugin.mapStore.sync(), plugin.saveSettings()); + await Promise.all(burst); + await settle(b); + // The reload really happened: fresh map objects from data.json, which holds no paths… + expect(loads).toBe(1); + expect(plugin.settings.maps).not.toBe(maps); + expect(plugin.getMap("coast")).not.toBe(maps[0]); + // …and no map lost a path, in its note or in memory. + expect(notePaths(v, COAST)).toHaveLength(2); + expect(notePaths(v, NORTH)).toHaveLength(1); + expect(JSON.stringify(plugin.getMap("coast")!.paths)).toBe(coastBefore); + expect(JSON.stringify(plugin.getMap("north")!.paths)).toBe(northBefore); + expect(plugin.mapStore.paths("coast")).toHaveLength(2); + // The write guard never had to step in. + expect((obsidian.Notice as unknown as { shown: { msg: string }[] }).shown.filter((n) => n.msg.includes("would have removed"))).toEqual([]); + }); + + it("the same, with our own save echoed back as an external change (echo filter bypassed): nothing is lost", async () => { + const b = await boot(); + const { v, plugin } = b; + const before = [JSON.stringify(plugin.getMap("coast")!.paths), JSON.stringify(plugin.getMap("north")!.paths)]; + plugin.getMap("north")!.world = { id: "w2", cx: 1, cy: 0 }; + const p = plugin as unknown as { isOwnWrite: (d: unknown) => boolean }; + const own = p.isOwnWrite; + p.isOwnWrite = () => false; // as if Obsidian's watcher missed that the write was ours + try { + const burst: Promise[] = [plugin.saveSettings(), plugin.onExternalSettingsChange(), plugin.saveSettings(), plugin.mapStore.sync()]; + await Promise.all(burst); + } finally { + p.isOwnWrite = own; + } + await settle(b); + expect(notePaths(v, COAST)).toHaveLength(2); + expect(notePaths(v, NORTH)).toHaveLength(1); + expect([JSON.stringify(plugin.getMap("coast")!.paths), JSON.stringify(plugin.getMap("north")!.paths)]).toEqual(before); + }); + + it("our own save echoed back is ignored: the settings aren't reloaded at all", async () => { + const { plugin } = await boot(); + let loads = 0; + const load = plugin.loadSettings.bind(plugin); + plugin.loadSettings = async () => { loads++; await load(); }; + await plugin.saveSettings(); + await plugin.onExternalSettingsChange(); + expect(loads).toBe(0); + }); + + it("after the burst, a fresh start reads the same paths back from the notes", async () => { + const b = await boot(); + const { v, plugin } = b; + plugin.getMap("coast")!.world = { id: "w3", cx: 0, cy: 0 }; + const disk = JSON.parse(v.files.get(DATA)!) as { dismissedHints?: string[] }; + disk.dismissedHints = ["x"]; + v.files.set(DATA, JSON.stringify(disk, null, 2)); + await Promise.all([plugin.saveSettings(), plugin.onExternalSettingsChange(), plugin.saveSettings()]); + await settle(b); + const expected = [JSON.stringify(plugin.getMap("coast")!.paths), JSON.stringify(plugin.getMap("north")!.paths)]; + // Restart: a new plugin instance on the same vault. + const { default: HexmakerPlugin } = await import("../../src/HexmakerPlugin"); + const again = new HexmakerPlugin(plugin.app as never, plugin.manifest as never) as unknown as Booted["plugin"] & Record; + again.app = (plugin as unknown as Record).app; + again.manifest = (plugin as unknown as Record).manifest; + again.refreshHexMap = () => {}; + again.loadAvailableIcons = () => {}; + again.ensureTablesForNewTerrains = async () => {}; + await again.loadSettings(); + await again.paletteStore.init(); + await again.mapStore.init(); + expect([JSON.stringify(again.getMap("coast")!.paths), JSON.stringify(again.getMap("north")!.paths)]).toEqual(expected); + expect(again.getMap("coast")!.world).toEqual({ id: "w3", cx: 0, cy: 0 }); + }); +}); From 4544441f6f823e099320b616e4f71ef08888c189 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 21:42:44 -0400 Subject: [PATCH 248/558] fix(nav): walk into new land from the region flower's empty petals Empty petals on the region-map nav flower show "+" ("New region to the ") and open WalkRegionModal: pick or roll a biome (roll is deterministic from the shown seed), live preview of the blended region (blend field + regionGen, neighbours pinned, default warp), Create and go. Past the overworld's grid the overworld grows by that hex first (walkIntoHex/gridToInclude). The hex editor's flower and the d-pad's empty sides use the same modal; legacy N/E/S/W worlds keep planWalk. Gated by work mode (walkLock: the region you're on and the overworld; Play shows the + locked with "Switch to Build to make a region."). Also: the map-note write guard says "its only path" / "all its N paths". Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- package.json | 4 +- src/hex-map/BiomeModals.ts | 100 ++++++++------- src/hex-map/HexEditorModal.ts | 25 ++++ src/hex-map/HexMapView.ts | 75 ++++++++--- src/hex-map/help.md | 6 +- src/maps/MapStore.ts | 16 ++- src/maps/mapNav.ts | 43 +++++++ src/overworld/regionWorld.ts | 32 +++++ src/overworld/regionsVault.ts | 55 +++++++- src/worldgen/WalkRegionModal.ts | 168 +++++++++++++++++++++++-- styles.css | 33 +++++ tests/mapStore.test.ts | 12 +- tests/walkNewRegion.test.ts | 216 ++++++++++++++++++++++++++++++++ 14 files changed, 710 insertions(+), 79 deletions(-) create mode 100644 tests/walkNewRegion.test.ts diff --git a/README.md b/README.md index 3070c757..6135b465 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which. The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. -**Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and a small hex flower on the toolbar shows all six neighbours in their directions (hover a petal for its name, click to go there; empty petals have no region yet). A new region is made from a short form: biome (the hex's terrain is its biome), blend, how wiggly the borders are, and a seed, with a live preview of the region against its neighbours. It blends with the overworld around it, and the hexes along its edges are pinned to the regions already made, so seams line up whatever order you make them in. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. +**Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and a small hex flower on the toolbar shows all six neighbours in their directions (hover a petal for its name, click to go there). An empty petal shows **+** ("New region to the north-east"): click it to walk into new land. Pick the biome that lies there, or **Roll** for one (the seed is shown, so a roll can be repeated; **Re-roll terrain** keeps the biome and tries a new seed), check the live preview of the new region blended with every region around it, and **Create and go**. A biome different from yours makes border country between the two. If that hex is past the overworld's edge, the overworld grows by a hex to fit it. The hex editor's neighbour flower offers the same walk on the hexes past a region's edge. Making a region needs Build or God; in Play the **+** is greyed out and says "Switch to Build to make a region." A new region is made from a short form: biome (the hex's terrain is its biome), blend, how wiggly the borders are, and a seed, with a live preview of the region against its neighbours. It blends with the overworld around it, and the hexes along its edges are pinned to the regions already made, so seams line up whatever order you make them in. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: @@ -133,7 +133,7 @@ A small **minimap** of the overworld (bottom right) shows on the overworld and o **Neighbouring maps.** In **Maps → New map…**, **Next to** makes the new map a region beside an existing one (same size and palette, lined up hex for hex); **Properties → New region here…** opens the form already placed. The generators marked *Continues … edge* (Overland and learned generators) carry the neighbour's terrain on across the shared border, and the preview shows the neighbour's edge faded around the new map. Region detail is only offered for submaps, since it zooms into a parent hex. -**Shared coordinates.** Neighbouring regions number their hexes on one grid, so a hex number is unique across the world: the map east of a 20-column map that starts at 0 starts at column 20. The placement note shows the range ("Hexes 20, 0 to 39, 13"). Maps joined before this, or two existing maps linked in **Properties → Neighbouring regions**, keep their own numbers; nothing is renamed. After the map button and the ← ↑ → arrows (back, parent, forward: always in that order, hover for the map each goes to), the neighbouring regions show as a small ◀ ▲ ▼ ▶ pad, one button per side, greyed out where there's no neighbour; hover for the name, click to go there. Inside a submap, the pad goes to its parent's neighbours, one click away. A road or river that ends on a region's edge, next to the end of the neighbour's path of the same type, is drawn on to the shared edge on both maps so they join. +**Shared coordinates.** Neighbouring regions number their hexes on one grid, so a hex number is unique across the world: the map east of a 20-column map that starts at 0 starts at column 20. The placement note shows the range ("Hexes 20, 0 to 39, 13"). Maps joined before this, or two existing maps linked in **Properties → Neighbouring regions**, keep their own numbers; nothing is renamed. After the map button and the ← ↑ → arrows (back, parent, forward: always in that order, hover for the map each goes to), the neighbouring regions show as a small ◀ ▲ ▼ ▶ pad, one button per side; hover for the name, click to go there. An empty side shows **+** and opens the same walk into new land (pick or roll a biome, preview, create). Inside a submap, the pad goes to its parent's neighbours, one click away. A road or river that ends on a region's edge, next to the end of the neighbour's path of the same type, is drawn on to the shared edge on both maps so they join. Generators only change hexes when a map is created or regenerated; you can always repaint by hand afterwards. diff --git a/package.json b/package.json index b11776bf..e05e7125 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-map/BiomeModals.ts b/src/hex-map/BiomeModals.ts index 1c2f32b4..8fcd77e5 100644 --- a/src/hex-map/BiomeModals.ts +++ b/src/hex-map/BiomeModals.ts @@ -53,7 +53,7 @@ export function mayReshape(host: BiomeHost, parentName: string, px: number, py: } /** Mark a button as locked by the work mode: disabled, with the hint as its tooltip. */ -function lockButton(btn: HTMLButtonElement, hint: string): void { +export function lockButton(btn: HTMLButtonElement, hint: string): void { btn.disabled = true; btn.addClass("is-locked"); btn.setAttr("title", hint); @@ -61,7 +61,7 @@ function lockButton(btn: HTMLButtonElement, hint: string): void { } /** The biomes this overworld's palette can paint, with the terrain each paints. */ -function paintableBiomes(plugin: HexmakerPlugin, parentName: string): { id: BiomeId; label: string; terrain: string; color: string }[] { +export function paintableBiomes(plugin: HexmakerPlugin, parentName: string): { id: BiomeId; label: string; terrain: string; color: string }[] { const palette = plugin.getMapPalette(parentName); const shown = representableBiomes(palette); const out: { id: BiomeId; label: string; terrain: string; color: string }[] = []; @@ -232,48 +232,9 @@ export class RegionGenModal extends HexmakerModal { } private redraw(): void { - const { plugin } = this.host; - const ow = overworldOf(plugin, this.parentName); - const ctx = this.canvas.getContext("2d"); - if (!ow || !ctx) return; // Preview with the chosen biome on the hex (nothing is written). - const hex = `${this.px}_${this.py}`; - const plan = planRegionAt(plugin, this.parentName, this.px, this.py, { ...this.opts, hexTerrain: this.biomeTerrain() }); - ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); - if (!plan) return; - const layout = ow.layout; - const colour = new Map(plugin.getPaletteOrPresetTerrains(ow.settings.palette ?? ow.map.paletteName).map((t) => [t.name, t.color])); - const own: RegionCell[] = [...plan.cells].map(([k, t]) => { - const [x, y] = k.split("_").map(Number); - return { x, y, color: colour.get(t) ?? "#333" }; - }); - const locked = regionMapAt(plugin.settings.maps, this.parentName, hex); - if (locked) for (const [k, h] of plugin.mapStore.all(locked.name)) { - if (!h.locked || !h.terrain) continue; - const [x, y] = k.split("_").map(Number); - own.push({ x, y, color: colour.get(h.terrain) ?? "#333" }); - } - const around: RegionCell[] = []; - for (const [qx, qy] of hexNeighbors(this.px, this.py, layout.orientation, layout.parentStagger)) { - const r = regionMapAt(plugin.settings.maps, this.parentName, `${qx}_${qy}`); - if (!r) continue; - const hexes = plugin.mapStore.all(r.name); - for (const [x, y] of regionCells(layout, qx, qy)) { - const t = hexes.get(`${x}_${y}`)?.terrain; - if (t) around.push({ x, y, color: colour.get(t) ?? "#333" }); - } - } - const all = [...own, ...around]; - if (!all.length) return; - const box = cellsBox(layout, regionCells(layout, this.px, this.py).map(([x, y]) => ({ x, y })), [1, 0, 0, 1, 0, 0]); - // Fit this region plus a margin of its neighbours into the canvas. - const pad = Math.max(box.w, box.h) * 0.45; - const k = Math.min(this.canvas.width / (box.w + 2 * pad), this.canvas.height / (box.h + 2 * pad)); - const to = composeAffine([1, 0, 0, 1, 0, 0], [k, 0, 0, k, (-box.x + pad) * k + (this.canvas.width - (box.w + 2 * pad) * k) / 2, (-box.y + pad) * k + (this.canvas.height - (box.h + 2 * pad) * k) / 2]); - ctx.globalAlpha = 0.45; - drawRegionCells(ctx, layout, around, to, { seams: false }); - ctx.globalAlpha = 1; - drawRegionCells(ctx, layout, own, to); + const plan = planRegionAt(this.host.plugin, this.parentName, this.px, this.py, { ...this.opts, hexTerrain: this.biomeTerrain() }); + drawRegionPlan(this.canvas, this.host.plugin, this.parentName, this.px, this.py, plan); } private async apply(): Promise { @@ -295,3 +256,56 @@ export class RegionGenModal extends HexmakerModal { this.contentEl.empty(); } } + +/** + * Draw a region plan (planRegionAt) for hex (px, py): the region bright + * (with its hand-painted, locked cells), the regions around it dimmed. + * Shared by the region settings modal and the walk-into-new-land flow. + */ +export function drawRegionPlan( + canvas: HTMLCanvasElement, + plugin: HexmakerPlugin, + parentName: string, + px: number, + py: number, + plan: ReturnType, +): void { + const ow = overworldOf(plugin, parentName); + const ctx = canvas.getContext("2d"); + if (!ow || !ctx) return; + const hex = `${px}_${py}`; + ctx.clearRect(0, 0, canvas.width, canvas.height); + if (!plan) return; + const layout = ow.layout; + const colour = new Map(plugin.getPaletteOrPresetTerrains(ow.settings.palette ?? ow.map.paletteName).map((t) => [t.name, t.color])); + const own: RegionCell[] = [...plan.cells].map(([k, t]) => { + const [x, y] = k.split("_").map(Number); + return { x, y, color: colour.get(t) ?? "#333" }; + }); + const locked = regionMapAt(plugin.settings.maps, parentName, hex); + if (locked) for (const [k, h] of plugin.mapStore.all(locked.name)) { + if (!h.locked || !h.terrain) continue; + const [x, y] = k.split("_").map(Number); + own.push({ x, y, color: colour.get(h.terrain) ?? "#333" }); + } + const around: RegionCell[] = []; + for (const [qx, qy] of hexNeighbors(px, py, layout.orientation, layout.parentStagger)) { + const r = regionMapAt(plugin.settings.maps, parentName, `${qx}_${qy}`); + if (!r) continue; + const hexes = plugin.mapStore.all(r.name); + for (const [x, y] of regionCells(layout, qx, qy)) { + const t = hexes.get(`${x}_${y}`)?.terrain; + if (t) around.push({ x, y, color: colour.get(t) ?? "#333" }); + } + } + if (!own.length && !around.length) return; + const box = cellsBox(layout, regionCells(layout, px, py).map(([x, y]) => ({ x, y })), [1, 0, 0, 1, 0, 0]); + // Fit this region plus a margin of its neighbours into the canvas. + const pad = Math.max(box.w, box.h) * 0.45; + const k = Math.min(canvas.width / (box.w + 2 * pad), canvas.height / (box.h + 2 * pad)); + const to = composeAffine([1, 0, 0, 1, 0, 0], [k, 0, 0, k, (-box.x + pad) * k + (canvas.width - (box.w + 2 * pad) * k) / 2, (-box.y + pad) * k + (canvas.height - (box.h + 2 * pad) * k) / 2]); + ctx.globalAlpha = 0.45; + drawRegionCells(ctx, layout, around, to, { seams: false }); + ctx.globalAlpha = 1; + drawRegionCells(ctx, layout, own, to); +} diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 90d44856..43bfd680 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -50,6 +50,9 @@ import { VIEW_TYPE_HEX_MAP, VIEW_TYPE_RANDOM_TABLES } from "../constants"; import { resolveHex, type Side } from "../worldgen/world"; import { neighbourSpec } from "../worldgen/neighbours"; import { WalkRegionModal } from "../worldgen/WalkRegionModal"; +import { regionHome, walkLock } from "../overworld/regionsVault"; +import { parentOf } from "../overworld/layout"; +import { flowerPetals, neighbourButton } from "../maps/mapNav"; import { hasFeature } from "../featureLevel"; import { withFeature } from "../advancedHints"; import type { MapData } from "../types"; @@ -588,6 +591,28 @@ export class HexEditorModal extends HexmakerModal { this.options.onCrossToRegion?.(target.map, target.x, target.y); }).open(); }); + } else if (here && regionHome(this.plugin, this.mapName)) { + // A region of an overworld: past the edge is the overworld hex + // next door, with no region yet. Same walk as the map toolbar's + // region flower (pick or roll its biome; Build and God only). + const home = regionHome(this.plugin, this.mapName)!; + const [px, py] = parentOf(home.layout, nx, ny); + const bearing = flowerPetals(home.layout.orientation, home.layout.parentStagger, home.px, home.py) + .find((p) => p.hex[0] === px && p.hex[1] === py)?.bearing ?? offMapSide(here, nx, ny); + const lock = walkLock(this.plugin, this.mapName, home.overworld.name); + const b = neighbourButton(bearing, undefined, { canMake: true, canAdd: !lock, lockedHint: lock ?? "" }); + tile.addClass("duckmage-neighbor-tile-new"); + tile.removeClass("duckmage-neighbor-tile-offmap"); + if (b.action.kind === "locked") tile.addClass("is-locked"); + tile.title = b.title; + if (b.action.kind === "new") { + tile.addEventListener("click", () => { + new WalkRegionModal(this.app, this.plugin, this.mapName, { overworld: home.overworld.name, px, py, bearing }, (name) => { + this.close(); + this.options.onCrossToRegion?.(name, nx, ny); + }).open(); + }); + } } else if (here && neighbourSpec(this.plugin, this.mapName, offMapSide(here, nx, ny)).ok) { // Nothing there yet: walk into new land (pick or roll its biome). const side = offMapSide(here, nx, ny); diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index e7bfacd5..064faef9 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -33,8 +33,8 @@ import { toolModeLabel } from "./toolMode"; import { PathTool } from "./pathTool"; import type { PinRecord } from "../paths/routePins"; import { pathListSummary } from "./pathTool"; -import { flowerPetals, MapHistory, navArrows, PAD_SIDES } from "../maps/mapNav"; -import { WORK_MODES, WORK_MODE_TEXT, workModeOf, type WorkMode } from "../workMode"; +import { flowerPetals, MapHistory, navArrows, neighbourButton, PAD_SIDES } from "../maps/mapNav"; +import { ADD_REGION_LOCKED_HINT, canAdd, WORK_MODES, WORK_MODE_TEXT, workModeOf, type WorkMode } from "../workMode"; import { REGION_AREAS_TOOL } from "./toolMode"; import { openNoteFocused } from "../openNote"; import { coordHaloColor } from "../coordStyle"; @@ -79,11 +79,14 @@ import { hexChildMaps, regionMapAt, submapMenuPlan } from "../maps/submaps"; import { OverworldLayer } from "./overworldLayer"; import { OverworldMinimap } from "./overworldMinimap"; import { BiomePickerModal, type BiomeHost } from "./BiomeModals"; -import { regionHome } from "../overworld/regionsVault"; +import { inOverworldGrid, regionHome, walkLock } from "../overworld/regionsVault"; +import { WalkRegionModal, type OverworldWalk } from "../worldgen/WalkRegionModal"; +import type { Side } from "../worldgen/world"; +import { withFeature } from "../advancedHints"; import { overworldRefreshFor } from "../overworld/overworldChanges"; import { parentOf as parentOfCell } from "../overworld/layout"; import { RegionNavigateModal } from "./RegionNavigateModal"; -import { neighbourShadow } from "../worldgen/neighbours"; +import { neighbourShadow, neighbourSpec } from "../worldgen/neighbours"; import { TokenInfoModal } from "./TokenInfoModal"; import { getTokenDataFromCache, @@ -790,6 +793,8 @@ export class HexMapView extends ItemView { map.workMode = mode; void this.plugin.saveSettings(); this.refreshWorkModeBtn(); + // The neighbour "+" buttons lock and unlock with the mode. + this.refreshSideCrumbs(); } /** @@ -811,21 +816,32 @@ export class HexMapView extends ItemView { const R = 12; // px from the middle to a petal's centre const here = flower.createSpan({ cls: "duckmage-region-flower-petal is-here", attr: { title: `Here: ${this.plugin.mapLabel(this.activeMapName)}` } }); here.setCssProps({ "--duckmage-petal-x": "0px", "--duckmage-petal-y": "0px" }); + const lock = walkLock(this.plugin, this.activeMapName, home.overworld.name); for (const p of petals) { const key = `${p.hex[0]}_${p.hex[1]}`; const region = regionMapAt(maps, home.overworld.name, key); const terrain = this.plugin.mapStore.get(home.overworld.name, key)?.terrain; const colour = terrain ? palette.find((t) => t.name === terrain)?.color : undefined; - const word = p.bearing[0].toUpperCase() + p.bearing.slice(1); - const title = region ? `${word}: ${this.plugin.mapLabel(region.name)}` : `${word}: no region yet`; + // An empty petal is new land: "+" walks into it (pick or roll its biome). + const b = neighbourButton(p.bearing, region ? { name: region.name, label: this.plugin.mapLabel(region.name) } : undefined, { + canMake: true, + canAdd: !lock, + lockedHint: lock ?? "", + inGrid: inOverworldGrid(home.overworld, p.hex[0], p.hex[1]), + }); const petal = flower.createEl("button", { - cls: "duckmage-region-flower-petal" + (region ? "" : " is-empty"), - attr: { title, "aria-label": title, "data-side": p.bearing }, + cls: "duckmage-region-flower-petal" + (region ? "" : " is-empty is-new") + (b.action.kind === "locked" ? " is-locked" : ""), + text: b.plus ? "+" : "", + attr: { title: b.title, "aria-label": b.title, "data-side": p.bearing, "data-hex": key }, }); petal.setCssProps({ "--duckmage-petal-x": `${(p.dx * R).toFixed(1)}px`, "--duckmage-petal-y": `${(p.dy * R).toFixed(1)}px` }); if (colour && region) petal.setCssProps({ "--duckmage-petal-bg": colour }); - if (region) petal.addEventListener("click", () => this.navigateToMap(region.name)); - else petal.disabled = true; + petal.disabled = b.disabled; + const action = b.action; + if (action.kind === "go") petal.addEventListener("click", () => this.navigateToMap(action.target)); + else if (action.kind === "new") { + petal.addEventListener("click", () => this.openWalk({ overworld: home.overworld.name, px: p.hex[0], py: p.hex[1], bearing: p.bearing })); + } } el.show(); return; @@ -845,23 +861,46 @@ export class HexMapView extends ItemView { return; } const pad = el.createDiv({ cls: "duckmage-map-pad", attr: { role: "group", "aria-label": "Neighbouring maps" } }); + const active = this.plugin.getMap(this.activeMapName); for (const { side: s, glyph } of PAD_SIDES) { const c = side.find((x) => x.side === s); - const word = s[0].toUpperCase() + s.slice(1); - const title = !c ? `${word}: nothing there` - : via ? `${word} of ${this.plugin.mapLabel(via)}: ${this.plugin.mapLabel(c.name)}` - : `${word}: ${this.plugin.mapLabel(c.name)}`; + // An empty side of this map's own world is new land (the hex editor's + // flower offers the same); a submap's borrowed pad only goes places. + const b = neighbourButton(s, c ? { name: c.name, label: this.plugin.mapLabel(c.name) } : undefined, { + canMake: !via && neighbourSpec(this.plugin, this.activeMapName, s).ok, + canAdd: canAdd(active), + lockedHint: ADD_REGION_LOCKED_HINT, + }); + const title = c && via ? `${s[0].toUpperCase() + s.slice(1)} of ${this.plugin.mapLabel(via)}: ${this.plugin.mapLabel(c.name)}` : b.title; const btn = pad.createEl("button", { - cls: `duckmage-map-pad-btn is-${s}`, - text: glyph, + cls: `duckmage-map-pad-btn is-${s}` + (b.plus ? " is-new" : "") + (b.action.kind === "locked" ? " is-locked" : ""), + text: b.plus ? "+" : glyph, attr: { title, "aria-label": title, "data-side": s }, }); - if (c) btn.addEventListener("click", () => this.navigateToMap(c.name)); - else btn.disabled = true; + btn.disabled = b.disabled; + const action = b.action; + if (action.kind === "go") btn.addEventListener("click", () => this.navigateToMap(action.target)); + else if (action.kind === "new") btn.addEventListener("click", () => this.openWalk(s)); } el.show(); } + /** + * Walk into new land from the open map (a "+" on the region flower or the + * d-pad): pick or roll its biome, preview, create, then go there. The same + * flow as the hex editor's neighbour flower (WalkRegionModal). + */ + private openWalk(to: Side | OverworldWalk): void { + const from = this.activeMapName; + const open = () => new WalkRegionModal(this.app, this.plugin, from, to, (name) => { + if (this.activeMapName === from) this.navigateToMap(name); + else this.refreshSideCrumbs(); + }).open(); + // A side-by-side world picks a terrain generator; an overworld needs neither feature. + if (typeof to === "string") withFeature(this.plugin, "regions", () => withFeature(this.plugin, "generators", open)); + else open(); + } + public switchMapFromModal(name: string): void { this.navigateToMap(name); } diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 67c66cbc..84dd0262 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -32,8 +32,8 @@ Hexes with locations show a small ring at the top, with a count once there are t | **↑** / **Alt+↑** | Up to the parent map; the hex you came from flashes | | **→** / **Alt+→** | Forward again after going back | | Breadcrumb (top left) | Jump to any map above this one | -| Small hex flower after the arrows (a region of an overworld) | The six regions around this one, each in its direction. Hover a petal for its name, click to go there. Empty petals have no region yet | -| **◀ ▲ ▼ ▶** after the arrows (neighbouring maps) | Go to the map on that side; hover for its name. Inside a submap they go to its parent's neighbours | +| Small hex flower after the arrows (a region of an overworld) | The six regions around this one, each in its direction. Hover a petal for its name, click to go there. An empty petal's **+** makes the region there (pick or roll its biome) | +| **◀ ▲ ▼ ▶** after the arrows (neighbouring maps) | Go to the map on that side; hover for its name. **+** on an empty side makes new land there. Inside a submap they go to its parent's neighbours | The arrows are always ← ↑ → in that order; one that doesn't apply right now is greyed out. Hover any of them for the map it goes to. @@ -140,6 +140,8 @@ Turn on any one of them from the hint (✦) where it would appear, or all of the **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards two things on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**; in Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region) needs **Build** or God; in Play the biome picker is greyed out and says "Switch to Build to place a biome.", and **New map from this hex… → Region** says "Switch to Build to make a region." Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. +**Walking into new land.** In a region, the hex flower on the toolbar shows a **+** on each neighbour that has no region yet ("New region to the east"). Click it, pick the biome that lies there or **Roll** for one (the seed is shown; the same seed rolls the same biome), watch the preview of the new region blended with the regions around it, then **Create and go**. A different biome makes border country in between. Past the overworld's edge, the overworld grows by a hex to fit the new region. The hex editor's neighbour flower does the same on the hexes past the region's edge, and maps joined side by side get a **+** on the empty sides of their arrow pad. Needs Build or God: in Play the **+** says "Switch to Build to make a region." + Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. A road or river that ends on the edge of a region, next to where the neighbour's road of the same type ends, is drawn on to the shared edge on both maps, so the two join up. diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index a87b5e4d..581ecea8 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -608,9 +608,9 @@ export class MapStore { const dropsPaths = disk.paths.length > 0 && data.paths.length === 0 && !this.clearedPaths.has(map.name); const dropsHexes = disk.hexes.size > 0 && data.hexes.size === 0 && !this.clearedHexes.has(map.name); if (!dropsPaths && !dropsHexes) return false; - const what = [dropsPaths ? `${disk.paths.length} path${disk.paths.length === 1 ? "" : "s"}` : "", dropsHexes ? `${disk.hexes.size} hex${disk.hexes.size === 1 ? "" : "es"}` : ""].filter(Boolean).join(" and "); - console.error(`Hexmap World Creator: a save of ${path} would have removed all its ${what} without them being deleted; the note's were kept.`, { map: map.name, paths: map.paths, hexes: data.hexes.size }); - new Notice(`Hexmap World Creator: a save would have removed all ${what} from ${path}. They weren't deleted, so the note's were kept. To remove them, delete them again.`, 15000); + const what = droppedWhat(dropsPaths ? disk.paths.length : 0, dropsHexes ? disk.hexes.size : 0); + console.error(`Hexmap World Creator: a save of ${path} would have removed ${what}, but nothing was deleted, so the note's copy was kept.`, { map: map.name, paths: map.paths, hexes: data.hexes.size }); + new Notice(`Hexmap World Creator: a save of ${path} would have removed ${what}. Nothing was deleted, so the note's copy was kept. If you meant to remove it, delete again.`, 15000); if (dropsHexes) this.hexes.set(map.name, this.matchCase(map, disk.hexes)); if (dropsPaths) { this.views.delete(map.name); @@ -1094,6 +1094,16 @@ function problemSignature(problems: MapNoteProblem[] | undefined): string { return (problems ?? []).map((p) => `${p.where}\u0000${p.text}\u0000${p.reason}`).join("\u0001"); } +/** + * What a refused save would have dropped, for the write guard's message: + * "its only path", "all its 3 paths", "its only path and all its 12 hexes". + * Zero counts are left out. + */ +export function droppedWhat(paths: number, hexes: number): string { + const part = (n: number, one: string, many: string) => (n === 1 ? `its only ${one}` : `all its ${n} ${many}`); + return [paths ? part(paths, "path", "paths") : "", hexes ? part(hexes, "hex", "hexes") : ""].filter(Boolean).join(" and "); +} + /** * Settings as written to data.json: maps whose note holds their paths * (`holds`) go without `pathChains`. Everything else is shared, not copied. diff --git a/src/maps/mapNav.ts b/src/maps/mapNav.ts index e5ea0961..5f814809 100644 --- a/src/maps/mapNav.ts +++ b/src/maps/mapNav.ts @@ -112,6 +112,49 @@ export function flowerPetals(orientation: Orientation, stagger: Stagger, px: num return out.map(({ bearing, hex, dx, dy }) => ({ bearing, hex, dx, dy })); } +/** + * What one neighbour button (a flower petal or a d-pad side) does: + * - go: a map is there, click to go to it; + * - new: nothing there yet, a "+" that walks into new land (pick or roll + * its biome, see WalkRegionModal); `grows` when the overworld must grow + * by that hex first; + * - locked: the "+" is there but the map's work mode is Play; + * - none: nothing there and nothing can be made (shown disabled). + */ +export type NeighbourAction = + | { kind: "go"; target: string } + | { kind: "new"; grows: boolean } + | { kind: "locked"; hint: string } + | { kind: "none" }; + +export interface NeighbourButton { + action: NeighbourAction; + /** Show a "+": an empty spot that can take a new region (now or in another mode). */ + plus: boolean; + disabled: boolean; + title: string; +} + +/** + * The button for the neighbour in `direction` ("north-east"). `there` is + * the map in that spot. With nothing there, `canMake` says whether new land + * can be made in that spot at all, `canAdd` whether the work mode allows it + * now (Build and God; src/workMode.ts), `inGrid` whether the spot is inside + * the overworld's grid (false: making it grows the overworld). + */ +export function neighbourButton( + direction: string, + there: { name: string; label: string } | undefined, + opts: { canMake: boolean; canAdd: boolean; lockedHint: string; inGrid?: boolean; emptyTitle?: string }, +): NeighbourButton { + const word = direction[0].toUpperCase() + direction.slice(1); + if (there) return { action: { kind: "go", target: there.name }, plus: false, disabled: false, title: `${word}: ${there.label}` }; + if (!opts.canMake) return { action: { kind: "none" }, plus: false, disabled: true, title: `${word}: ${opts.emptyTitle ?? "nothing there"}` }; + const title = `New region to the ${direction}`; + if (!opts.canAdd) return { action: { kind: "locked", hint: opts.lockedHint }, plus: true, disabled: true, title: `${title}. ${opts.lockedHint}` }; + return { action: { kind: "new", grows: opts.inGrid === false }, plus: true, disabled: false, title }; +} + /** The four sides of a world-grid map, always in this order (a d-pad: ◀ ▲ ▼ ▶). */ export const PAD_SIDES = [ { side: "west", glyph: "◀" }, diff --git a/src/overworld/regionWorld.ts b/src/overworld/regionWorld.ts index 3279449a..5ee159d6 100644 --- a/src/overworld/regionWorld.ts +++ b/src/overworld/regionWorld.ts @@ -25,6 +25,7 @@ import { biomeForTerrain, biomeGeneratorId, ecotoneBetween, type BiomeId, type B import { BlendField, REGION_WARP, type BlendWidth } from "./blendField"; import { regionBox, regionCells, regionCentrePoint, type RegionLayout } from "./layout"; import { generateRegion } from "./regionGen"; +import { hash2 } from "./noise"; export interface GridRules { orientation: Orientation; @@ -312,3 +313,34 @@ export function parseBiomeRiver(raw: string | undefined): string[] { export function formatBiomeRiver(keys: string[]): string { return keys.map((k) => k.replace("_", ",")).join(" > "); } + +// ── walking into new land ──────────────────────────────────────────────── + +/** + * The grid that also holds hex (x, y): the smallest growth of offset/size + * that takes it in (like the map's + expand buttons), or null when it is + * inside already. Hex numbers never change, so regions keep their slots. + */ +export function gridToInclude( + offset: { x: number; y: number }, + size: { cols: number; rows: number }, + x: number, + y: number, +): { offset: { x: number; y: number }; size: { cols: number; rows: number } } | null { + const x0 = Math.min(offset.x, x), y0 = Math.min(offset.y, y); + const x1 = Math.max(offset.x + size.cols - 1, x), y1 = Math.max(offset.y + size.rows - 1, y); + if (x0 === offset.x && y0 === offset.y && x1 - x0 + 1 === size.cols && y1 - y0 + 1 === size.rows) return null; + return { offset: { x: x0, y: y0 }, size: { cols: x1 - x0 + 1, rows: y1 - y0 + 1 } }; +} + +/** + * Roll a biome from `ids` with `seed`: the same seed always gives the same + * biome, so a roll can be shown and repeated. Avoids `avoid` (the biome + * being walked from) when there is any other. + */ +export function rollBiome(ids: readonly string[], seed: number, avoid?: string): string | undefined { + const others = ids.filter((id) => id !== avoid); + const pool = others.length ? others : ids; + if (!pool.length) return undefined; + return pool[Math.floor(hash2(seed >>> 0, 0x5eed, 0xb10e) * pool.length)]; +} diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index acd7ad1e..c464335d 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -21,6 +21,7 @@ import { ADD_REGION_LOCKED_HINT, canAdd, canReshape, PLACE_LOCKED_HINT, RESHAPE_ import { defaultRegionName, dominantTerrain, + gridToInclude, meshes, overworldBiomes, paletteTypeOf, @@ -311,7 +312,7 @@ export async function setBiomeAt( px: number, py: number, biome: BiomeId, - opts: RegionGenOptions = {}, + opts: RegionGenOptions & { name?: string } = {}, ): Promise<{ name: string } | { error: string }> { const parent = plugin.getMap(parentName); if (!parent) return { error: "Map not found." }; @@ -331,3 +332,55 @@ export async function setBiomeAt( } return createRegion(plugin, parentName, px, py, { ...opts, fill: "match" }); } + +// ── walking into new land ──────────────────────────────────────────────── + +/** Is overworld hex (px, py) inside the overworld's grid? */ +export function inOverworldGrid(map: Pick, px: number, py: number): boolean { + return gridToInclude(map.gridOffset, map.gridSize, px, py) === null; +} + +/** + * Why walking from `fromMap` into new land on overworld `overworldName` is + * locked, or undefined when it may go ahead. Both maps' work modes count: + * the one you're on (its mode is on the toolbar) and the overworld the new + * region is added to. Build and God allow it; Play doesn't. + */ +export function walkLock(plugin: HexmakerPlugin, fromMap: string, overworldName: string): string | undefined { + if (!canAdd(plugin.getMap(fromMap))) return ADD_REGION_LOCKED_HINT; + if (!canAdd(plugin.getMap(overworldName))) return `Switch ${plugin.mapLabel(overworldName)} to Build to make a region.`; + return undefined; +} + +/** + * Walk from a region into new land at overworld hex (px, py) (the region + * flower's "+"): grow the overworld to take the hex in when it lies past + * the grid, set the hex's biome and make its region, blended with the + * overworld and pinned to the regions around it. Build and God only; a hex + * that already has a region is refused (its biome is God's to change). + */ +export async function walkIntoHex( + plugin: HexmakerPlugin, + parentName: string, + px: number, + py: number, + biome: BiomeId, + opts: RegionGenOptions & { name?: string; from?: string } = {}, +): Promise<{ name: string; grew: boolean } | { error: string }> { + const parent = plugin.getMap(parentName); + if (!parent) return { error: "Map not found." }; + const lock = walkLock(plugin, opts.from ?? parentName, parentName); + if (lock) return { error: lock }; + if (!overworldOf(plugin, parentName)) return { error: "This map has no rectangle region settings." }; + const existing = regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`); + if (existing) return { error: `That hex's region is ${plugin.mapLabel(existing.name)}.` }; + if (!representativeTerrain(biome, plugin.getMapPalette(parentName))) return { error: "This map's palette has no terrain for that biome." }; + const grow = gridToInclude(parent.gridOffset, parent.gridSize, px, py); + if (grow) { + parent.gridOffset = grow.offset; + parent.gridSize = grow.size; + await plugin.saveSettings(); + } + const res = await setBiomeAt(plugin, parentName, px, py, biome, opts); + return "error" in res ? res : { name: res.name, grew: !!grow }; +} diff --git a/src/worldgen/WalkRegionModal.ts b/src/worldgen/WalkRegionModal.ts index 926487af..1ff1f4bc 100644 --- a/src/worldgen/WalkRegionModal.ts +++ b/src/worldgen/WalkRegionModal.ts @@ -6,35 +6,187 @@ import { generatorFitsPalette, listGenerators, paletteColors, pathColors, type G import { createWalkRegion, planWalk, previewWalk, regionBiome, type WalkPlan } from "./neighbours"; import { drawPreview } from "./preview"; import type { Side } from "./world"; +import { biomeForTerrain, biomeInfo, representativeTerrain } from "../overworld/biomes"; +import { regionHome, inOverworldGrid, planRegionAt, walkIntoHex, walkLock } from "../overworld/regionsVault"; +import { defaultRegionName, rollBiome } from "../overworld/regionWorld"; +import { drawRegionPlan, lockButton, paintableBiomes } from "../hex-map/BiomeModals"; +import { ADD_REGION_LOCKED_HINT, canAdd } from "../workMode"; +import { slugify } from "../utils"; + +/** Walking from a region of an overworld into the empty overworld hex (px, py), which lies `bearing` of it. */ +export interface OverworldWalk { + overworld: string; + px: number; + py: number; + /** Compass word ("north-east"). */ + bearing: string; +} /** * "New land to the east": stepping off a map's edge where no region is yet. * Pick (or roll) the biome that lies beyond; the new region is blended with * its neighbours, so a different biome arrives through a transition region. * Creates the region and hands back its name. + * + * One flow for both entry points (the hex editor's neighbour flower and the + * map toolbar's region flower / d-pad), in two flavours: + * - a region of an overworld (`to` is an OverworldWalk): the biome is one + * the overworld's palette can paint; the region is made in that hex's + * slot by the blend field, pinned to every region around it, and the + * overworld grows to take the hex in when it lies past its grid + * (walkIntoHex). Build and God only (src/workMode.ts). + * - a map on an older side-by-side world (`to` is a side): the biome is a + * terrain generator, blended with the neighbours (planWalk). */ export class WalkRegionModal extends HexmakerModal { private seed = randomSeed(); + private side: Side = "east"; + private walk: OverworldWalk | null = null; constructor( app: App, private plugin: HexmakerPlugin, private fromMap: string, - private side: Side, + to: Side | OverworldWalk, private onCreated: (name: string) => void, ) { super(app); + if (typeof to === "string") this.side = to; + else this.walk = to; } onOpen(): void { this.makeDraggable(); - this.titleEl.setText(`New land to the ${this.side}`); + this.titleEl.setText(`New land to the ${this.walk?.bearing ?? this.side}`); const { contentEl } = this; contentEl.addClass("duckmage-region-nav"); + if (this.walk) { + this.renderOverworld(this.walk); + return; + } contentEl.createEl("p", { text: "Loading generators…", cls: "duckmage-map-origin-desc" }); void listGenerators(this.plugin).then((generators) => this.render(generators)); } + /** The overworld flavour: pick or roll a biome, preview the blended region, create it. */ + private renderOverworld(walk: OverworldWalk): void { + const { contentEl, plugin } = this; + contentEl.empty(); + const ow = plugin.getMap(walk.overworld); + if (!ow) return; + const { px, py } = walk; + const hex = `${px}_${py}`; + const owPalette = plugin.getMapPalette(walk.overworld); + const biomes = paintableBiomes(plugin, walk.overworld); + if (!biomes.length) { + contentEl.createEl("p", { text: "This overworld's palette has no terrain that stands for a biome, so there's nothing to make the new land from.", cls: "duckmage-map-origin-desc" }); + return; + } + const home = regionHome(plugin, this.fromMap); + const hereTerrain = home ? plugin.mapStore.get(walk.overworld, `${home.px}_${home.py}`)?.terrain : undefined; + const here = hereTerrain ? biomeForTerrain(hereTerrain, owPalette) : undefined; + const grows = !inOverworldGrid(ow, px, py); + contentEl.createEl("p", { + text: `Nothing lies ${walk.bearing} of ${plugin.mapLabel(this.fromMap)} yet. Pick what's out there, or roll for it. If it's a different biome, the new region is the border country in between.` + + (grows ? " The overworld grows by a hex to fit it." : ""), + cls: "duckmage-map-origin-desc", + }); + + const row = contentEl.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + row.createSpan({ text: "Biome", cls: "duckmage-map-origin-label" }); + const select = row.createEl("select", { attr: { "aria-label": "Biome" } }); + for (const b of biomes) select.createEl("option", { value: b.id, text: b.id === here ? `${b.label} (same as here)` : b.label }); + let biome = biomes.some((b) => b.id === here) ? here! : biomes[0].id; + select.value = biome; + const roll = row.createEl("button", { text: "Roll", attr: { title: "Roll a biome from a new seed (a different one from here, if there is one)" } }); + + const seedRow = contentEl.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + seedRow.createSpan({ text: "Seed", cls: "duckmage-map-origin-label" }); + const seedInput = seedRow.createEl("input", { type: "number", cls: "duckmage-walk-seed", attr: { "aria-label": "Seed" } }); + seedInput.value = String(this.seed); + const reroll = seedRow.createEl("button", { text: "Re-roll terrain", attr: { title: "Same biome, new seed" } }); + + const note = contentEl.createEl("p", { cls: "duckmage-map-origin-desc" }); + const canvas = contentEl.createEl("canvas", { cls: "duckmage-region-gen-preview" }); + canvas.width = 360; + canvas.height = 300; + + const nameRow = contentEl.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + nameRow.createSpan({ text: "Name", cls: "duckmage-map-origin-label" }); + const taken = (n: string) => plugin.settings.maps.some((m) => m.name === slugify(n)); + const nameInput = nameRow.createEl("input", { + type: "text", + attr: { placeholder: defaultRegionName(plugin.mapLabel(walk.overworld), px, py, plugin.mapStore.get(walk.overworld, hex)?.name, taken) }, + }); + + const buttons = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); + const create = buttons.createEl("button", { text: "Create and go", cls: "mod-cta" }); + buttons.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); + const lock = walkLock(plugin, this.fromMap, walk.overworld); + const locked = !!lock; + if (lock) { + lockButton(create, lock); + contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); + } + + const labelOf = (id: string) => biomeInfo(id)?.label ?? id; + let rolled = ""; + const refresh = () => { + const plan = planRegionAt(plugin, walk.overworld, px, py, { seed: this.seed, hexTerrain: representativeTerrain(biome, owPalette) }); + drawRegionPlan(canvas, plugin, walk.overworld, px, py, plan); + // The biomes it blends from: the field's, plus the one walked from. + const fromIds = new Set((plan?.biome?.from ?? []).filter((b) => b !== biome)); + if (here && here !== biome) fromIds.add(here); + const from = [...fromIds].map(labelOf); + note.setText( + (rolled ? `${rolled} ` : "") + + (from.length ? `Border country: ${from.join(" + ")} turning into ${labelOf(biome)}.` : `${labelOf(biome)} carries on from here.`), + ); + }; + select.addEventListener("change", () => { + biome = select.value; + rolled = ""; + refresh(); + }); + roll.addEventListener("click", () => { + this.seed = randomSeed(); + seedInput.value = String(this.seed); + biome = rollBiome(biomes.map((b) => b.id), this.seed, here) ?? biome; + select.value = biome; + rolled = `Rolled ${labelOf(biome)} (seed ${this.seed}).`; + refresh(); + }); + reroll.addEventListener("click", () => { + this.seed = randomSeed(); + seedInput.value = String(this.seed); + rolled = ""; + refresh(); + }); + seedInput.addEventListener("change", () => { + const n = Number(seedInput.value); + if (!Number.isFinite(n)) return; + this.seed = Math.trunc(n) >>> 0; + rolled = ""; + refresh(); + }); + create.addEventListener("click", () => { + if (locked) return; + create.disabled = true; + create.setText("Creating…"); + void walkIntoHex(plugin, walk.overworld, px, py, biome, { seed: this.seed, name: nameInput.value.trim() || undefined, from: this.fromMap }).then((r) => { + if ("error" in r) { + new Notice(r.error); + create.disabled = false; + create.setText("Create and go"); + return; + } + this.close(); + this.onCreated(r.name); + }); + }); + refresh(); + } + private render(generators: GeneratorFile[]): void { const { contentEl } = this; contentEl.empty(); @@ -76,6 +228,8 @@ export class WalkRegionModal extends HexmakerModal { const buttons = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); const create = buttons.createEl("button", { text: "Create and go", cls: "mod-cta" }); buttons.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); + const locked = !canAdd(from); + if (locked) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: ADD_REGION_LOCKED_HINT }); let plan: WalkPlan | null = null; let nameTouched = false; @@ -103,7 +257,7 @@ export class WalkRegionModal extends HexmakerModal { ); if (!nameTouched) nameInput.value = suggestName(chosen.model.name); const preview = previewWalk(this.plugin, plan, this.seed); - create.disabled = !preview.ok; + create.disabled = !preview.ok || locked; if (!preview.ok) { note.setText(`Couldn't generate: ${preview.message}`); return; @@ -119,9 +273,9 @@ export class WalkRegionModal extends HexmakerModal { }; select.addEventListener("change", refresh); roll.addEventListener("click", () => { - const others = biomes.filter((g) => g.model.name !== here?.name); - const pool = others.length ? others : biomes; - select.value = pool[Math.floor(Math.random() * pool.length)].model.name; + // A new seed rolls the biome (repeatably) and the terrain. + this.seed = randomSeed(); + select.value = rollBiome(biomes.map((g) => g.model.name), this.seed, here?.name) ?? select.value; refresh(); }); reroll.addEventListener("click", () => { @@ -129,7 +283,7 @@ export class WalkRegionModal extends HexmakerModal { refresh(); }); create.addEventListener("click", () => { - if (!plan) return; + if (!plan || locked) return; create.disabled = true; void createWalkRegion(this.plugin, plan, nameInput.value.trim() || suggestName(select.value), this.seed, (done, total) => create.setText(`Creating ${done} / ${total}…`), diff --git a/styles.css b/styles.css index aa220511..d081ec26 100644 --- a/styles.css +++ b/styles.css @@ -6442,6 +6442,13 @@ button.duckmage-wfc-library-tab.is-active { opacity: 0.9; } +/* Play mode: the "+" stays, locked (its tooltip says to switch to Build). */ +.duckmage-neighbor-tile.duckmage-neighbor-tile-new.is-locked, +.duckmage-neighbor-tile.duckmage-neighbor-tile-new.is-locked:hover { + opacity: 0.25; + cursor: default; +} + /* "Go to region?" box. */ .duckmage-region-nav-preview { display: block; @@ -8357,6 +8364,28 @@ button.duckmage-terrain-legend-chip { opacity: 0.6; cursor: default; } +/* An empty petal is new land: a "+" that opens the walk (pick or roll a biome). */ +.duckmage-region-flower-petal.is-new { + display: flex; + align-items: center; + justify-content: center; + font-size: 9px; + font-weight: 700; + line-height: 1; + color: var(--text-muted); + opacity: 0.85; + cursor: pointer; +} +.duckmage-region-flower-petal.is-new:hover:not(:disabled) { + color: var(--interactive-accent); +} +.duckmage-region-flower-petal.is-new.is-locked { + opacity: 0.4; + cursor: default; +} +.duckmage-region-nav input.duckmage-walk-seed { + width: 9em; +} /* Maps on a world grid: their four sides as a d-pad (◀ ▲ ▼ ▶), fixed order. */ .duckmage-map-pad { @@ -8382,6 +8411,10 @@ button.duckmage-terrain-legend-chip { opacity: 0.35; cursor: default; } +.duckmage-map-pad .duckmage-map-pad-btn.is-new { + font-weight: 700; + border-style: dashed; +} /* Work mode (Play / Build / God): always on the toolbar. */ .duckmage-map-nav-group .duckmage-work-mode-btn { diff --git a/tests/mapStore.test.ts b/tests/mapStore.test.ts index b0d06e68..b64755ff 100644 --- a/tests/mapStore.test.ts +++ b/tests/mapStore.test.ts @@ -1,6 +1,6 @@ import { describe, it, beforeEach } from "node:test"; import expect from "expect"; -import { MapStore, HEX_DATA_KEYS, withoutNotePaths } from "../src/maps/MapStore"; +import { MapStore, HEX_DATA_KEYS, droppedWhat, withoutNotePaths } from "../src/maps/MapStore"; import { parseMapNote } from "../src/maps/mapNote"; import { MemVault } from "./helpers/memVault"; import { Notice } from "obsidian"; @@ -630,3 +630,13 @@ describe("map store: derived Summary and Route (#46)", () => { expect(v.files.get(NOTE)).not.toContain("not in the palette"); }); }); + +describe("map store: the write guard says what it kept", () => { + it("pluralises: its only path, all its N paths", () => { + expect(droppedWhat(1, 0)).toBe("its only path"); + expect(droppedWhat(3, 0)).toBe("all its 3 paths"); + expect(droppedWhat(0, 1)).toBe("its only hex"); + expect(droppedWhat(2, 12)).toBe("all its 2 paths and all its 12 hexes"); + expect(droppedWhat(1, 5)).toBe("its only path and all its 5 hexes"); + }); +}); diff --git a/tests/walkNewRegion.test.ts b/tests/walkNewRegion.test.ts new file mode 100644 index 00000000..7a28a941 --- /dev/null +++ b/tests/walkNewRegion.test.ts @@ -0,0 +1,216 @@ +/** + * Walking into new land from a region (owner: "when you go from region to + * region walking you should be able to pick or roll for what the NEXT biome + * is"): the region flower's empty petals, the d-pad's empty sides, rolling a + * biome from a seed, and making the region, growing the overworld when the + * hex lies past its grid. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { flowerPetals, neighbourButton } from "../src/maps/mapNav"; +import { gridToInclude, rollBiome } from "../src/overworld/regionWorld"; +import { inOverworldGrid, walkIntoHex, walkLock } from "../src/overworld/regionsVault"; +import { representativeTerrain } from "../src/overworld/biomes"; +import { ADD_REGION_LOCKED_HINT } from "../src/workMode"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import type { MapData } from "../src/types"; + +const LOCK = { lockedHint: ADD_REGION_LOCKED_HINT }; + +describe("region flower petals and d-pad sides", () => { + it("a petal with a region goes there", () => { + const b = neighbourButton("north-east", { name: "ow-2-1", label: "Pinewood" }, { canMake: true, canAdd: true, ...LOCK }); + expect(b).toEqual({ action: { kind: "go", target: "ow-2-1" }, plus: false, disabled: false, title: "North-east: Pinewood" }); + }); + + it("an empty petal is a + that walks into new land, named by its direction", () => { + const b = neighbourButton("south-west", undefined, { canMake: true, canAdd: true, inGrid: true, ...LOCK }); + expect(b.action).toEqual({ kind: "new", grows: false }); + expect(b.plus).toBe(true); + expect(b.disabled).toBe(false); + expect(b.title).toBe("New region to the south-west"); + }); + + it("an empty petal past the overworld's grid grows it", () => { + const b = neighbourButton("north", undefined, { canMake: true, canAdd: true, inGrid: false, ...LOCK }); + expect(b.action).toEqual({ kind: "new", grows: true }); + }); + + it("in Play the + stays but is locked, and says to switch to Build", () => { + const b = neighbourButton("east", undefined, { canMake: true, canAdd: false, ...LOCK }); + expect(b.action).toEqual({ kind: "locked", hint: "Switch to Build to make a region." }); + expect(b.plus).toBe(true); + expect(b.disabled).toBe(true); + expect(b.title).toBe("New region to the east. Switch to Build to make a region."); + }); + + it("Play still goes to regions that are there", () => { + const b = neighbourButton("east", { name: "r", label: "R" }, { canMake: true, canAdd: false, ...LOCK }); + expect(b.action).toEqual({ kind: "go", target: "r" }); + expect(b.disabled).toBe(false); + }); + + it("a side where nothing can be made stays a plain disabled arrow", () => { + const b = neighbourButton("west", undefined, { canMake: false, canAdd: true, ...LOCK }); + expect(b).toEqual({ action: { kind: "none" }, plus: false, disabled: true, title: "West: nothing there" }); + }); + + it("every petal of the flower has a direction to name its +", () => { + for (const o of ["flat", "pointy"] as const) { + const petals = flowerPetals(o, "odd", 2, 3); + expect(petals).toHaveLength(6); + for (const p of petals) { + expect(neighbourButton(p.bearing, undefined, { canMake: true, canAdd: true, ...LOCK }).title).toMatch(/^New region to the [a-z-]+$/); + } + } + }); +}); + +describe("rolling the next biome", () => { + const ids = ["taiga", "grassland", "swamp", "alpine"]; + it("is repeatable: the same seed rolls the same biome", () => { + for (const seed of [1, 42, 123456789, 4294967295]) expect(rollBiome(ids, seed)).toBe(rollBiome(ids, seed)); + }); + it("avoids the biome walked from when there is another", () => { + for (let seed = 0; seed < 200; seed++) expect(rollBiome(ids, seed, "taiga")).not.toBe("taiga"); + expect(rollBiome(["taiga"], 7, "taiga")).toBe("taiga"); + expect(rollBiome([], 7)).toBeUndefined(); + }); + it("reaches every other biome over many seeds", () => { + const seen = new Set(); + for (let seed = 0; seed < 400; seed++) seen.add(rollBiome(ids, seed, "taiga")!); + expect([...seen].sort()).toEqual(["alpine", "grassland", "swamp"]); + }); +}); + +describe("growing the overworld to take a hex in", () => { + const off = { x: 0, y: 0 }, size = { cols: 5, rows: 5 }; + it("is null inside the grid", () => { + expect(gridToInclude(off, size, 0, 0)).toBeNull(); + expect(gridToInclude(off, size, 4, 4)).toBeNull(); + }); + it("grows by one column or row toward the hex, keeping hex numbers", () => { + expect(gridToInclude(off, size, 5, 2)).toEqual({ offset: { x: 0, y: 0 }, size: { cols: 6, rows: 5 } }); + expect(gridToInclude(off, size, -1, 2)).toEqual({ offset: { x: -1, y: 0 }, size: { cols: 6, rows: 5 } }); + expect(gridToInclude(off, size, 2, -1)).toEqual({ offset: { x: 0, y: -1 }, size: { cols: 5, rows: 6 } }); + expect(gridToInclude(off, size, -1, 5)).toEqual({ offset: { x: -1, y: 0 }, size: { cols: 6, rows: 6 } }); + }); +}); + +describe("walkIntoHex: making the next region", () => { + type Hex = { terrain?: string; locked?: boolean }; + function world(mode?: string) { + const overworld = { + name: "ow", paletteName: "Default", workMode: mode, + gridSize: { cols: 3, rows: 3 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", + regions: { footprint: "rect", size: 4, blend: "normal", worldId: "w1", stagger: "odd" }, + pathChains: [], + } as unknown as MapData; + const here = { name: "ow-1-1", submapKind: "region", parent: { map: "ow", hex: "1_1" }, gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 4, y: 6 } } as unknown as MapData; + const maps: MapData[] = [overworld, here]; + const store = new Map>(); + const hexes = (m: string): Map => { + let h = store.get(m); + if (!h) store.set(m, (h = new Map())); + return h; + }; + hexes("ow").set("1_1", { terrain: representativeTerrain("taiga", DEFAULT_TERRAIN_PALETTE)! }); + const writes: string[] = []; + const made: { name: string; cols: number; rows: number; cells?: Map }[] = []; + const plugin = { + settings: { maps, hexOrientation: "flat", staggerOffset: "odd" }, + getMap: (n: string) => maps.find((m) => m.name === n), + getMapPalette: () => DEFAULT_TERRAIN_PALETTE, + getPaletteOrPresetTerrains: () => DEFAULT_TERRAIN_PALETTE, + mapLabel: (n: string) => n, + mapStore: { + get: (m: string, k: string) => store.get(m)?.get(k), + all: (m: string) => hexes(m), + set: (m: string, k: string, patch: Hex) => { + writes.push(`${m}|${k}`); + hexes(m).set(k, { ...hexes(m).get(k), ...patch }); + }, + setMany: (m: string) => writes.push(m), + flush: async () => {}, + }, + saveSettings: async () => {}, + createNewMap: async ( + name: string, cols: number, rows: number, _palette: string, x: number, y: number, stagger: string, + _progress: unknown, cells?: Map, extra?: { parent?: { map: string; hex: string } }, + ) => { + const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-"); + maps.push({ name: slug, paletteName: "Default", gridSize: { cols, rows }, gridOffset: { x, y }, staggerOffset: stagger, parent: extra?.parent, submapKind: "region", pathChains: [] } as unknown as MapData); + for (const [k, t] of cells ?? []) hexes(slug).set(k, { terrain: t }); + made.push({ name: slug, cols, rows, cells }); + return { name: slug }; + }, + linkRegion: async () => true, + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { plugin: plugin as any, store, overworld, maps, writes, made }; + } + + it("in Play nothing is made or grown", async () => { + const w = world("play"); + expect(await walkIntoHex(w.plugin, "ow", 3, 1, "grassland")).toEqual({ error: ADD_REGION_LOCKED_HINT }); + expect(w.overworld.gridSize).toEqual({ cols: 3, rows: 3 }); + expect(w.writes).toEqual([]); + expect(w.made).toEqual([]); + }); + + it("a hex inside the overworld with no region gets the biome and its region", async () => { + const w = world("build"); + const r = await walkIntoHex(w.plugin, "ow", 2, 1, "grassland", { seed: 99, name: "Plains" }); + expect(r).toEqual({ name: "plains", grew: false }); + expect(w.overworld.gridSize).toEqual({ cols: 3, rows: 3 }); + expect(w.store.get("ow")?.get("2_1")?.terrain).toBe(representativeTerrain("grassland", DEFAULT_TERRAIN_PALETTE)); + const child = w.maps.find((m) => m.name === "plains")!; + expect(child.parent).toEqual({ map: "ow", hex: "2_1" }); + expect(child.world).toEqual({ id: "w1", cx: 2, cy: 1 }); + expect(child.regionSeed).toBe(99); + expect(w.made[0].cols).toBe(4); + // Generated from the blend field ("match"), not blank. (The shipped + // biome models aren't loaded in unit tests, so the cells' content is + // checked in the sandbox run instead.) + expect(w.made[0].cells).toBeInstanceOf(Map); + }); + + it("a hex past the overworld's edge grows the overworld first, then makes the region", async () => { + const w = world("god"); + expect(inOverworldGrid(w.overworld, 3, 1)).toBe(false); + const r = await walkIntoHex(w.plugin, "ow", 3, 1, "swamp", { seed: 5 }); + expect(r).toMatchObject({ grew: true }); + expect(w.overworld.gridSize).toEqual({ cols: 4, rows: 3 }); + expect(w.overworld.gridOffset).toEqual({ x: 0, y: 0 }); + expect(inOverworldGrid(w.overworld, 3, 1)).toBe(true); + expect(w.store.get("ow")?.get("3_1")?.terrain).toBe(representativeTerrain("swamp", DEFAULT_TERRAIN_PALETTE)); + expect(w.maps.find((m) => m.parent?.hex === "3_1")?.world).toEqual({ id: "w1", cx: 3, cy: 1 }); + }); + + it("growing west keeps every hex number (regions keep their slots)", async () => { + const w = world("build"); + const r = await walkIntoHex(w.plugin, "ow", -1, 1, "alpine", { seed: 1 }); + expect(r).toMatchObject({ grew: true }); + expect(w.overworld.gridOffset).toEqual({ x: -1, y: 0 }); + expect(w.overworld.gridSize).toEqual({ cols: 4, rows: 3 }); + expect(w.maps.find((m) => m.name === "ow-1-1")!.parent).toEqual({ map: "ow", hex: "1_1" }); + }); + + it("the region you walk from counts too: Play there locks it, and the overworld's Play is named", async () => { + const w = world("build"); + w.maps.find((m) => m.name === "ow-1-1")!.workMode = "play"; + expect(walkLock(w.plugin, "ow-1-1", "ow")).toBe(ADD_REGION_LOCKED_HINT); + expect(await walkIntoHex(w.plugin, "ow", 2, 1, "grassland", { from: "ow-1-1" })).toEqual({ error: ADD_REGION_LOCKED_HINT }); + expect(w.made).toEqual([]); + const v = world("play"); + expect(walkLock(v.plugin, "ow-1-1", "ow")).toBe("Switch ow to Build to make a region."); + expect(walkLock(world("god").plugin, "ow-1-1", "ow")).toBeUndefined(); + }); + + it("a hex that already has a region is refused (changing it is God's biome swap)", async () => { + const w = world("god"); + const r = await walkIntoHex(w.plugin, "ow", 1, 1, "swamp"); + expect(r).toEqual({ error: "That hex's region is ow-1-1." }); + expect(w.writes).toEqual([]); + }); +}); From f386f745d5a9767ba6d22ac27a5c0e117db89915 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 21:56:37 -0400 Subject: [PATCH 249/558] =?UTF-8?q?fix(overworld):=20left=20click=20enters?= =?UTF-8?q?=20regions;=20Edit=20region=E2=80=A6=20in=20the=20right-click?= =?UTF-8?q?=20menu=20(#49);=20terrain=20brush=20paints=20regions=20live?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clicks (#49): a left click on a hex or brick that has a region enters it, in every mode and both views; on an empty one it opens the biome picker in Build/God and only hints in Play. Changing a placed region moved to the right-click menu as "Edit region…" (God only; otherwise shown disabled with "Switch to God to change a placed region."), next to Enter region. Routing is pure (overworldInput.ts: overworldLeftClick / overworldMenu). Terrain brush on overworlds: picking a terrain (or pressing in the Biomes view) switches to the Regions view and offers the regions' palette; the brush at any size writes each sub-hex into its region map as you draw, across seams, locked; one undo step per stroke. The overworld layer now redraws once per animation frame during the stroke (it was a trailing 120 ms debounce that never fired while the pointer kept moving) and rebuilds only invalidated region bitmaps. Another open view of a painted region repaints just the changed hexes (shownTerrain diff). No region under the brush: "No region here yet; place a biome first". Play locks it. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- package.json | 4 +- src/hex-map/HexMapView.ts | 147 +++++++++++++++++++++++-------- src/hex-map/help.md | 2 +- src/hex-map/overworldLayer.ts | 18 ++-- src/hex-map/overworldMinimap.ts | 2 +- src/overworld/overworldInput.ts | 150 ++++++++++++++++++++++++++++++++ tests/overworldInput.test.ts | 149 +++++++++++++++++++++++++++++++ 8 files changed, 426 insertions(+), 48 deletions(-) create mode 100644 src/overworld/overworldInput.ts create mode 100644 tests/overworldInput.test.ts diff --git a/README.md b/README.md index 6135b465..7e6e8e30 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: -- **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Painted hexes are locked, so remaking a region keeps them. +- **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Each hex is written to its region as you draw, so the overworld and any open view of those regions update during the stroke. Picking a terrain on an overworld switches to this view; where there's no region yet the brush does nothing ("No region here yet; place a biome first"), and in Play it's locked ("Switch to Build to paint the regions."). In both views, clicking a hex or brick with a region goes into it in every mode; clicking an empty one sets its biome (Build and God). Changing a placed region is in the right-click menu: **Edit region…** (God; greyed out with "Switch to God to change a placed region." otherwise), next to **Enter region**. Painted hexes are locked, so remaking a region keeps them. - **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one; hover a hex for its region's name). Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. **Work modes: Play, Build, God.** Each map has a work mode, always shown on the toolbar next to the map button; click it to switch. It's saved in the map note as a plain `mode:` property (`play`, `build` or `god`), so each map opens in its own mode; new maps are in Build. For now two rules are enforced on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs God; in Build and Play those buttons are greyed out with "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region), or making regions at all (**Make the missing regions…**), needs Build or God; in Play the biome picker is greyed out with "Switch to Build to place a biome.", and **New map from this hex… → Region** is greyed out with "Switch to Build to make a region." There are no confirm boxes for these any more: the mode is the safety catch. Note text is never locked in any mode, and settings and palettes aren't either. diff --git a/package.json b/package.json index e05e7125..e00e4cda 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 064faef9..ba8b047f 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -79,12 +79,12 @@ import { hexChildMaps, regionMapAt, submapMenuPlan } from "../maps/submaps"; import { OverworldLayer } from "./overworldLayer"; import { OverworldMinimap } from "./overworldMinimap"; import { BiomePickerModal, type BiomeHost } from "./BiomeModals"; -import { inOverworldGrid, regionHome, walkLock } from "../overworld/regionsVault"; +import { inOverworldGrid, overworldOf, regionHome, regionPalette, walkLock } from "../overworld/regionsVault"; +import { brushCells, FrameThrottle, terrainDiff, overworldLeftClick, overworldMenu, PAINT_LOCKED_HINT, PAINT_NO_REGION_HINT, paintTargets } from "../overworld/overworldInput"; import { WalkRegionModal, type OverworldWalk } from "../worldgen/WalkRegionModal"; import type { Side } from "../worldgen/world"; import { withFeature } from "../advancedHints"; import { overworldRefreshFor } from "../overworld/overworldChanges"; -import { parentOf as parentOfCell } from "../overworld/layout"; import { RegionNavigateModal } from "./RegionNavigateModal"; import { neighbourShadow, neighbourSpec } from "../worldgen/neighbours"; import { TokenInfoModal } from "./TokenInfoModal"; @@ -374,6 +374,15 @@ export class HexMapView extends ItemView { private currentFactionStroke: Map | null = null; private currentRegionStroke: Map | null = null; private currentSubStroke: Map | null = null; + /** The "no region here" hint was shown this stroke (once is enough). */ + private subStrokeMissHinted = false; + /** + * A region map's terrain as this view last drew it, so a brush stroke on + * its overworld (in another view) repaints just the hexes it changed, live. + * Empty for other maps. + */ + private shownTerrain = new Map(); + private terrainSync = new FrameThrottle((cb) => window.requestAnimationFrame(cb)); /** Overworlds (OW1): every region's hexes stitched on one canvas, and the minimap. */ private overworldLayer!: OverworldLayer; private minimap!: OverworldMinimap; @@ -1130,7 +1139,19 @@ export class HexMapView extends ItemView { } if (e.button !== 0) return; // Overworld full view: the terrain tool paints the regions' own hexes. + if (this.drawingMode === "terrain" && OverworldLayer.viewOf(this.plugin, this.getActiveMap()) === "biomes") { + // The brush paints the regions, so it works in the Regions view. + this.showOverworldRegions(); + hasDragged = true; + return; + } if (this.drawingMode === "terrain" && this.overworldLayer.showsRegions(this.getActiveMap())) { + if (!canAdd(this.getActiveMap())) { + new Notice(PAINT_LOCKED_HINT); + hasDragged = true; + return; + } + this.subStrokeMissHinted = false; isTerrainPainting = true; lastPaintedKey = null; this.currentTerrainStroke = new Map(); @@ -1611,6 +1632,8 @@ export class HexMapView extends ItemView { this.plugin.mapStore.onChange((map) => { this.onOverworldDataChange(map); if (map !== this.activeMapName) return; + // Painted from its overworld in another view: repaint those hexes now. + if (this.shownTerrain.size && !this.currentTerrainStroke) this.terrainSync.request(() => this.syncShownTerrain()); this.scheduleTerrainLegend(); // A name set without a redraw (hex table, code, map note edit) shows up. this.scheduleHexNames(); @@ -2125,11 +2148,14 @@ export class HexMapView extends ItemView { // Show crosshair on the viewport while the picker is open this.viewportEl?.addClass("duckmage-terrain-picking"); + // On an overworld the brush paints its regions' hexes, so it offers + // the regions' palette, and picking a terrain shows the Regions view. + const owInfo = overworldOf(this.plugin, this.activeMapName); // Always open the picker — even if already active, so user can switch terrain new TerrainPickerModal( this.app, this.plugin, - this.plugin.getMapPalette(this.activeMapName), + owInfo ? regionPalette(this.plugin, owInfo.map) : this.plugin.getMapPalette(this.activeMapName), (terrainName: string | null) => { this.viewportEl?.removeClass("duckmage-terrain-picking"); this.leaveOtherToolFor("terrain"); @@ -2139,6 +2165,7 @@ export class HexMapView extends ItemView { this.paintTerrainName = terrainName; this.paintIconName = null; this.updateToolbarButtonStates(); + this.showOverworldRegions(); }, () => { // Eyedropper: enter terrain mode in pick-from-map state @@ -2149,6 +2176,7 @@ export class HexMapView extends ItemView { this.terrainPickMode = true; this.paintTerrainName = null; this.updateToolbarButtonStates(); + this.showOverworldRegions(); }, () => { // Dismissed without selecting @@ -4066,7 +4094,7 @@ export class HexMapView extends ItemView { const cell = this.overworldLayer.cellAt(gridContainer, e.clientX, e.clientY); const tip = !cell ? "" : cell.region ? `${this.plugin.mapLabel(cell.region)}: click to go there` - : `No region yet (hex ${cell.parentHex.replace("_", ", ")}): click to set its biome`; + : `No region yet (hex ${cell.parentHex.replace("_", ", ")})` + (canAdd(this.getActiveMap()) ? ": click to set its biome" : ""); if (gridContainer.title !== tip) gridContainer.title = tip; }); }); @@ -4307,6 +4335,7 @@ export class HexMapView extends ItemView { /** The layers placed from measured hex geometry (see renderGrid). */ private renderMeasuredLayers(gridContainer: HTMLElement, region: MapData): void { + this.snapshotShownTerrain(region); this.renderNeighbourShadow(gridContainer, region); this.overworldLayer.render(gridContainer, region); this.minimap.render(this.contentEl, region); @@ -4553,12 +4582,19 @@ export class HexMapView extends ItemView { const menu = new Menu(); if (OverworldLayer.viewOf(this.plugin, this.getActiveMap())) { - menu.addItem((item) => - item - .setTitle("Set biome…") - .setIcon("trees") - .onClick(() => new BiomePickerModal(this.biomeHost(), this.activeMapName, x, y).open()), - ); + // Placing a biome (empty hex) or changing a placed region (God): + // locked items are shown disabled with their hint, and open nothing. + const hasRegion = !!regionMapAt(this.plugin.settings.maps, this.activeMapName, `${x}_${y}`); + for (const it of overworldMenu(this.getActiveMap(), hasRegion)) { + if (it.id === "enter-region") continue; // the "Enter region: " item below + menu.addItem((item) => { + item + .setTitle(it.enabled ? it.title : `${it.title} (${it.hint})`) + .setIcon(it.id === "edit-region" ? "settings-2" : "trees") + .setDisabled(!it.enabled); + if (it.enabled) item.onClick(() => new BiomePickerModal(this.biomeHost(), this.activeMapName, x, y).open()); + }); + } menu.addItem((item) => item .setTitle("Edit hex…") @@ -4744,11 +4780,15 @@ export class HexMapView extends ItemView { if (ow && !e?.ctrlKey && !e?.metaKey) { const grid = this.viewportEl?.querySelector(".duckmage-hex-map-grid"); const cell = ow === "regions" && e && grid ? this.overworldLayer.cellAt(grid, e.clientX, e.clientY) : null; - if (cell?.region) { - this.enterRegionAt(cell.region, cell.x, cell.y); - return; - } - new BiomePickerModal(this.biomeHost(), this.activeMapName, x, y).open(); + // The brick under the pointer in the Regions view, else the hex clicked. + const [px, py] = cell ? cell.parentHex.split("_").map(Number) : [x, y]; + const region = cell ? cell.region : regionMapAt(this.plugin.settings.maps, this.activeMapName, `${x}_${y}`)?.name; + const act = overworldLeftClick(this.getActiveMap(), !!region); + if (act.kind === "enter" && region) { + if (cell) this.enterRegionAt(region, cell.x, cell.y); + else this.navigateToMap(region); + } else if (act.kind === "place") new BiomePickerModal(this.biomeHost(), this.activeMapName, px, py).open(); + else if (act.kind === "hint") new Notice(act.hint); return; } @@ -5264,7 +5304,7 @@ export class HexMapView extends ItemView { private subHexKeyAt(clientX: number, clientY: number): string | null { const grid = this.viewportEl?.querySelector(".duckmage-hex-map-grid"); const cell = grid ? this.overworldLayer.cellAt(grid, clientX, clientY) : null; - return cell?.region ? `${cell.region}|${cell.x}_${cell.y}` : null; + return cell ? `${cell.x}_${cell.y}` : null; } /** @@ -5275,35 +5315,72 @@ export class HexMapView extends ItemView { private paintSubHexAt(clientX: number, clientY: number): string | null { const grid = this.viewportEl?.querySelector(".duckmage-hex-map-grid"); const cell = grid ? this.overworldLayer.cellAt(grid, clientX, clientY) : null; - if (!cell?.region) return null; - const home = regionHome(this.plugin, cell.region); - if (!home) return null; + if (!cell) return null; + const ow = this.activeMapName; + const owInfo = overworldOf(this.plugin, ow); + if (!owInfo) return null; + const layout = owInfo.layout; if (this.terrainPickMode && !this.isErasingMode) { + if (!cell.region) return null; this.terrainPickMode = false; this.paintTerrainName = this.plugin.mapStore.get(cell.region, `${cell.x}_${cell.y}`)?.terrain ?? null; this.updateToolbarButtonStates(); return null; } const terrain = this.isErasingMode ? null : this.paintTerrainName; - const brush: [number, number][] = [[cell.x, cell.y]]; - if (this.paintBrushSize > 1) { - const nb = hexNeighbors(cell.x, cell.y, home.layout.orientation, home.layout.childStagger); - brush.push(...(this.paintBrushSize === 3 ? [nb[2], nb[3]] : nb)); - } - const ow = home.overworld.name; - for (const [x, y] of brush) { - const ph = parentOfCell(home.layout, x, y).join("_"); - const region = regionMapAt(this.plugin.settings.maps, ow, ph); - if (!region) continue; - const key = `${x}_${y}`; - const cur = this.plugin.mapStore.get(region.name, key); - const id = `${region.name}|${key}`; + // Each brushed cell goes into the region map that holds it (across + // seams), written now so the layer, the minimap and any open view of + // that region update during the stroke. Painted cells are locked. + const { targets, missed } = paintTargets( + layout, + brushCells(layout, cell.x, cell.y, this.paintBrushSize), + (hex) => regionMapAt(this.plugin.settings.maps, ow, hex)?.name, + ); + if (!targets.length && missed && !this.subStrokeMissHinted) { + this.subStrokeMissHinted = true; + new Notice(PAINT_NO_REGION_HINT); + } + for (const { map, key } of targets) { + const cur = this.plugin.mapStore.get(map, key); + const id = `${map}|${key}`; const prev = this.currentSubStroke?.get(id); if (prev) prev.newTerrain = terrain; - else this.currentSubStroke?.set(id, { map: region.name, key, oldTerrain: cur?.terrain ?? null, oldLocked: !!cur?.locked, newTerrain: terrain }); - this.plugin.mapStore.set(region.name, key, { terrain, locked: terrain ? true : null }); + else this.currentSubStroke?.set(id, { map, key, oldTerrain: cur?.terrain ?? null, oldLocked: !!cur?.locked, newTerrain: terrain }); + if (cur?.terrain === terrain && !!cur?.locked === !!terrain) continue; + this.plugin.mapStore.set(map, key, { terrain, locked: terrain ? true : null }); } - return `${cell.region}|${cell.x}_${cell.y}`; + return `${cell.x}_${cell.y}`; + } + + /** Remember a region map's terrain as drawn (see shownTerrain). */ + private snapshotShownTerrain(map: MapData): void { + this.shownTerrain.clear(); + if (map.submapKind !== "region") return; + const { x: ox, y: oy } = map.gridOffset, { cols, rows } = map.gridSize; + for (let y = oy; y < oy + rows; y++) { + for (let x = ox; x < ox + cols; x++) this.shownTerrain.set(`${x}_${y}`, this.plugin.mapStore.get(map.name, `${x}_${y}`)?.terrain ?? null); + } + } + + /** Repaint the hexes whose terrain changed since they were drawn (see shownTerrain). */ + private syncShownTerrain(): void { + const map = this.activeMapName; + const changes = terrainDiff(this.shownTerrain, (k) => this.plugin.mapStore.get(map, k)?.terrain); + for (const [key, terrain] of changes) { + this.shownTerrain.set(key, terrain); + const [x, y] = key.split("_"); + const el = this.viewportEl?.querySelector(`.duckmage-hex[data-x="${x}"][data-y="${y}"]`); + if (el) this.applyTerrainToHexEl(el, terrain); + } + } + + /** Show an overworld's Regions view (the terrain brush paints there). */ + private showOverworldRegions(): void { + const map = this.getActiveMap(); + if (OverworldLayer.viewOf(this.plugin, map) !== "biomes") return; + map.overworldView = "regions"; + void this.plugin.saveSettings(); + this.renderGrid(); } /** Enter a region from the overworld, centred on (and flashing) the hex that was clicked. */ diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 84dd0262..9f0612ec 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -136,7 +136,7 @@ Tokens show their name underneath. The layers panel's **Labels** group turns coo Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. -**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name; click to set one: an empty hex gets its region). The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. +**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). To change a placed region, right-click it → **Edit region…** (God mode; in Build and Play it's greyed out and says "Switch to God to change a placed region."). The terrain tool always paints the regions: picking a terrain switches to the Regions view, the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards two things on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**; in Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region) needs **Build** or God; in Play the biome picker is greyed out and says "Switch to Build to place a biome.", and **New map from this hex… → Region** says "Switch to Build to make a region." Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. diff --git a/src/hex-map/overworldLayer.ts b/src/hex-map/overworldLayer.ts index eb943fbe..0d1b922c 100644 --- a/src/hex-map/overworldLayer.ts +++ b/src/hex-map/overworldLayer.ts @@ -41,6 +41,7 @@ import { } from "../overworld/overworldRender"; import { ecotoneHexes, overworldBiomes, parseBiomeRiver } from "../overworld/regionWorld"; import { overworldOf, overworldTerrain } from "../overworld/regionsVault"; +import { FrameThrottle } from "../overworld/overworldInput"; interface Geometry { map: string; @@ -85,7 +86,8 @@ export class OverworldLayer { readonly cache = new RegionBitmapCache(); private geom: Geometry | null = null; private canvas: HTMLCanvasElement | null = null; - private redrawTimer: number | null = null; + /** Redraws coalesce to one per animation frame, and keep coming during a brush stroke. */ + private redraws = new FrameThrottle((cb) => window.requestAnimationFrame(cb)); /** Timings of the last draw (ms) and how many region bitmaps it built. */ lastStats = { ms: 0, builds: 0, regions: 0, cells: 0 }; @@ -108,8 +110,6 @@ export class OverworldLayer { this.canvas?.remove(); this.canvas = null; this.geom = null; - if (this.redrawTimer !== null) window.clearTimeout(this.redrawTimer); - this.redrawTimer = null; } /** Draw the layer for `map` into `grid` (call after the hexes are laid out). */ @@ -152,14 +152,16 @@ export class OverworldLayer { this.cache.invalidate(regionName); } - /** The overworld itself changed (biomes view): redraw. */ + /** + * Something on the layer changed (a region painted, the overworld's + * biomes): redraw on the next animation frame. Only invalidated region + * bitmaps are rebuilt; the rest are copied from the cache. + */ scheduleRedraw(): void { if (!this.canvas) return; - if (this.redrawTimer !== null) window.clearTimeout(this.redrawTimer); - this.redrawTimer = window.setTimeout(() => { - this.redrawTimer = null; + this.redraws.request(() => { if (this.canvas?.isConnected) this.draw(); - }, 120); + }); } /** diff --git a/src/hex-map/overworldMinimap.ts b/src/hex-map/overworldMinimap.ts index 1498e5d9..8ba44385 100644 --- a/src/hex-map/overworldMinimap.ts +++ b/src/hex-map/overworldMinimap.ts @@ -54,7 +54,7 @@ export class OverworldMinimap { sw.createSpan({ cls: "duckmage-ow-view-label", text: "View:" }); for (const [id, label, tip] of [ ["regions", "Regions", "Every region's hexes, stitched together (blank bricks where there's none yet). Click to enter a region; the terrain tool paints its hexes."], - ["biomes", "Biomes", "One biome per hex. Click a hex to set its biome: a hex with no region gets one; changing a placed one needs God mode."], + ["biomes", "Biomes", "One biome per hex. Click a hex to enter its region, or to set the biome of one with none yet. Right-click → Edit region… changes a placed one (God mode)."], ] as const) { const on = view === id; const b = sw.createEl("button", { text: label, cls: on ? "is-active" : "", attr: { title: on ? `${tip} (showing now)` : tip, "aria-pressed": on ? "true" : "false" } }); diff --git a/src/overworld/overworldInput.ts b/src/overworld/overworldInput.ts new file mode 100644 index 00000000..5e08b27d --- /dev/null +++ b/src/overworld/overworldInput.ts @@ -0,0 +1,150 @@ +/** + * Clicks and the terrain brush on an overworld, the pure part. + * + * Clicks (owner report 2026-10-10: a left click on a region brick in Build + * opened a biome picker full of disabled buttons): + * - left click on a hex or brick WITH a region enters it, in every mode + * and both views; + * - left click on an empty one places a biome (Build, God) or says how to + * unlock it (Play); + * - changing a placed region is a right-click item, "Edit region…", that + * is enabled in God only and otherwise shown disabled with its hint. + * + * The terrain brush (owner: "the terrain brush doesn't work on the + * overworld map, I would like it to paint + update the submaps as you draw + * with it") paints the region maps' own hexes under the brush, across + * seams, written as you draw. Painting counts as Build. + * + * Pure: no Obsidian imports. + */ + +import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; +import { canAdd, canReshape, PLACE_LOCKED_HINT } from "../workMode"; +import { parentOf, type RegionLayout } from "./layout"; + +/** The hint on "Edit region…" outside God. */ +export const EDIT_REGION_LOCKED_HINT = "Switch to God to change a placed region."; + +/** The hint when the terrain brush is used on an overworld in Play. */ +export const PAINT_LOCKED_HINT = "Switch to Build to paint the regions."; + +/** The hint when the brush lands where there's no region. */ +export const PAINT_NO_REGION_HINT = "No region here yet; place a biome first."; + +type Mode = { workMode?: string } | undefined; + +export type OverworldLeftClick = + | { kind: "enter" } + | { kind: "place" } + | { kind: "hint"; hint: string }; + +/** What a plain left click on an overworld hex or brick does. */ +export function overworldLeftClick(map: Mode, hasRegion: boolean): OverworldLeftClick { + if (hasRegion) return { kind: "enter" }; + return canAdd(map) ? { kind: "place" } : { kind: "hint", hint: PLACE_LOCKED_HINT }; +} + +export interface OverworldMenuItem { + id: "enter-region" | "edit-region" | "set-biome"; + title: string; + enabled: boolean; + /** Why it's disabled (shown with it). */ + hint?: string; +} + +/** + * The overworld items of a hex's right-click menu. "Enter region" is listed + * by the menu's own region item, so `enter-region` is only here to keep the + * rule in one place (the caller can skip it when it already has one). + */ +export function overworldMenu(map: Mode, hasRegion: boolean): OverworldMenuItem[] { + if (hasRegion) { + const god = canReshape(map); + return [ + { id: "enter-region", title: "Enter region", enabled: true }, + { id: "edit-region", title: "Edit region…", enabled: god, ...(god ? {} : { hint: EDIT_REGION_LOCKED_HINT }) }, + ]; + } + const add = canAdd(map); + return [{ id: "set-biome", title: "Set biome…", enabled: add, ...(add ? {} : { hint: PLACE_LOCKED_HINT }) }]; +} + +/** The child cells a brush of `size` (1, 3 or 7) covers around (x, y), same shape as the map's brush. */ +export function brushCells(layout: RegionLayout, x: number, y: number, size: number): [number, number][] { + const out: [number, number][] = [[x, y]]; + if (size > 1) { + const nb = hexNeighbors(x, y, layout.orientation, layout.childStagger); + out.push(...(size === 3 ? [nb[2], nb[3]] : nb)); + } + return out; +} + +export interface PaintTarget { + /** The region map the cell belongs to. */ + map: string; + /** Shared-grid key "x_y". */ + key: string; +} + +/** + * Which region map each brushed cell is written to (cells reach across + * seams into the next region). Cells over a slot with no region are + * skipped and counted in `missed`. + */ +export function paintTargets( + layout: RegionLayout, + cells: [number, number][], + regionAt: (parentHex: string) => string | undefined, +): { targets: PaintTarget[]; missed: number } { + const targets: PaintTarget[] = []; + let missed = 0; + for (const [x, y] of cells) { + const map = regionAt(parentOf(layout, x, y).join("_")); + if (map) targets.push({ map, key: `${x}_${y}` }); + else missed++; + } + return { targets, missed }; +} + +/** + * Hexes whose shown terrain differs from the map's data now, for a view + * showing a map that's being painted elsewhere (the overworld brush): only + * those are repainted. `null`: no terrain. + */ +export function terrainDiff(shown: ReadonlyMap, now: (key: string) => string | undefined): [string, string | null][] { + const out: [string, string | null][] = []; + for (const [key, was] of shown) { + const t = now(key) ?? null; + if (t !== was) out.push([key, t]); + } + return out; +} + +/** + * Run a job at most once per animation frame: repeated requests within a + * frame coalesce into one run (the last job wins). Unlike a trailing + * debounce it keeps firing during a continuous stroke. + */ +export class FrameThrottle { + private pending: (() => void) | null = null; + private scheduled = false; + + constructor(private raf: (cb: () => void) => unknown) {} + + request(job: () => void): void { + this.pending = job; + if (this.scheduled) return; + this.scheduled = true; + this.raf(() => { + this.scheduled = false; + const run = this.pending; + this.pending = null; + run?.(); + }); + } + + /** Is a run waiting for the next frame? */ + get waiting(): boolean { + return this.scheduled; + } +} diff --git a/tests/overworldInput.test.ts b/tests/overworldInput.test.ts new file mode 100644 index 00000000..da287ce3 --- /dev/null +++ b/tests/overworldInput.test.ts @@ -0,0 +1,149 @@ +/** + * Overworld clicks and the terrain brush (owner reports 2026-10-10): click + * routing by mode × has-region × button, and the brush that paints the + * region maps under it live, across seams, redrawing only touched regions. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + brushCells, + EDIT_REGION_LOCKED_HINT, + FrameThrottle, + overworldLeftClick, + overworldMenu, + paintTargets, + terrainDiff, +} from "../src/overworld/overworldInput"; +import { overworldRefreshFor } from "../src/overworld/overworldChanges"; +import { RegionBitmapCache } from "../src/overworld/overworldRender"; +import { parentOf, regionCells, type RegionLayout } from "../src/overworld/layout"; +import { PLACE_LOCKED_HINT } from "../src/workMode"; + +const MODES = ["play", "build", "god", undefined] as const; +const m = (mode: string | undefined) => ({ workMode: mode }); + +describe("overworld click routing (mode × has region × button)", () => { + it("left click on a hex or brick with a region enters it, in every mode", () => { + for (const mode of MODES) expect(overworldLeftClick(m(mode), true)).toEqual({ kind: "enter" }); + }); + + it("left click on an empty one places a biome in Build and God, and only hints in Play", () => { + expect(overworldLeftClick(m("build"), false)).toEqual({ kind: "place" }); + expect(overworldLeftClick(m(undefined), false)).toEqual({ kind: "place" }); + expect(overworldLeftClick(m("god"), false)).toEqual({ kind: "place" }); + expect(overworldLeftClick(m("play"), false)).toEqual({ kind: "hint", hint: PLACE_LOCKED_HINT }); + }); + + it("right click on a region: Enter region always, Edit region… enabled in God only, else disabled with its hint", () => { + expect(overworldMenu(m("god"), true)).toEqual([ + { id: "enter-region", title: "Enter region", enabled: true }, + { id: "edit-region", title: "Edit region…", enabled: true }, + ]); + for (const mode of ["build", "play", undefined]) { + const items = overworldMenu(m(mode), true); + expect(items[0]).toEqual({ id: "enter-region", title: "Enter region", enabled: true }); + expect(items[1]).toEqual({ id: "edit-region", title: "Edit region…", enabled: false, hint: EDIT_REGION_LOCKED_HINT }); + } + expect(EDIT_REGION_LOCKED_HINT).toBe("Switch to God to change a placed region."); + }); + + it("right click on an empty hex: Set biome…, disabled in Play", () => { + expect(overworldMenu(m("build"), false)).toEqual([{ id: "set-biome", title: "Set biome…", enabled: true }]); + expect(overworldMenu(m("play"), false)).toEqual([{ id: "set-biome", title: "Set biome…", enabled: false, hint: PLACE_LOCKED_HINT }]); + }); +}); + +const LAYOUT: RegionLayout = { footprint: "rect", size: 4, orientation: "flat", parentStagger: "odd", childStagger: "odd" }; + +describe("the terrain brush on an overworld", () => { + it("brush sizes 1, 3 and 7 cover that many cells", () => { + expect(brushCells(LAYOUT, 5, 5, 1)).toEqual([[5, 5]]); + expect(brushCells(LAYOUT, 5, 5, 3)).toHaveLength(3); + expect(brushCells(LAYOUT, 5, 5, 7)).toHaveLength(7); + }); + + it("a wide brush on a seam writes into both regions", () => { + // A cell on the right edge of region 0_0's block: its neighbours east are in the next region. + const cells = regionCells(LAYOUT, 0, 0); + const edge = cells.find(([x, y]) => brushCells(LAYOUT, x, y, 7).some(([a, b]) => parentOf(LAYOUT, a, b).join("_") !== "0_0"))!; + const regions = new Map([["0_0", "r00"], ["1_0", "r10"], ["1_1", "r11"], ["0_1", "r01"], ["1_-1", "r1m"], ["0_-1", "r0m"]]); + const { targets, missed } = paintTargets(LAYOUT, brushCells(LAYOUT, edge[0], edge[1], 7), (h) => regions.get(h)); + expect(targets.length + missed).toBe(7); + expect(new Set(targets.map((t) => t.map)).size).toBeGreaterThan(1); + for (const t of targets) { + const [x, y] = t.key.split("_").map(Number); + expect(regions.get(parentOf(LAYOUT, x, y).join("_"))).toBe(t.map); + } + }); + + it("cells over a slot with no region are skipped and counted (the caller hints once)", () => { + const { targets, missed } = paintTargets(LAYOUT, brushCells(LAYOUT, 1, 1, 7), () => undefined); + expect(targets).toEqual([]); + expect(missed).toBe(7); + }); + + it("a view showing a region repaints only the hexes that changed", () => { + const shown = new Map([["0_0", "grass"], ["1_0", "grass"], ["2_0", null]]); + const now = new Map([["0_0", "grass"], ["1_0", "volcano"], ["2_0", "volcano"]]); + expect(terrainDiff(shown, (k) => now.get(k))).toEqual([["1_0", "volcano"], ["2_0", "volcano"]]); + expect(terrainDiff(new Map([["0_0", "grass"]]), () => undefined)).toEqual([["0_0", null]]); + }); + + it("frame throttle: many requests in a frame run once, and it keeps firing during a stroke", () => { + const frames: (() => void)[] = []; + const t = new FrameThrottle((cb) => frames.push(cb)); + let runs = 0; + for (let i = 0; i < 5; i++) t.request(() => runs++); + expect(frames).toHaveLength(1); + frames.shift()!(); + expect(runs).toBe(1); + t.request(() => runs++); + frames.shift()!(); + expect(runs).toBe(2); + }); +}); + +describe("live write + invalidation during a stroke", () => { + /** + * The view's path, with its real pieces: each painted cell is written to + * its region map at once; the store's change event says which bitmap to + * drop (overworldRefreshFor); redraws come once per frame and rebuild + * only the dropped bitmaps. + */ + it("writes each cell as it's painted and rebuilds only the touched regions, frame by frame", () => { + const regions = new Map([["0_0", "r00"], ["1_0", "r10"], ["2_0", "r20"]]); + const store = new Map>([...regions.values()].map((n) => [n, new Map()])); + const cache = new RegionBitmapCache(); + const built: string[] = []; + const draw = () => { for (const n of regions.values()) cache.get(n, "zoom1", () => { built.push(n); return 1; }); }; + draw(); // first draw: every region + built.length = 0; + const frames: (() => void)[] = []; + const redraws = new FrameThrottle((cb) => frames.push(cb)); + const onChange = (map: string) => { + const r = overworldRefreshFor({ name: map, submapKind: "region", parent: { map: "ow", hex: [...regions].find(([, n]) => n === map)![0] } }, "ow", undefined); + if (r.invalidate) cache.invalidate(r.invalidate); + if (r.redrawLayer) redraws.request(draw); + }; + const paint = (x: number, y: number) => { + for (const t of paintTargets(LAYOUT, brushCells(LAYOUT, x, y, 1), (h) => regions.get(h)).targets) { + store.get(t.map)!.set(t.key, "volcano"); + onChange(t.map); + } + }; + // Two cells of region 0_0 in one frame: written at once, one rebuild. + const [a, b] = regionCells(LAYOUT, 0, 0); + paint(...a); + paint(...b); + expect(store.get("r00")!.size).toBe(2); + expect(frames).toHaveLength(1); + frames.shift()!(); + expect(built).toEqual(["r00"]); + // The stroke moves on into region 1_0 (mid-stroke, next frame). + paint(...regionCells(LAYOUT, 1, 0)[0]); + frames.shift()!(); + expect(built).toEqual(["r00", "r10"]); + expect(store.get("r20")!.size).toBe(0); + expect(cache.builds).toBe(5); + }); +}); From 1b6a3f3081734ca92e666fe885e24bc34abe692b Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:26:06 -0400 Subject: [PATCH 250/558] feat(biomes #50): biome note format + BiomeNoteFields / BiomeStoreApi interface Co-Authored-By: Claude Opus 5.5 --- src/overworld/biomeNote.ts | 423 +++++++++++++++++++++++++++++++++++++ 1 file changed, 423 insertions(+) create mode 100644 src/overworld/biomeNote.ts diff --git a/src/overworld/biomeNote.ts b/src/overworld/biomeNote.ts new file mode 100644 index 00000000..b186a557 --- /dev/null +++ b/src/overworld/biomeNote.ts @@ -0,0 +1,423 @@ +/** + * Biome notes (#50): one plain note per overworld biome, at + * `/biomes/.md`, built-in and user-made alike. + * + * --- + * hexmaker-biome: 1 + * id: tundra + * label: Tundra + * colour: "#d8e4ea" + * blend: normal + * land-share: 90% + * min-islands: 3 + * generator: "[[My tundra]]" + * --- + * + * # Tundra + * + * > [!info] Biome + * > … (short help) + * + * ## Mix + * + * | Type | Weight | + * | --- | ---: | + * | snow | 40 | + * + * ## Transitions + * + * | Next to | Put between | + * | --- | --- | + * | Temperate forest | Taiga | + * + * - *Mix* is by terrain TYPE (the palette's Type column), never by terrain + * name: a region of this biome gets each type in proportion to its weight + * (any scale), spread over the palette's terrains of that type. + * - *Transitions*: biomes this one shouldn't touch on an overworld, and the + * biome put between them. Biomes are named by label, id or note name. + * - `blend`: narrow, normal or wide (how far the biome mixes into its + * neighbours' regions). `land-share` (0–100%, or 0–1) and `min-islands` + * are for watery biomes. All optional. + * - `generator`: a generator note this biome's regions come from (once + * generator regions land); without one it mixes with the blend field. + * + * Reading is forgiving: columns by header name in any order, `colour` or + * `color`, weights like `40` or `40%`. Rows that can't be read are reported + * (`problems`) and left in the note as written. Writing touches only the + * plugin's own frontmatter keys and the two tables; every other line (the + * user's prose, extra frontmatter keys) stays; a table is only rewritten + * when what it says changed. + * + * Pure: no Obsidian imports. + */ + +/** Frontmatter key written into every biome note (the format version). */ +export const BIOME_NOTE_MARKER = "hexmaker-biome"; +export const BIOME_NOTE_FORMAT = 1; + +export type BiomeBlend = "narrow" | "normal" | "wide"; +export const BIOME_BLENDS: readonly BiomeBlend[] = ["narrow", "normal", "wide"]; + +export interface BiomeMixRow { + /** Terrain type id (TERRAIN_TYPES), e.g. "forest". */ + type: string; + /** Relative weight, > 0, any scale. */ + weight: number; +} + +export interface BiomeTransition { + /** The biome this one shouldn't touch (as written: label, id or note name). */ + next: string; + /** The biome put between them. */ + between: string; +} + +/** What a biome note says. Shared with the generator page (other session). */ +export interface BiomeNoteFields { + /** Stable id: references (region maps, transitions) use it, so a renamed note keeps them. */ + id: string; + label: string; + /** Swatch colour (CSS colour, hex lower-cased). */ + color?: string; + /** Terrain-type mix (by type only). */ + mix: BiomeMixRow[]; + transitions: BiomeTransition[]; + /** Inter-region blend width; unset = the overworld's setting. */ + blend?: BiomeBlend; + /** Share of land, 0..1 (watery biomes). */ + landShare?: number; + /** Fewest islands a region of this biome gets. */ + minIslands?: number; + /** Link target of a generator note (no brackets), e.g. "world/generators/My tundra". */ + generator?: string; +} + +export interface BiomeNoteProblem { + /** "settings" (frontmatter), "Mix" or "Transitions". */ + where: string; + text: string; +} + +export interface ParsedBiomeNote { + fields: BiomeNoteFields; + problems: BiomeNoteProblem[]; +} + +/** Lower-case id from a name: "Temperate forest" → "temperate-forest". */ +export function biomeSlug(name: string): string { + return name.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, ""); +} + +const UNSAFE_NAME_CHARS = /[\\/:*?"<>|#^[\]]/g; + +/** A label as a legal note basename. */ +export function biomeFileName(label: string): string { + return label.replace(UNSAFE_NAME_CHARS, "-").replace(/\s+/g, " ").trim().replace(/^\.+/, "") || "Biome"; +} + +export const BIOME_HELP = [ + "> [!info] Biome", + "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `generator` links a generator note. Delete a row to drop it.", +]; + +// ── reading ────────────────────────────────────────────────────────────── + +function splitRow(line: string): string[] { + let s = line.trim(); + if (s.startsWith("|")) s = s.slice(1); + if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1); + const cells: string[] = []; + let cur = ""; + for (let i = 0; i < s.length; i++) { + if (s[i] === "\\" && s[i + 1] === "|") { cur += "|"; i++; } + else if (s[i] === "|") { cells.push(cur.trim()); cur = ""; } + else cur += s[i]; + } + cells.push(cur.trim()); + return cells; +} + +const SEPARATOR_ROW = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/; + +interface Span { start: number; end: number; headers: string[] } + +const norm = (h: string) => h.trim().toLowerCase().replace(/\s+/g, " "); + +/** First table whose headers satisfy `want`. */ +function findTable(lines: string[], want: (headers: string[]) => boolean): Span | null { + for (let i = 0; i < lines.length - 1; i++) { + if (!lines[i].trim().startsWith("|") || !SEPARATOR_ROW.test(lines[i + 1])) continue; + const headers = splitRow(lines[i]).map(norm); + if (!want(headers)) continue; + let end = i + 2; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { start: i, end, headers }; + } + return null; +} + +const isMix = (h: string[]) => h.includes("type") && (h.includes("weight") || h.includes("share")); +const isTransitions = (h: string[]) => (h.includes("next to") || h.includes("biome")) && (h.includes("put between") || h.includes("between") || h.includes("transition")); + +/** The frontmatter span (line indices: the opening and closing `---`), or null. */ +function frontmatterSpan(lines: string[]): { open: number; close: number } | null { + if (lines[0]?.trim() !== "---") return null; + const close = lines.findIndex((l, i) => i > 0 && l.trim() === "---"); + return close > 0 ? { open: 0, close } : null; +} + +const unquote = (v: string) => { + const t = v.trim(); + if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) return t.slice(1, -1).replace(/\\"/g, '"'); + return t; +}; + +/** Plain `key: value` frontmatter (no nesting needed here). Keys lower-cased. */ +function readFrontmatter(lines: string[]): Map { + const out = new Map(); + const fm = frontmatterSpan(lines); + if (!fm) return out; + for (const l of lines.slice(fm.open + 1, fm.close)) { + const m = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(l); + if (m) out.set(m[1].toLowerCase(), unquote(m[2].replace(/\s+#.*$/, ""))); + } + return out; +} + +/** "40", "40%", "0.4" → a number, or NaN. */ +const num = (raw: string) => Number(raw.trim().replace(/%$/, "").trim()); + +/** "60%" → 0.6, "0.6" → 0.6, "60" → 0.6. NaN when unreadable. */ +export function parseShare(raw: string): number { + const t = raw.trim(); + if (!t) return NaN; + const pct = t.endsWith("%"); + const n = num(t); + if (!Number.isFinite(n)) return NaN; + const v = pct || n > 1 ? n / 100 : n; + return v >= 0 && v <= 1 ? v : NaN; +} + +const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i; +function readColour(raw: string): string { + const v = raw.trim().replace(/^`+|`+$/g, "").trim(); + if (HEX.test(v)) return (v.startsWith("#") ? v : `#${v}`).toLowerCase(); + return v; +} + +/** `[[Target|Alias]]` / `[[Target]]` / plain text → "Target". */ +export function linkTarget(raw: string): string { + const m = /\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]/.exec(raw); + return (m ? m[1] : raw).trim(); +} + +/** + * Read a biome note. `basename` (the note's name) gives the label and id + * when the frontmatter has none. Never throws; unreadable bits go to `problems`. + */ +export function parseBiomeNote(content: string, basename: string): ParsedBiomeNote { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const fm = readFrontmatter(lines); + const problems: BiomeNoteProblem[] = []; + const label = fm.get("label")?.trim() || basename.trim(); + const fields: BiomeNoteFields = { + id: biomeSlug(fm.get("id") ?? "") || biomeSlug(basename) || biomeSlug(label) || "biome", + label, + mix: [], + transitions: [], + }; + const colour = fm.get("colour") ?? fm.get("color"); + if (colour) fields.color = readColour(colour); + const blend = fm.get("blend")?.trim().toLowerCase(); + if (blend) { + if ((BIOME_BLENDS as readonly string[]).includes(blend)) fields.blend = blend as BiomeBlend; + else problems.push({ where: "settings", text: `blend should be narrow, normal or wide, not "${blend}"` }); + } + const land = fm.get("land-share"); + if (land) { + const v = parseShare(land); + if (Number.isFinite(v)) fields.landShare = v; + else problems.push({ where: "settings", text: `land-share should be a share like 60%, not "${land}"` }); + } + const isl = fm.get("min-islands"); + if (isl) { + const v = num(isl); + if (Number.isInteger(v) && v >= 0) fields.minIslands = v; + else problems.push({ where: "settings", text: `min-islands should be a whole number, not "${isl}"` }); + } + const gen = fm.get("generator"); + if (gen && linkTarget(gen)) fields.generator = linkTarget(gen); + + const mix = findTable(lines, isMix); + if (mix) { + const ti = mix.headers.indexOf("type"); + const wi = mix.headers.includes("weight") ? mix.headers.indexOf("weight") : mix.headers.indexOf("share"); + for (let i = mix.start + 2; i < mix.end; i++) { + const cells = splitRow(lines[i]); + if (cells.every((c) => c === "")) continue; + const type = (cells[ti] ?? "").trim().toLowerCase().replace(/\s+/g, "-"); + const w = num(cells[wi] ?? ""); + if (!type) { problems.push({ where: "Mix", text: `row ${i + 1}: no type` }); continue; } + if (!Number.isFinite(w) || w < 0) { problems.push({ where: "Mix", text: `row ${i + 1}: weight "${cells[wi] ?? ""}" isn't a number` }); continue; } + if (w === 0) continue; + const hit = fields.mix.find((r) => r.type === type); + if (hit) hit.weight += w; + else fields.mix.push({ type, weight: w }); + } + } + const tr = findTable(lines, isTransitions); + if (tr) { + const ni = tr.headers.includes("next to") ? tr.headers.indexOf("next to") : tr.headers.indexOf("biome"); + const bi = ["put between", "between", "transition"].map((h) => tr.headers.indexOf(h)).find((x) => x >= 0)!; + for (let i = tr.start + 2; i < tr.end; i++) { + const cells = splitRow(lines[i]); + if (cells.every((c) => c === "")) continue; + const next = linkTarget(cells[ni] ?? ""), between = linkTarget(cells[bi] ?? ""); + if (!next || !between) { problems.push({ where: "Transitions", text: `row ${i + 1}: needs both a biome and the one put between` }); continue; } + fields.transitions.push({ next, between }); + } + } + return { fields, problems }; +} + +// ── writing ────────────────────────────────────────────────────────────── + +const esc = (s: string) => s.replace(/\|/g, "\\|"); +const fmt = (n: number) => String(Math.round(n * 1000) / 1000); +const quote = (s: string) => (/^[\w .,()'-]*$/.test(s) && !/^\s|\s$/.test(s) && !/^(yes|no|true|false|null|~|-?\d[\d.]*)$/i.test(s) ? s : `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`); + +/** "0.6" → "60%". */ +export const shareText = (v: number) => `${fmt(v * 100)}%`; + +function mixTable(rows: BiomeMixRow[]): string[] { + return ["| Type | Weight |", "| --- | ---: |", ...rows.map((r) => `| ${esc(r.type)} | ${fmt(r.weight)} |`)]; +} + +function transitionsTable(rows: BiomeTransition[]): string[] { + return ["| Next to | Put between |", "| --- | --- |", ...rows.map((r) => `| ${esc(r.next)} | ${esc(r.between)} |`)]; +} + +/** Our frontmatter keys, in writing order, with their values (undefined = remove). */ +function ownKeys(f: BiomeNoteFields): [string, string | undefined][] { + return [ + [BIOME_NOTE_MARKER, String(BIOME_NOTE_FORMAT)], + ["id", f.id], + ["label", quote(f.label)], + ["colour", f.color ? `"${f.color}"` : undefined], + ["blend", f.blend], + ["land-share", f.landShare !== undefined ? shareText(f.landShare) : undefined], + ["min-islands", f.minIslands !== undefined ? String(f.minIslands) : undefined], + ["generator", f.generator ? `"[[${f.generator}]]"` : undefined], + ]; +} + +const OWN_ALIASES: Record = { color: "colour" }; + +/** A fresh biome note. */ +export function buildBiomeNote(f: BiomeNoteFields): string { + const fm = ownKeys(f).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}: ${v}`); + return [ + "---", ...fm, "---", "", + `# ${f.label}`, "", + ...BIOME_HELP, "", + "## Mix", "", + ...mixTable(f.mix), "", + "## Transitions", "", + ...transitionsTable(f.transitions), "", + ].join("\n"); +} + +/** + * The note with `f` written into it: our frontmatter keys set (others kept, + * in place), the Mix and Transitions tables replaced (or added under their + * own heading at the end). Everything else stays as it was; line endings + * are kept. The same string when nothing changed. + */ +export function updateBiomeNote(content: string, f: BiomeNoteFields): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + let lines = content.replace(/\r\n?/g, "\n").split("\n"); + // Frontmatter. + const keys = ownKeys(f); + let fm = frontmatterSpan(lines); + if (!fm) { + lines = ["---", "---", ...lines]; + fm = { open: 0, close: 1 }; + } + const body = lines.slice(fm.open + 1, fm.close); + const seen = new Set(); + const nextBody: string[] = []; + for (const l of body) { + const m = /^([A-Za-z][\w-]*)\s*:/.exec(l); + const key = m ? (OWN_ALIASES[m[1].toLowerCase()] ?? m[1].toLowerCase()) : undefined; + const own = key ? keys.find(([k]) => k === key) : undefined; + if (!own) { nextBody.push(l); continue; } + if (seen.has(key!)) continue; // a duplicate key: one is enough + seen.add(key!); + if (own[1] === undefined) continue; + const want = `${m![1]}: ${own[1]}`; + // Keep the user's spelling when it already reads as the same value. + const cur = readFrontmatter(["---", l, "---"]).get(m![1].toLowerCase()) ?? ""; + nextBody.push(sameValue(key!, cur, own[1]) ? l : want); + } + for (const [k, v] of keys) if (!seen.has(k) && v !== undefined) nextBody.push(`${k}: ${v}`); + lines.splice(fm.open + 1, fm.close - fm.open - 1, ...nextBody); + // Tables. + lines = putTable(lines, isMix, mixTable(f.mix), "## Mix"); + lines = putTable(lines, isTransitions, transitionsTable(f.transitions), "## Transitions"); + const out = lines.join(eol); + return out === content.replace(/\r\n?/g, "\n").split("\n").join(eol) ? content : out; +} + +function sameValue(key: string, cur: string, want: string): boolean { + const w = unquote(want); + if (key === "land-share") return parseShare(cur) === parseShare(w); + if (key === "colour") return readColour(cur) === readColour(w); + if (key === "generator") return linkTarget(cur) === linkTarget(w); + if (key === "id") return biomeSlug(cur) === biomeSlug(w); + return cur.trim() === w.trim(); +} + +function putTable(lines: string[], want: (h: string[]) => boolean, table: string[], heading: string): string[] { + const span = findTable(lines, want); + if (span) { + const cur = lines.slice(span.start, span.end); + // Rows the plugin reads the same are left alone (spacing, alignment, extra columns). + if (sameTable(cur, table)) return lines; + return [...lines.slice(0, span.start), ...table, ...lines.slice(span.end)]; + } + const out = [...lines]; + while (out.length && out[out.length - 1].trim() === "") out.pop(); + out.push("", heading, "", ...table, ""); + return out; +} + +function sameTable(cur: string[], next: string[]): boolean { + const rows = (ls: string[]) => ls.slice(2).filter((l) => splitRow(l).some((c) => c !== "")).map((l) => splitRow(l).join("|").toLowerCase()); + const a = rows(cur), b = rows(next); + return a.length === b.length && a.every((r, i) => r === b[i]) && splitRow(cur[0]).map(norm).join("|") === splitRow(next[0]).map(norm).join("|"); +} + +/** Mix as shares summing to 1 (types with weight 0 dropped). */ +export function mixShares(mix: BiomeMixRow[]): Map { + const total = mix.reduce((s, r) => s + Math.max(0, r.weight), 0); + const out = new Map(); + if (total <= 0) return out; + for (const r of mix) if (r.weight > 0) out.set(r.type, (out.get(r.type) ?? 0) + r.weight / total); + return out; +} + +/** + * The biome store as the rest of the plugin sees it (`plugin.biomeStore`). + * `name` is a biome's id, label or note name (case-insensitive). + */ +export interface BiomeStoreApi { + get(name: string): BiomeNoteFields | undefined; + /** Every biome, in note-name order. */ + list(): BiomeNoteFields[]; + /** Write a change to a biome's note (user prose kept). False when there's no such biome or its note doesn't read. */ + update(name: string, patch: Partial>): Promise; + /** Rewrite a shipped biome's note from its preset data (the old note is backed up). False for user biomes. */ + restoreDefault(name: string): Promise; + /** Whether a biome has shipped preset data (Restore default applies). */ + hasDefault(name: string): boolean; +} From 17b2c118bff14ba2372954abaf46366f7bbf0353 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:34:36 -0400 Subject: [PATCH 251/558] fix(overworld): archipelago regions get islands (landShare / minIslands) Archipelago regions on the overworld were all open ocean: the region sampler draws ~14% land per cell, scattered over many land types, and the first smoothing pass flips every isolated land cell to the majority water type. Ringed by open sea, 200/200 seeds came out 100% water (8x8 bricks); in generated worlds 44% of archipelago regions were all water. Biomes now carry landShare (0..1) and minIslands (the field names the biome-note store uses). After smoothing, placeIslands grows islands where the biome's influence is strongest until the region has minIslands separate islands wholly inside it and landShare of its cells are land. Each island is one of the biome's land types by its shares, ringed with the SHORE_TYPES (coast, shallows) the biome has. Land/water is by terrain type (WATER_TYPES), never by name. Archipelago: landShare 25%, 2 islands. Open sea sets neither and stays open. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/overworld/biomes.ts | 26 +++++- src/overworld/regionGen.ts | 166 ++++++++++++++++++++++++++++++++- tests/overworldIslands.test.ts | 162 ++++++++++++++++++++++++++++++++ 4 files changed, 354 insertions(+), 4 deletions(-) create mode 100644 tests/overworldIslands.test.ts diff --git a/package.json b/package.json index e00e4cda..2ca02c7e 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/overworldIslands.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/overworldIslands.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index eabe5703..1c345a8a 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -30,8 +30,27 @@ export interface BiomeInfo { zone: "sea" | "low" | "high" | "peak"; /** Rare biomes: at most one per ~20 overworld hexes. */ rare?: boolean; + /** + * Watery biomes: the share of land (0..1) a region of this biome gets as + * islands, counting land already there (regionGen placeIslands). + * Unset: no land is added beyond `minIslands`. + */ + landShare?: number; + /** Fewest islands (separate land patches inside the region) a region of this biome gets. */ + minIslands?: number; } +/** + * Terrain types that are water, for islands (landShare / minIslands): every + * other type is land, except settlements. Types only, never names. + */ +export const WATER_TYPES: readonly string[] = ["water", "deep-water", "shallows"]; +/** + * Rings round a placed island, inner first: a ring is painted only when the + * biome's generator has that type on the palette. + */ +export const SHORE_TYPES: readonly string[] = ["coast", "shallows"]; + export const BIOMES: BiomeInfo[] = [ { id: "tundra", label: "Tundra", slug: "biome-tundra", temp: 0.08, moist: 0.4, zone: "low" }, { id: "taiga", label: "Taiga", slug: "biome-taiga", temp: 0.28, moist: 0.55, zone: "low" }, @@ -48,7 +67,7 @@ export const BIOMES: BiomeInfo[] = [ { id: "alpine", label: "Alpine", slug: "biome-alpine", temp: 0.2, moist: 0.5, zone: "peak" }, { id: "volcanic", label: "Volcanic", slug: "preset-volcanic", temp: 0.7, moist: 0.3, zone: "peak", rare: true }, { id: "coastal-fjord", label: "Coastal fjord", slug: "biome-coastal-fjord", temp: 0.2, moist: 0.7, zone: "low" }, - { id: "archipelago", label: "Archipelago", slug: "preset-archipelago", temp: 0.6, moist: 0.7, zone: "sea" }, + { id: "archipelago", label: "Archipelago", slug: "preset-archipelago", temp: 0.6, moist: 0.7, zone: "sea", landShare: 0.25, minIslands: 2 }, { id: OPEN_SEA, label: "Open sea", temp: 0.5, moist: 1, zone: "sea" }, ]; @@ -240,6 +259,9 @@ export interface BiomeProfile { id: BiomeId; types: Map; names: Map>; + /** BiomeInfo.landShare / minIslands, carried for region generation. */ + landShare?: number; + minIslands?: number; } /** Open sea has no shipped generator: deep water with a rim of ocean. */ @@ -297,6 +319,8 @@ export function biomeProfiles(models: Map, pale const terrains = b.id === OPEN_SEA ? OPEN_SEA_TERRAINS : b.slug ? models.get(b.slug)?.terrains : undefined; if (!terrains) continue; const p = profileFromWeights(b.id, terrains, palette); + if (b.landShare !== undefined) p.landShare = b.landShare; + if (b.minIslands !== undefined) p.minIslands = b.minIslands; if (p.types.size) out.set(b.id, p); } return out; diff --git a/src/overworld/regionGen.ts b/src/overworld/regionGen.ts index 30b42d20..d36457a5 100644 --- a/src/overworld/regionGen.ts +++ b/src/overworld/regionGen.ts @@ -23,7 +23,7 @@ */ import { mulberry32 } from "../../packages/hex-wfc/src/rng"; -import type { BiomeId, BiomeProfile } from "./biomes"; +import { SHORE_TYPES, WATER_TYPES, type BiomeId, type BiomeProfile } from "./biomes"; import { namesWithinType, typeMix, type BlendField } from "./blendField"; import { childNeighbours, parentOf, regionCells, type RegionLayout } from "./layout"; @@ -138,6 +138,25 @@ export function generateRegion(input: RegionGenInput): Map { } for (const [k, v] of next) work.set(k, v); } + + // 3. Islands for watery biomes (landShare / minIslands), after smoothing: + // smoothing pulls every cell toward the majority type, so scattered + // land in a mostly water biome would otherwise vanish. + const ownBiome = field.biomes.get(`${input.parent[0]}_${input.parent[1]}`); + const profile = ownBiome ? profiles.get(ownBiome) : undefined; + if (ownBiome && profile && (profile.minIslands || profile.landShare)) { + placeIslands({ + layout, + cells, + work, + terrainAt, + typeOf, + profile, + influence: (x, y) => field.at(x, y).get(ownBiome) ?? 0, + rng: mulberry32(cellSeed(input.seed ^ 0x6a09e667, input.parent[0], input.parent[1])), + }); + } + const out = new Map(); for (const k of own) { const v = work.get(k); @@ -149,6 +168,151 @@ export function generateRegion(input: RegionGenInput): Map { /** Depth of the smoothed halo around a region. */ const HALO = 2; +interface IslandInput { + layout: RegionLayout; + /** The region's own (unpinned) cells: the only cells changed. */ + cells: [number, number][]; + /** Terrain being generated; own cells are rewritten in place. */ + work: Map; + /** Terrain of any cell (own, halo, pinned), reading `work` first. */ + terrainAt: (key: string) => string | undefined; + typeOf: (terrain: string) => string | undefined; + /** The region's own biome (its landShare / minIslands, and its land types and names). */ + profile: BiomeProfile; + /** The region biome's share of the field at a cell (islands go where it is strongest). */ + influence: (x: number, y: number) => number; + rng: () => number; +} + +/** + * Islands for watery biomes (BiomeInfo.landShare / minIslands). Smoothing + * pulls every cell toward the majority type, so scattered land in a mostly + * water biome would vanish; this runs after it. + * + * Land is any typed terrain whose type isn't in WATER_TYPES. Islands that + * already lie wholly inside the region count (a coast running in from a + * neighbour doesn't). New islands are grown from cells where the biome is + * strongest, a cell apart from other land, until the region has + * `minIslands` islands and `landShare` of its cells are land. Each island + * is one of the biome's land types (by its shares) and gets a ring of each + * SHORE_TYPES type the biome has. Islands stay small (each covers at most a + * quarter of the region split between `minIslands`, its beach included, + * though never less than one core hex), and a region too small for `minIslands` + * still gets as many as fit, at least one when it has any free cell. + */ +export function placeIslands(input: IslandInput): void { + const { layout, work, terrainAt, typeOf, profile, rng } = input; + const minIslands = Math.max(0, Math.floor(profile.minIslands ?? 0)); + const landShare = Math.min(1, Math.max(0, profile.landShare ?? 0)); + if (!minIslands && !landShare) return; + const water = new Set(WATER_TYPES); + const cores = new Map([...profile.types].filter(([t, s]) => s > 0 && !water.has(t) && !SHORE_TYPES.includes(t) && t !== "settlement")); + if (!cores.size) return; + const own = new Set(input.cells.map(([x, y]) => `${x}_${y}`)); + const ownList = [...own].sort(); + const n = own.size; + if (!n) return; + const nbrs = (k: string): string[] => { + const [x, y] = k.split("_").map(Number); + return childNeighbours(layout, x, y).map(([a, b]) => `${a}_${b}`); + }; + const isLand = (k: string) => { + const t = terrainAt(k); + const ty = t ? typeOf(t) : undefined; + return ty !== undefined && !water.has(ty); + }; + const nameOf = (type: string): string | undefined => { + const names = profile.names.get(type); + return names?.size ? pick(names, rng()) : undefined; + }; + + // Islands already wholly inside the region, and the land there. + let have = 0; + const seen = new Set(); + for (const k of ownList) { + if (seen.has(k) || !isLand(k)) continue; + let inside = true; + const stack = [k]; + seen.add(k); + while (stack.length) { + const c = stack.pop()!; + for (const m of nbrs(c)) { + if (!isLand(m)) continue; + if (!own.has(m)) { inside = false; continue; } + if (!seen.has(m)) { seen.add(m); stack.push(m); } + } + } + if (inside) have++; + } + const landCount = () => ownList.filter(isLand).length; + const landTarget = Math.round(landShare * n); + + const maxSize = Math.max(1, Math.floor(n / (4 * Math.max(1, minIslands)))); + // Shore rings that are land (a beach) count toward an island's size: the + // leading SHORE_TYPES the biome has, up to the first water one. + let landRings = 0; + for (const shore of SHORE_TYPES) { + if (!profile.names.get(shore)?.size) continue; + if (water.has(shore)) break; + landRings++; + } + const taken = new Set(); + const free = (k: string) => own.has(k) && !taken.has(k) && !isLand(k); + /** Land an island will cover once its land shore rings are on (own cells only). */ + const footprint = (island: Set): number => { + const all = new Set(island); + let ring = [...island]; + for (let i = 0; i < landRings; i++) { + ring = [...new Set(ring.flatMap(nbrs))].filter((k) => free(k) && !all.has(k)); + for (const k of ring) all.add(k); + } + return all.size; + }; + for (let guard = 0; guard < n && (have < minIslands || landCount() < landTarget); guard++) { + // Seed: a free cell with no land next to it, best where the biome is strongest and away from the edge. + let start: string | undefined, best = -1; + for (const k of ownList) { + if (!free(k)) continue; + const around = nbrs(k); + if (around.some(isLand)) continue; + const [x, y] = k.split("_").map(Number); + const score = (input.influence(x, y) + 0.05) * (around.every((m) => own.has(m)) ? 1 : 0.3) * (0.5 + rng()); + if (score > best) { best = score; start = k; } + } + if (!start) break; + const remaining = landTarget - landCount(); + const toAdd = Math.max(1, minIslands - have); + const want = remaining > 0 ? (remaining / toAdd) * (0.7 + 0.6 * rng()) : 2 + rng() * 2; + const size = Math.max(1, Math.min(maxSize, Math.round(want))); + const type = pick(cores, rng())!; + const island = new Set(); + const add = (k: string) => { + work.set(k, nameOf(type)!); + island.add(k); + taken.add(k); + }; + add(start); + while (footprint(island) < size) { + // Grow onto a free cell that touches no land but this island. + const options = [...new Set([...island].flatMap(nbrs))].filter((k) => free(k) && nbrs(k).every((m) => island.has(m) || !isLand(m))).sort(); + if (!options.length) break; + add(options[Math.floor(rng() * options.length)]); + } + // Shore rings, inner first, for the shore types the biome has. + let ring = [...island]; + for (const shore of SHORE_TYPES) { + if (!profile.names.get(shore)?.size) continue; + const next = [...new Set(ring.flatMap(nbrs))].filter(free).sort(); + for (const k of next) { + work.set(k, nameOf(shore)!); + taken.add(k); + } + ring = next; + } + have++; + } +} + /** Spiral order from a centre hex: the order regions are generated in (each pins the earlier ones). */ export function spiralOrder(hexes: [number, number][], centre: [number, number], distance: (a: [number, number], b: [number, number]) => number): [number, number][] { return [...hexes].sort((a, b) => distance(a, centre) - distance(b, centre) || a[1] - b[1] || a[0] - b[0]); diff --git a/tests/overworldIslands.test.ts b/tests/overworldIslands.test.ts new file mode 100644 index 00000000..247edb8d --- /dev/null +++ b/tests/overworldIslands.test.ts @@ -0,0 +1,162 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { hexDistance, hexNeighbors } from "../packages/hex-wfc/src/grid"; +import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { BlendField, REGION_WARP } from "../src/overworld/blendField"; +import { WATER_TYPES, biomeInfo } from "../src/overworld/biomes"; +import { regionCells, type RegionLayout } from "../src/overworld/layout"; +import { generateRegion } from "../src/overworld/regionGen"; +import { regionOrder } from "../src/overworld/regionWorld"; +import { worldBiomes } from "../src/overworld/worldBiomes"; +import type { TerrainColor } from "../src/types"; +import { profilesFor, typeLookup } from "./overworldFixtures"; + +/** + * Islands for watery biomes (#archipelago report: "the archipelago is just + * open ocean"). Smoothing used to wash every scattered land cell out of an + * archipelago region, so a region ringed by open sea was 100% water on + * every seed. `landShare` / `minIslands` on the biome now guarantee islands. + */ + +const brick = (size: number): RegionLayout => ({ footprint: "rect", size, orientation: "flat", parentStagger: "odd", childStagger: "odd" }); +const flower = (size: number): RegionLayout => ({ footprint: "hex", size, orientation: "flat", parentStagger: "odd", childStagger: "odd" }); + +const water = new Set(WATER_TYPES); + +function setup(palette: TerrainColor[]) { + const profiles = profilesFor(palette); + const typeOf = typeLookup(palette); + const isLand = (t: string) => { + const ty = typeOf(t); + return ty !== undefined && !water.has(ty); + }; + return { profiles, typeOf, isLand }; +} + +/** A 5×5 overworld: `centre` biome at 2,2, `around` everywhere else. */ +function ringed(centre: string, around: string): Map { + const m = new Map(); + for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) m.set(`${x}_${y}`, hexDistance([x, y], [2, 2], "flat", "odd") === 0 ? centre : around); + return m; +} + +/** Land patches (connected land cells) of a region's cells, by size. */ +function islands(l: RegionLayout, cells: Map, isLand: (t: string) => boolean): number[] { + const land = new Set([...cells].filter(([, t]) => isLand(t)).map(([k]) => k)); + const seen = new Set(); + const sizes: number[] = []; + for (const k of land) { + if (seen.has(k)) continue; + let n = 0; + const stack = [k]; + seen.add(k); + while (stack.length) { + const [x, y] = stack.pop()!.split("_").map(Number); + n++; + for (const [a, b] of hexNeighbors(x, y, l.orientation, l.childStagger)) { + const nk = `${a}_${b}`; + if (land.has(nk) && !seen.has(nk)) { seen.add(nk); stack.push(nk); } + } + } + sizes.push(n); + } + return sizes; +} + +const allOcean = (l: RegionLayout) => { + const pinned = new Map(); + for (const [x, y] of hexNeighbors(2, 2, l.orientation, l.parentStagger)) for (const [a, b] of regionCells(l, x, y)) pinned.set(`${a}_${b}`, "ocean"); + return pinned; +}; + +describe("overworld islands (landShare / minIslands)", () => { + const { profiles, typeOf, isLand } = setup(DEFAULT_TERRAIN_PALETTE); + + it("the archipelago biome asks for islands; open sea doesn't", () => { + expect(biomeInfo("archipelago")?.minIslands).toBeGreaterThanOrEqual(1); + expect(biomeInfo("archipelago")?.landShare).toBeGreaterThan(0); + expect(biomeInfo("open-sea")?.minIslands).toBeUndefined(); + expect(biomeInfo("open-sea")?.landShare).toBeUndefined(); + expect(profiles.get("archipelago")?.minIslands).toBe(biomeInfo("archipelago")?.minIslands); + }); + + for (const [label, pinnedOf] of [["ringed by open sea", () => undefined], ["with all-ocean neighbour regions already made", allOcean]] as const) { + it(`an 8×8 archipelago region ${label} always has 2+ small islands (200 seeds)`, () => { + const l = brick(8); + const biomes = ringed("archipelago", "open-sea"); + const pinned = pinnedOf(l); + for (let seed = 1; seed <= 200; seed++) { + const field = new BlendField(l, biomes, "normal", { warp: REGION_WARP, seed }); + const out = generateRegion({ layout: l, parent: [2, 2], field, profiles, typeOf, seed, pinned }); + const sizes = islands(l, out, isLand); + const land = sizes.reduce((a, b) => a + b, 0); + expect({ seed, islands: sizes.length >= 2 }).toEqual({ seed, islands: true }); + // Small islands, not a continent: under 40% land and no island over 16 hexes (beach included). + expect({ seed, small: land / out.size < 0.4 && Math.max(...sizes) <= 16 }).toEqual({ seed, small: true }); + // Mostly still sea. + expect([...out.values()].filter((t) => water.has(typeOf(t) ?? "")).length / out.size).toBeGreaterThan(0.6); + } + }); + } + + it("small regions still get land (rect 2–4, hex flowers 1–2)", () => { + for (const l of [brick(2), brick(3), brick(4), flower(1), flower(2)]) { + const biomes = ringed("archipelago", "open-sea"); + for (let seed = 1; seed <= 60; seed++) { + const field = new BlendField(l, biomes, "normal", { warp: REGION_WARP, seed }); + const out = generateRegion({ layout: l, parent: [2, 2], field, profiles, typeOf, seed, pinned: allOcean(l) }); + expect({ l: `${l.footprint} ${l.size}`, seed, land: [...out.values()].some(isLand) }).toEqual({ l: `${l.footprint} ${l.size}`, seed, land: true }); + } + } + }); + + it("open sea stays open", () => { + const l = brick(8); + for (let seed = 1; seed <= 50; seed++) { + const field = new BlendField(l, ringed("open-sea", "open-sea"), "normal", { warp: REGION_WARP, seed }); + const out = generateRegion({ layout: l, parent: [2, 2], field, profiles, typeOf, seed }); + expect([...out.values()].filter(isLand)).toEqual([]); + } + }); + + it("is deterministic and leaves pinned (locked) cells alone", () => { + const l = brick(8); + const field = new BlendField(l, ringed("archipelago", "open-sea"), "normal", { warp: REGION_WARP, seed: 4 }); + const own = regionCells(l, 2, 2).map(([x, y]) => `${x}_${y}`); + const locked = new Map([own[0], own[27], own[36]].map((k) => [k, "ocean"])); + const a = generateRegion({ layout: l, parent: [2, 2], field, profiles, typeOf, seed: 4, pinned: locked }); + const b = generateRegion({ layout: l, parent: [2, 2], field, profiles, typeOf, seed: 4, pinned: locked }); + expect([...a]).toEqual([...b]); + for (const k of locked.keys()) expect(a.has(k)).toBe(false); + }); + + it("archipelago regions in generated worlds are never all water", () => { + const l = brick(8); + let n = 0; + for (let seed = 1; seed <= 25; seed++) { + const cells: [number, number][] = []; + for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) cells.push([x, y]); + const w = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed, climate: "varied", water: 0.4 }); + const field = new BlendField(l, w.biomes, "normal", { warp: REGION_WARP, seed }); + const all = new Map(); + for (const p of regionOrder(cells, "flat", "odd")) { + const out = generateRegion({ layout: l, parent: p, field, profiles, typeOf, seed, pinned: all }); + for (const [k, v] of out) all.set(k, v); + if (w.biomes.get(`${p[0]}_${p[1]}`) !== "archipelago") continue; + n++; + expect({ seed, p, land: [...out.values()].some(isLand) }).toEqual({ seed, p, land: true }); + } + } + expect(n).toBeGreaterThan(20); + }); + + it("works on the Limited palette too", () => { + const lim = setup(LIMITED_TERRAIN_PALETTE); + const l = brick(8); + for (let seed = 1; seed <= 30; seed++) { + const field = new BlendField(l, ringed("archipelago", "open-sea"), "normal", { warp: REGION_WARP, seed }); + const out = generateRegion({ layout: l, parent: [2, 2], field, profiles: lim.profiles, typeOf: lim.typeOf, seed }); + expect(islands(l, out, lim.isLand).length).toBeGreaterThanOrEqual(2); + } + }); +}); From b2c1348c5d19882f8d7f8fdced0c1cea9f39c131 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:39:48 -0400 Subject: [PATCH 252/558] =?UTF-8?q?feat(overworld):=20one=20"Edit=20region?= =?UTF-8?q?=E2=80=A6"=20modal;=20no=20hex=20editor=20on=20the=20overworld?= =?UTF-8?q?=20(#49)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner: get rid of "Edit hex" on the region-level view; only "Edit region" with whatever we have at region/map level, in a modal. Overworld right-click (both views) is now region-level only (overworldMenu): Enter region and Edit region… on a region (every mode), Set biome… on an empty hex (disabled with its hint in Play), Center on this hex, and the hex's Locations when it has any. Edit hex and the per-hex items are gone, and Ctrl+click no longer falls through to the hex editor. In the Regions view the brick under the pointer counts. EditRegionModal (extends HexmakerModal, compact, scrolling body): - editable display name (setMapDisplayName) and the overworld hex it's on; Enter region (focused) and Open map note; - biome: God gets a scrolling picker in the hex editor's terrain-strip style (current one scrolled into view) with Reroll and Settings… (RegionGenModal); Build/Play show it read-only with "Switch to God to change it." (editRegionPlan); - facts: size/shape, palette, terrain counts (terrainCounts, now shared with the map note Summary), neighbouring regions from the nav flower (click to go), locations inside / on the hex with a link to the list; - notes: the region map note's `## Notes` section (mapNoteNotes.ts), editable in every mode, saved as you type via MapStore.editNoteText (in the write queue, so no map write lands between read and write). Tests: overworld menu per mode (no Edit hex, no per-hex items), the modal plan per mode, terrain counts text, Notes round-trip (placement, hand-written sections, escaping, CRLF, survives updateMapNote). Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- package.json | 4 +- src/hex-map/EditRegionModal.ts | 281 ++++++++++++++++++++++++++++++++ src/hex-map/HexMapView.ts | 73 ++++++--- src/hex-map/help.md | 2 +- src/hex-map/overworldMinimap.ts | 2 +- src/maps/MapStore.ts | 28 ++++ src/maps/mapNote.ts | 34 +++- src/maps/mapNoteNotes.ts | 86 ++++++++++ src/overworld/overworldInput.ts | 72 ++++++-- styles.css | 69 ++++++++ tests/editRegion.test.ts | 121 ++++++++++++++ tests/overworldInput.test.ts | 32 ++-- 13 files changed, 741 insertions(+), 65 deletions(-) create mode 100644 src/hex-map/EditRegionModal.ts create mode 100644 src/maps/mapNoteNotes.ts create mode 100644 tests/editRegion.test.ts diff --git a/README.md b/README.md index 7e6e8e30..a165b257 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: -- **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Each hex is written to its region as you draw, so the overworld and any open view of those regions update during the stroke. Picking a terrain on an overworld switches to this view; where there's no region yet the brush does nothing ("No region here yet; place a biome first"), and in Play it's locked ("Switch to Build to paint the regions."). In both views, clicking a hex or brick with a region goes into it in every mode; clicking an empty one sets its biome (Build and God). Changing a placed region is in the right-click menu: **Edit region…** (God; greyed out with "Switch to God to change a placed region." otherwise), next to **Enter region**. Painted hexes are locked, so remaking a region keeps them. +- **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Each hex is written to its region as you draw, so the overworld and any open view of those regions update during the stroke. Picking a terrain on an overworld switches to this view; where there's no region yet the brush does nothing ("No region here yet; place a biome first"), and in Play it's locked ("Switch to Build to paint the regions."). In both views, clicking a hex or brick with a region goes into it in every mode; clicking an empty one sets its biome (Build and God). Right-click a region for **Enter region** and **Edit region…**: one window with the region's name (editable), the overworld hex it's on, **Enter region** and **Open map note**, its biome, a few facts (size and shape, palette, terrain counts, neighbouring regions you can click to go to, locations) and its notes. The notes are kept in the region's map note under a plain `## Notes` heading, so you can also edit them there; they're editable in every mode. In God mode the biome is a picker (choosing another remakes the region), with **Reroll** and **Settings…** (biome, blend, seed, live preview); in Build and Play it's shown with "Switch to God to change it." On an empty hex the menu offers **Set biome…** (Build and God). The overworld is the big-picture view, so it has no hex editor: right-click shows only these region-level items, **Center on this hex** and the hex's **Locations**. Painted hexes are locked, so remaking a region keeps them. - **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one; hover a hex for its region's name). Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. **Work modes: Play, Build, God.** Each map has a work mode, always shown on the toolbar next to the map button; click it to switch. It's saved in the map note as a plain `mode:` property (`play`, `build` or `god`), so each map opens in its own mode; new maps are in Build. For now two rules are enforced on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs God; in Build and Play those buttons are greyed out with "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region), or making regions at all (**Make the missing regions…**), needs Build or God; in Play the biome picker is greyed out with "Switch to Build to place a biome.", and **New map from this hex… → Region** is greyed out with "Switch to Build to make a region." There are no confirm boxes for these any more: the mode is the safety catch. Note text is never locked in any mode, and settings and palettes aren't either. diff --git a/package.json b/package.json index e00e4cda..aac1a8f2 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/hex-map/EditRegionModal.ts b/src/hex-map/EditRegionModal.ts new file mode 100644 index 00000000..24983a0e --- /dev/null +++ b/src/hex-map/EditRegionModal.ts @@ -0,0 +1,281 @@ +/** + * "Edit region…" (owner, #49): one modal for an overworld region, opened + * from a region's right-click menu on the overworld (both views), in every + * work mode. The overworld is the big-picture view, so it offers this + * instead of the per-hex editor. + * + * - header: the region's name (editable, as Map properties' Name) and the + * overworld hex it sits on; Enter region, Open map note; + * - biome: God shows a scrolling picker like the hex editor's terrain + * strip, with Reroll and Settings… (RegionGenModal: options, blend, seed, + * live preview). Build and Play show it read-only with one line saying + * how to change it (editRegionPlan); + * - facts: size and shape, palette, terrain counts (the map note Summary's + * counts), neighbouring regions (the nav flower's), locations; + * - notes: the region map note's `## Notes` section, editable in every + * mode (note text is never locked). + */ + +import { Notice, TFile } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import { regionMapAt, regionSettingsLabel } from "../maps/submaps"; +import { terrainCounts } from "../maps/mapNote"; +import { readNotesSection, writeNotesSection } from "../maps/mapNoteNotes"; +import { flowerPetals } from "../maps/mapNav"; +import { biomeForTerrain, biomeInfo, type BiomeId } from "../overworld/biomes"; +import { overworldOf, regenerateRegion, setBiomeAt } from "../overworld/regionsVault"; +import { editRegionPlan, terrainCountsText } from "../overworld/overworldInput"; +import { mayReshape, paintableBiomes, RegionGenModal, type BiomeHost } from "./BiomeModals"; +import { openNoteFocused } from "../openNote"; +import { createIconEl, getIconUrl } from "../utils"; + +export interface EditRegionHost extends BiomeHost { + /** The overworld hex's Locations list. */ + openLocations(px: number, py: number): void; +} + +const NOTES_SAVE_MS = 800; + +export class EditRegionModal extends HexmakerModal { + private stopKeepInViewport: (() => void) | null = null; + private notesTimer: number | null = null; + /** Notes typed and not written yet (null: nothing pending). */ + private pendingNotes: string | null = null; + private notesStatus: HTMLElement | null = null; + + constructor(private host: EditRegionHost, private overworld: string, private px: number, private py: number) { + super(host.app); + } + + private get regionName(): string | undefined { + return regionMapAt(this.host.plugin.settings.maps, this.overworld, `${this.px}_${this.py}`)?.name; + } + + onOpen(): void { + this.makeDraggable(); + this.modalEl.addClass("duckmage-edit-region-modal"); + this.stopKeepInViewport = this.keepInViewport(); + this.render(); + } + + private render(): void { + const { plugin } = this.host; + const name = this.regionName; + const region = name ? plugin.getMap(name) : undefined; + const { contentEl } = this; + contentEl.empty(); + this.titleEl.setText("Edit region"); + if (!name || !region) { + contentEl.createEl("p", { text: "There's no region on this hex any more." }); + return; + } + const overworld = plugin.getMap(this.overworld); + const plan = editRegionPlan(overworld); + + // ── header: name, where it is, enter / open note ───────────────────── + const head = contentEl.createDiv({ cls: "duckmage-edit-region-head" }); + const nameRow = head.createDiv({ cls: "duckmage-region-row" }); + const nameInput = nameRow.createEl("input", { + type: "text", + cls: "duckmage-edit-region-name", + value: plugin.mapLabel(name), + attr: { "aria-label": "Region name" }, + }); + const saveName = () => { + const typed = nameInput.value.trim(); + if (!typed || typed === plugin.mapLabel(name)) return; + void plugin.setMapDisplayName(name, typed).then(() => { + nameInput.value = plugin.mapLabel(name); + this.host.changed(); + }); + }; + nameInput.addEventListener("change", saveName); + nameInput.addEventListener("keydown", (e: KeyboardEvent) => { + if (e.key === "Enter") nameInput.blur(); + }); + head.createEl("p", { + cls: "duckmage-map-origin-desc", + text: `Hex ${this.px}, ${this.py} of ${plugin.mapLabel(this.overworld)}.`, + }); + const actions = head.createDiv({ cls: "duckmage-token-modal-buttons duckmage-edit-region-actions" }); + const enter = actions.createEl("button", { text: "Enter region", cls: "mod-cta" }); + enter.addEventListener("click", () => { + this.close(); + this.host.enter(name); + }); + // Focus the primary action, not the name box (a stray key would rename). + window.setTimeout(() => enter.focus(), 0); + actions.createEl("button", { text: "Open map note" }).addEventListener("click", () => { + const file = plugin.app.vault.getAbstractFileByPath(plugin.mapStore.notePath(name)); + if (!(file instanceof TFile)) { + new Notice("This region's map note isn't written yet."); + return; + } + this.close(); + void openNoteFocused(plugin.app, file); + }); + + // ── biome ───────────────────────────────────────────────────────────── + const terrain = plugin.mapStore.get(this.overworld, `${this.px}_${this.py}`)?.terrain; + const palette = plugin.getMapPalette(this.overworld); + const current = terrain ? biomeForTerrain(terrain, palette) : undefined; + const biomeSec = contentEl.createDiv({ cls: "duckmage-editor-section duckmage-edit-region-biome" }); + biomeSec.createEl("h4", { text: "Biome" }); + const biomes = paintableBiomes(plugin, this.overworld); + if (plan.biome === "pick") { + const grid = biomeSec.createDiv({ cls: "duckmage-terrain-picker duckmage-edit-region-biomes" }); + for (const b of biomes) { + const tile = grid.createDiv({ + cls: `duckmage-terrain-option${b.id === current ? " is-selected" : ""}`, + attr: { title: `${b.label}: paints ${b.terrain}`, "data-biome": b.id, role: "button", tabindex: "0" }, + }); + const preview = tile.createDiv({ cls: "duckmage-terrain-preview" }); + preview.setCssProps({ "--duckmage-bg": b.color }); + const entry = palette.find((t) => t.name === b.terrain); + if (entry?.icon) createIconEl(preview, getIconUrl(plugin, entry.icon), b.label, entry.iconColor, "duckmage-terrain-preview-icon"); + tile.createSpan({ text: b.label, cls: "duckmage-terrain-option-name" }); + const pick = () => { + if (b.id === current) return; + void this.setBiome(b.id); + }; + tile.addEventListener("click", pick); + tile.addEventListener("keydown", (e: KeyboardEvent) => { + if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } + }); + } + // Scroll the current biome into the strip's view (it may be past row two). + window.requestAnimationFrame(() => { + const sel = grid.querySelector(".is-selected"); + if (!sel) return; + const g = grid.getBoundingClientRect(), r = sel.getBoundingClientRect(); + if (r.bottom > g.bottom || r.top < g.top) grid.scrollTop += r.top - g.top - 4; + }); + const row = biomeSec.createDiv({ cls: "duckmage-token-modal-buttons duckmage-edit-region-gen" }); + if (plan.reroll) { + row.createEl("button", { text: "Reroll", attr: { title: "Remake the region with a new seed (hand-painted hexes stay)" } }) + .addEventListener("click", () => void this.reroll(name)); + } + if (plan.settings) { + row.createEl("button", { text: "Settings…", attr: { title: "Biome, blend, seed, with a live preview" } }).addEventListener("click", () => { + this.close(); + new RegionGenModal(this.host, this.overworld, this.px, this.py).open(); + }); + } + } else { + const shown = biomes.find((b) => b.id === current); + const row = biomeSec.createDiv({ cls: "duckmage-edit-region-biome-show" }); + const swatch = row.createSpan({ cls: "duckmage-biome-swatch" }); + if (shown) swatch.setCssProps({ "--duckmage-biome-color": shown.color }); + row.createSpan({ text: shown?.label ?? (current ? biomeInfo(current)?.label ?? current : terrain ?? "None") }); + if (plan.hint) biomeSec.createEl("p", { cls: "duckmage-locked-hint", text: plan.hint }); + } + + // ── facts ───────────────────────────────────────────────────────────── + const facts = contentEl.createDiv({ cls: "duckmage-editor-section duckmage-edit-region-facts" }); + facts.createEl("h4", { text: "Region" }); + const dl = facts.createEl("dl", { cls: "duckmage-edit-region-dl" }); + const fact = (label: string): HTMLElement => { + dl.createEl("dt", { text: label }); + return dl.createEl("dd"); + }; + const ow = overworldOf(plugin, this.overworld); + const { cols, rows } = region.gridSize; + fact("Size").setText(ow ? regionSettingsLabel(ow.settings) : `${cols} × ${rows}`); + fact("Palette").setText(region.paletteName ?? plugin.mapPaletteName(name) ?? "none"); + const { counts, blank } = terrainCounts(plugin.mapStore.all(name), region); + fact("Terrain").setText(terrainCountsText(counts, blank)); + + const near = fact("Next to"); + const layout = ow?.layout; + const neighbours = layout + ? flowerPetals(layout.orientation, layout.parentStagger, this.px, this.py) + .map((p) => ({ bearing: p.bearing, region: regionMapAt(plugin.settings.maps, this.overworld, `${p.hex[0]}_${p.hex[1]}`)?.name })) + .filter((n): n is { bearing: string; region: string } => !!n.region) + : []; + if (!neighbours.length) near.setText("None yet"); + for (const n of neighbours) { + const link = near.createEl("a", { + cls: "duckmage-edit-region-neighbour", + text: plugin.mapLabel(n.region), + attr: { href: "#", title: `${n.bearing[0].toUpperCase()}${n.bearing.slice(1)}: go to ${plugin.mapLabel(n.region)}` }, + }); + link.addEventListener("click", (e) => { + e.preventDefault(); + this.close(); + this.host.enter(n.region); + }); + } + + let inside = 0; + for (const h of plugin.mapStore.all(name).values()) inside += h.locations?.length ?? 0; + const onHex = plugin.mapStore.get(this.overworld, `${this.px}_${this.py}`)?.locations?.length ?? 0; + const locs = fact("Locations"); + locs.setText(`${inside} inside` + (onHex ? `, ${onHex} on this hex ` : " ")); + const list = locs.createEl("a", { text: "List…", attr: { href: "#", title: "This hex's locations: open, link, reorder" } }); + list.addEventListener("click", (e) => { + e.preventDefault(); + this.close(); + this.host.openLocations(this.px, this.py); + }); + + // ── notes (never locked) ────────────────────────────────────────────── + const notesSec = contentEl.createDiv({ cls: "duckmage-editor-section duckmage-edit-region-notes" }); + const notesHead = notesSec.createDiv({ cls: "duckmage-edit-region-notes-head" }); + notesHead.createEl("h4", { text: "Notes" }); + this.notesStatus = notesHead.createSpan({ cls: "duckmage-edit-region-notes-status" }); + const notes = notesSec.createEl("textarea", { + cls: "duckmage-edit-region-notes-input", + attr: { rows: "4", placeholder: "What's this region like? Kept in its map note.", "aria-label": "Region notes" }, + }); + notes.disabled = true; + void plugin.mapStore.readNoteText(name).then((text) => { + notes.value = text === null ? "" : readNotesSection(text); + notes.disabled = false; + }); + notes.addEventListener("input", () => { + this.pendingNotes = notes.value; + this.notesStatus?.setText(""); + if (this.notesTimer !== null) window.clearTimeout(this.notesTimer); + this.notesTimer = window.setTimeout(() => void this.saveNotes(), NOTES_SAVE_MS); + }); + notes.addEventListener("blur", () => void this.saveNotes()); + } + + /** Write typed notes into the region map note's Notes section. */ + private async saveNotes(): Promise { + if (this.notesTimer !== null) { window.clearTimeout(this.notesTimer); this.notesTimer = null; } + const text = this.pendingNotes; + const name = this.regionName; + if (text === null || !name) return; + this.pendingNotes = null; + const ok = await this.host.plugin.mapStore.editNoteText(name, (c) => writeNotesSection(c, text)); + if (!ok) new Notice("This region's map note isn't written yet; notes not saved."); + else this.notesStatus?.setText("Saved"); + } + + private async setBiome(biome: BiomeId): Promise { + if (!mayReshape(this.host, this.overworld, this.px, this.py)) return; + const notice = new Notice("Remaking the region…", 0); + const res = await setBiomeAt(this.host.plugin, this.overworld, this.px, this.py, biome); + notice.hide(); + if ("error" in res) new Notice(res.error); + this.host.changed(); + await this.saveNotes(); + this.render(); + } + + private async reroll(name: string): Promise { + if (!mayReshape(this.host, this.overworld, this.px, this.py)) return; + await regenerateRegion(this.host.plugin, name, { seed: Math.floor(Math.random() * 1e9) }); + this.host.changed(); + await this.saveNotes(); + this.render(); + } + + onClose(): void { + void this.saveNotes(); + this.stopKeepInViewport?.(); + this.stopKeepInViewport = null; + this.contentEl.empty(); + } +} diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index ba8b047f..01d3f76b 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -79,6 +79,7 @@ import { hexChildMaps, regionMapAt, submapMenuPlan } from "../maps/submaps"; import { OverworldLayer } from "./overworldLayer"; import { OverworldMinimap } from "./overworldMinimap"; import { BiomePickerModal, type BiomeHost } from "./BiomeModals"; +import { EditRegionModal } from "./EditRegionModal"; import { inOverworldGrid, overworldOf, regionHome, regionPalette, walkLock } from "../overworld/regionsVault"; import { brushCells, FrameThrottle, terrainDiff, overworldLeftClick, overworldMenu, PAINT_LOCKED_HINT, PAINT_NO_REGION_HINT, paintTargets } from "../overworld/overworldInput"; import { WalkRegionModal, type OverworldWalk } from "../worldgen/WalkRegionModal"; @@ -4569,6 +4570,13 @@ export class HexMapView extends ItemView { // only fires when drawingMode === null. if (this.drawingMode !== null) return; + // Overworlds are the big-picture view (#49): region-level items only, + // no hex editor. + if (OverworldLayer.viewOf(this.plugin, this.getActiveMap())) { + this.showOverworldMenu(evt, x, y); + return; + } + const hexPath = this.plugin.hexPath(x, y, this.activeMapName); // Terrain, icon and submap live in the map note, and a hex can have them // before its hex note exists (a generated map, a submap made from this @@ -4581,28 +4589,6 @@ export class HexMapView extends ItemView { const menu = new Menu(); - if (OverworldLayer.viewOf(this.plugin, this.getActiveMap())) { - // Placing a biome (empty hex) or changing a placed region (God): - // locked items are shown disabled with their hint, and open nothing. - const hasRegion = !!regionMapAt(this.plugin.settings.maps, this.activeMapName, `${x}_${y}`); - for (const it of overworldMenu(this.getActiveMap(), hasRegion)) { - if (it.id === "enter-region") continue; // the "Enter region: " item below - menu.addItem((item) => { - item - .setTitle(it.enabled ? it.title : `${it.title} (${it.hint})`) - .setIcon(it.id === "edit-region" ? "settings-2" : "trees") - .setDisabled(!it.enabled); - if (it.enabled) item.onClick(() => new BiomePickerModal(this.biomeHost(), this.activeMapName, x, y).open()); - }); - } - menu.addItem((item) => - item - .setTitle("Edit hex…") - .setIcon("pencil") - .onClick(() => this.openHexEditorModal(x, y)), - ); - } - menu.addItem((item) => item .setTitle("Center on this hex") @@ -4744,6 +4730,47 @@ export class HexMapView extends ItemView { menu.showAtMouseEvent(evt); } + /** + * An overworld hex's right-click menu (overworldMenu): Enter region and + * Edit region… on a region, Set biome… on an empty hex, Center, and the + * hex's Locations. In the Regions view the brick under the pointer counts. + */ + private showOverworldMenu(evt: MouseEvent, x: number, y: number): void { + const grid = this.viewportEl?.querySelector(".duckmage-hex-map-grid"); + const cell = OverworldLayer.viewOf(this.plugin, this.getActiveMap()) === "regions" && grid + ? this.overworldLayer.cellAt(grid, evt.clientX, evt.clientY) : null; + const [px, py] = cell ? cell.parentHex.split("_").map(Number) : [x, y]; + const key = `${px}_${py}`; + const region = regionMapAt(this.plugin.settings.maps, this.activeMapName, key)?.name; + const locations = this.plugin.mapStore.get(this.activeMapName, key)?.locations?.length ?? 0; + const menu = new Menu(); + const icons: Record = { "enter-region": "log-in", "edit-region": "settings-2", "set-biome": "trees", center: "crosshair", locations: "list" }; + for (const it of overworldMenu(this.getActiveMap(), !!region, locations)) { + menu.addItem((item) => { + item + .setTitle(it.id === "enter-region" && region ? `Enter region: ${this.plugin.mapLabel(region)}` : it.enabled ? it.title : `${it.title} (${it.hint})`) + .setIcon(icons[it.id] ?? "dot") + .setDisabled(!it.enabled); + if (!it.enabled) return; + item.onClick(() => { + if (it.id === "enter-region" && region) { + if (cell) this.enterRegionAt(region, cell.x, cell.y); + else this.navigateToMap(region); + } else if (it.id === "edit-region") this.openEditRegion(px, py); + else if (it.id === "set-biome") new BiomePickerModal(this.biomeHost(), this.activeMapName, px, py).open(); + else if (it.id === "center") this.centerOnHex(px, py); + else if (it.id === "locations") this.openLocationsList(px, py); + }); + }); + } + menu.showAtMouseEvent(evt); + } + + /** "Edit region…" for the region on overworld hex (px, py). */ + openEditRegion(px: number, py: number): void { + new EditRegionModal({ ...this.biomeHost(), openLocations: (hx, hy) => this.openLocationsList(hx, hy) }, this.activeMapName, px, py).open(); + } + private async onHexClick(x: number, y: number, e?: MouseEvent): Promise { if (this.drawingMode === "path") { this.pathTool.click(x, y, e, this.isErasingMode); @@ -4810,6 +4837,8 @@ export class HexMapView extends ItemView { } } + // No hex editor on an overworld (#49): it's the big-picture view. + if (ow) return; this.openHexEditorModal(x, y); } diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 9f0612ec..c60f7e16 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -136,7 +136,7 @@ Tokens show their name underneath. The layers panel's **Labels** group turns coo Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. -**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). To change a placed region, right-click it → **Edit region…** (God mode; in Build and Play it's greyed out and says "Switch to God to change a placed region."). The terrain tool always paints the regions: picking a terrain switches to the Regions view, the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. +**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). Right-click a region → **Edit region…** for its name, the hex it's on, **Enter region**, **Open map note**, its biome, facts (size, palette, terrain counts, neighbouring regions, locations) and notes (kept in its map note under `## Notes`, editable in every mode). The biome can only be changed in God mode: there it's a picker with **Reroll** and **Settings…**; in Build and Play it's shown with "Switch to God to change it." The overworld has no hex editor: right-click shows only region-level items. The terrain tool always paints the regions: picking a terrain switches to the Regions view, the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards two things on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**; in Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region) needs **Build** or God; in Play the biome picker is greyed out and says "Switch to Build to place a biome.", and **New map from this hex… → Region** says "Switch to Build to make a region." Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. diff --git a/src/hex-map/overworldMinimap.ts b/src/hex-map/overworldMinimap.ts index 8ba44385..59b951f1 100644 --- a/src/hex-map/overworldMinimap.ts +++ b/src/hex-map/overworldMinimap.ts @@ -54,7 +54,7 @@ export class OverworldMinimap { sw.createSpan({ cls: "duckmage-ow-view-label", text: "View:" }); for (const [id, label, tip] of [ ["regions", "Regions", "Every region's hexes, stitched together (blank bricks where there's none yet). Click to enter a region; the terrain tool paints its hexes."], - ["biomes", "Biomes", "One biome per hex. Click a hex to enter its region, or to set the biome of one with none yet. Right-click → Edit region… changes a placed one (God mode)."], + ["biomes", "Biomes", "One biome per hex. Click a hex to enter its region, or to set the biome of one with none yet. Right-click a region → Edit region… for its name, biome and notes."], ] as const) { const on = view === id; const b = sw.createEl("button", { text: label, cls: on ? "is-active" : "", attr: { title: on ? `${tip} (showing now)` : tip, "aria-pressed": on ? "true" : "false" } }); diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index 581ecea8..a129195f 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -456,6 +456,34 @@ export class MapStore { return this.queue; } + /** A map note's text as it is now (null: no note yet). */ + async readNoteText(map: string): Promise { + const file = this.plugin.app.vault.getAbstractFileByPath(this.notePath(map)); + return file instanceof TFile ? this.plugin.app.vault.read(file) : null; + } + + /** + * Edit a map note's free text (outside its tables, e.g. the Notes + * section), in the write queue so no map write lands between the read and + * the write. Returns false when the map has no note yet. The tables are + * untouched, so when we already knew the note's text the edit counts as + * our own write (no reload). + */ + editNoteText(map: string, edit: (content: string) => string): Promise { + let done = false; + return this.enqueue(async () => { + const { vault } = this.plugin.app; + const file = vault.getAbstractFileByPath(this.notePath(map)); + if (!(file instanceof TFile)) return; + done = true; + const current = await vault.read(file); + const next = edit(current); + if (next === current) return; + if (this.lastContent.get(file.path) === current) this.lastContent.set(file.path, next); + await vault.modify(file, next); + }).then(() => done); + } + /** Write every dirty map's note now (and report unreadable rows still waiting). */ flush(): Promise { window.clearTimeout(this.writeTimer); diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index d23f1bd7..a2e818a5 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -1616,6 +1616,30 @@ const plural = (n: number, one: string, many = one + "s") => `${n} ${n === 1 ? o /** A coordinate for reading (true minus sign): −7. */ const coord = (n: number) => (n < 0 ? `−${-n}` : String(n)); +/** + * Hexes per terrain (the Summary's legend; also shown by "Edit region…"): + * every cell of the grid when it has a size (unlisted ones count as the + * base terrain, or as `blank`), else just the listed rows. + */ +export function terrainCounts( + hexes: ReadonlyMap>, + s: { baseTerrain?: string; gridSize?: { cols: number; rows: number }; gridOffset?: { x: number; y: number } }, +): { counts: Map; blank: number } { + const counts = new Map(); + let blank = 0; + const base = s.baseTerrain; + const count = (t: string | undefined) => { if (t) counts.set(t, (counts.get(t) ?? 0) + 1); else blank++; }; + const g = s.gridSize, o = s.gridOffset ?? { x: 0, y: 0 }; + if (g && g.cols > 0 && g.rows > 0) { + for (let y = o.y; y < o.y + g.rows; y++) { + for (let x = o.x; x < o.x + g.cols; x++) count(hexes.get(`${x}_${y}`)?.terrain || base); + } + } else { + for (const h of hexes.values()) if (h.terrain) count(h.terrain); + } + return { counts, blank }; +} + /** * The Summary section: derived from the note's data and the palette, * written on every write, never read. No headings inside (see summaryRange). @@ -1632,20 +1656,12 @@ export function summaryLines(data: MapNoteData, ctx: MapNoteContext = {}): strin bullets.push(`- **Palette:** ${note && linkSafe(note) && linkSafe(pal) ? (note.split("/").pop() === pal ? `[[${note}]]` : `[[${note}|${pal}]]`) : pal}`); } - // Terrain per hex: the grid's cells when it has a size, else the listed rows. - const counts = new Map(); - let blank = 0; const base = s.baseTerrain; - const count = (t: string | undefined) => { if (t) counts.set(t, (counts.get(t) ?? 0) + 1); else blank++; }; const g = s.gridSize, o = s.gridOffset ?? { x: 0, y: 0 }; if (g && g.cols > 0 && g.rows > 0) { bullets.push(`- **Hexes:** ${coord(o.x)}…${coord(o.x + g.cols - 1)} × ${coord(o.y)}…${coord(o.y + g.rows - 1)} (${g.cols}×${g.rows})`); - for (let y = o.y; y < o.y + g.rows; y++) { - for (let x = o.x; x < o.x + g.cols; x++) count(data.hexes.get(`${x}_${y}`)?.terrain || base); - } - } else { - for (const h of data.hexes.values()) if (h.terrain) count(h.terrain); } + const { counts, blank } = terrainCounts(data.hexes, s); bullets.push(base ? `- **Base terrain:** ${base} (hexes not listed in the table)${unknown(base) ? " ⚠ not in the palette" : ""}` : "- **Base terrain:** none (hexes not listed have no terrain)"); diff --git a/src/maps/mapNoteNotes.ts b/src/maps/mapNoteNotes.ts new file mode 100644 index 00000000..69c5cbf1 --- /dev/null +++ b/src/maps/mapNoteNotes.ts @@ -0,0 +1,86 @@ +/** + * A map note's `## Notes` section: a short, free-text description of the + * map (an overworld region's notes, edited from "Edit region…"). It's plain + * text under a plain heading, so it reads like a hand-written note and can + * be edited in the note itself just as well; the map note's writer leaves + * text outside its tables alone, so it survives every map write. + * + * Only the section's own lines are touched: from its heading to the next + * `#` or `##` heading. A line typed in the box that would itself be such a + * heading is escaped (`\## …`) so it can't end the section early, and is + * read back unescaped. + * + * Pure: no Obsidian imports. + */ + +export const NOTES_HEADING = "## Notes"; + +const NOTES_RE = /^##\s+notes\s*$/i; +/** A heading that ends the section (`#` or `##`, not `###` and deeper). */ +const SECTION_END_RE = /^#{1,2}\s/; +const ESCAPED_RE = /^\\(#{1,2}\s)/; + +function splitBody(content: string): { eol: string; front: string[]; lines: string[] } { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const all = content.split(/\r?\n/); + // Skip the frontmatter (a `## Notes` there is YAML, not a heading). + let start = 0; + if (all[0]?.trim() === "---") { + const close = all.findIndex((l, i) => i > 0 && l.trim() === "---"); + if (close > 0) start = close + 1; + } + return { eol, front: all.slice(0, start), lines: all.slice(start) }; +} + +/** [heading, end) of the Notes section in `lines`, or null. */ +function notesRange(lines: string[]): [number, number] | null { + const at = lines.findIndex((l) => NOTES_RE.test(l)); + if (at < 0) return null; + let end = at + 1; + while (end < lines.length && !SECTION_END_RE.test(lines[end])) end++; + return [at, end]; +} + +/** The Notes section's text (blank lines around it trimmed), or "" when there's none. */ +export function readNotesSection(content: string): string { + const { lines } = splitBody(content); + const r = notesRange(lines); + if (!r) return ""; + const body = lines.slice(r[0] + 1, r[1]).map((l) => l.replace(ESCAPED_RE, "$1")); + while (body.length && !body[0].trim()) body.shift(); + while (body.length && !body[body.length - 1].trim()) body.pop(); + return body.join("\n"); +} + +/** + * The note with its Notes section set to `text`. An existing section is + * replaced in place (its heading kept); otherwise one is added above the + * generated Summary (else above the Hexes table, else at the end). Blank + * text with no section changes nothing. + */ +export function writeNotesSection(content: string, text: string): string { + const { eol, front, lines } = splitBody(content); + const body = text.replace(/\r\n?/g, "\n").split("\n").map((l) => (SECTION_END_RE.test(l) ? `\\${l}` : l)); + while (body.length && !body[0].trim()) body.shift(); + while (body.length && !body[body.length - 1].trim()) body.pop(); + const r = notesRange(lines); + let out: string[]; + if (r) { + // One blank line after it: before the next heading, or the note's final newline. + out = [...lines.slice(0, r[0] + 1), ...(body.length ? ["", ...body] : []), "", ...lines.slice(r[1])]; + } else { + if (!body.length) return content; + const section = [NOTES_HEADING, "", ...body]; + let at = lines.findIndex((l) => /^##\s+summary\s*$/i.test(l)); + if (at < 0) at = lines.findIndex((l) => /^##\s+hexes\s*$/i.test(l)); + if (at < 0) { + const tail = [...lines]; + while (tail.length && !tail[tail.length - 1].trim()) tail.pop(); + out = [...tail, "", ...section, ""]; + } else { + const before = at > 0 && lines[at - 1].trim() ? [""] : []; + out = [...lines.slice(0, at), ...before, ...section, "", ...lines.slice(at)]; + } + } + return [...front, ...out].join(eol); +} diff --git a/src/overworld/overworldInput.ts b/src/overworld/overworldInput.ts index 5e08b27d..5f032356 100644 --- a/src/overworld/overworldInput.ts +++ b/src/overworld/overworldInput.ts @@ -7,8 +7,9 @@ * and both views; * - left click on an empty one places a biome (Build, God) or says how to * unlock it (Play); - * - changing a placed region is a right-click item, "Edit region…", that - * is enabled in God only and otherwise shown disabled with its hint. + * - a region's right-click item "Edit region…" opens one modal with its + * name, biome, facts and notes (#49), in every mode; only God may + * change the biome there. The overworld offers no hex editor. * * The terrain brush (owner: "the terrain brush doesn't work on the * overworld map, I would like it to paint + update the submaps as you draw @@ -22,8 +23,8 @@ import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; import { canAdd, canReshape, PLACE_LOCKED_HINT } from "../workMode"; import { parentOf, type RegionLayout } from "./layout"; -/** The hint on "Edit region…" outside God. */ -export const EDIT_REGION_LOCKED_HINT = "Switch to God to change a placed region."; +/** The line under a region's biome in "Edit region…" outside God (shown read-only there). */ +export const BIOME_LOCKED_HINT = "Switch to God to change it."; /** The hint when the terrain brush is used on an overworld in Play. */ export const PAINT_LOCKED_HINT = "Switch to Build to paint the regions."; @@ -45,7 +46,7 @@ export function overworldLeftClick(map: Mode, hasRegion: boolean): OverworldLeft } export interface OverworldMenuItem { - id: "enter-region" | "edit-region" | "set-biome"; + id: "enter-region" | "edit-region" | "set-biome" | "center" | "locations"; title: string; enabled: boolean; /** Why it's disabled (shown with it). */ @@ -53,20 +54,59 @@ export interface OverworldMenuItem { } /** - * The overworld items of a hex's right-click menu. "Enter region" is listed - * by the menu's own region item, so `enter-region` is only here to keep the - * rule in one place (the caller can skip it when it already has one). + * A hex's right-click menu on an overworld (both views). The overworld is + * the big-picture view (owner, #49): no hex editor and no per-hex items + * (notes, tables, swaps, terrain clears), only region-level ones. A hex + * with a region: Enter region, and Edit region… in every mode (the modal + * shows what the mode may change). An empty hex: Set biome… (Build and + * God; shown disabled with its hint in Play). Then Center on this hex, + * and the hex's Locations when it has any. */ -export function overworldMenu(map: Mode, hasRegion: boolean): OverworldMenuItem[] { +export function overworldMenu(map: Mode, hasRegion: boolean, locations = 0): OverworldMenuItem[] { + const out: OverworldMenuItem[] = []; if (hasRegion) { - const god = canReshape(map); - return [ - { id: "enter-region", title: "Enter region", enabled: true }, - { id: "edit-region", title: "Edit region…", enabled: god, ...(god ? {} : { hint: EDIT_REGION_LOCKED_HINT }) }, - ]; + out.push({ id: "enter-region", title: "Enter region", enabled: true }); + out.push({ id: "edit-region", title: "Edit region…", enabled: true }); + } else { + const add = canAdd(map); + out.push({ id: "set-biome", title: "Set biome…", enabled: add, ...(add ? {} : { hint: PLACE_LOCKED_HINT }) }); } - const add = canAdd(map); - return [{ id: "set-biome", title: "Set biome…", enabled: add, ...(add ? {} : { hint: PLACE_LOCKED_HINT }) }]; + out.push({ id: "center", title: "Center on this hex", enabled: true }); + if (locations > 0) out.push({ id: "locations", title: `Locations (${locations})…`, enabled: true }); + return out; +} + +/** + * What "Edit region…" offers in this mode. God: the biome as a picker, + * with Reroll and Settings… (generator options, live preview). Build and + * Play: the biome shown read-only with one line saying how to change it, + * never a wall of disabled buttons. Name and notes are editable in every + * mode (note text is never locked, WM2). + */ +export interface EditRegionPlan { + biome: "pick" | "show"; + reroll: boolean; + settings: boolean; + /** Shown under a read-only biome. */ + hint?: string; +} + +export function editRegionPlan(map: Mode): EditRegionPlan { + return canReshape(map) + ? { biome: "pick", reroll: true, settings: true } + : { biome: "show", reroll: false, settings: false, hint: BIOME_LOCKED_HINT }; +} + +/** + * The terrain counts as one short line, most first: "forest 30, hills 12, + * lake 4 and 2 more". Hexes with no terrain are listed last as "blank". + */ +export function terrainCountsText(counts: ReadonlyMap, blank = 0, max = 4): string { + const rows = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); + if (blank) rows.push(["blank", blank]); + if (!rows.length) return "none yet"; + const shown = rows.slice(0, max).map(([t, n]) => `${t} ${n}`).join(", "); + return rows.length > max ? `${shown} and ${rows.length - max} more` : shown; } /** The child cells a brush of `size` (1, 3 or 7) covers around (x, y), same shape as the map's brush. */ diff --git a/styles.css b/styles.css index d081ec26..d888ca52 100644 --- a/styles.css +++ b/styles.css @@ -8462,3 +8462,72 @@ button.duckmage-terrain-legend-chip { align-self: center; padding-right: 4px; } + +/* "Edit region…" (#49): compact, never taller than the window, body scrolls. */ +.modal.duckmage-edit-region-modal.duckmage-editor-modal-drag { + width: min(480px, 94vw); + min-width: 0; + min-height: 0; + max-height: calc(100vh - 16px); + display: flex; + flex-direction: column; +} +.duckmage-edit-region-modal > .modal-content { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; +} +.duckmage-edit-region-modal h4 { + margin: 0.6em 0 0.3em; +} +.duckmage-edit-region-modal input.duckmage-edit-region-name { + flex: 1 1 auto; + min-width: 0; + font-size: 1.1em; + font-weight: 600; +} +.duckmage-edit-region-modal .duckmage-map-origin-desc { + margin: 0.3em 0; +} +.duckmage-edit-region-modal .duckmage-token-modal-buttons { + justify-content: flex-start; + flex-wrap: wrap; +} +.duckmage-edit-region-biome-show { + display: flex; + align-items: center; + gap: 6px; +} +.duckmage-edit-region-dl { + display: grid; + grid-template-columns: max-content 1fr; + gap: 2px 10px; + margin: 0; + font-size: 0.9em; +} +.duckmage-edit-region-dl dt { + color: var(--text-muted); +} +.duckmage-edit-region-dl dd { + margin: 0; + min-width: 0; + overflow-wrap: anywhere; +} +.duckmage-edit-region-neighbour + .duckmage-edit-region-neighbour::before { + content: ", "; + color: var(--text-normal); +} +.duckmage-edit-region-notes-head { + display: flex; + align-items: baseline; + gap: 8px; +} +.duckmage-edit-region-notes-status { + font-size: 0.8em; + color: var(--text-muted); +} +textarea.duckmage-edit-region-notes-input { + width: 100%; + min-height: 4.5em; + resize: vertical; +} diff --git a/tests/editRegion.test.ts b/tests/editRegion.test.ts new file mode 100644 index 00000000..10335925 --- /dev/null +++ b/tests/editRegion.test.ts @@ -0,0 +1,121 @@ +/** + * "Edit region…" (#49): what the modal offers per work mode, the facts it + * shows, and the region notes it keeps in the map note's `## Notes`. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { BIOME_LOCKED_HINT, editRegionPlan, terrainCountsText } from "../src/overworld/overworldInput"; +import { NOTES_HEADING, readNotesSection, writeNotesSection } from "../src/maps/mapNoteNotes"; +import { buildMapNote, parseMapNote, terrainCounts, updateMapNote, type MapNoteData } from "../src/maps/mapNote"; + +const m = (mode: string | undefined) => ({ workMode: mode }); + +describe("Edit region: sections per work mode", () => { + it("God shows the biome picker with Reroll and Settings…", () => { + expect(editRegionPlan(m("god"))).toEqual({ biome: "pick", reroll: true, settings: true }); + }); + + it("Build and Play show the biome read-only with one line, no buttons", () => { + for (const mode of ["build", "play", undefined]) { + expect(editRegionPlan(m(mode))).toEqual({ biome: "show", reroll: false, settings: false, hint: BIOME_LOCKED_HINT }); + } + expect(BIOME_LOCKED_HINT).toBe("Switch to God to change it."); + }); +}); + +describe("Edit region: facts", () => { + it("terrain counts cover the whole grid, base terrain filling unlisted hexes", () => { + const hexes = new Map([["0_0", { terrain: "forest" }], ["1_0", { terrain: "forest" }], ["0_1", { terrain: "hills" }]]); + const { counts, blank } = terrainCounts(hexes, { gridSize: { cols: 2, rows: 2 }, gridOffset: { x: 0, y: 0 }, baseTerrain: "plains" }); + expect([...counts]).toEqual([["forest", 2], ["hills", 1], ["plains", 1]]); + expect(blank).toBe(0); + expect(terrainCounts(hexes, { gridSize: { cols: 2, rows: 2 } }).blank).toBe(1); + }); + + it("the counts read as one short line, most first", () => { + expect(terrainCountsText(new Map([["hills", 3], ["forest", 30], ["lake", 3]]))).toBe("forest 30, hills 3, lake 3"); + expect(terrainCountsText(new Map([["a", 5], ["b", 4], ["c", 3], ["d", 2], ["e", 1]]), 2)).toBe("a 5, b 4, c 3, d 2 and 2 more"); + expect(terrainCountsText(new Map(), 0)).toBe("none yet"); + expect(terrainCountsText(new Map([["forest", 1]]), 4)).toBe("forest 1, blank 4"); + }); +}); + +const NOTE = [ + "---", + "hexmaker-map: 5", + "---", + "# Saltmere", + "", + "## Summary", + "", + "*Generated by Hexmaker from the tables below and the map's palette. Edits here are replaced.*", + "", + "## Hexes", + "", + "| Hex | Terrain |", + "| --- | --- |", + "| 0, 0 | forest |", + "", +].join("\n"); + +describe("Edit region: notes in the map note", () => { + it("round-trips through a `## Notes` section placed above the Summary", () => { + const text = "Salt flats and a drowned abbey.\n\nThe ferry runs at dawn."; + const out = writeNotesSection(NOTE, text); + expect(readNotesSection(out)).toBe(text); + expect(out.indexOf(NOTES_HEADING)).toBeLessThan(out.indexOf("## Summary")); + expect(out).toContain("# Saltmere\n\n## Notes\n\nSalt flats and a drowned abbey.\n\nThe ferry runs at dawn.\n\n## Summary"); + // Writing the same text again changes nothing. + expect(writeNotesSection(out, text)).toBe(out); + }); + + it("replaces only its own lines, keeping the rest of the note as it was", () => { + const once = writeNotesSection(NOTE, "first"); + const twice = writeNotesSection(once, "second\nline"); + expect(readNotesSection(twice)).toBe("second\nline"); + expect(twice.replace(/## Notes\n\nsecond\nline\n\n/, "")).toBe(NOTE); + expect(twice.split("## Notes").length).toBe(2); + }); + + it("keeps a section the user wrote by hand (its heading and place), and ### subheadings inside it", () => { + const hand = NOTE.replace("## Hexes", "## Notes\nold text\n### Factions\nthe reeve\n\n## Hexes"); + expect(readNotesSection(hand)).toBe("old text\n### Factions\nthe reeve"); + const out = writeNotesSection(hand, "new text\n### Factions\nthe reeve"); + expect(out.indexOf("## Notes")).toBeGreaterThan(out.indexOf("## Summary")); + expect(readNotesSection(out)).toBe("new text\n### Factions\nthe reeve"); + }); + + it("escapes a typed # or ## line so it can't end the section, and reads it back as typed", () => { + const out = writeNotesSection(NOTE, "intro\n## not a heading\n# nor this"); + expect(out).toContain("\\## not a heading"); + expect(readNotesSection(out)).toBe("intro\n## not a heading\n# nor this"); + }); + + it("blank notes add nothing; clearing keeps the heading empty", () => { + expect(writeNotesSection(NOTE, " \n")).toBe(NOTE); + const cleared = writeNotesSection(writeNotesSection(NOTE, "x"), ""); + expect(readNotesSection(cleared)).toBe(""); + expect(cleared).toContain("## Notes\n\n## Summary"); + }); + + it("keeps CRLF notes CRLF and ignores frontmatter", () => { + const crlf = NOTE.replace(/\n/g, "\r\n"); + const out = writeNotesSection(crlf, "a\nb"); + expect(out.includes("\n") && !/[^\r]\n/.test(out)).toBe(true); + expect(readNotesSection(out)).toBe("a\nb"); + expect(readNotesSection("---\nnotes: x\n---\n# T\n")).toBe(""); + }); + + it("survives the map note writer and isn't read as data", () => { + const data: MapNoteData = { + settings: { gridSize: { cols: 2, rows: 1 }, gridOffset: { x: 0, y: 0 } } as MapNoteData["settings"], + hexes: new Map([["0_0", { terrain: "forest" }]]), + paths: [], + }; + const note = writeNotesSection(buildMapNote("saltmere", data), "Salt flats."); + const next: MapNoteData = { ...data, hexes: new Map([["0_0", { terrain: "hills" }], ["1_0", { terrain: "lake" }]]) }; + const rewritten = updateMapNote(note, "saltmere", next); + expect(readNotesSection(rewritten)).toBe("Salt flats."); + expect([...parseMapNote(rewritten)!.hexes]).toEqual([...next.hexes]); + }); +}); diff --git a/tests/overworldInput.test.ts b/tests/overworldInput.test.ts index da287ce3..e6da6168 100644 --- a/tests/overworldInput.test.ts +++ b/tests/overworldInput.test.ts @@ -7,7 +7,6 @@ import { describe, it } from "node:test"; import expect from "expect"; import { brushCells, - EDIT_REGION_LOCKED_HINT, FrameThrottle, overworldLeftClick, overworldMenu, @@ -34,22 +33,29 @@ describe("overworld click routing (mode × has region × button)", () => { expect(overworldLeftClick(m("play"), false)).toEqual({ kind: "hint", hint: PLACE_LOCKED_HINT }); }); - it("right click on a region: Enter region always, Edit region… enabled in God only, else disabled with its hint", () => { - expect(overworldMenu(m("god"), true)).toEqual([ - { id: "enter-region", title: "Enter region", enabled: true }, - { id: "edit-region", title: "Edit region…", enabled: true }, - ]); - for (const mode of ["build", "play", undefined]) { + it("right click on a region: Enter region and Edit region… in every mode, no Edit hex (#49)", () => { + for (const mode of MODES) { const items = overworldMenu(m(mode), true); - expect(items[0]).toEqual({ id: "enter-region", title: "Enter region", enabled: true }); - expect(items[1]).toEqual({ id: "edit-region", title: "Edit region…", enabled: false, hint: EDIT_REGION_LOCKED_HINT }); + expect(items.map((i) => i.id)).toEqual(["enter-region", "edit-region", "center"]); + expect(items.every((i) => i.enabled)).toBe(true); + expect(items.find((i) => i.id === "edit-region")!.title).toBe("Edit region…"); + expect(items.some((i) => /edit hex/i.test(i.title))).toBe(false); } - expect(EDIT_REGION_LOCKED_HINT).toBe("Switch to God to change a placed region."); }); - it("right click on an empty hex: Set biome…, disabled in Play", () => { - expect(overworldMenu(m("build"), false)).toEqual([{ id: "set-biome", title: "Set biome…", enabled: true }]); - expect(overworldMenu(m("play"), false)).toEqual([{ id: "set-biome", title: "Set biome…", enabled: false, hint: PLACE_LOCKED_HINT }]); + it("right click on an empty hex: Set biome…, disabled in Play; never a hex editor", () => { + expect(overworldMenu(m("build"), false)).toEqual([ + { id: "set-biome", title: "Set biome…", enabled: true }, + { id: "center", title: "Center on this hex", enabled: true }, + ]); + expect(overworldMenu(m("play"), false)[0]).toEqual({ id: "set-biome", title: "Set biome…", enabled: false, hint: PLACE_LOCKED_HINT }); + for (const mode of MODES) expect(overworldMenu(m(mode), false).some((i) => /edit hex/i.test(i.title))).toBe(false); + }); + + it("only region-level items: the hex's Locations when it has any, no per-hex items", () => { + expect(overworldMenu(m("build"), true, 3).map((i) => i.title)).toEqual(["Enter region", "Edit region…", "Center on this hex", "Locations (3)…"]); + const titles = overworldMenu(m("god"), true, 1).map((i) => i.title).join(" | "); + for (const hexItem of ["Open note", "Link table", "Swap hex", "Clear terrain", "New map from this hex"]) expect(titles).not.toContain(hexItem); }); }); From a5b75414f65d2d61648e52e1aa24bea43c7da68c Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:39:59 -0400 Subject: [PATCH 253/558] fix(overworld): ragged beaches round islands; archipelago land share 30% A full beach ring made every island the same fried-egg shape. A land shore ring now covers ~60% of the shore (the shallows ring fills the gaps), and an island's planned size counts its beach at that rate. Co-Authored-By: Claude Opus 5.5 --- src/overworld/biomes.ts | 2 +- src/overworld/regionGen.ts | 24 ++++++++++++++++-------- tests/overworldIslands.test.ts | 4 ++-- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index 1c345a8a..22d0b9e7 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -67,7 +67,7 @@ export const BIOMES: BiomeInfo[] = [ { id: "alpine", label: "Alpine", slug: "biome-alpine", temp: 0.2, moist: 0.5, zone: "peak" }, { id: "volcanic", label: "Volcanic", slug: "preset-volcanic", temp: 0.7, moist: 0.3, zone: "peak", rare: true }, { id: "coastal-fjord", label: "Coastal fjord", slug: "biome-coastal-fjord", temp: 0.2, moist: 0.7, zone: "low" }, - { id: "archipelago", label: "Archipelago", slug: "preset-archipelago", temp: 0.6, moist: 0.7, zone: "sea", landShare: 0.25, minIslands: 2 }, + { id: "archipelago", label: "Archipelago", slug: "preset-archipelago", temp: 0.6, moist: 0.7, zone: "sea", landShare: 0.3, minIslands: 2 }, { id: OPEN_SEA, label: "Open sea", temp: 0.5, moist: 1, zone: "sea" }, ]; diff --git a/src/overworld/regionGen.ts b/src/overworld/regionGen.ts index d36457a5..bb9480ab 100644 --- a/src/overworld/regionGen.ts +++ b/src/overworld/regionGen.ts @@ -168,6 +168,9 @@ export function generateRegion(input: RegionGenInput): Map { /** Depth of the smoothed halo around a region. */ const HALO = 2; +/** Share of an island's shore a land shore ring (a beach) covers. */ +const BEACH_COVER = 0.6; + interface IslandInput { layout: RegionLayout; /** The region's own (unpinned) cells: the only cells changed. */ @@ -261,12 +264,13 @@ export function placeIslands(input: IslandInput): void { /** Land an island will cover once its land shore rings are on (own cells only). */ const footprint = (island: Set): number => { const all = new Set(island); - let ring = [...island]; + let ring = [...island], size = island.size; for (let i = 0; i < landRings; i++) { ring = [...new Set(ring.flatMap(nbrs))].filter((k) => free(k) && !all.has(k)); for (const k of ring) all.add(k); + size += ring.length * BEACH_COVER; } - return all.size; + return size; }; for (let guard = 0; guard < n && (have < minIslands || landCount() < landTarget); guard++) { // Seed: a free cell with no land next to it, best where the biome is strongest and away from the edge. @@ -298,16 +302,20 @@ export function placeIslands(input: IslandInput): void { if (!options.length) break; add(options[Math.floor(rng() * options.length)]); } - // Shore rings, inner first, for the shore types the biome has. - let ring = [...island]; + // Shore rings, inner first, for the shore types the biome has. A land + // ring (a beach) is ragged: it covers only part of the shore, and the + // next ring fills the gaps, so islands aren't all ringed alike. + const shoreSoFar = new Set(island); for (const shore of SHORE_TYPES) { if (!profile.names.get(shore)?.size) continue; - const next = [...new Set(ring.flatMap(nbrs))].filter(free).sort(); - for (const k of next) { + const next = [...new Set([...shoreSoFar].flatMap(nbrs))].filter(free).sort(); + const ragged = !water.has(shore); + next.forEach((k, i) => { + if (ragged && i > 0 && rng() >= BEACH_COVER) return; work.set(k, nameOf(shore)!); taken.add(k); - } - ring = next; + shoreSoFar.add(k); + }); } have++; } diff --git a/tests/overworldIslands.test.ts b/tests/overworldIslands.test.ts index 247edb8d..7d97dafb 100644 --- a/tests/overworldIslands.test.ts +++ b/tests/overworldIslands.test.ts @@ -91,8 +91,8 @@ describe("overworld islands (landShare / minIslands)", () => { const sizes = islands(l, out, isLand); const land = sizes.reduce((a, b) => a + b, 0); expect({ seed, islands: sizes.length >= 2 }).toEqual({ seed, islands: true }); - // Small islands, not a continent: under 40% land and no island over 16 hexes (beach included). - expect({ seed, small: land / out.size < 0.4 && Math.max(...sizes) <= 16 }).toEqual({ seed, small: true }); + // Small islands, not a continent: under 45% land and no island over 16 hexes (beach included). + expect({ seed, small: land / out.size < 0.45 && Math.max(...sizes) <= 16 }).toEqual({ seed, small: true }); // Mostly still sea. expect([...out.values()].filter((t) => water.has(typeOf(t) ?? "")).length / out.size).toBeGreaterThan(0.6); } From 99eb63c407e1feaade6fa0ed5cc7b3ce460133ad Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:43:04 -0400 Subject: [PATCH 254/558] feat(biomes #50): BiomeStore, notes-backed biome lookups, Biomes list and Add/Edit biome form Co-Authored-By: Claude Opus 5.5 --- src/HexmakerPlugin.ts | 8 + src/HexmakerSettingTab.ts | 25 +++ src/constants.ts | 1 + src/hex-map/BiomeLibraryModal.ts | 353 +++++++++++++++++++++++++++++ src/hex-map/BiomeModals.ts | 32 ++- src/hex-map/overworldLayer.ts | 4 +- src/hex-map/overworldMinimap.ts | 13 +- src/overworld/BiomeStore.ts | 367 +++++++++++++++++++++++++++++++ src/overworld/biomeForm.ts | 132 +++++++++++ src/overworld/biomePresets.ts | 41 ++++ src/overworld/biomes.ts | 138 +++++++++++- src/overworld/regionWorld.ts | 7 +- src/overworld/regionsVault.ts | 63 +++++- src/types.ts | 4 + styles.css | 35 +++ 15 files changed, 1194 insertions(+), 29 deletions(-) create mode 100644 src/hex-map/BiomeLibraryModal.ts create mode 100644 src/overworld/BiomeStore.ts create mode 100644 src/overworld/biomeForm.ts create mode 100644 src/overworld/biomePresets.ts diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index dc152880..c7b9e8f1 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -32,6 +32,7 @@ import { VIEW_TYPE_PALETTE_EDITOR, } from "./constants"; import { SetupWizardView } from "./SetupWizardView"; +import { BiomeStore } from "./overworld/BiomeStore"; import { PaletteStore } from "./palettes/PaletteStore"; import { PathsService } from "./paths/PathsService"; import { RoutePins } from "./paths/routePins"; @@ -98,6 +99,8 @@ export default class HexmakerPlugin extends Plugin { availableIcons: string[] = []; vaultIconsSet: Set = new Set(); paletteStore = new PaletteStore(this); + /** Overworld biome notes (#50). */ + biomeStore = new BiomeStore(this); /** Per-hex map data, backed by one map note per map (src/maps). */ mapStore = new MapStore(this); /** Terrain names that have (or were offered) tables; new ones get theirs (HG5). */ @@ -143,6 +146,7 @@ export default class HexmakerPlugin extends Plugin { this.loadAvailableIcons(); // Palettes first (maps reference them), then map notes — which may // migrate per-hex data out of hex notes on the first run. + void this.biomeStore.init(); void this.paletteStore.init().then(() => this.mapStore.init()).then(() => this.ensureTablesForNewTerrains()); // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. void this.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { @@ -184,18 +188,21 @@ export default class HexmakerPlugin extends Plugin { this.app.vault.on("create", (f) => { if (isIconFile(f.path)) this.loadAvailableIcons(); this.paletteStore.onModify(f); + this.biomeStore.onModify(f); }), ); this.registerEvent( this.app.vault.on("delete", (f) => { if (isIconFile(f.path)) this.loadAvailableIcons(); this.paletteStore.onDelete(f); + this.biomeStore.onDelete(f); }), ); this.registerEvent( this.app.vault.on("rename", (f, oldPath) => { if (isIconFile(f.path) || isIconFile(oldPath)) this.loadAvailableIcons(); this.paletteStore.onRename(f, oldPath); + this.biomeStore.onRename(f, oldPath); if (f instanceof TFile) void this.onRegionNoteRenamed(f, oldPath); }), ); @@ -209,6 +216,7 @@ export default class HexmakerPlugin extends Plugin { this.registerEvent( this.app.vault.on("modify", (f) => { this.paletteStore.onModify(f); + this.biomeStore.onModify(f); this.mapStore.onModify(f); }), ); diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index 8342c86f..6c177e44 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -13,6 +13,9 @@ const NAME_SIZE_TEXT: Record = { small: "Small", medium: "M const PALETTES_FOLDER_DESC = "Vault-relative folder for terrain palette notes (one note per palette — edit as text, copy between vaults to share). Defaults to a palettes folder inside the world folder."; +const BIOMES_FOLDER_DESC = + "Vault-relative folder for overworld biome notes (one note per biome: its mix of terrain types, colour and transitions). Defaults to a biomes folder inside the world folder."; + // --------------------------------------------------------------------------- // Obsidian 1.13 declarative settings API — local structural types. // @@ -121,6 +124,7 @@ const FOLDER_PATH_KEYS = new Set([ "workflowsFolder", "templatesFolder", "palettesFolder", + "biomesFolder", ]); /** Settings keys whose change should re-render open hex map views. */ @@ -656,6 +660,12 @@ export class HexmakerSettingTab extends PluginSettingTab { "World/palettes", PALETTES_FOLDER_DESC, ), + folderText( + "Biomes folder", + "biomesFolder", + "World/biomes", + BIOMES_FOLDER_DESC, + ), { type: "group", heading: "Map types", @@ -780,6 +790,7 @@ export class HexmakerSettingTab extends PluginSettingTab { } return this.plugin.saveSettings().then(() => { if (MAP_REFRESH_KEYS.has(key)) this.plugin.refreshHexMap(); + if (key === "biomesFolder") void this.plugin.biomeStore.reload(); if (key === "iconsFolder") this.plugin.loadAvailableIcons(); }); } @@ -1553,6 +1564,20 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); + new Setting(containerEl) + .setName("Biomes folder") + .setDesc(BIOMES_FOLDER_DESC) + .addText((text) => + text + .setPlaceholder("World/biomes") + .setValue(this.plugin.settings.biomesFolder ?? "") + .onChange(async (value) => { + this.plugin.settings.biomesFolder = normalizeFolder(value ?? ""); + await this.plugin.saveSettings(); + void this.plugin.biomeStore.reload(); + }), + ); + new Setting(containerEl).setName("Map types").setHeading(); for (const k of MAP_KINDS) { new Setting(containerEl) diff --git a/src/constants.ts b/src/constants.ts index c7d7154f..9bb9ee84 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -400,6 +400,7 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { setupComplete: false, setupDismissed: false, palettesFolder: "", + biomesFolder: "", palettesMigrated: false, // Space is opt-in (setup wizard / settings → Map types). Upgrades without // the setting get space too if they already have space palettes diff --git a/src/hex-map/BiomeLibraryModal.ts b/src/hex-map/BiomeLibraryModal.ts new file mode 100644 index 00000000..2fa9f824 --- /dev/null +++ b/src/hex-map/BiomeLibraryModal.ts @@ -0,0 +1,353 @@ +/** + * The Biomes list and the Add / Edit biome form (#50). + * + * - BiomeLibraryModal: every biome note (swatch, name, what makes its + * regions) with Edit… and Edit generator…, and Add biome…. Opened from + * the overworld's Biomes view and the biome picker. + * - BiomeFormModal: label, colour, generator (or "Blend (built-in mixing)"), + * terrain-type mix, blend width, land share / min islands, transitions, + * with a live preview of one region made by the blend field. Save writes + * the biome's note (BiomeStore). Built-in biomes get Restore default. + * + * Adding and editing biomes follows the overworld's work mode: Build and + * God (canAdd), not Play. + */ + +import { App, Notice, TFile } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { canAdd } from "../workMode"; +import { BIOME_BLENDS, type BiomeBlend, type BiomeNoteFields } from "../overworld/biomeNote"; +import { fieldsFromForm, formFromFields, formProblem, formTypes, generatorName, previewRegion, routeNote, type BiomeFormState } from "../overworld/biomeForm"; +import { overworldOf, regionPalette } from "../overworld/regionsVault"; +import { cellsBox, composeAffine, drawRegionCells, type RegionCell } from "../overworld/overworldRender"; +import { regionCells } from "../overworld/layout"; +import { listGenerators } from "../worldgen/generators"; +import { lockButton } from "./BiomeModals"; + +/** Why biomes can't be added or edited from this overworld now, or undefined. */ +export function biomeEditLock(plugin: HexmakerPlugin, overworldName: string): string | undefined { + return canAdd(plugin.getMap(overworldName)) ? undefined : "Switch to Build to add or edit biomes."; +} + +/** + * Whether the generator page can open a biome (`openTerrainGenerator({ biome })`). + * TODO(#50): set true once the generator page takes biomes (other session). + */ +const GENERATOR_PAGE_TAKES_BIOMES = false; + +/** + * "Edit generator…" for a biome, in one place: a biome with a generator + * link opens that generator; otherwise the generator page opens the biome + * when it can, else the biome's note opens. + */ +export async function openBiomeGenerator(plugin: HexmakerPlugin, biome: string): Promise { + const b = plugin.biomeStore.get(biome); + if (!b) { new Notice(`No biome called ${biome}.`); return; } + if (b.generator) { + const file = plugin.app.metadataCache.getFirstLinkpathDest(b.generator, ""); + if (file) { await plugin.openTerrainGenerator({ generatorPath: file.path }); return; } + new Notice(`Generator ${generatorName(b.generator)} wasn't found; opening the biome's note.`); + } else if (GENERATOR_PAGE_TAKES_BIOMES) { + await (plugin.openTerrainGenerator as (s: { biome: string }) => Promise)({ biome: b.id }); + return; + } + const path = plugin.biomeStore.pathOf(b.id); + const file = path ? plugin.app.vault.getAbstractFileByPath(path) : null; + if (file instanceof TFile) await plugin.app.workspace.getLeaf("tab").openFile(file); +} + +export class BiomeLibraryModal extends HexmakerModal { + private off: (() => void) | undefined; + + constructor(app: App, private plugin: HexmakerPlugin, private overworldName: string) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + this.modalEl.addClass("duckmage-biome-library-modal"); + this.titleEl.setText("Biomes"); + this.off = this.plugin.biomeStore.onChange(() => this.render()); + this.render(); + } + + private render(): void { + const { contentEl, plugin } = this; + contentEl.empty(); + const lock = biomeEditLock(plugin, this.overworldName); + contentEl.createEl("p", { cls: "setting-item-description", text: `Each biome is a note in ${plugin.biomeStore.folder()}. Edit it here or as text.` }); + if (lock) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); + const list = contentEl.createDiv({ cls: "duckmage-biome-list" }); + for (const b of plugin.biomeStore.list()) { + const row = list.createDiv({ cls: "duckmage-biome-row" }); + row.createSpan({ cls: "duckmage-biome-swatch" }).setCssProps({ "--duckmage-biome-color": b.color ?? "" }); + const text = row.createDiv({ cls: "duckmage-biome-row-text" }); + text.createSpan({ cls: "duckmage-biome-row-name", text: b.label }); + text.createSpan({ cls: "duckmage-biome-row-note", text: routeNote(b) ?? "Blend (built-in mixing)" }); + const edit = row.createEl("button", { text: "Edit…" }); + if (lock) lockButton(edit, lock); + edit.addEventListener("click", () => { + if (biomeEditLock(plugin, this.overworldName)) return; + new BiomeFormModal(this.app, plugin, this.overworldName, b.id).open(); + }); + row.createEl("button", { text: "Edit generator…" }).addEventListener("click", () => { + this.close(); + void openBiomeGenerator(plugin, b.id); + }); + } + const buttons = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); + const add = buttons.createEl("button", { text: "Add biome…", cls: "mod-cta" }); + if (lock) lockButton(add, lock); + add.addEventListener("click", () => { + if (biomeEditLock(plugin, this.overworldName)) return; + new BiomeFormModal(this.app, plugin, this.overworldName).open(); + }); + } + + onClose(): void { + this.off?.(); + this.contentEl.empty(); + } +} + +const BLEND_GENERATOR = ""; + +export class BiomeFormModal extends HexmakerModal { + private state!: BiomeFormState; + private canvas!: HTMLCanvasElement; + private problemEl!: HTMLElement; + private saveBtn!: HTMLButtonElement; + private seed = Math.floor(Math.random() * 1e9); + private redrawTimer: number | undefined; + + /** `biome`: the biome to edit (id, label or note name); none = a new one. */ + constructor(app: App, private plugin: HexmakerPlugin, private overworldName: string, private biome?: string) { + super(app); + } + + private get existing(): BiomeNoteFields | undefined { + return this.biome ? this.plugin.biomeStore.get(this.biome) : undefined; + } + + private palette() { + const ow = this.plugin.getMap(this.overworldName); + return ow ? regionPalette(this.plugin, ow) : this.plugin.getMapPalette(this.overworldName); + } + + onOpen(): void { + this.makeDraggable(); + this.modalEl.addClass("duckmage-biome-form-modal"); + const existing = this.existing; + this.titleEl.setText(existing ? `Edit biome: ${existing.label}` : "Add biome"); + const palette = this.palette(); + this.state = formFromFields(existing, formTypes(palette, existing)); + void this.build(); + } + + private async build(): Promise { + const { contentEl, plugin, state } = this; + contentEl.empty(); + const existing = this.existing; + const form = contentEl.createDiv({ cls: "duckmage-region-gen-form" }); + const field = (label: string, parent: HTMLElement = form) => { + const row = parent.createDiv({ cls: "duckmage-region-gen-row" }); + row.createSpan({ cls: "duckmage-region-gen-label", text: label }); + return row; + }; + + // Generator. + const genRow = field("Made by"); + const gen = genRow.createEl("select", { attr: { "aria-label": "Made by" } }); + gen.createEl("option", { text: "Blend (built-in mixing)", value: BLEND_GENERATOR }); + const gens = await listGenerators(plugin).catch(() => []); + for (const g of gens) gen.createEl("option", { text: g.model.name || g.file.basename, value: g.file.path.replace(/\.md$/, "") }); + if (state.generator && ![...gen.options].some((o) => o.value === state.generator)) gen.createEl("option", { text: generatorName(state.generator), value: state.generator }); + gen.value = state.generator; + const genNote = form.createEl("p", { cls: "setting-item-description" }); + const showGenNote = () => genNote.setText(routeNote({ generator: state.generator || undefined }) ?? "Blend mixes the terrain types below, and blends into the biomes next to it. A temporary stand-in until generator regions land."); + showGenNote(); + gen.addEventListener("change", () => { state.generator = gen.value; showGenNote(); }); + + // Name and colour. + const name = field("Name").createEl("input", { type: "text", attr: { "aria-label": "Name", placeholder: "Glass wastes" } }); + name.value = state.label; + name.addEventListener("input", () => { state.label = name.value; this.check(); }); + const colour = field("Colour").createEl("input", { type: "color", attr: { "aria-label": "Colour" } }); + colour.value = /^#[0-9a-f]{6}$/i.test(state.color) ? state.color : "#7a9a5a"; + colour.addEventListener("input", () => { state.color = colour.value; }); + + // Mix. + const mixBox = form.createEl("details", { cls: "duckmage-biome-mix" }); + mixBox.open = true; + mixBox.createEl("summary", { text: "Terrain types (weights)" }); + const typesPresent = new Set(this.palette().map((t) => t.type)); + for (const [type, w] of state.mix) { + const row = field(type, mixBox); + if (!typesPresent.has(type)) row.addClass("is-missing"); + const slider = row.createEl("input", { type: "range", attr: { min: "0", max: "100", step: "1", "aria-label": `${type} weight` } }); + const num = row.createEl("input", { type: "number", cls: "duckmage-biome-weight", attr: { min: "0", step: "1", "aria-label": `${type} weight value` } }); + slider.value = String(Math.min(100, w)); + num.value = String(w); + const set = (v: number) => { state.mix.set(type, Math.max(0, Number.isFinite(v) ? v : 0)); this.check(); this.schedule(); }; + slider.addEventListener("input", () => { num.value = slider.value; set(Number(slider.value)); }); + num.addEventListener("change", () => { slider.value = String(Math.min(100, Number(num.value) || 0)); set(Number(num.value)); }); + if (!typesPresent.has(type)) row.createSpan({ cls: "setting-item-description", text: "not in this palette" }); + } + + // Blend, land, islands. + const blend = field("Blend with neighbours").createEl("select", { attr: { "aria-label": "Blend" } }); + blend.createEl("option", { text: "Overworld setting", value: "" }); + for (const b of BIOME_BLENDS) blend.createEl("option", { text: b, value: b }); + blend.value = state.blend; + blend.addEventListener("change", () => { state.blend = blend.value as BiomeBlend | ""; this.schedule(); }); + + const landRow = field("Land share"); + const landOn = landRow.createEl("input", { type: "checkbox", attr: { "aria-label": "Set a land share" } }); + const land = landRow.createEl("input", { type: "range", attr: { min: "0", max: "100", step: "5", "aria-label": "Land share" } }); + const landVal = landRow.createSpan(); + const showLand = () => { + landOn.checked = state.landPercent !== undefined; + land.disabled = state.landPercent === undefined; + land.value = String(state.landPercent ?? 50); + landVal.setText(state.landPercent !== undefined ? `${state.landPercent}%` : "Not set"); + }; + showLand(); + landOn.addEventListener("change", () => { state.landPercent = landOn.checked ? Number(land.value) : undefined; showLand(); }); + land.addEventListener("input", () => { state.landPercent = Number(land.value); showLand(); }); + const isl = field("Fewest islands").createEl("input", { type: "number", attr: { min: "0", step: "1", placeholder: "Not set", "aria-label": "Fewest islands" } }); + isl.value = state.minIslands !== undefined ? String(state.minIslands) : ""; + isl.addEventListener("change", () => { state.minIslands = isl.value.trim() === "" ? undefined : Math.max(0, Math.round(Number(isl.value) || 0)); }); + form.createEl("p", { cls: "setting-item-description", text: "Land share and fewest islands are for watery biomes (archipelagos)." }); + + // Transitions. + const trBox = form.createEl("details", { cls: "duckmage-biome-transitions" }); + trBox.open = state.transitions.length > 0; + trBox.createEl("summary", { text: `Transitions (${state.transitions.length})` }); + trBox.createEl("p", { cls: "setting-item-description", text: "Biomes this one shouldn't touch on the overworld, and the biome put between them." }); + const others = plugin.biomeStore.list().filter((b) => b.id !== existing?.id); + const trList = trBox.createDiv(); + const renderTr = () => { + trList.empty(); + state.transitions.forEach((t, i) => { + const row = trList.createDiv({ cls: "duckmage-region-gen-row" }); + const pick = (value: string, label: string) => { + const sel = row.createEl("select", { attr: { "aria-label": label } }); + sel.createEl("option", { text: "—", value: "" }); + for (const b of plugin.biomeStore.list()) sel.createEl("option", { text: b.label, value: b.label }); + if (value && ![...sel.options].some((o) => o.value.toLowerCase() === value.toLowerCase())) sel.createEl("option", { text: `${value} (unknown)`, value }); + sel.value = [...sel.options].find((o) => o.value.toLowerCase() === value.toLowerCase())?.value ?? ""; + return sel; + }; + row.createSpan({ text: "Next to" }); + const next = pick(t.next, "Next to"); + row.createSpan({ text: "put" }); + const between = pick(t.between, "Put between"); + next.addEventListener("change", () => { t.next = next.value; }); + between.addEventListener("change", () => { t.between = between.value; }); + row.createEl("button", { text: "Remove", attr: { "aria-label": "Remove transition" } }).addEventListener("click", () => { + state.transitions.splice(i, 1); + renderTr(); + }); + }); + const add = trList.createEl("button", { text: "Add transition" }); + add.disabled = !others.length; + add.addEventListener("click", () => { state.transitions.push({ next: "", between: "" }); renderTr(); }); + }; + renderTr(); + + // Preview. + this.canvas = contentEl.createEl("canvas", { cls: "duckmage-region-gen-preview" }); + this.canvas.width = 320; + this.canvas.height = 220; + const prevRow = contentEl.createDiv({ cls: "duckmage-region-gen-row" }); + prevRow.createSpan({ cls: "setting-item-description", text: "Preview: one region of this biome, blended." }); + prevRow.createEl("button", { text: "Reroll" }).addEventListener("click", () => { this.seed = Math.floor(Math.random() * 1e9); this.redraw(); }); + + this.problemEl = contentEl.createEl("p", { cls: "duckmage-locked-hint" }); + const row = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); + if (existing && plugin.biomeStore.hasDefault(existing.id)) { + row.createEl("button", { text: "Restore default" }).addEventListener("click", () => { + void plugin.biomeStore.restoreDefault(existing.id).then((ok) => { + if (!ok) return; + new Notice(`${existing.label} is back to its default (the old note is in the plugin's backups folder).`); + this.state = formFromFields(plugin.biomeStore.get(existing.id), formTypes(this.palette(), plugin.biomeStore.get(existing.id))); + void this.build(); + }); + }); + } + if (existing) { + row.createEl("button", { text: "Edit generator…" }).addEventListener("click", () => { + this.close(); + void openBiomeGenerator(plugin, existing.id); + }); + } + row.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); + this.saveBtn = row.createEl("button", { text: "Save", cls: "mod-cta" }); + const lock = biomeEditLock(plugin, this.overworldName); + if (lock) lockButton(this.saveBtn, lock); + this.saveBtn.addEventListener("click", () => void this.save()); + this.check(); + this.redraw(); + } + + private check(): void { + const existing = this.existing; + const others = this.plugin.biomeStore.list().filter((b) => b.id !== existing?.id).map((b) => ({ id: b.id, label: b.label })); + const problem = formProblem(this.state, others); + this.problemEl?.setText(problem ?? ""); + if (this.saveBtn && !this.saveBtn.hasClass("is-locked")) this.saveBtn.disabled = !!problem; + } + + private schedule(): void { + if (this.redrawTimer !== undefined) window.clearTimeout(this.redrawTimer); + this.redrawTimer = window.setTimeout(() => { this.redrawTimer = undefined; this.redraw(); }, 120); + } + + private redraw(): void { + const ctx = this.canvas?.getContext("2d"); + const ow = overworldOf(this.plugin, this.overworldName); + if (!ctx || !this.canvas) return; + ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + if (!ow) return; + const palette = this.palette(); + const fields = fieldsFromForm(this.state, this.existing?.id ?? "preview"); + if (!fields.mix.length) return; + const plan = previewRegion(ow.layout, palette, fields, this.seed); + const colour = new Map(palette.map((t) => [t.name, t.color])); + const cells: RegionCell[] = [...plan.cells].map(([k, t]) => { + const [x, y] = k.split("_").map(Number); + return { x, y, color: colour.get(t) ?? "#333" }; + }); + const box = cellsBox(ow.layout, regionCells(ow.layout, 0, 0).map(([x, y]) => ({ x, y })), [1, 0, 0, 1, 0, 0]); + const pad = Math.max(box.w, box.h) * 0.05; + const k = Math.min(this.canvas.width / (box.w + 2 * pad), this.canvas.height / (box.h + 2 * pad)); + const to = composeAffine([1, 0, 0, 1, 0, 0], [k, 0, 0, k, (-box.x + pad) * k + (this.canvas.width - (box.w + 2 * pad) * k) / 2, (-box.y + pad) * k + (this.canvas.height - (box.h + 2 * pad) * k) / 2]); + drawRegionCells(ctx, ow.layout, cells, to); + } + + private async save(): Promise { + const { plugin } = this; + if (biomeEditLock(plugin, this.overworldName)) return; + const existing = this.existing; + const others = plugin.biomeStore.list().filter((b) => b.id !== existing?.id).map((b) => ({ id: b.id, label: b.label })); + if (formProblem(this.state, others)) return; + const fields = fieldsFromForm(this.state, existing?.id); + if (existing) { + // Unset optional fields are written as removed. + const full: Partial = { color: undefined, generator: undefined, blend: undefined, landShare: undefined, minIslands: undefined, ...fields }; + delete full.id; + if (!(await plugin.biomeStore.update(existing.id, full))) return; + } else { + const res = await plugin.biomeStore.create(fields); + if ("error" in res) { new Notice(res.error); return; } + } + this.close(); + plugin.refreshHexMap(); + } + + onClose(): void { + if (this.redrawTimer !== undefined) window.clearTimeout(this.redrawTimer); + this.contentEl.empty(); + } +} diff --git a/src/hex-map/BiomeModals.ts b/src/hex-map/BiomeModals.ts index 8fcd77e5..7f1327e9 100644 --- a/src/hex-map/BiomeModals.ts +++ b/src/hex-map/BiomeModals.ts @@ -16,13 +16,16 @@ import { App, Notice } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { regionMapAt } from "../maps/submaps"; -import { BIOMES, biomeForTerrain, representableBiomes, representativeTerrain, type BiomeId } from "../overworld/biomes"; +import { allBiomeIds, biomeInfo, representableBiomes, representativeTerrain, type BiomeId } from "../overworld/biomes"; import { REGION_WARP, type BlendWidth } from "../overworld/blendField"; import { regionCells } from "../overworld/layout"; import { composeAffine, drawRegionCells, cellsBox, type RegionCell } from "../overworld/overworldRender"; import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; +import { BiomeLibraryModal, openBiomeGenerator } from "./BiomeLibraryModal"; import { createRegion, + hexBiomeAt, + regionBiomeStatus, overworldOf, planRegionAt, regenerateRegion, @@ -65,10 +68,10 @@ export function paintableBiomes(plugin: HexmakerPlugin, parentName: string): { i const palette = plugin.getMapPalette(parentName); const shown = representableBiomes(palette); const out: { id: BiomeId; label: string; terrain: string; color: string }[] = []; - for (const b of BIOMES) { - if (!shown.has(b.id)) continue; - const terrain = representativeTerrain(b.id, palette)!; - out.push({ id: b.id, label: b.label, terrain, color: palette.find((t) => t.name === terrain)?.color ?? "#888" }); + for (const id of allBiomeIds()) { + if (!shown.has(id)) continue; + const terrain = representativeTerrain(id, palette)!; + out.push({ id, label: biomeInfo(id)?.label ?? id, terrain, color: palette.find((t) => t.name === terrain)?.color ?? "#888" }); } return out; } @@ -83,8 +86,7 @@ export class BiomePickerModal extends HexmakerModal { this.modalEl.addClass("duckmage-biome-modal"); const { plugin } = this.host; const hex = `${this.px}_${this.py}`; - const terrain = plugin.mapStore.get(this.parentName, hex)?.terrain; - const current = terrain ? biomeForTerrain(terrain, plugin.getMapPalette(this.parentName)) : undefined; + const current = hexBiomeAt(plugin, this.parentName, hex); const region = regionMapAt(plugin.settings.maps, this.parentName, hex); this.titleEl.setText(`Hex ${this.px}, ${this.py}`); const { contentEl } = this; @@ -126,6 +128,10 @@ export class BiomePickerModal extends HexmakerModal { this.close(); new RegionGenModal(this.host, this.parentName, this.px, this.py).open(); }); + row.createEl("button", { text: "Biomes…", attr: { title: "Add your own biomes, or edit these" } }).addEventListener("click", () => { + this.close(); + new BiomeLibraryModal(this.app, plugin, this.parentName).open(); + }); } private async apply(biome: BiomeId): Promise { @@ -160,10 +166,8 @@ export class RegionGenModal extends HexmakerModal { if (!ow) { this.close(); return; } const hex = `${this.px}_${this.py}`; const region = regionMapAt(plugin.settings.maps, this.parentName, hex); - const palette = plugin.getMapPalette(this.parentName); - const terrain = plugin.mapStore.get(this.parentName, hex)?.terrain; this.opts = { - biome: terrain ? biomeForTerrain(terrain, palette) : undefined, + biome: hexBiomeAt(plugin, this.parentName, hex), blend: ow.settings.blend ?? "normal", warp: REGION_WARP, seed: region?.regionSeed ?? newSeed(), @@ -181,6 +185,14 @@ export class RegionGenModal extends HexmakerModal { for (const b of paintableBiomes(plugin, this.parentName)) biomeSel.createEl("option", { text: b.label, value: b.id }); if (this.opts.biome) biomeSel.value = this.opts.biome; biomeSel.addEventListener("change", () => { this.opts.biome = biomeSel.value; this.redraw(); }); + const status = region ? regionBiomeStatus(plugin, region.name) : undefined; + if (status && "unknown" in status) form.createEl("p", { cls: "duckmage-locked-hint", text: `Unknown biome: ${status.unknown} (its note is gone). The region keeps its terrain; pick a biome to remake it.` }); + const genRow = field("Biome generator"); + genRow.createEl("button", { text: "Edit generator…" }).addEventListener("click", () => { + if (!this.opts.biome) return; + this.close(); + void openBiomeGenerator(plugin, this.opts.biome); + }); const blendSel = field("Blend with neighbours").createEl("select", { attr: { "aria-label": "Blend" } }); for (const w of ["narrow", "normal", "wide"] as BlendWidth[]) blendSel.createEl("option", { text: w, value: w }); diff --git a/src/hex-map/overworldLayer.ts b/src/hex-map/overworldLayer.ts index 0d1b922c..9e340fd2 100644 --- a/src/hex-map/overworldLayer.ts +++ b/src/hex-map/overworldLayer.ts @@ -40,7 +40,7 @@ import { type RegionCell, } from "../overworld/overworldRender"; import { ecotoneHexes, overworldBiomes, parseBiomeRiver } from "../overworld/regionWorld"; -import { overworldOf, overworldTerrain } from "../overworld/regionsVault"; +import { overworldOf, overworldTerrain, placedBiomes } from "../overworld/regionsVault"; import { FrameThrottle } from "../overworld/overworldInput"; interface Geometry { @@ -308,7 +308,7 @@ export class OverworldLayer { const [gx, gy] = applyAffine(geom.p2g, ...hexCenter(x, y, geom.layout.orientation, geom.layout.parentStagger)); return [(gx - minX) * k, (gy - minY) * k]; }; - const biomes = overworldBiomes(overworldTerrain(this.plugin, map), this.plugin.getMapPalette(map.name), geom.layout.orientation, geom.layout.parentStagger); + const biomes = overworldBiomes(overworldTerrain(this.plugin, map), this.plugin.getMapPalette(map.name), geom.layout.orientation, geom.layout.parentStagger, placedBiomes(this.plugin, map.name)); const ecotones = ecotoneHexes(biomes, geom.layout.orientation, geom.layout.parentStagger); for (const k2 of ecotones) { const [x, y] = k2.split("_").map(Number); diff --git a/src/hex-map/overworldMinimap.ts b/src/hex-map/overworldMinimap.ts index 8ba44385..f5f856cd 100644 --- a/src/hex-map/overworldMinimap.ts +++ b/src/hex-map/overworldMinimap.ts @@ -13,8 +13,9 @@ import { regionMapAt } from "../maps/submaps"; import { biomeInfo } from "../overworld/biomes"; import { drawMiniOverworld, miniHexAt, miniLayout, type MiniHex } from "../overworld/overworldRender"; import { ecotoneHexes, overworldBiomes, parseBiomeRiver } from "../overworld/regionWorld"; -import { overworldOf, overworldTerrain, regionHome } from "../overworld/regionsVault"; +import { overworldOf, overworldTerrain, placedBiomes, regionHome } from "../overworld/regionsVault"; import { OverworldLayer } from "./overworldLayer"; +import { BiomeLibraryModal } from "./BiomeLibraryModal"; const W = 220, H = 180; @@ -65,7 +66,13 @@ export class OverworldMinimap { this.host.redraw(); }); } - if (view === "biomes") return; + if (view === "biomes") { + // The Biomes tab: the biome notes, and adding your own (#50). + sw.createEl("button", { text: "Biomes…", attr: { title: "Add your own biomes, or edit these" } }).addEventListener("click", () => { + new BiomeLibraryModal(this.plugin.app, this.plugin, map.name).open(); + }); + return; + } } const head = box.createDiv({ cls: "duckmage-ow-minimap-head" }); head.createSpan({ cls: "duckmage-ow-minimap-title", text: this.plugin.mapLabel(t.overworld.name) }); @@ -85,7 +92,7 @@ export class OverworldMinimap { const palette = this.plugin.getMapPalette(t.overworld.name); const colour = new Map(palette.map((p) => [p.name, p.color])); const terrain = overworldTerrain(this.plugin, t.overworld); - const biomes = overworldBiomes(terrain, palette, ow.layout.orientation, ow.layout.parentStagger); + const biomes = overworldBiomes(terrain, palette, ow.layout.orientation, ow.layout.parentStagger, placedBiomes(this.plugin, t.overworld.name)); const eco = ecotoneHexes(biomes, ow.layout.orientation, ow.layout.parentStagger); const hexes: MiniHex[] = []; for (const [k, terr] of terrain) { diff --git a/src/overworld/BiomeStore.ts b/src/overworld/BiomeStore.ts new file mode 100644 index 00000000..e3468d5f --- /dev/null +++ b/src/overworld/BiomeStore.ts @@ -0,0 +1,367 @@ +/** + * Biome notes in the vault (#50): `/.md`, one per + * overworld biome, the built-ins included. The notes are the only copy: + * nothing about a biome is kept in data.json except which shipped biomes + * have been written into notes already (`biomesSeeded`), so a deleted one + * never comes back. + * + * - init(): reads every note, then writes each shipped biome (biomePresets) + * that hasn't been seeded yet and has no note: once, never over a note. + * - Hand edits are read back live (vault events); unreadable rows are + * reported once per edit and left as written. + * - A biome's `id` (frontmatter) is what references use, so renaming the + * note keeps every region and transition that names it. A note without + * an `id` key gets its old id written in when it's renamed. + * - A deleted note's biome is gone: regions made from it keep their + * terrain and show "unknown biome". + * + * Every change is handed to the lookups in biomes.ts (setBiomeSource). + */ + +import { Notice, TAbstractFile, TFile, TFolder } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { normalizeFolder } from "../utils"; +import { writeJsonBackup } from "../backup"; +import { + biomeFileName, + biomeSlug, + buildBiomeNote, + parseBiomeNote, + updateBiomeNote, + type BiomeNoteFields, + type BiomeNoteProblem, + type BiomeStoreApi, +} from "./biomeNote"; +import { BIOME_PRESETS, biomePreset } from "./biomePresets"; +import { setBiomeSource } from "./biomes"; + +interface Entry { + path: string; + fields: BiomeNoteFields; + problems: BiomeNoteProblem[]; + /** The note has its own `id:` key (else the id is its name's). */ + ownId: boolean; +} + +/** Which presets to write: not seeded before, and no note has their id or their file name. */ +export function presetsToSeed( + seeded: readonly string[], + ids: ReadonlySet, + fileTaken: (fileName: string) => boolean, + presets: readonly BiomeNoteFields[] = BIOME_PRESETS, +): { write: BiomeNoteFields[]; done: string[] } { + const write: BiomeNoteFields[] = []; + const done: string[] = []; + for (const p of presets) { + if (seeded.includes(p.id)) continue; + done.push(p.id); + if (ids.has(p.id) || fileTaken(biomeFileName(p.label))) continue; + write.push(p); + } + return { write, done }; +} + +export class BiomeStore implements BiomeStoreApi { + private entries = new Map(); + private lastContent = new Map(); + private reported = new Map(); + private listeners = new Set<() => void>(); + private ready = false; + private queue: Promise = Promise.resolve(); + + constructor(private plugin: HexmakerPlugin) {} + + isReady(): boolean { + return this.ready; + } + + folder(): string { + const configured = normalizeFolder(this.plugin.settings.biomesFolder ?? ""); + if (configured) return configured; + const world = normalizeFolder(this.plugin.settings.worldFolder ?? ""); + return world ? `${world}/biomes` : "biomes"; + } + + /** Call `fn` after every change to the biomes. Returns an unsubscribe. */ + onChange(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + async init(): Promise { + await this.enqueue(async () => { + for (const f of this.files()) await this.load(f); + await this.seed(); + this.ready = true; + this.publish(); + }); + } + + /** Re-read every note (the folder setting changed). */ + async reload(): Promise { + await this.enqueue(async () => { + this.entries.clear(); + this.lastContent.clear(); + for (const f of this.files()) await this.load(f); + this.publish(); + }); + } + + // ── API ──────────────────────────────────────────────────────────────── + + list(): BiomeNoteFields[] { + return this.active().map((e) => e.fields); + } + + get(name: string): BiomeNoteFields | undefined { + return this.find(name)?.fields; + } + + /** The note a biome lives in. */ + pathOf(name: string): string | undefined { + return this.find(name)?.path; + } + + /** What couldn't be read in a biome's note. */ + problemsOf(name: string): BiomeNoteProblem[] { + return this.find(name)?.problems ?? []; + } + + hasDefault(name: string): boolean { + const e = this.find(name); + return !!e && !!biomePreset(e.fields.id); + } + + async update(name: string, patch: Partial>): Promise { + const e = this.find(name); + if (!e) return false; + const tables = e.problems.filter((p) => p.where !== "settings"); + if (tables.length && (patch.mix || patch.transitions)) { + new Notice(`Biome ${e.fields.label}: fix the rows that can't be read in its note first (${tables[0].text}).`); + return false; + } + const f = this.plugin.app.vault.getAbstractFileByPath(e.path); + if (!(f instanceof TFile)) return false; + const fields: BiomeNoteFields = { ...e.fields, ...patch, id: e.fields.id }; + for (const [k, v] of Object.entries(patch)) if (v === undefined) delete (fields as unknown as Record)[k]; + await this.enqueue(async () => { + const content = await this.plugin.app.vault.read(f); + const next = updateBiomeNote(content, fields); + if (next !== content) await this.plugin.app.vault.modify(f, next); + this.take(f.path, f.basename, next); + this.publish(); + }); + return true; + } + + /** Write a new biome note. Returns its id, or an error. */ + async create(fields: Omit & { id?: string }): Promise<{ id: string } | { error: string }> { + const label = fields.label.trim(); + if (!label) return { error: "Give the biome a name." }; + let id = biomeSlug(fields.id ?? label) || "biome"; + const taken = new Set(this.active().map((e) => e.fields.id)); + for (let n = 2; taken.has(id); n++) id = `${biomeSlug(fields.id ?? label) || "biome"}-${n}`; + const folder = this.folder(); + let path = `${folder}/${biomeFileName(label)}.md`; + for (let n = 2; this.plugin.app.vault.getAbstractFileByPath(path); n++) path = `${folder}/${biomeFileName(label)} ${n}.md`; + const full: BiomeNoteFields = { ...fields, id, label }; + await this.enqueue(async () => { + await this.ensureFolder(folder); + const text = buildBiomeNote(full); + await this.plugin.app.vault.create(path, text); + this.take(path, path.slice(path.lastIndexOf("/") + 1, -3), text); + this.publish(); + }); + return { id }; + } + + async restoreDefault(name: string): Promise { + const e = this.find(name); + const preset = e ? biomePreset(e.fields.id) : undefined; + if (!e || !preset) return false; + const f = this.plugin.app.vault.getAbstractFileByPath(e.path); + if (!(f instanceof TFile)) return false; + await this.enqueue(async () => { + const content = await this.plugin.app.vault.read(f); + await this.backup(`biome-${e.fields.id}`, { [e.path]: content }); + // Keep the note's name for the label only if the user renamed it. + const next = updateBiomeNote(content, { ...preset }); + if (next !== content) await this.plugin.app.vault.modify(f, next); + this.take(f.path, f.basename, next); + this.publish(); + }); + return true; + } + + // ── vault events ─────────────────────────────────────────────────────── + + onModify(f: TAbstractFile): void { + if (!this.isBiomeFile(f)) return; + void this.enqueue(async () => { + if (await this.load(f)) this.publish(); + }); + } + + onDelete(f: TAbstractFile): void { + if (!this.entries.has(f.path)) return; + this.entries.delete(f.path); + this.lastContent.delete(f.path); + this.publish(); + } + + onRename(f: TAbstractFile, oldPath: string): void { + const old = this.entries.get(oldPath); + if (old) { + this.entries.delete(oldPath); + this.lastContent.delete(oldPath); + } + if (!this.isBiomeFile(f)) { + if (old) this.publish(); + return; + } + void this.enqueue(async () => { + await this.load(f); + const now = this.entries.get(f.path); + // A note whose id came from its old name keeps that id (references follow). + if (old && now && !now.ownId && now.fields.id !== old.fields.id) { + const fields = { ...now.fields, id: old.fields.id }; + const content = await this.plugin.app.vault.read(f); + const next = updateBiomeNote(content, fields); + if (next !== content) await this.plugin.app.vault.modify(f, next); + this.take(f.path, f.basename, next); + } + this.publish(); + }); + } + + // ── internals ────────────────────────────────────────────────────────── + + /** Entries in path order, one per id (the first note with an id wins). */ + private active(): Entry[] { + const seen = new Set(); + const out: Entry[] = []; + for (const e of [...this.entries.values()].sort((a, b) => a.path.localeCompare(b.path))) { + if (seen.has(e.fields.id)) continue; + seen.add(e.fields.id); + out.push(e); + } + return out; + } + + private find(name: string): Entry | undefined { + const k = biomeSlug(name); + const list = this.active(); + return list.find((e) => e.fields.id === k) + ?? list.find((e) => biomeSlug(e.fields.label) === k) + ?? list.find((e) => biomeSlug(e.path.slice(e.path.lastIndexOf("/") + 1, -3)) === k); + } + + private publish(): void { + if (this.ready) setBiomeSource(this.list()); + for (const fn of this.listeners) fn(); + } + + private inFolder(path: string): boolean { + return path.startsWith(this.folder() + "/") && path.endsWith(".md"); + } + + private isBiomeFile(f: TAbstractFile): f is TFile { + return f instanceof TFile && f.extension === "md" && !f.basename.startsWith("_") && this.inFolder(f.path); + } + + private files(): TFile[] { + const root = this.plugin.app.vault.getAbstractFileByPath(this.folder()); + if (!(root instanceof TFolder)) return []; + const out: TFile[] = []; + const walk = (folder: TFolder) => { + for (const child of folder.children) { + if (child instanceof TFolder) walk(child); + else if (child instanceof TFile && child.path.endsWith(".md") && !child.name.startsWith("_")) out.push(child); + } + }; + walk(root); + return out.sort((a, b) => a.path.localeCompare(b.path)); + } + + /** Read one note. True when what it says changed. */ + private async load(f: TFile): Promise { + const content = await this.plugin.app.vault.read(f); + if (this.lastContent.get(f.path) === content && this.entries.has(f.path)) return false; + this.take(f.path, f.basename ?? f.path.slice(f.path.lastIndexOf("/") + 1, -3), content); + return true; + } + + private take(path: string, basename: string, content: string): void { + const { fields, problems } = parseBiomeNote(content, basename); + const ownId = /^id\s*:\s*\S/m.test(content.split(/\r?\n---/)[0] ?? ""); + this.entries.set(path, { path, fields, problems, ownId }); + this.lastContent.set(path, content); + this.report(path, fields.label, problems); + const dup = [...this.entries.values()].find((e) => e.path !== path && e.fields.id === fields.id); + if (dup && this.ready) new Notice(`Biome notes ${dup.path} and ${path} have the same id (${fields.id}); the first is used. Change one note's id.`); + } + + private report(path: string, label: string, problems: BiomeNoteProblem[]): void { + const key = problems.map((p) => `${p.where}: ${p.text}`).join("; "); + if (this.reported.get(path) === key) return; + this.reported.set(path, key); + if (key && this.ready) new Notice(`Biome ${label}: couldn't read ${key}. Those rows are left as written.`, 8000); + } + + private async seed(): Promise { + const s = this.plugin.settings; + const seeded = s.biomesSeeded ?? []; + const ids = new Set([...this.entries.values()].map((e) => e.fields.id)); + const folder = this.folder(); + const plan = presetsToSeed(seeded, ids, (name) => !!this.plugin.app.vault.getAbstractFileByPath(`${folder}/${name}.md`)); + if (!plan.done.length) return; + if (plan.write.length) { + await this.ensureFolder(folder); + // Anything already in the folder is saved first (nothing is written over, but just in case). + if (this.entries.size) { + const notes: Record = {}; + for (const [p, c] of this.lastContent) notes[p] = c; + await this.backup("biomes-before-seeding", notes); + } + for (const p of plan.write) { + const path = `${folder}/${biomeFileName(p.label)}.md`; + const text = buildBiomeNote(p); + try { + await this.plugin.app.vault.create(path, text); + this.take(path, biomeFileName(p.label), text); + } catch (e) { + console.error("Hexmaker: couldn't write biome note", path, e); + } + } + } + s.biomesSeeded = [...seeded, ...plan.done]; + await this.plugin.saveSettings(); + } + + private async ensureFolder(folder: string): Promise { + const vault = this.plugin.app.vault; + const parts = folder.split("/"); + for (let i = 1; i <= parts.length; i++) { + const p = parts.slice(0, i).join("/"); + if (!vault.getAbstractFileByPath(p)) { + try { await vault.createFolder(p); } catch { /* made meanwhile */ } + } + } + } + + private async backup(base: string, notes: Record): Promise { + try { + const dir = `${this.plugin.manifest.dir}/backups/biome-notes-${new Date().toISOString().slice(0, 10)}`; + await writeJsonBackup(this.plugin.app.vault.adapter, dir, base, JSON.stringify({ savedAt: new Date().toISOString(), notes })); + } catch (e) { + console.error("Hexmaker: biome backup failed", e); + } + } + + private enqueue(task: () => Promise): Promise { + this.queue = this.queue.then(task).catch((e) => { + console.error("Hexmaker: biome notes", e); + }); + return this.queue; + } +} diff --git a/src/overworld/biomeForm.ts b/src/overworld/biomeForm.ts new file mode 100644 index 00000000..caaf047c --- /dev/null +++ b/src/overworld/biomeForm.ts @@ -0,0 +1,132 @@ +/** + * The Add / Edit biome form's model (#50), kept apart from the DOM so it + * can be tested, plus the one routing point for how a biome's regions are + * made (regionGenerator). + * + * Pure: no Obsidian imports. + */ + +import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; +import type { TerrainColor } from "../types"; +import { biomeSlug, type BiomeBlend, type BiomeNoteFields, type BiomeTransition } from "./biomeNote"; +import { profileFromMix, type BiomeId } from "./biomes"; +import { planRegion, paletteTypeOf, type RegionPlan } from "./regionWorld"; +import type { RegionLayout } from "./layout"; + +// ── routing ────────────────────────────────────────────────────────────── + +export type RegionRoute = + | { kind: "blend" } + /** Made by a generator note; `ready` once the generator-region bridge lands. */ + | { kind: "generator"; generator: string; ready: boolean }; + +/** + * How regions of this biome are made: the single routing point. Today + * every biome blends (the blend field mixes its type mix with its + * neighbours'); a biome with a `generator:` link is marked as waiting. + * TODO(#50 bridge): when generateBiomeRegion(plugin, req) lands, return + * `ready: true` for linked biomes and route planRegionAt through it. + */ +export function regionGenerator(biome: Pick | undefined): RegionRoute { + if (biome?.generator) return { kind: "generator", generator: biome.generator, ready: false }; + return { kind: "blend" }; +} + +/** A link target's display name: "world/generators/My tundra" → "My tundra". */ +export const generatorName = (target: string): string => target.slice(target.lastIndexOf("/") + 1).replace(/\.md$/, ""); + +/** The status line shown for a biome (undefined when it simply blends). */ +export function routeNote(biome: Pick | undefined): string | undefined { + const r = regionGenerator(biome); + if (r.kind === "generator" && !r.ready) return `Uses ${generatorName(r.generator)}: available once generator regions land. Blends until then.`; + return undefined; +} + +// ── the form ───────────────────────────────────────────────────────────── + +export interface BiomeFormState { + label: string; + color: string; + /** Generator link target, or "" for the built-in blend. */ + generator: string; + /** Type → weight (0 = not in the mix). */ + mix: Map; + /** "" = the overworld's setting. */ + blend: BiomeBlend | ""; + /** 0..100, or undefined (not set). */ + landPercent?: number; + minIslands?: number; + transitions: BiomeTransition[]; +} + +/** The types a form offers: the palette's (in order, settlements left out), then any others the biome already uses. */ +export function formTypes(palette: TerrainColor[], fields?: Pick): string[] { + const out: string[] = []; + for (const t of palette) if (t.type && t.type !== "settlement" && !out.includes(t.type)) out.push(t.type); + for (const r of fields?.mix ?? []) if (!out.includes(r.type)) out.push(r.type); + return out; +} + +/** A form filled from a biome (or blank for a new one). */ +export function formFromFields(fields: BiomeNoteFields | undefined, types: string[]): BiomeFormState { + const mix = new Map(types.map((t) => [t, 0])); + for (const r of fields?.mix ?? []) mix.set(r.type, (mix.get(r.type) ?? 0) + r.weight); + return { + label: fields?.label ?? "", + color: fields?.color ?? "#7a9a5a", + generator: fields?.generator ?? "", + mix, + blend: fields?.blend ?? "", + landPercent: fields?.landShare !== undefined ? Math.round(fields.landShare * 100) : undefined, + minIslands: fields?.minIslands, + transitions: (fields?.transitions ?? []).map((t) => ({ ...t })), + }; +} + +/** The note fields a form says (`id` kept from the biome being edited, else from the label). */ +export function fieldsFromForm(s: BiomeFormState, id?: string): BiomeNoteFields { + const f: BiomeNoteFields = { + id: id ?? (biomeSlug(s.label) || "biome"), + label: s.label.trim(), + color: s.color || undefined, + mix: [...s.mix].filter(([, w]) => w > 0).map(([type, weight]) => ({ type, weight })), + transitions: s.transitions.filter((t) => t.next.trim() && t.between.trim()).map((t) => ({ next: t.next.trim(), between: t.between.trim() })), + }; + if (!f.color) delete f.color; + if (s.generator) f.generator = s.generator; + if (s.blend) f.blend = s.blend; + if (s.landPercent !== undefined) f.landShare = Math.min(100, Math.max(0, s.landPercent)) / 100; + if (s.minIslands !== undefined) f.minIslands = Math.max(0, Math.round(s.minIslands)); + return f; +} + +/** Why the form can't be saved, or undefined. `others`: the labels and ids of the other biomes. */ +export function formProblem(s: BiomeFormState, others: { id: string; label: string }[]): string | undefined { + const label = s.label.trim(); + if (!label) return "Give the biome a name."; + const k = biomeSlug(label); + if (!k) return "Use some letters or numbers in the name."; + if (others.some((o) => o.id === k || biomeSlug(o.label) === k)) return `There's already a biome called ${label}.`; + if (![...s.mix.values()].some((w) => w > 0)) return "Give at least one terrain type a weight."; + return undefined; +} + +/** + * A preview of one region of this biome: the region of hex (0, 0) with its + * neighbours the same biome, made by the blend field from the form's mix. + */ +export function previewRegion(layout: RegionLayout, palette: TerrainColor[], fields: BiomeNoteFields, seed: number): RegionPlan { + const id: BiomeId = fields.id; + const biomes = new Map([["0_0", id]]); + for (const [x, y] of hexNeighbors(0, 0, layout.orientation, layout.parentStagger)) biomes.set(`${x}_${y}`, id); + return planRegion({ + layout, + parent: [0, 0], + biomes, + profiles: new Map([[id, profileFromMix(id, fields.mix, palette)]]), + typeOf: paletteTypeOf(palette), + worldSeed: seed, + seed, + blend: fields.blend, + }); +} diff --git a/src/overworld/biomePresets.ts b/src/overworld/biomePresets.ts new file mode 100644 index 00000000..f134c0bd --- /dev/null +++ b/src/overworld/biomePresets.ts @@ -0,0 +1,41 @@ +/** + * The shipped biomes as preset DATA (#50): written into biome notes once by + * BiomeStore (seedBiomeNotes), then the notes are what counts. Nothing here + * is read at run time except to seed a missing note and for "Restore + * default". + * + * Mixes are each biome's terrain-type shares (percent) from the shipped + * generator it used to borrow its mix from (src/worldgen/builtin), fitted + * to the Expanded palette; transitions are the old ecotone table; colours + * are the Expanded terrain each biome painted. + * + * Pure: no Obsidian imports. + */ + +import type { BiomeNoteFields } from "./biomeNote"; + +export const BIOME_PRESETS: readonly BiomeNoteFields[] = [ + { id: "tundra", label: "Tundra", color: "#e0f2fe", mix: [{ type: "snow", weight: 26 }, { type: "hills", weight: 21 }, { type: "grassland", weight: 21 }, { type: "water", weight: 10 }, { type: "peaks", weight: 6 }, { type: "wetland", weight: 6 }, { type: "desert", weight: 4 }, { type: "forest", weight: 3 }, { type: "mountains", weight: 3 }], transitions: [{ next: "Temperate forest", between: "Taiga" }, { next: "Deep forest", between: "Taiga" }, { next: "Grassland", between: "Taiga" }, { next: "Jungle", between: "Grassland" }, { next: "Savanna", between: "Grassland" }, { next: "Badlands", between: "Grassland" }] }, + { id: "taiga", label: "Taiga", color: "#428a5e", mix: [{ type: "forest", weight: 63 }, { type: "hills", weight: 13 }, { type: "water", weight: 12 }, { type: "wetland", weight: 7 }, { type: "snow", weight: 3 }, { type: "mountains", weight: 2 }], transitions: [{ next: "Jungle", between: "Temperate forest" }, { next: "Badlands", between: "Grassland" }] }, + { id: "temperate-forest", label: "Temperate forest", color: "#2d9553", mix: [{ type: "forest", weight: 67 }, { type: "hills", weight: 17 }, { type: "grassland", weight: 8 }, { type: "water", weight: 5 }, { type: "wetland", weight: 3 }], transitions: [] }, + { id: "deep-forest", label: "Deep forest", color: "#257445", mix: [{ type: "forest", weight: 80 }, { type: "hills", weight: 14 }, { type: "grassland", weight: 3 }, { type: "wetland", weight: 3 }], transitions: [] }, + { id: "grassland", label: "Grassland", color: "#69a168", mix: [{ type: "grassland", weight: 59 }, { type: "hills", weight: 17 }, { type: "forest", weight: 9 }, { type: "desert", weight: 4 }, { type: "water", weight: 4 }, { type: "wetland", weight: 4 }, { type: "mountains", weight: 4 }], transitions: [{ next: "Alpine", between: "Valley" }] }, + { id: "savanna", label: "Savanna", color: "#c4b25c", mix: [{ type: "grassland", weight: 46 }, { type: "desert", weight: 26 }, { type: "jungle", weight: 10 }, { type: "hills", weight: 7 }, { type: "forest", weight: 6 }, { type: "wetland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Alpine", between: "Valley" }] }, + { id: "jungle", label: "Jungle", color: "#15803d", mix: [{ type: "jungle", weight: 63 }, { type: "wetland", weight: 14 }, { type: "hills", weight: 11 }, { type: "mountains", weight: 6 }, { type: "water", weight: 4 }, { type: "grassland", weight: 2 }], transitions: [{ next: "Badlands", between: "Savanna" }] }, + { id: "badlands", label: "Badlands", color: "#c2410c", mix: [{ type: "badlands", weight: 42 }, { type: "desert", weight: 26 }, { type: "mountains", weight: 21 }, { type: "hills", weight: 7 }, { type: "coast", weight: 4 }], transitions: [] }, + { id: "swamp", label: "Swamp", color: "#909f23", mix: [{ type: "wetland", weight: 62 }, { type: "forest", weight: 21 }, { type: "water", weight: 10 }, { type: "grassland", weight: 6 }, { type: "shallows", weight: 2 }], transitions: [{ next: "Badlands", between: "Grassland" }, { next: "Alpine", between: "Valley" }] }, + { id: "river-delta", label: "River delta", color: "#5f9a7a", mix: [{ type: "wetland", weight: 39 }, { type: "water", weight: 32 }, { type: "shallows", weight: 13 }, { type: "grassland", weight: 10 }, { type: "coast", weight: 4 }, { type: "forest", weight: 2 }], transitions: [] }, + { id: "valley", label: "Valley", color: "#e0e8a1", mix: [{ type: "grassland", weight: 34 }, { type: "hills", weight: 21 }, { type: "mountains", weight: 18 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 11 }, { type: "water", weight: 3 }, { type: "wetland", weight: 2 }], transitions: [] }, + { id: "karst", label: "Karst", color: "#4ade80", mix: [{ type: "grassland", weight: 30 }, { type: "hills", weight: 24 }, { type: "mountains", weight: 18 }, { type: "forest", weight: 17 }, { type: "water", weight: 5 }, { type: "badlands", weight: 4 }, { type: "wetland", weight: 2 }], transitions: [] }, + { id: "alpine", label: "Alpine", color: "#bfdbfe", mix: [{ type: "mountains", weight: 44 }, { type: "peaks", weight: 20 }, { type: "hills", weight: 18 }, { type: "forest", weight: 9 }, { type: "snow", weight: 4 }, { type: "grassland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Jungle", between: "Karst" }] }, + { id: "volcanic", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1 }], transitions: [] }, + { id: "coastal-fjord", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [] }, + { id: "archipelago", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [] }, + { id: "open-sea", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20 }], transitions: [] }, +]; + +/** A copy of a preset's fields (callers may change it). */ +export function biomePreset(id: string): BiomeNoteFields | undefined { + const p = BIOME_PRESETS.find((b) => b.id === id); + return p ? { ...p, mix: p.mix.map((r) => ({ ...r })), transitions: p.transitions.map((t) => ({ ...t })) } : undefined; +} diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index eabe5703..f9279307 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -12,7 +12,8 @@ */ import type { HexWfcModel, TerrainEntry } from "../../packages/hex-wfc/src/model"; -import { mapTerrainsByType } from "../worldgen/builtinGenerators"; +import { mapTerrainsByType, TYPE_FALLBACKS } from "../worldgen/builtinGenerators"; +import { biomeSlug, mixShares, type BiomeMixRow, type BiomeNoteFields } from "./biomeNote"; import type { TerrainColor } from "../types"; export type BiomeId = string; @@ -53,8 +54,8 @@ export const BIOMES: BiomeInfo[] = [ ]; const BY_ID = new Map(BIOMES.map((b) => [b.id, b])); -export const biomeInfo = (id: BiomeId): BiomeInfo | undefined => BY_ID.get(id); -export const isSeaBiome = (id: BiomeId): boolean => BY_ID.get(id)?.zone === "sea"; +export const biomeInfo = (id: BiomeId): BiomeInfo | undefined => noteBiomeInfo(id) ?? BY_ID.get(id); +export const isSeaBiome = (id: BiomeId): boolean => biomeInfo(id)?.zone === "sea"; /** How badly (T, M) suits a biome: 0 = its ideal climate. */ export function climateMisfit(id: BiomeId, temp: number, moist: number): number { @@ -153,6 +154,7 @@ export function biomeForTerrain(terrain: string, palette: TerrainColor[]): Biome * the biome's preferred type first. */ export function representativeTerrain(biome: BiomeId, palette: TerrainColor[]): string | undefined { + if (!BY_ID.has(biome)) return noteBiomeTerrain(biome, palette); const map = biomesOf(palette); const cands = palette.filter((t) => map.get(t.name) === biome); if (!cands.length) return undefined; @@ -165,7 +167,7 @@ export function representativeTerrain(biome: BiomeId, palette: TerrainColor[]): /** Biomes a palette can show (each has a terrain that reads back as it). */ export function representableBiomes(palette: TerrainColor[]): Set { - return new Set(BIOMES.map((b) => b.id).filter((id) => representativeTerrain(id, palette) !== undefined)); + return new Set(allBiomeIds().filter((id) => representativeTerrain(id, palette) !== undefined)); } /** Nearest biomes in character, best first: used to swap a biome for variety or when a palette can't show it. */ @@ -223,7 +225,7 @@ export const ECOTONES: [BiomeId, BiomeId, BiomeId][] = [ /** The ecotone between two biomes, or undefined when they may touch. */ export function ecotoneBetween(a: BiomeId, b: BiomeId): BiomeId | undefined { - for (const [x, y, e] of ECOTONES) if ((x === a && y === b) || (x === b && y === a)) return e; + for (const [x, y, e] of source ? source.ecotones : ECOTONES) if ((x === a && y === b) || (x === b && y === a)) return e; return undefined; } @@ -301,3 +303,129 @@ export function biomeProfiles(models: Map, pale } return out; } + +// ── biomes from notes (#50): the data-loading seam ─────────────────────── +// +// BiomeStore loads the biome notes (/biomes, the built-ins +// seeded into notes once) and hands them here. With a source set: labels, +// transitions (ecotones) and the biome list come from the notes, and +// biomes that aren't in the table above (the user's own) are looked up in +// it. Without one (tests, before the notes load) everything reads the +// table above, as before. + +interface BiomeSource { + biomes: Map; + infos: Map; + ecotones: [BiomeId, BiomeId, BiomeId][]; + /** id, label or note name (slugged) → id. */ + names: Map; +} + +let source: BiomeSource | undefined; +let sourceVersion = 0; + +/** Bumped on every setBiomeSource (for cache keys). */ +export const biomeSourceVersion = (): number => sourceVersion; + +/** Load (or, with undefined, drop) the biomes read from notes. */ +export function setBiomeSource(list: readonly BiomeNoteFields[] | undefined): void { + sourceVersion++; + if (!list) { source = undefined; return; } + const biomes = new Map(); + const names = new Map(); + for (const b of list) if (!biomes.has(b.id)) biomes.set(b.id, b); + for (const b of biomes.values()) names.set(b.id, b.id); + for (const b of biomes.values()) { const k = biomeSlug(b.label); if (k && !names.has(k)) names.set(k, b.id); } + const infos = new Map(); + for (const b of biomes.values()) { + const base = BY_ID.get(b.id); + infos.set(b.id, base ? { ...base, label: b.label } + : { id: b.id, label: b.label, temp: 0.5, moist: 0.5, zone: b.landShare !== undefined && b.landShare < 0.5 ? "sea" : "low" }); + } + const ecotones: [BiomeId, BiomeId, BiomeId][] = []; + const resolve = (n: string) => names.get(biomeSlug(n)); + for (const b of biomes.values()) { + for (const t of b.transitions) { + const next = resolve(t.next), between = resolve(t.between); + if (next && between && next !== b.id) ecotones.push([b.id, next, between]); + } + } + source = { biomes, infos, ecotones, names }; +} + +/** Whether biomes come from notes now. */ +export const biomeSourceActive = (): boolean => !!source; + +/** Every biome id: the notes' (with a source), else the table's. */ +export function allBiomeIds(): BiomeId[] { + return source ? [...source.biomes.keys()] : BIOMES.map((b) => b.id); +} + +/** A biome's note fields (with a source). */ +export const biomeNoteOf = (id: BiomeId): BiomeNoteFields | undefined => source?.biomes.get(id); + +/** The biome a reference names (its id, label or note name), when it's a known biome note. */ +export function biomeByRef(ref: string | undefined): BiomeId | undefined { + return ref && source ? source.names.get(biomeSlug(ref)) : undefined; +} + +function noteBiomeInfo(id: BiomeId): BiomeInfo | undefined { + return source?.infos.get(id); +} + +/** A note biome's terrain types, heaviest first, then each one's fallbacks. */ +function typesToTry(mix: BiomeMixRow[]): string[] { + const own = [...mix].sort((a, b) => b.weight - a.weight).map((r) => r.type); + return [...own, ...own.flatMap((t) => TYPE_FALLBACKS[t] ?? [])]; +} + +/** The palette terrain painted for a note-only biome: the first terrain of its heaviest type the palette has. */ +function noteBiomeTerrain(biome: BiomeId, palette: TerrainColor[]): string | undefined { + const n = source?.biomes.get(biome); + if (!n) return undefined; + for (const ty of typesToTry(n.mix)) { + if (ty === "settlement") continue; + const hit = palette.find((t) => typeOf(t) === ty); + if (hit) return hit.name; + } + return undefined; +} + +/** + * Profile from a type mix (a biome note's): each type's share, spread + * evenly over the palette's terrains of that type. A type the palette + * doesn't have goes to its first fallback type it does (TYPE_FALLBACKS), + * else is dropped. Settlements never count. + */ +export function profileFromMix(id: BiomeId, mix: BiomeMixRow[], palette: TerrainColor[]): BiomeProfile { + const byType = new Map(); + for (const t of palette) { + const ty = typeOf(t); + if (!ty || ty === "settlement") continue; + byType.set(ty, [...(byType.get(ty) ?? []), t.name]); + } + const types = new Map(); + for (const [ty, share] of mixShares(mix)) { + const to = [ty, ...(TYPE_FALLBACKS[ty] ?? [])].find((x) => byType.has(x)); + if (to) types.set(to, (types.get(to) ?? 0) + share); + } + const total = [...types.values()].reduce((s, v) => s + v, 0); + const names = new Map>(); + for (const [ty, v] of types) { + types.set(ty, v / total); + const list = byType.get(ty)!; + names.set(ty, new Map(list.map((n) => [n, 1 / list.length]))); + } + return { id, types, names }; +} + +/** Profiles of every note biome with a mix the palette can show. */ +export function noteBiomeProfiles(palette: TerrainColor[]): Map { + const out = new Map(); + if (!source) return out; + for (const b of source.biomes.values()) { + const p = profileFromMix(b.id, b.mix, palette); + if (p.types.size) out.set(b.id, p); + } + return out; +} diff --git a/src/overworld/regionWorld.ts b/src/overworld/regionWorld.ts index 5ee159d6..698e9721 100644 --- a/src/overworld/regionWorld.ts +++ b/src/overworld/regionWorld.ts @@ -152,18 +152,21 @@ export function regionNeighbourMaps, palette: TerrainColor[], orientation: Orientation, stagger: Stagger, + placed?: ReadonlyMap, ): Map { const out = new Map(); const unresolved: string[] = []; for (const [k, t] of terrain) { - const b = biomeForTerrain(t, palette); + const b = placed?.get(k) ?? biomeForTerrain(t, palette); if (b) out.set(k, b); else unresolved.push(k); } diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index c464335d..d5a73d0d 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -14,7 +14,7 @@ import { slugify } from "../utils"; import { newWorldId } from "../worldgen/world"; import { BUILTIN_GENERATORS, builtinModel } from "../worldgen/builtinGenerators"; import { regionMapAt } from "../maps/submaps"; -import { biomeProfiles, representativeTerrain, type BiomeId, type BiomeProfile } from "./biomes"; +import { biomeByRef, biomeForTerrain, biomeNoteOf, biomeProfiles, biomeSourceVersion, noteBiomeProfiles, representativeTerrain, type BiomeId, type BiomeProfile } from "./biomes"; import { regionCells, type RegionLayout } from "./layout"; import type { BlendWidth } from "./blendField"; import { ADD_REGION_LOCKED_HINT, canAdd, canReshape, PLACE_LOCKED_HINT, RESHAPE_LOCKED_HINT } from "../workMode"; @@ -60,13 +60,20 @@ export function regionHome(plugin: HexmakerPlugin, regionName: string): { overwo const profileCache = new WeakMap }>(); -/** Biome profiles fitted to a palette (cached until its terrains change). */ +/** + * Biome profiles fitted to a palette (cached until its terrains or the + * biome notes change): each biome note's type mix (#50). A biome with no + * note (the notes haven't loaded, or its note was deleted while the + * overworld's terrain still reads as it) falls back to the shipped + * generator's mix, so a region is never left without one. + */ export function profilesForPalette(palette: TerrainColor[]): Map { - const key = palette.map((t) => `${t.name}:${t.type ?? ""}`).join("|"); + const key = `${biomeSourceVersion()}#` + palette.map((t) => `${t.name}:${t.type ?? ""}`).join("|"); const hit = profileCache.get(palette); if (hit && hit.key === key) return hit.profiles; const models = new Map(BUILTIN_GENERATORS.map((g) => [g.slug, builtinModel(g.slug)])); const profiles = biomeProfiles(models, palette); + for (const [id, p] of noteBiomeProfiles(palette)) profiles.set(id, p); profileCache.set(palette, { key, profiles }); return profiles; } @@ -82,6 +89,43 @@ export function overworldTerrain(plugin: HexmakerPlugin, map: MapData): Map { + const out = new Map(); + for (const m of plugin.settings.maps) { + if (m.submapKind !== "region" || m.parent?.map !== overworldName) continue; + const id = biomeByRef(m.biome?.generator); + if (id) out.set(m.parent.hex, id); + } + return out; +} + +/** One overworld hex's biome: its placed biome, else read from its terrain. */ +export function hexBiomeAt(plugin: HexmakerPlugin, overworldName: string, hex: string): BiomeId | undefined { + const region = regionMapAt(plugin.settings.maps, overworldName, hex); + const placed = region ? biomeByRef(region.biome?.generator) : undefined; + if (placed) return placed; + const terrain = plugin.mapStore.get(overworldName, hex)?.terrain; + return terrain ? biomeForTerrain(terrain, plugin.getMapPalette(overworldName)) : undefined; +} + +/** + * What a region says it was made from: its biome's id, or `unknown` (the + * name it recorded) when that biome's note is gone. Undefined when it + * recorded none, or a shipped generator (`builtin:…`). + */ +export function regionBiomeStatus(plugin: HexmakerPlugin, regionName: string): { id: BiomeId } | { unknown: string } | undefined { + const ref = plugin.getMap(regionName)?.biome?.generator; + if (!ref || ref.startsWith("builtin:")) return undefined; + const id = biomeByRef(ref); + return id ? { id } : { unknown: ref }; +} + /** Fill the shared-grid fields once (world id, stagger) and save, before the first region. */ async function ensureMeshFields(plugin: HexmakerPlugin, map: MapData): Promise { const s = map.regions!; @@ -115,6 +159,8 @@ export interface RegionGenOptions { warp?: number; /** Preview only: treat the region's own overworld hex as this terrain (nothing is written). */ hexTerrain?: string; + /** The region's own biome (a hex set to a user's biome, which its terrain can't tell); default read from the overworld. */ + biome?: BiomeId; } /** @@ -129,7 +175,10 @@ export function planRegionAt(plugin: HexmakerPlugin, parentName: string, px: num const owPalette = plugin.getMapPalette(ow.map.name); const terrain = overworldTerrain(plugin, ow.map); if (opts.hexTerrain) terrain.set(`${px}_${py}`, opts.hexTerrain); - const biomes = overworldBiomes(terrain, owPalette, ow.layout.orientation, ow.layout.parentStagger); + const placed = placedBiomes(plugin, parentName); + if (opts.biome) placed.set(`${px}_${py}`, opts.biome); + const biomes = overworldBiomes(terrain, owPalette, ow.layout.orientation, ow.layout.parentStagger, placed); + const ownBiome = biomes.get(`${px}_${py}`); const ws = worldSeed(ow.settings.worldId ?? ow.map.name); const pinned = pinnedAround(plugin, parentName, ow.layout, px, py); const own = regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`); @@ -143,7 +192,7 @@ export function planRegionAt(plugin: HexmakerPlugin, parentName: string, px: num typeOf: paletteTypeOf(palette), worldSeed: ws, seed: opts.seed ?? own?.regionSeed ?? ws, - blend: opts.blend ?? ow.settings.blend, + blend: opts.blend ?? (ownBiome ? biomeNoteOf(ownBiome)?.blend : undefined) ?? ow.settings.blend, warp: opts.warp, }); } @@ -327,10 +376,10 @@ export async function setBiomeAt( } const existing = regionMapAt(plugin.settings.maps, parentName, hex); if (existing) { - await regenerateRegion(plugin, existing.name, opts); + await regenerateRegion(plugin, existing.name, { ...opts, biome }); return { name: existing.name }; } - return createRegion(plugin, parentName, px, py, { ...opts, fill: "match" }); + return createRegion(plugin, parentName, px, py, { ...opts, biome, fill: "match" }); } // ── walking into new land ──────────────────────────────────────────────── diff --git a/src/types.ts b/src/types.ts index 45b49cc0..605e558e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -341,6 +341,10 @@ export interface HexmakerPluginSettings { setupDismissed: boolean; /** Vault folder holding palette notes. Empty = "{worldFolder}/palettes". */ palettesFolder: string; + /** Vault folder holding biome notes (#50). Empty = "{worldFolder}/biomes". */ + biomesFolder?: string; + /** Shipped biomes already written into biome notes (ids): each is written once, so a deleted one stays deleted. */ + biomesSeeded?: string[]; /** True once settings-only palettes were written out as notes. */ palettesMigrated: boolean; /** diff --git a/styles.css b/styles.css index d081ec26..42739109 100644 --- a/styles.css +++ b/styles.css @@ -8462,3 +8462,38 @@ button.duckmage-terrain-legend-chip { align-self: center; padding-right: 4px; } + +/* Biomes list and the Add / Edit biome form (#50). */ +.duckmage-biome-list { + display: grid; + gap: 4px; + max-height: 50vh; + overflow-y: auto; + margin-bottom: 0.6em; +} +.duckmage-biome-row { + display: flex; + align-items: center; + gap: 8px; +} +.duckmage-biome-row-text { + display: flex; + flex-direction: column; + flex: 1; + min-width: 0; +} +.duckmage-biome-row-note { + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} +.duckmage-biome-mix, +.duckmage-biome-transitions { + display: grid; + gap: 4px; +} +.duckmage-biome-mix .duckmage-region-gen-row.is-missing .duckmage-region-gen-label { + font-style: italic; +} +.duckmage-biome-weight { + width: 5em; +} From 0499406366719dd6820a4846d7dc1010e8b41bb8 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:45:15 -0400 Subject: [PATCH 255/558] fix(overworld): water types for islands come from the terrain types' water group So a water type added to the type data counts as water without a code change (no-special-defaults rule). Co-Authored-By: Claude Opus 5.5 --- src/overworld/biomes.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index 22d0b9e7..7aee8475 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -14,6 +14,7 @@ import type { HexWfcModel, TerrainEntry } from "../../packages/hex-wfc/src/model"; import { mapTerrainsByType } from "../worldgen/builtinGenerators"; import type { TerrainColor } from "../types"; +import { typesInGroup } from "../terrainTypes"; export type BiomeId = string; export const OPEN_SEA = "open-sea"; @@ -41,10 +42,11 @@ export interface BiomeInfo { } /** - * Terrain types that are water, for islands (landShare / minIslands): every - * other type is land, except settlements. Types only, never names. + * Terrain types that are water, for islands (landShare / minIslands): the + * terrain types data's water group, so a new water type counts without a + * code change. Every other type is land, except settlements. Never names. */ -export const WATER_TYPES: readonly string[] = ["water", "deep-water", "shallows"]; +export const WATER_TYPES: readonly string[] = typesInGroup("water"); /** * Rings round a placed island, inner first: a ring is painted only when the * biome's generator has that type on the palette. From a2ff4faf19b58e80bab2313fee493664afaf47a1 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:45:32 -0400 Subject: [PATCH 256/558] test(biomes #50): note format, compat fixture, store seeding/rename/delete/update, lookups by type, form model Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/overworld/BiomeStore.ts | 1 + tests/biomeNotes.test.ts | 409 ++++++++++++++++++++++++++++++++ tests/fixtures/biome-note-v1.md | 32 +++ 4 files changed, 444 insertions(+), 2 deletions(-) create mode 100644 tests/biomeNotes.test.ts create mode 100644 tests/fixtures/biome-note-v1.md diff --git a/package.json b/package.json index e00e4cda..f3dbe663 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/biomeNotes.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/biomeNotes.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/overworld/BiomeStore.ts b/src/overworld/BiomeStore.ts index e3468d5f..738bc713 100644 --- a/src/overworld/BiomeStore.ts +++ b/src/overworld/BiomeStore.ts @@ -133,6 +133,7 @@ export class BiomeStore implements BiomeStoreApi { } async update(name: string, patch: Partial>): Promise { + await this.queue; // hand edits read first const e = this.find(name); if (!e) return false; const tables = e.problems.filter((p) => p.where !== "settings"); diff --git a/tests/biomeNotes.test.ts b/tests/biomeNotes.test.ts new file mode 100644 index 00000000..337d7cb6 --- /dev/null +++ b/tests/biomeNotes.test.ts @@ -0,0 +1,409 @@ +/** + * Biome notes (#50): the note format (round trip, tolerance, a hand-written + * compat fixture), the store (seeding once, hand edits, rename, delete, + * update, restore default), the lookups by type, and the form model. + */ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { Notice } from "obsidian"; +import { + buildBiomeNote, + parseBiomeNote, + parseShare, + updateBiomeNote, + type BiomeNoteFields, +} from "../src/overworld/biomeNote"; +import { BIOME_PRESETS } from "../src/overworld/biomePresets"; +import { BiomeStore, presetsToSeed } from "../src/overworld/BiomeStore"; +import { + BIOMES, + ECOTONES, + allBiomeIds, + biomeByRef, + biomeInfo, + ecotoneBetween, + isSeaBiome, + noteBiomeProfiles, + profileFromMix, + representableBiomes, + representativeTerrain, + setBiomeSource, +} from "../src/overworld/biomes"; +import { overworldBiomes } from "../src/overworld/regionWorld"; +import { + fieldsFromForm, + formFromFields, + formProblem, + formTypes, + previewRegion, + regionGenerator, + routeNote, +} from "../src/overworld/biomeForm"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import type { TerrainColor } from "../src/types"; +import type { RegionLayout } from "../src/overworld/layout"; +import { MemVault } from "./helpers/memVault"; + +(globalThis as Record).window ??= globalThis; + +const GLASS: BiomeNoteFields = { + id: "glass-wastes", + label: "Glass wastes", + color: "#c0d8e0", + mix: [{ type: "desert", weight: 60 }, { type: "badlands", weight: 25 }], + transitions: [{ next: "Jungle", between: "Savanna" }], + blend: "wide", + landShare: 0.4, + minIslands: 2, + generator: "world/generators/Glass dunes", +}; + +// ── the note ───────────────────────────────────────────────────────────── + +describe("biome note format", () => { + it("round-trips every field", () => { + const { fields, problems } = parseBiomeNote(buildBiomeNote(GLASS), "Glass wastes"); + expect(problems).toEqual([]); + expect(fields).toEqual(GLASS); + }); + + it("reads minimal notes: name from the file, no frontmatter", () => { + const { fields } = parseBiomeNote("| Type | Weight |\n| --- | --- |\n| forest | 3 |\n", "Pine Barrens"); + expect(fields).toEqual({ id: "pine-barrens", label: "Pine Barrens", mix: [{ type: "forest", weight: 3 }], transitions: [] }); + }); + + it("reads a hand-written note (compat fixture) and reports what it can't read", () => { + const text = readFileSync(join(__dirname, "fixtures/biome-note-v1.md"), "utf8"); + const { fields, problems } = parseBiomeNote(text, "Glass wastes"); + expect(fields.id).toBe("glass-wastes"); + expect(fields.color).toBe("#c0d8e0"); + expect(fields.landShare).toBe(0.4); + expect(fields.minIslands).toBe(2); + expect(fields.blend).toBe("wide"); + expect(fields.generator).toBe("world/generators/Glass dunes"); + expect(fields.mix).toEqual([{ type: "desert", weight: 60 }, { type: "badlands", weight: 25 }, { type: "water", weight: 15 }]); + expect(fields.transitions).toEqual([{ next: "Jungle", between: "Savanna" }]); + expect(problems.map((p) => p.where)).toEqual(["Mix", "Transitions"]); + }); + + it("reports bad settings and keeps going", () => { + const { fields, problems } = parseBiomeNote("---\nblend: huge\nland-share: 140%\nmin-islands: two\n---\n", "X"); + expect(fields.blend).toBeUndefined(); + expect(fields.landShare).toBeUndefined(); + expect(problems).toHaveLength(3); + }); + + it("shares: 60%, 0.6 and 60 all read as 0.6", () => { + expect(parseShare("60%")).toBe(0.6); + expect(parseShare("0.6")).toBe(0.6); + expect(parseShare("60")).toBe(0.6); + expect(parseShare("x")).toBeNaN(); + }); + + it("update keeps the user's prose, extra keys and line endings", () => { + const text = readFileSync(join(__dirname, "fixtures/biome-note-v1.md"), "utf8").replace(/\r?\n/g, "\r\n"); + const next = updateBiomeNote(text, { ...GLASS, label: "Glass sea", mix: [{ type: "desert", weight: 1 }] }); + expect(next).toContain("Sand fused to glass by an old war. My own notes stay here."); + expect(next).toContain("More prose after the tables."); + expect(next).toContain("tags: [desert]"); + expect(next).not.toMatch(/[^\r]\n/); + const back = parseBiomeNote(next, "Glass wastes").fields; + expect(back.label).toBe("Glass sea"); + expect(back.mix).toEqual([{ type: "desert", weight: 1 }]); + }); + + it("update with what the note already says changes nothing", () => { + const text = buildBiomeNote(GLASS); + expect(updateBiomeNote(text, GLASS)).toBe(text); + // The user's own spelling of the same value stays. + const hand = text.replace("land-share: 40%", "land-share: 0.4"); + expect(updateBiomeNote(hand, GLASS)).toBe(hand); + }); + + it("update removes cleared keys and adds missing tables", () => { + const next = updateBiomeNote("---\nlabel: A\nblend: wide\n---\n\nprose\n", { id: "a", label: "A", mix: [{ type: "forest", weight: 2 }], transitions: [] }); + expect(next).not.toContain("blend:"); + expect(next).toContain("prose"); + expect(parseBiomeNote(next, "A").fields.mix).toEqual([{ type: "forest", weight: 2 }]); + }); +}); + +// ── presets ────────────────────────────────────────────────────────────── + +describe("shipped biome presets", () => { + it("cover every built-in biome with the same label", () => { + expect(BIOME_PRESETS.map((b) => b.id)).toEqual(BIOMES.map((b) => b.id)); + for (const p of BIOME_PRESETS) expect(p.label).toBe(BIOMES.find((b) => b.id === p.id)!.label); + }); + + it("as notes, give the same transitions as the old table", () => { + setBiomeSource(BIOME_PRESETS); + try { + for (const [a, b, e] of ECOTONES) { + expect(ecotoneBetween(a, b)).toBe(e); + expect(ecotoneBetween(b, a)).toBe(e); + } + expect(ecotoneBetween("tundra", "taiga")).toBeUndefined(); + } finally { + setBiomeSource(undefined); + } + }); + + it("as notes, every built-in still has a terrain on Expanded", () => { + const before = representableBiomes(DEFAULT_TERRAIN_PALETTE); + setBiomeSource(BIOME_PRESETS); + try { + expect(representableBiomes(DEFAULT_TERRAIN_PALETTE)).toEqual(before); + } finally { + setBiomeSource(undefined); + } + }); +}); + +// ── lookups ────────────────────────────────────────────────────────────── + +const PAL: TerrainColor[] = [ + { name: "sand", color: "#eeddaa", type: "desert" }, + { name: "dunes", color: "#ddcc99", type: "desert" }, + { name: "scrub", color: "#aa8855", type: "badlands" }, + { name: "grass", color: "#66aa66", type: "grassland" }, + { name: "sea", color: "#225588", type: "water" }, + { name: "town", color: "#999999", type: "settlement" }, +]; + +describe("biome lookups from notes", () => { + afterEach(() => setBiomeSource(undefined)); + + it("a user's biome is listed, labelled and painted by its heaviest type", () => { + setBiomeSource([...BIOME_PRESETS, GLASS]); + expect(allBiomeIds()).toContain("glass-wastes"); + expect(biomeInfo("glass-wastes")?.label).toBe("Glass wastes"); + expect(representativeTerrain("glass-wastes", PAL)).toBe("sand"); + expect(representableBiomes(PAL).has("glass-wastes")).toBe(true); + expect(isSeaBiome("glass-wastes")).toBe(true); // land share 40% + }); + + it("falls back by type when the palette lacks the heaviest type", () => { + setBiomeSource([{ id: "x", label: "X", mix: [{ type: "volcanic", weight: 5 }], transitions: [] }]); + // volcanic → mountains, badlands, hills: badlands is here. + expect(representativeTerrain("x", PAL)).toBe("scrub"); + }); + + it("profiles go by type, spread evenly over that type's terrains", () => { + const p = profileFromMix("g", [{ type: "desert", weight: 3 }, { type: "water", weight: 1 }, { type: "settlement", weight: 9 }], PAL); + expect(p.types.get("desert")).toBeCloseTo(0.75); + expect(p.types.get("water")).toBeCloseTo(0.25); + expect(p.types.has("settlement")).toBe(false); + expect([...p.names.get("desert")!]).toEqual([["sand", 0.5], ["dunes", 0.5]]); + }); + + it("never reads terrain names: an untyped terrain named like a type isn't used", () => { + const p = profileFromMix("g", [{ type: "desert", weight: 1 }], [{ name: "desert", color: "#fff" }]); + expect(p.types.size).toBe(0); + }); + + it("note profiles exist for every note biome the palette can show", () => { + setBiomeSource([GLASS, { id: "y", label: "Y", mix: [{ type: "peaks", weight: 1 }], transitions: [] }]); + const ps = noteBiomeProfiles(PAL); + expect(ps.has("glass-wastes")).toBe(true); + expect(ps.has("y")).toBe(false); // peaks → mountains, snow, hills: none here + }); + + it("references resolve by id, label or note name", () => { + setBiomeSource([GLASS]); + expect(biomeByRef("glass-wastes")).toBe("glass-wastes"); + expect(biomeByRef("Glass wastes")).toBe("glass-wastes"); + expect(biomeByRef("builtin:biome-tundra")).toBeUndefined(); + }); + + it("placed biomes win over the hex's terrain", () => { + setBiomeSource([...BIOME_PRESETS, GLASS]); + const terrain = new Map([["0_0", "sand"], ["1_0", "sand"]]); + const b = overworldBiomes(terrain, DEFAULT_TERRAIN_PALETTE.concat(PAL), "flat", "odd", new Map([["0_0", "glass-wastes"]])); + expect(b.get("0_0")).toBe("glass-wastes"); + expect(b.get("1_0")).not.toBe("glass-wastes"); + }); + + it("without notes, lookups read the built-in table as before", () => { + expect(allBiomeIds()).toEqual(BIOMES.map((b) => b.id)); + expect(biomeInfo("glass-wastes")).toBeUndefined(); + }); +}); + +// ── the store ──────────────────────────────────────────────────────────── + +function plugin(vault: MemVault, settings: Record = {}) { + const p = { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { worldFolder: "world", biomesFolder: "", ...settings } as Record, + saves: 0, + saveSettings: async () => { p.saves++; }, + }; + return p; +} + +const FOLDER = "world/biomes"; +const tick = () => new Promise((r) => setTimeout(r, 0)); + +async function boot(vault: MemVault, settings: Record = {}) { + const p = plugin(vault, settings); + const store = new BiomeStore(p as never); + await store.init(); + return { p, store }; +} + +describe("BiomeStore", () => { + afterEach(() => { setBiomeSource(undefined); Notice.shown = []; }); + + it("presetsToSeed: once, and never over a note", () => { + const presets = BIOME_PRESETS.slice(0, 3); + const plan = presetsToSeed(["tundra"], new Set(["taiga"]), (f) => f === "Temperate forest", presets); + expect(plan.write).toEqual([]); + expect(plan.done).toEqual(["taiga", "temperate-forest"]); + }); + + it("seeds the built-ins into notes once; a deleted one stays deleted", async () => { + const v = new MemVault(); + const { p, store } = await boot(v); + expect(store.list().map((b) => b.id).sort()).toEqual(BIOME_PRESETS.map((b) => b.id).sort()); + expect(v.files.has(`${FOLDER}/Tundra.md`)).toBe(true); + expect(p.settings.biomesSeeded).toHaveLength(BIOME_PRESETS.length); + expect(allBiomeIds()).toContain("tundra"); + // Delete Tundra; a restart doesn't bring it back. + v.files.delete(`${FOLDER}/Tundra.md`); + const again = await boot(v, { biomesSeeded: p.settings.biomesSeeded }); + expect(again.store.get("tundra")).toBeUndefined(); + expect(v.files.has(`${FOLDER}/Tundra.md`)).toBe(false); + }); + + it("never writes over a note that's already there", async () => { + const mine = "---\nlabel: Tundra\nid: tundra\n---\n\n| Type | Weight |\n| --- | --- |\n| snow | 1 |\n"; + const v = new MemVault({ [`${FOLDER}/Tundra.md`]: mine }); + const { store } = await boot(v); + expect(v.files.get(`${FOLDER}/Tundra.md`)).toBe(mine); + expect(store.get("tundra")!.mix).toEqual([{ type: "snow", weight: 1 }]); + }); + + it("imports hand edits live and reports unreadable rows once", async () => { + const v = new MemVault(); + const { store } = await boot(v); + const path = `${FOLDER}/Taiga.md`; + v.files.set(path, v.files.get(path)!.replace(/\| forest \| 63 \|/, "| forest | 90 |").replace("| hills | 13 |", "| hills | lots |")); + store.onModify(v.app().vault.getAbstractFileByPath(path)!); + await tick(); await tick(); + expect(store.get("taiga")!.mix.find((r) => r.type === "forest")!.weight).toBe(90); + expect(store.problemsOf("taiga")).toHaveLength(1); + expect(Notice.shown.filter((n) => n.msg.includes("Taiga"))).toHaveLength(1); + }); + + it("update writes the note through the writer, keeping prose", async () => { + const v = new MemVault(); + const { store } = await boot(v); + const path = `${FOLDER}/Swamp.md`; + v.files.set(path, v.files.get(path)! + "\nMy swamp notes.\n"); + store.onModify(v.app().vault.getAbstractFileByPath(path)!); + expect(await store.update("Swamp", { blend: "narrow", mix: [{ type: "wetland", weight: 1 }] })).toBe(true); + expect(v.files.get(path)).toContain("My swamp notes."); + expect(v.files.get(path)).toContain("blend: narrow"); + expect(store.get("swamp")!.mix).toEqual([{ type: "wetland", weight: 1 }]); + }); + + it("won't rewrite a table that has unreadable rows", async () => { + const v = new MemVault(); + const { store } = await boot(v); + const path = `${FOLDER}/Swamp.md`; + v.files.set(path, v.files.get(path)!.replace("| wetland | 62 |", "| wetland | ?? |")); + store.onModify(v.app().vault.getAbstractFileByPath(path)!); + expect(await store.update("swamp", { mix: [{ type: "forest", weight: 1 }] })).toBe(false); + expect(v.files.get(path)).toContain("| wetland | ?? |"); + }); + + it("restore default rewrites a shipped biome from its preset, with a backup", async () => { + const v = new MemVault(); + const { store } = await boot(v); + await store.update("jungle", { label: "Rainforest", mix: [{ type: "jungle", weight: 1 }] }); + expect(store.hasDefault("Rainforest")).toBe(true); + expect(await store.restoreDefault("Rainforest")).toBe(true); + expect(store.get("jungle")!.label).toBe("Jungle"); + expect(store.get("jungle")!.mix).toEqual(BIOME_PRESETS.find((b) => b.id === "jungle")!.mix); + expect([...v.binaries.keys()].some((k) => k.includes("biome-jungle"))).toBe(true); + }); + + it("create writes a new note; user biomes have no default", async () => { + const v = new MemVault(); + const { store } = await boot(v); + const res = await store.create({ label: "Glass wastes", mix: [{ type: "desert", weight: 1 }], transitions: [] }); + expect(res).toEqual({ id: "glass-wastes" }); + expect(v.files.has(`${FOLDER}/Glass wastes.md`)).toBe(true); + expect(store.hasDefault("glass-wastes")).toBe(false); + expect(allBiomeIds()).toContain("glass-wastes"); + // A second one with the same name gets its own id and file. + const two = await store.create({ label: "Glass wastes", mix: [{ type: "desert", weight: 1 }], transitions: [] }); + expect(two).toEqual({ id: "glass-wastes-2" }); + }); + + it("rename keeps the id (references follow), writing it in when the note had none", async () => { + const v = new MemVault({ [`${FOLDER}/Ash.md`]: "| Type | Weight |\n| --- | --- |\n| volcanic | 1 |\n" }); + const { store } = await boot(v); + expect(store.get("ash")).toBeDefined(); + const text = v.files.get(`${FOLDER}/Ash.md`)!; + v.files.delete(`${FOLDER}/Ash.md`); + v.files.set(`${FOLDER}/Cinder fields.md`, text); + store.onRename(v.app().vault.getAbstractFileByPath(`${FOLDER}/Cinder fields.md`)!, `${FOLDER}/Ash.md`); + await tick(); await tick(); + expect(store.get("ash")!.label).toBe("Cinder fields"); + expect(v.files.get(`${FOLDER}/Cinder fields.md`)).toMatch(/^id: ash$/m); + expect(biomeByRef("ash")).toBe("ash"); + }); + + it("delete drops the biome from the lookups", async () => { + const v = new MemVault(); + const { store } = await boot(v); + store.onDelete(v.app().vault.getAbstractFileByPath(`${FOLDER}/Karst.md`)!); + expect(store.get("karst")).toBeUndefined(); + expect(allBiomeIds()).not.toContain("karst"); + }); +}); + +// ── the form ───────────────────────────────────────────────────────────── + +const LAYOUT: RegionLayout = { footprint: "rect", size: 4, orientation: "flat", parentStagger: "odd", childStagger: "odd" }; + +describe("biome form model", () => { + it("offers the palette's types (no settlements), then the biome's others", () => { + expect(formTypes(PAL, { mix: [{ type: "snow", weight: 1 }] })).toEqual(["desert", "badlands", "grassland", "water", "snow"]); + }); + + it("round-trips a biome through the form", () => { + const s = formFromFields(GLASS, formTypes(PAL, GLASS)); + expect(s.landPercent).toBe(40); + expect(fieldsFromForm(s, GLASS.id)).toEqual(GLASS); + }); + + it("a blank form needs a name and a weight, and a name of its own", () => { + const s = formFromFields(undefined, formTypes(PAL)); + expect(formProblem(s, [])).toMatch(/name/); + s.label = "Tundra"; + expect(formProblem(s, [])).toMatch(/weight/); + s.mix.set("desert", 5); + expect(formProblem(s, [{ id: "tundra", label: "Tundra" }])).toMatch(/already/); + expect(formProblem(s, [])).toBeUndefined(); + expect(fieldsFromForm(s)).toEqual({ id: "tundra", label: "Tundra", color: "#7a9a5a", mix: [{ type: "desert", weight: 5 }], transitions: [] }); + }); + + it("routes: blend, or a generator marked as waiting for generator regions", () => { + expect(regionGenerator({})).toEqual({ kind: "blend" }); + expect(regionGenerator(GLASS)).toEqual({ kind: "generator", generator: GLASS.generator, ready: false }); + expect(routeNote(GLASS)).toMatch(/^Uses Glass dunes: available once generator regions land/); + expect(routeNote({})).toBeUndefined(); + }); + + it("previews one region from the mix with the blend field", () => { + const plan = previewRegion(LAYOUT, PAL, { ...GLASS, mix: [{ type: "water", weight: 1 }] }, 7); + expect(plan.cells.size).toBeGreaterThan(0); + expect(new Set(plan.cells.values())).toEqual(new Set(["sea"])); + }); +}); diff --git a/tests/fixtures/biome-note-v1.md b/tests/fixtures/biome-note-v1.md new file mode 100644 index 00000000..d83da7ed --- /dev/null +++ b/tests/fixtures/biome-note-v1.md @@ -0,0 +1,32 @@ +--- +hexmaker-biome: 1 +label: Glass wastes +color: c0d8e0 +blend: wide +land-share: 0.4 +min-islands: 2 +generator: "[[world/generators/Glass dunes|Glass dunes]]" +tags: [desert] +--- + +# Glass wastes + +Sand fused to glass by an old war. My own notes stay here. + +## Mix + +| Weight | Type | Notes | +| ---: | --- | --- | +| 60% | desert | mostly | +| 25 | Badlands | | +| lots | hills | | +| 15 | water | oases | + +## Transitions + +| Next to | Put between | +| --- | --- | +| [[Jungle]] | Savanna | +| Tundra | | + +More prose after the tables. From 4e3a31ded0c8a516b7f702fd5284a1185ab9c2de Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:52:42 -0400 Subject: [PATCH 257/558] =?UTF-8?q?feat(biomes=20#50):=20Edit=20generator?= =?UTF-8?q?=E2=80=A6=20in=20Edit=20region;=20Edit=20region=20from=20the=20?= =?UTF-8?q?flower's=20centre;=20Create=20token=20here=20on=20the=20overwor?= =?UTF-8?q?ld;=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +++ src/hex-map/EditRegionModal.ts | 20 +++++++++++++++++--- src/hex-map/HexMapView.ts | 23 +++++++++++++++++++---- src/hex-map/help.md | 2 ++ styles.css | 4 +++- 5 files changed, 44 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a165b257..e145bbb5 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,8 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma Which biome a hex is comes from its terrain's **Type**, never its name: forest-type terrains are temperate forest, wetland swamp, and so on. Where a type has variants, the **last** terrains of that type in the palette stand for them, in this order: forest → taiga, deep forest; grassland → savanna; hills → karst; wetland → river delta. Reorder the palette to choose (on Expanded: evergreen, evergreen heavy, savanna, jungle hills, river delta). A terrain with no type has no biome. +**Your own biomes.** Every biome is a plain note in the biomes folder (default `{world folder}/biomes`, see Settings). The built-in ones are written there once when the plugin starts, so you can edit them like any other note; delete one and it stays deleted. A biome note has a name, a colour, a **Mix** table of terrain *types* with weights (never terrain names, so it works on any palette with types), a **Transitions** table (biomes it shouldn't touch and the biome put between them), and in its frontmatter `blend` (narrow, normal or wide), `land-share` and `min-islands` (for watery biomes) and an optional `generator: [[…]]` link. Rows that can't be read are reported and left as you wrote them; your own text in the note is kept. On an overworld's **Biomes** view, **Biomes…** lists them: **Add biome…** opens a form (pick **Blend (built-in mixing)** or one of your generators, name, colour, type weights, blend, land share, fewest islands, transitions) with a live preview of one region, and **Save** writes the note. **Edit…** opens the same form for an existing biome (built-in ones also have **Restore default**, which backs up the old note first). **Edit generator…** (also in **Edit region…**) opens the biome's generator, or its note for now. Biomes linked to a generator say "available once generator regions land" and blend until then. Your biomes appear in the biome picker and make regions with the blend field straight away. Adding and editing biomes needs Build or God. A region keeps its biome when you rename the biome's note; if you delete the note, the region keeps its terrain and **Edit region…** shows "Unknown biome". Inside a region, click the middle of the hex flower to open **Edit region…** for it; the overworld's right-click menu has **Create token here** to mark the party. + A small **minimap** of the overworld (bottom right) shows on the overworld and on each of its regions, with the region you're in outlined; click a hex on it to go there. **Neighbouring maps** (below) and overworlds both stay available: pick per map. A map can have N/E/S/W neighbours and regions at once; a region itself joins its neighbours by itself, so it doesn't offer the neighbour tools. **Neighbouring maps.** In **Maps → New map…**, **Next to** makes the new map a region beside an existing one (same size and palette, lined up hex for hex); **Properties → New region here…** opens the form already placed. The generators marked *Continues … edge* (Overland and learned generators) carry the neighbour's terrain on across the shared border, and the preview shows the neighbour's edge faded around the new map. Region detail is only offered for submaps, since it zooms into a parent hex. @@ -326,6 +328,7 @@ Open **Settings → Hexmap World Creator** to configure: | **Hex orientation** | `flat` (default) or `pointy` top hex style. | | **Path types** | Named path types used by the Path drawing tool. Each type has a name, colour, width, line style, and routing mode. Manage them from the Path button on the hex map toolbar. | | **Palettes folder** | Folder holding one note per terrain palette (default `{world folder}/palettes`). | +| **Biomes folder** | Folder holding one note per overworld biome (default `{world folder}/biomes`). | | **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | | **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | diff --git a/src/hex-map/EditRegionModal.ts b/src/hex-map/EditRegionModal.ts index 24983a0e..30ea3db0 100644 --- a/src/hex-map/EditRegionModal.ts +++ b/src/hex-map/EditRegionModal.ts @@ -22,8 +22,9 @@ import { regionMapAt, regionSettingsLabel } from "../maps/submaps"; import { terrainCounts } from "../maps/mapNote"; import { readNotesSection, writeNotesSection } from "../maps/mapNoteNotes"; import { flowerPetals } from "../maps/mapNav"; -import { biomeForTerrain, biomeInfo, type BiomeId } from "../overworld/biomes"; -import { overworldOf, regenerateRegion, setBiomeAt } from "../overworld/regionsVault"; +import { biomeInfo, type BiomeId } from "../overworld/biomes"; +import { hexBiomeAt, overworldOf, regenerateRegion, regionBiomeStatus, setBiomeAt } from "../overworld/regionsVault"; +import { openBiomeGenerator } from "./BiomeLibraryModal"; import { editRegionPlan, terrainCountsText } from "../overworld/overworldInput"; import { mayReshape, paintableBiomes, RegionGenModal, type BiomeHost } from "./BiomeModals"; import { openNoteFocused } from "../openNote"; @@ -118,9 +119,20 @@ export class EditRegionModal extends HexmakerModal { // ── biome ───────────────────────────────────────────────────────────── const terrain = plugin.mapStore.get(this.overworld, `${this.px}_${this.py}`)?.terrain; const palette = plugin.getMapPalette(this.overworld); - const current = terrain ? biomeForTerrain(terrain, palette) : undefined; + const current = hexBiomeAt(plugin, this.overworld, `${this.px}_${this.py}`); const biomeSec = contentEl.createDiv({ cls: "duckmage-editor-section duckmage-edit-region-biome" }); biomeSec.createEl("h4", { text: "Biome" }); + const status = regionBiomeStatus(plugin, name); + if (status && "unknown" in status) { + biomeSec.createEl("p", { cls: "duckmage-locked-hint", text: `Unknown biome: ${status.unknown} (its note is gone). The region keeps its terrain.` }); + } + const editGenerator = (row: HTMLElement) => { + if (!current) return; + row.createEl("button", { text: "Edit generator…", attr: { title: "Tune how this biome's regions are made" } }).addEventListener("click", () => { + this.close(); + void openBiomeGenerator(plugin, current); + }); + }; const biomes = paintableBiomes(plugin, this.overworld); if (plan.biome === "pick") { const grid = biomeSec.createDiv({ cls: "duckmage-terrain-picker duckmage-edit-region-biomes" }); @@ -161,6 +173,7 @@ export class EditRegionModal extends HexmakerModal { new RegionGenModal(this.host, this.overworld, this.px, this.py).open(); }); } + editGenerator(row); } else { const shown = biomes.find((b) => b.id === current); const row = biomeSec.createDiv({ cls: "duckmage-edit-region-biome-show" }); @@ -168,6 +181,7 @@ export class EditRegionModal extends HexmakerModal { if (shown) swatch.setCssProps({ "--duckmage-biome-color": shown.color }); row.createSpan({ text: shown?.label ?? (current ? biomeInfo(current)?.label ?? current : terrain ?? "None") }); if (plan.hint) biomeSec.createEl("p", { cls: "duckmage-locked-hint", text: plan.hint }); + editGenerator(biomeSec.createDiv({ cls: "duckmage-token-modal-buttons duckmage-edit-region-gen" })); } // ── facts ───────────────────────────────────────────────────────────── diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 01d3f76b..fa22b286 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -824,8 +824,13 @@ export class HexMapView extends ItemView { const palette = this.plugin.getMapPalette(home.overworld.name); const flower = el.createDiv({ cls: "duckmage-region-flower", attr: { role: "group", "aria-label": "Neighbouring regions" } }); const R = 12; // px from the middle to a petal's centre - const here = flower.createSpan({ cls: "duckmage-region-flower-petal is-here", attr: { title: `Here: ${this.plugin.mapLabel(this.activeMapName)}` } }); + // The centre petal is this region: click it for Edit region…. + const here = flower.createEl("button", { + cls: "duckmage-region-flower-petal is-here", + attr: { title: `Here: ${this.plugin.mapLabel(this.activeMapName)}. Click to edit this region.`, "aria-label": "Edit region" }, + }); here.setCssProps({ "--duckmage-petal-x": "0px", "--duckmage-petal-y": "0px" }); + here.addEventListener("click", () => this.openEditRegion(home.px, home.py, home.overworld.name)); const lock = walkLock(this.plugin, this.activeMapName, home.overworld.name); for (const p of petals) { const key = `${p.hex[0]}_${p.hex[1]}`; @@ -4763,12 +4768,22 @@ export class HexMapView extends ItemView { }); }); } + // Mark the party (or anything) on the overworld: tokens sit on its hexes. + menu.addItem((item) => + item.setTitle("Create token here").setIcon("circle-user").onClick(() => this.createTokenAtHex(px, py)), + ); menu.showAtMouseEvent(evt); } - /** "Edit region…" for the region on overworld hex (px, py). */ - openEditRegion(px: number, py: number): void { - new EditRegionModal({ ...this.biomeHost(), openLocations: (hx, hy) => this.openLocationsList(hx, hy) }, this.activeMapName, px, py).open(); + /** "Edit region…" for the region on hex (px, py) of `overworld` (default the open map; from inside a region, its overworld). */ + openEditRegion(px: number, py: number, overworld = this.activeMapName): void { + const openLocations = (hx: number, hy: number) => { + if (overworld === this.activeMapName) { this.openLocationsList(hx, hy); return; } + // The list belongs to the overworld hex: go there first. + this.navigateToMap(overworld); + window.setTimeout(() => this.openLocationsList(hx, hy), 50); + }; + new EditRegionModal({ ...this.biomeHost(), openLocations }, overworld, px, py).open(); } private async onHexClick(x: number, y: number, e?: MouseEvent): Promise { diff --git a/src/hex-map/help.md b/src/hex-map/help.md index c60f7e16..630d51af 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -140,6 +140,8 @@ Turn on any one of them from the hint (✦) where it would appear, or all of the **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards two things on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**; in Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region) needs **Build** or God; in Play the biome picker is greyed out and says "Switch to Build to place a biome.", and **New map from this hex… → Region** says "Switch to Build to make a region." Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. +**Your own biomes.** Each biome is a note in the biomes folder (default `{world folder}/biomes`); the built-in ones are written there once, so you can edit them. A note lists terrain *types* with weights (**Mix**), **Transitions** (biomes it shouldn't touch, and what goes between), and `blend`, `land-share`, `min-islands` and an optional `generator` link. In the **Biomes** view, **Biomes…** lists them with **Add biome…**, **Edit…** (built-ins also have **Restore default**) and **Edit generator…**; the form has a live preview of one region. Needs Build or God. Inside a region, click the middle of the hex flower for **Edit region…**; right-click an overworld hex for **Create token here**. + **Walking into new land.** In a region, the hex flower on the toolbar shows a **+** on each neighbour that has no region yet ("New region to the east"). Click it, pick the biome that lies there or **Roll** for one (the seed is shown; the same seed rolls the same biome), watch the preview of the new region blended with the regions around it, then **Create and go**. A different biome makes border country in between. Past the overworld's edge, the overworld grows by a hex to fit the new region. The hex editor's neighbour flower does the same on the hexes past the region's edge, and maps joined side by side get a **+** on the empty sides of their arrow pad. Needs Build or God: in Play the **+** says "Switch to Build to make a region." Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. diff --git a/styles.css b/styles.css index 4e3df5bb..f55f6537 100644 --- a/styles.css +++ b/styles.css @@ -8356,7 +8356,7 @@ button.duckmage-terrain-legend-chip { .duckmage-region-flower-petal.is-here { background: var(--interactive-accent); border-color: var(--interactive-accent); - cursor: default; + cursor: pointer; } .duckmage-region-flower-petal.is-empty { background: transparent; @@ -8530,6 +8530,8 @@ textarea.duckmage-edit-region-notes-input { width: 100%; min-height: 4.5em; resize: vertical; +} + /* Biomes list and the Add / Edit biome form (#50). */ .duckmage-biome-list { display: grid; From 4f115e6959dca2229498c967c0fda0951a49d5ec Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 22:55:47 -0400 Subject: [PATCH 258/558] feat(biomes #50): biome notes drive land-share / min-islands (archipelago presets 30% / 2) Co-Authored-By: Claude Opus 5.5 --- src/overworld/biomePresets.ts | 5 +++-- src/overworld/biomes.ts | 12 ++++++++++-- tests/biomeNotes.test.ts | 17 +++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/overworld/biomePresets.ts b/src/overworld/biomePresets.ts index f134c0bd..721232bf 100644 --- a/src/overworld/biomePresets.ts +++ b/src/overworld/biomePresets.ts @@ -7,7 +7,8 @@ * Mixes are each biome's terrain-type shares (percent) from the shipped * generator it used to borrow its mix from (src/worldgen/builtin), fitted * to the Expanded palette; transitions are the old ecotone table; colours - * are the Expanded terrain each biome painted. + * are the Expanded terrain each biome painted; the archipelago's islands + * (land share 30%, at least 2) are the archipelago fix's (BiomeInfo). * * Pure: no Obsidian imports. */ @@ -30,7 +31,7 @@ export const BIOME_PRESETS: readonly BiomeNoteFields[] = [ { id: "alpine", label: "Alpine", color: "#bfdbfe", mix: [{ type: "mountains", weight: 44 }, { type: "peaks", weight: 20 }, { type: "hills", weight: 18 }, { type: "forest", weight: 9 }, { type: "snow", weight: 4 }, { type: "grassland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Jungle", between: "Karst" }] }, { id: "volcanic", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1 }], transitions: [] }, { id: "coastal-fjord", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [] }, - { id: "archipelago", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [] }, + { id: "archipelago", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [], landShare: 0.3, minIslands: 2 }, { id: "open-sea", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20 }], transitions: [] }, ]; diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index 4a2f7990..ffb34f86 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -365,8 +365,14 @@ export function setBiomeSource(list: readonly BiomeNoteFields[] | undefined): vo const infos = new Map(); for (const b of biomes.values()) { const base = BY_ID.get(b.id); - infos.set(b.id, base ? { ...base, label: b.label } - : { id: b.id, label: b.label, temp: 0.5, moist: 0.5, zone: b.landShare !== undefined && b.landShare < 0.5 ? "sea" : "low" }); + const info: BiomeInfo = base ? { ...base, label: b.label } + : { id: b.id, label: b.label, temp: 0.5, moist: 0.5, zone: b.landShare !== undefined && b.landShare < 0.5 ? "sea" : "low" }; + // The note says the islands (land-share / min-islands); unset there = unset. + delete info.landShare; + delete info.minIslands; + if (b.landShare !== undefined) info.landShare = b.landShare; + if (b.minIslands !== undefined) info.minIslands = b.minIslands; + infos.set(b.id, info); } const ecotones: [BiomeId, BiomeId, BiomeId][] = []; const resolve = (n: string) => names.get(biomeSlug(n)); @@ -451,6 +457,8 @@ export function noteBiomeProfiles(palette: TerrainColor[]): Map { } }); + it("carry the islands settings of the built-in table, and the notes drive them", () => { + for (const b of BIOMES) { + const p = BIOME_PRESETS.find((x) => x.id === b.id)!; + expect([p.landShare, p.minIslands]).toEqual([b.landShare, b.minIslands]); + } + setBiomeSource(BIOME_PRESETS.map((b) => (b.id === "archipelago" ? { ...b, landShare: 0.5, minIslands: undefined } : b))); + try { + expect(biomeInfo("archipelago")?.landShare).toBe(0.5); + expect(biomeInfo("archipelago")?.minIslands).toBeUndefined(); + const prof = noteBiomeProfiles(DEFAULT_TERRAIN_PALETTE).get("archipelago")!; + expect(prof.landShare).toBe(0.5); + expect(noteBiomeProfiles(DEFAULT_TERRAIN_PALETTE).get("open-sea")!.landShare).toBeUndefined(); + } finally { + setBiomeSource(undefined); + } + }); + it("as notes, every built-in still has a terrain on Expanded", () => { const before = representableBiomes(DEFAULT_TERRAIN_PALETTE); setBiomeSource(BIOME_PRESETS); From be51ec5026ead0c11796a698c6d3306b0431fb6c Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sat, 10 Oct 2026 23:02:05 -0400 Subject: [PATCH 259/558] fix(biomes #50): compact biome form (two-column type weights, islands folded); preview shows islands Co-Authored-By: Claude Opus 5.5 --- src/hex-map/BiomeLibraryModal.ts | 18 +++++++++++------- src/overworld/biomeForm.ts | 5 ++++- styles.css | 18 +++++++++++++++++- tests/biomeNotes.test.ts | 7 +++++++ 4 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/hex-map/BiomeLibraryModal.ts b/src/hex-map/BiomeLibraryModal.ts index 2fa9f824..3f6e0b60 100644 --- a/src/hex-map/BiomeLibraryModal.ts +++ b/src/hex-map/BiomeLibraryModal.ts @@ -181,9 +181,10 @@ export class BiomeFormModal extends HexmakerModal { const mixBox = form.createEl("details", { cls: "duckmage-biome-mix" }); mixBox.open = true; mixBox.createEl("summary", { text: "Terrain types (weights)" }); + const mixGrid = mixBox.createDiv({ cls: "duckmage-biome-mix-grid" }); const typesPresent = new Set(this.palette().map((t) => t.type)); for (const [type, w] of state.mix) { - const row = field(type, mixBox); + const row = field(type, mixGrid); if (!typesPresent.has(type)) row.addClass("is-missing"); const slider = row.createEl("input", { type: "range", attr: { min: "0", max: "100", step: "1", "aria-label": `${type} weight` } }); const num = row.createEl("input", { type: "number", cls: "duckmage-biome-weight", attr: { min: "0", step: "1", "aria-label": `${type} weight value` } }); @@ -202,7 +203,10 @@ export class BiomeFormModal extends HexmakerModal { blend.value = state.blend; blend.addEventListener("change", () => { state.blend = blend.value as BiomeBlend | ""; this.schedule(); }); - const landRow = field("Land share"); + const isles = form.createEl("details", { cls: "duckmage-biome-islands" }); + isles.open = state.landPercent !== undefined || state.minIslands !== undefined; + isles.createEl("summary", { text: "Islands (watery biomes)" }); + const landRow = field("Land share", isles); const landOn = landRow.createEl("input", { type: "checkbox", attr: { "aria-label": "Set a land share" } }); const land = landRow.createEl("input", { type: "range", attr: { min: "0", max: "100", step: "5", "aria-label": "Land share" } }); const landVal = landRow.createSpan(); @@ -213,12 +217,12 @@ export class BiomeFormModal extends HexmakerModal { landVal.setText(state.landPercent !== undefined ? `${state.landPercent}%` : "Not set"); }; showLand(); - landOn.addEventListener("change", () => { state.landPercent = landOn.checked ? Number(land.value) : undefined; showLand(); }); - land.addEventListener("input", () => { state.landPercent = Number(land.value); showLand(); }); - const isl = field("Fewest islands").createEl("input", { type: "number", attr: { min: "0", step: "1", placeholder: "Not set", "aria-label": "Fewest islands" } }); + landOn.addEventListener("change", () => { state.landPercent = landOn.checked ? Number(land.value) : undefined; showLand(); this.schedule(); }); + land.addEventListener("input", () => { state.landPercent = Number(land.value); showLand(); this.schedule(); }); + const isl = field("Fewest islands", isles).createEl("input", { type: "number", attr: { min: "0", step: "1", placeholder: "Not set", "aria-label": "Fewest islands" } }); isl.value = state.minIslands !== undefined ? String(state.minIslands) : ""; - isl.addEventListener("change", () => { state.minIslands = isl.value.trim() === "" ? undefined : Math.max(0, Math.round(Number(isl.value) || 0)); }); - form.createEl("p", { cls: "setting-item-description", text: "Land share and fewest islands are for watery biomes (archipelagos)." }); + isl.addEventListener("change", () => { state.minIslands = isl.value.trim() === "" ? undefined : Math.max(0, Math.round(Number(isl.value) || 0)); this.schedule(); }); + isles.createEl("p", { cls: "setting-item-description", text: "For archipelagos: how much of a region is land, and the fewest islands it gets." }); // Transitions. const trBox = form.createEl("details", { cls: "duckmage-biome-transitions" }); diff --git a/src/overworld/biomeForm.ts b/src/overworld/biomeForm.ts index caaf047c..504381aa 100644 --- a/src/overworld/biomeForm.ts +++ b/src/overworld/biomeForm.ts @@ -119,11 +119,14 @@ export function previewRegion(layout: RegionLayout, palette: TerrainColor[], fie const id: BiomeId = fields.id; const biomes = new Map([["0_0", id]]); for (const [x, y] of hexNeighbors(0, 0, layout.orientation, layout.parentStagger)) biomes.set(`${x}_${y}`, id); + const profile = profileFromMix(id, fields.mix, palette); + if (fields.landShare !== undefined) profile.landShare = fields.landShare; + if (fields.minIslands !== undefined) profile.minIslands = fields.minIslands; return planRegion({ layout, parent: [0, 0], biomes, - profiles: new Map([[id, profileFromMix(id, fields.mix, palette)]]), + profiles: new Map([[id, profile]]), typeOf: paletteTypeOf(palette), worldSeed: seed, seed, diff --git a/styles.css b/styles.css index f55f6537..86ab6015 100644 --- a/styles.css +++ b/styles.css @@ -8564,5 +8564,21 @@ textarea.duckmage-edit-region-notes-input { font-style: italic; } .duckmage-biome-weight { - width: 5em; + width: 4em; +} +.duckmage-biome-mix-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(16em, 1fr)); + gap: 2px 12px; +} +.duckmage-biome-mix-grid .duckmage-region-gen-label { + min-width: 6.5em; +} +.duckmage-biome-mix-grid input[type="range"] { + flex: 1 1 auto; + min-width: 3em; +} +.duckmage-biome-islands { + display: grid; + gap: 4px; } diff --git a/tests/biomeNotes.test.ts b/tests/biomeNotes.test.ts index 5d8cc394..644c8583 100644 --- a/tests/biomeNotes.test.ts +++ b/tests/biomeNotes.test.ts @@ -423,4 +423,11 @@ describe("biome form model", () => { expect(plan.cells.size).toBeGreaterThan(0); expect(new Set(plan.cells.values())).toEqual(new Set(["sea"])); }); + + it("the preview makes islands from the form's land share", () => { + const fields = { ...GLASS, mix: [{ type: "water", weight: 9 }, { type: "grassland", weight: 1 }], landShare: 0.4, minIslands: 2 }; + const plan = previewRegion(LAYOUT, PAL, fields, 7); + const land = [...plan.cells.values()].filter((t) => t !== "sea").length; + expect(land / plan.cells.size).toBeGreaterThan(0.2); + }); }); From 93e83d43efe9b24070d4253f7c84202ecd015238 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 00:22:55 -0400 Subject: [PATCH 260/558] wip(biomes #50): min patches column, shore setting, Coast preset, generator routing marked ready Co-Authored-By: Claude Opus 5.5 --- dev/measure-patches.ts | 41 +++++ src/overworld/biomeForm.ts | 32 ++-- src/overworld/biomeNote.ts | 56 +++++- src/overworld/biomePresets.ts | 39 ++-- src/overworld/biomes.ts | 28 ++- src/overworld/regionGen.ts | 322 +++++++++++++++++++++++++++++++++- tests/biomeNotes.test.ts | 15 +- 7 files changed, 488 insertions(+), 45 deletions(-) create mode 100644 dev/measure-patches.ts diff --git a/dev/measure-patches.ts b/dev/measure-patches.ts new file mode 100644 index 00000000..d46a6df1 --- /dev/null +++ b/dev/measure-patches.ts @@ -0,0 +1,41 @@ +/** + * Measure how often each biome's terrain types survive in a region (#50 + * min patches): for every shipped biome, 200 seeds of an 8×8 region ringed + * by the same biome and by grassland, the share of regions with no cell of + * each type. Run: npx tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs dev/measure-patches.ts + */ +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { BIOME_PRESETS } from "../src/overworld/biomePresets"; +import { noteBiomeProfiles, setBiomeSource } from "../src/overworld/biomes"; +import { BlendField, REGION_WARP } from "../src/overworld/blendField"; +import { generateRegion } from "../src/overworld/regionGen"; +import type { RegionLayout } from "../src/overworld/layout"; +import { hexDistance } from "../packages/hex-wfc/src/grid"; + +const strip = !!(globalThis as { process?: { argv: string[] } }).process?.argv.includes("--no-min"); +setBiomeSource(strip ? BIOME_PRESETS.map((b) => ({ ...b, mix: b.mix.map((r) => ({ type: r.type, weight: r.weight })) })) : BIOME_PRESETS); +const palette = DEFAULT_TERRAIN_PALETTE; +const profiles = noteBiomeProfiles(palette); +const typeOfMap = new Map(palette.map((t) => [t.name, t.type])); +const typeOf = (n: string) => typeOfMap.get(n); +const l: RegionLayout = { footprint: "rect", size: 8, orientation: "flat", parentStagger: "odd", childStagger: "odd" }; +const ringed = (centre: string, around: string) => { + const m = new Map(); + for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) m.set(`${x}_${y}`, hexDistance([x, y], [2, 2], "flat", "odd") === 0 ? centre : around); + return m; +}; +for (const b of BIOME_PRESETS) { + const p = profiles.get(b.id); + if (!p) continue; + for (const around of [b.id, "grassland"]) { + const missing = new Map(); + for (let seed = 1; seed <= 200; seed++) { + const field = new BlendField(l, ringed(b.id, around), "normal", { warp: REGION_WARP, seed }); + const out = generateRegion({ layout: l, parent: [2, 2], field, profiles, typeOf, seed }); + const types = new Set([...out.values()].map(typeOf)); + for (const t of p.types.keys()) if (!types.has(t)) missing.set(t, (missing.get(t) ?? 0) + 1); + } + const row = [...p.types].map(([t, s]) => `${t} ${Math.round(s * 100)}%: ${Math.round(((missing.get(t) ?? 0) / 200) * 100)}%`).join(", "); + console.log(`${b.id} (ringed by ${around}) missing → ${row}`); + } +} diff --git a/src/overworld/biomeForm.ts b/src/overworld/biomeForm.ts index 504381aa..d71faf69 100644 --- a/src/overworld/biomeForm.ts +++ b/src/overworld/biomeForm.ts @@ -9,7 +9,7 @@ import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; import type { TerrainColor } from "../types"; import { biomeSlug, type BiomeBlend, type BiomeNoteFields, type BiomeTransition } from "./biomeNote"; -import { profileFromMix, type BiomeId } from "./biomes"; +import { profileFromFields, type BiomeId } from "./biomes"; import { planRegion, paletteTypeOf, type RegionPlan } from "./regionWorld"; import type { RegionLayout } from "./layout"; @@ -17,18 +17,18 @@ import type { RegionLayout } from "./layout"; export type RegionRoute = | { kind: "blend" } - /** Made by a generator note; `ready` once the generator-region bridge lands. */ + /** Made by a generator note (generateBiomeRegion, src/worldgen/biomeRegion.ts). */ | { kind: "generator"; generator: string; ready: boolean }; /** - * How regions of this biome are made: the single routing point. Today - * every biome blends (the blend field mixes its type mix with its - * neighbours'); a biome with a `generator:` link is marked as waiting. - * TODO(#50 bridge): when generateBiomeRegion(plugin, req) lands, return - * `ready: true` for linked biomes and route planRegionAt through it. + * How regions of this biome are made: the single routing point. A biome + * with a `generator:` link has its regions made by that generator + * (generateBiomeRegion, joined to the cells already painted around it; + * regionsVault.planRegionWithGenerator); every other biome blends (the + * blend field mixes its type mix with its neighbours'). */ export function regionGenerator(biome: Pick | undefined): RegionRoute { - if (biome?.generator) return { kind: "generator", generator: biome.generator, ready: false }; + if (biome?.generator) return { kind: "generator", generator: biome.generator, ready: true }; return { kind: "blend" }; } @@ -39,6 +39,7 @@ export const generatorName = (target: string): string => target.slice(target.las export function routeNote(biome: Pick | undefined): string | undefined { const r = regionGenerator(biome); if (r.kind === "generator" && !r.ready) return `Uses ${generatorName(r.generator)}: available once generator regions land. Blends until then.`; + if (r.kind === "generator") return `Made by ${generatorName(r.generator)}, joined to its neighbours.`; return undefined; } @@ -56,6 +57,9 @@ export interface BiomeFormState { /** 0..100, or undefined (not set). */ landPercent?: number; minIslands?: number; + /** Type → fewest patches (the Mix table's Min patches); kept through the form. */ + minPatches: Map; + shore: boolean; transitions: BiomeTransition[]; } @@ -79,6 +83,8 @@ export function formFromFields(fields: BiomeNoteFields | undefined, types: strin blend: fields?.blend ?? "", landPercent: fields?.landShare !== undefined ? Math.round(fields.landShare * 100) : undefined, minIslands: fields?.minIslands, + minPatches: new Map((fields?.mix ?? []).filter((r) => r.minPatches !== undefined).map((r) => [r.type, r.minPatches!])), + shore: !!fields?.shore, transitions: (fields?.transitions ?? []).map((t) => ({ ...t })), }; } @@ -89,7 +95,10 @@ export function fieldsFromForm(s: BiomeFormState, id?: string): BiomeNoteFields id: id ?? (biomeSlug(s.label) || "biome"), label: s.label.trim(), color: s.color || undefined, - mix: [...s.mix].filter(([, w]) => w > 0).map(([type, weight]) => ({ type, weight })), + mix: [...s.mix].filter(([, w]) => w > 0).map(([type, weight]) => { + const minPatches = s.minPatches?.get(type); + return minPatches !== undefined ? { type, weight, minPatches } : { type, weight }; + }), transitions: s.transitions.filter((t) => t.next.trim() && t.between.trim()).map((t) => ({ next: t.next.trim(), between: t.between.trim() })), }; if (!f.color) delete f.color; @@ -97,6 +106,7 @@ export function fieldsFromForm(s: BiomeFormState, id?: string): BiomeNoteFields if (s.blend) f.blend = s.blend; if (s.landPercent !== undefined) f.landShare = Math.min(100, Math.max(0, s.landPercent)) / 100; if (s.minIslands !== undefined) f.minIslands = Math.max(0, Math.round(s.minIslands)); + if (s.shore) f.shore = true; return f; } @@ -119,9 +129,7 @@ export function previewRegion(layout: RegionLayout, palette: TerrainColor[], fie const id: BiomeId = fields.id; const biomes = new Map([["0_0", id]]); for (const [x, y] of hexNeighbors(0, 0, layout.orientation, layout.parentStagger)) biomes.set(`${x}_${y}`, id); - const profile = profileFromMix(id, fields.mix, palette); - if (fields.landShare !== undefined) profile.landShare = fields.landShare; - if (fields.minIslands !== undefined) profile.minIslands = fields.minIslands; + const profile = profileFromFields({ ...fields, id }, palette); return planRegion({ layout, parent: [0, 0], diff --git a/src/overworld/biomeNote.ts b/src/overworld/biomeNote.ts index b186a557..122fef8b 100644 --- a/src/overworld/biomeNote.ts +++ b/src/overworld/biomeNote.ts @@ -63,6 +63,11 @@ export interface BiomeMixRow { type: string; /** Relative weight, > 0, any scale. */ weight: number; + /** + * Fewest separate patches of this type a region of the biome gets (the + * Mix table's optional "Min patches" column). Unset = no minimum. + */ + minPatches?: number; } export interface BiomeTransition { @@ -88,6 +93,12 @@ export interface BiomeNoteFields { landShare?: number; /** Fewest islands a region of this biome gets. */ minIslands?: number; + /** + * A shoreline biome (`shore: yes`): a region's land goes toward its + * land-heavy neighbours and its water toward the others, with a coast + * band between (regionGen placeShore). + */ + shore?: boolean; /** Link target of a generator note (no brackets), e.g. "world/generators/My tundra". */ generator?: string; } @@ -117,7 +128,7 @@ export function biomeFileName(label: string): string { export const BIOME_HELP = [ "> [!info] Biome", - "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `generator` links a generator note. Delete a row to drop it.", + "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale; an optional *Min patches* column asks for at least that many separate patches of the type). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `shore: yes` puts a region's land on the side of its land neighbours and its water on the other; `generator` links a generator note. Delete a row to drop it.", ]; // ── reading ────────────────────────────────────────────────────────────── @@ -184,6 +195,17 @@ function readFrontmatter(lines: string[]): Map { return out; } +/** Headers the Mix table's min-patches column may have. */ +const MIN_PATCH_HEADERS = ["min patches", "min-patches", "minimum patches", "fewest patches", "patches"]; + +/** "yes" / "true" / "on" / "1" → true, "no" / "false" / "off" / "0" → false, else undefined. */ +function readYesNo(raw: string): boolean | undefined { + const t = raw.trim().toLowerCase(); + if (["yes", "y", "true", "on", "1"].includes(t)) return true; + if (["no", "n", "false", "off", "0"].includes(t)) return false; + return undefined; +} + /** "40", "40%", "0.4" → a number, or NaN. */ const num = (raw: string) => Number(raw.trim().replace(/%$/, "").trim()); @@ -247,11 +269,18 @@ export function parseBiomeNote(content: string, basename: string): ParsedBiomeNo } const gen = fm.get("generator"); if (gen && linkTarget(gen)) fields.generator = linkTarget(gen); + const shore = fm.get("shore"); + if (shore) { + const v = readYesNo(shore); + if (v === true) fields.shore = true; + else if (v === undefined) problems.push({ where: "settings", text: `shore should be yes or no, not "${shore}"` }); + } const mix = findTable(lines, isMix); if (mix) { const ti = mix.headers.indexOf("type"); const wi = mix.headers.includes("weight") ? mix.headers.indexOf("weight") : mix.headers.indexOf("share"); + const pi = mix.headers.findIndex((h) => MIN_PATCH_HEADERS.includes(h)); for (let i = mix.start + 2; i < mix.end; i++) { const cells = splitRow(lines[i]); if (cells.every((c) => c === "")) continue; @@ -260,9 +289,19 @@ export function parseBiomeNote(content: string, basename: string): ParsedBiomeNo if (!type) { problems.push({ where: "Mix", text: `row ${i + 1}: no type` }); continue; } if (!Number.isFinite(w) || w < 0) { problems.push({ where: "Mix", text: `row ${i + 1}: weight "${cells[wi] ?? ""}" isn't a number` }); continue; } if (w === 0) continue; + // Min patches: blank = none; a bad value is reported, the row still counts. + const rawP = pi >= 0 ? (cells[pi] ?? "").trim() : ""; + let minPatches: number | undefined; + if (rawP && rawP !== "-" && rawP !== "—") { + const p = num(rawP); + if (Number.isInteger(p) && p >= 0) minPatches = p; + else problems.push({ where: "Mix", text: `row ${i + 1}: min patches "${rawP}" isn't a whole number` }); + } const hit = fields.mix.find((r) => r.type === type); - if (hit) hit.weight += w; - else fields.mix.push({ type, weight: w }); + if (hit) { + hit.weight += w; + if (minPatches !== undefined) hit.minPatches = Math.max(hit.minPatches ?? 0, minPatches); + } else fields.mix.push(minPatches !== undefined ? { type, weight: w, minPatches } : { type, weight: w }); } } const tr = findTable(lines, isTransitions); @@ -289,8 +328,15 @@ const quote = (s: string) => (/^[\w .,()'-]*$/.test(s) && !/^\s|\s$/.test(s) && /** "0.6" → "60%". */ export const shareText = (v: number) => `${fmt(v * 100)}%`; +/** The Mix table; the Min patches column only when some row has one (older notes stay as they were). */ function mixTable(rows: BiomeMixRow[]): string[] { - return ["| Type | Weight |", "| --- | ---: |", ...rows.map((r) => `| ${esc(r.type)} | ${fmt(r.weight)} |`)]; + if (!rows.some((r) => r.minPatches !== undefined)) + return ["| Type | Weight |", "| --- | ---: |", ...rows.map((r) => `| ${esc(r.type)} | ${fmt(r.weight)} |`)]; + return [ + "| Type | Weight | Min patches |", + "| --- | ---: | ---: |", + ...rows.map((r) => `| ${esc(r.type)} | ${fmt(r.weight)} | ${r.minPatches !== undefined ? String(r.minPatches) : ""} |`), + ]; } function transitionsTable(rows: BiomeTransition[]): string[] { @@ -307,6 +353,7 @@ function ownKeys(f: BiomeNoteFields): [string, string | undefined][] { ["blend", f.blend], ["land-share", f.landShare !== undefined ? shareText(f.landShare) : undefined], ["min-islands", f.minIslands !== undefined ? String(f.minIslands) : undefined], + ["shore", f.shore ? "yes" : undefined], ["generator", f.generator ? `"[[${f.generator}]]"` : undefined], ]; } @@ -374,6 +421,7 @@ function sameValue(key: string, cur: string, want: string): boolean { if (key === "colour") return readColour(cur) === readColour(w); if (key === "generator") return linkTarget(cur) === linkTarget(w); if (key === "id") return biomeSlug(cur) === biomeSlug(w); + if (key === "shore") return readYesNo(cur) === readYesNo(w); return cur.trim() === w.trim(); } diff --git a/src/overworld/biomePresets.ts b/src/overworld/biomePresets.ts index 721232bf..89b578ed 100644 --- a/src/overworld/biomePresets.ts +++ b/src/overworld/biomePresets.ts @@ -10,29 +10,36 @@ * are the Expanded terrain each biome painted; the archipelago's islands * (land share 30%, at least 2) are the archipelago fix's (BiomeInfo). * + * Min patches: the types smoothing washed out of most regions of the biome + * (measured with dev/measure-patches.ts: 200 seeds of an 8×8 region, on + * Expanded) that give it its character, e.g. alpine peaks, a volcano. + * Coast is the one note-only preset (no row in the BIOMES table): a + * `shore` biome whose land faces its land neighbours. + * * Pure: no Obsidian imports. */ import type { BiomeNoteFields } from "./biomeNote"; export const BIOME_PRESETS: readonly BiomeNoteFields[] = [ - { id: "tundra", label: "Tundra", color: "#e0f2fe", mix: [{ type: "snow", weight: 26 }, { type: "hills", weight: 21 }, { type: "grassland", weight: 21 }, { type: "water", weight: 10 }, { type: "peaks", weight: 6 }, { type: "wetland", weight: 6 }, { type: "desert", weight: 4 }, { type: "forest", weight: 3 }, { type: "mountains", weight: 3 }], transitions: [{ next: "Temperate forest", between: "Taiga" }, { next: "Deep forest", between: "Taiga" }, { next: "Grassland", between: "Taiga" }, { next: "Jungle", between: "Grassland" }, { next: "Savanna", between: "Grassland" }, { next: "Badlands", between: "Grassland" }] }, - { id: "taiga", label: "Taiga", color: "#428a5e", mix: [{ type: "forest", weight: 63 }, { type: "hills", weight: 13 }, { type: "water", weight: 12 }, { type: "wetland", weight: 7 }, { type: "snow", weight: 3 }, { type: "mountains", weight: 2 }], transitions: [{ next: "Jungle", between: "Temperate forest" }, { next: "Badlands", between: "Grassland" }] }, - { id: "temperate-forest", label: "Temperate forest", color: "#2d9553", mix: [{ type: "forest", weight: 67 }, { type: "hills", weight: 17 }, { type: "grassland", weight: 8 }, { type: "water", weight: 5 }, { type: "wetland", weight: 3 }], transitions: [] }, - { id: "deep-forest", label: "Deep forest", color: "#257445", mix: [{ type: "forest", weight: 80 }, { type: "hills", weight: 14 }, { type: "grassland", weight: 3 }, { type: "wetland", weight: 3 }], transitions: [] }, - { id: "grassland", label: "Grassland", color: "#69a168", mix: [{ type: "grassland", weight: 59 }, { type: "hills", weight: 17 }, { type: "forest", weight: 9 }, { type: "desert", weight: 4 }, { type: "water", weight: 4 }, { type: "wetland", weight: 4 }, { type: "mountains", weight: 4 }], transitions: [{ next: "Alpine", between: "Valley" }] }, - { id: "savanna", label: "Savanna", color: "#c4b25c", mix: [{ type: "grassland", weight: 46 }, { type: "desert", weight: 26 }, { type: "jungle", weight: 10 }, { type: "hills", weight: 7 }, { type: "forest", weight: 6 }, { type: "wetland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Alpine", between: "Valley" }] }, - { id: "jungle", label: "Jungle", color: "#15803d", mix: [{ type: "jungle", weight: 63 }, { type: "wetland", weight: 14 }, { type: "hills", weight: 11 }, { type: "mountains", weight: 6 }, { type: "water", weight: 4 }, { type: "grassland", weight: 2 }], transitions: [{ next: "Badlands", between: "Savanna" }] }, - { id: "badlands", label: "Badlands", color: "#c2410c", mix: [{ type: "badlands", weight: 42 }, { type: "desert", weight: 26 }, { type: "mountains", weight: 21 }, { type: "hills", weight: 7 }, { type: "coast", weight: 4 }], transitions: [] }, - { id: "swamp", label: "Swamp", color: "#909f23", mix: [{ type: "wetland", weight: 62 }, { type: "forest", weight: 21 }, { type: "water", weight: 10 }, { type: "grassland", weight: 6 }, { type: "shallows", weight: 2 }], transitions: [{ next: "Badlands", between: "Grassland" }, { next: "Alpine", between: "Valley" }] }, - { id: "river-delta", label: "River delta", color: "#5f9a7a", mix: [{ type: "wetland", weight: 39 }, { type: "water", weight: 32 }, { type: "shallows", weight: 13 }, { type: "grassland", weight: 10 }, { type: "coast", weight: 4 }, { type: "forest", weight: 2 }], transitions: [] }, - { id: "valley", label: "Valley", color: "#e0e8a1", mix: [{ type: "grassland", weight: 34 }, { type: "hills", weight: 21 }, { type: "mountains", weight: 18 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 11 }, { type: "water", weight: 3 }, { type: "wetland", weight: 2 }], transitions: [] }, - { id: "karst", label: "Karst", color: "#4ade80", mix: [{ type: "grassland", weight: 30 }, { type: "hills", weight: 24 }, { type: "mountains", weight: 18 }, { type: "forest", weight: 17 }, { type: "water", weight: 5 }, { type: "badlands", weight: 4 }, { type: "wetland", weight: 2 }], transitions: [] }, - { id: "alpine", label: "Alpine", color: "#bfdbfe", mix: [{ type: "mountains", weight: 44 }, { type: "peaks", weight: 20 }, { type: "hills", weight: 18 }, { type: "forest", weight: 9 }, { type: "snow", weight: 4 }, { type: "grassland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Jungle", between: "Karst" }] }, - { id: "volcanic", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1 }], transitions: [] }, - { id: "coastal-fjord", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [] }, + { id: "tundra", label: "Tundra", color: "#e0f2fe", mix: [{ type: "snow", weight: 26 }, { type: "hills", weight: 21 }, { type: "grassland", weight: 21 }, { type: "water", weight: 10, minPatches: 1 }, { type: "peaks", weight: 6 }, { type: "wetland", weight: 6 }, { type: "desert", weight: 4 }, { type: "forest", weight: 3 }, { type: "mountains", weight: 3 }], transitions: [{ next: "Temperate forest", between: "Taiga" }, { next: "Deep forest", between: "Taiga" }, { next: "Grassland", between: "Taiga" }, { next: "Jungle", between: "Grassland" }, { next: "Savanna", between: "Grassland" }, { next: "Badlands", between: "Grassland" }] }, + { id: "taiga", label: "Taiga", color: "#428a5e", mix: [{ type: "forest", weight: 63 }, { type: "hills", weight: 13, minPatches: 1 }, { type: "water", weight: 12, minPatches: 1 }, { type: "wetland", weight: 7 }, { type: "snow", weight: 3 }, { type: "mountains", weight: 2 }], transitions: [{ next: "Jungle", between: "Temperate forest" }, { next: "Badlands", between: "Grassland" }] }, + { id: "temperate-forest", label: "Temperate forest", color: "#2d9553", mix: [{ type: "forest", weight: 67 }, { type: "hills", weight: 17, minPatches: 1 }, { type: "grassland", weight: 8 }, { type: "water", weight: 5 }, { type: "wetland", weight: 3 }], transitions: [] }, + { id: "deep-forest", label: "Deep forest", color: "#257445", mix: [{ type: "forest", weight: 80 }, { type: "hills", weight: 14, minPatches: 1 }, { type: "grassland", weight: 3 }, { type: "wetland", weight: 3 }], transitions: [] }, + { id: "grassland", label: "Grassland", color: "#69a168", mix: [{ type: "grassland", weight: 59 }, { type: "hills", weight: 17, minPatches: 1 }, { type: "forest", weight: 9, minPatches: 1 }, { type: "desert", weight: 4 }, { type: "water", weight: 4 }, { type: "wetland", weight: 4 }, { type: "mountains", weight: 4 }], transitions: [{ next: "Alpine", between: "Valley" }] }, + { id: "savanna", label: "Savanna", color: "#c4b25c", mix: [{ type: "grassland", weight: 46 }, { type: "desert", weight: 26, minPatches: 1 }, { type: "jungle", weight: 10, minPatches: 1 }, { type: "hills", weight: 7 }, { type: "forest", weight: 6 }, { type: "wetland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Alpine", between: "Valley" }] }, + { id: "jungle", label: "Jungle", color: "#15803d", mix: [{ type: "jungle", weight: 63 }, { type: "wetland", weight: 14, minPatches: 1 }, { type: "hills", weight: 11, minPatches: 1 }, { type: "mountains", weight: 6 }, { type: "water", weight: 4 }, { type: "grassland", weight: 2 }], transitions: [{ next: "Badlands", between: "Savanna" }] }, + { id: "badlands", label: "Badlands", color: "#c2410c", mix: [{ type: "badlands", weight: 42 }, { type: "desert", weight: 26, minPatches: 1 }, { type: "mountains", weight: 21, minPatches: 1 }, { type: "hills", weight: 7 }, { type: "coast", weight: 4 }], transitions: [] }, + { id: "swamp", label: "Swamp", color: "#909f23", mix: [{ type: "wetland", weight: 62 }, { type: "forest", weight: 21, minPatches: 1 }, { type: "water", weight: 10, minPatches: 1 }, { type: "grassland", weight: 6 }, { type: "shallows", weight: 2 }], transitions: [{ next: "Badlands", between: "Grassland" }, { next: "Alpine", between: "Valley" }] }, + { id: "river-delta", label: "River delta", color: "#5f9a7a", mix: [{ type: "wetland", weight: 39 }, { type: "water", weight: 32 }, { type: "shallows", weight: 13, minPatches: 1 }, { type: "grassland", weight: 10 }, { type: "coast", weight: 4 }, { type: "forest", weight: 2 }], transitions: [] }, + { id: "valley", label: "Valley", color: "#e0e8a1", mix: [{ type: "grassland", weight: 34 }, { type: "hills", weight: 21, minPatches: 1 }, { type: "mountains", weight: 18, minPatches: 1 }, { type: "forest", weight: 12, minPatches: 1 }, { type: "peaks", weight: 11 }, { type: "water", weight: 3 }, { type: "wetland", weight: 2 }], transitions: [] }, + { id: "karst", label: "Karst", color: "#4ade80", mix: [{ type: "grassland", weight: 30 }, { type: "hills", weight: 24 }, { type: "mountains", weight: 18, minPatches: 1 }, { type: "forest", weight: 17, minPatches: 1 }, { type: "water", weight: 5 }, { type: "badlands", weight: 4 }, { type: "wetland", weight: 2 }], transitions: [] }, + { id: "alpine", label: "Alpine", color: "#bfdbfe", mix: [{ type: "mountains", weight: 44 }, { type: "peaks", weight: 20, minPatches: 2 }, { type: "hills", weight: 18, minPatches: 1 }, { type: "forest", weight: 9, minPatches: 1 }, { type: "snow", weight: 4 }, { type: "grassland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Jungle", between: "Karst" }] }, + { id: "volcanic", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15, minPatches: 1 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1, minPatches: 1 }], transitions: [] }, + { id: "coastal-fjord", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16, minPatches: 1 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10, minPatches: 1 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [] }, { id: "archipelago", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [], landShare: 0.3, minIslands: 2 }, - { id: "open-sea", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20 }], transitions: [] }, + { id: "coast", label: "Coast", color: "#d9c98f", mix: [{ type: "coast", weight: 30 }, { type: "water", weight: 28 }, { type: "shallows", weight: 18 }, { type: "grassland", weight: 14 }, { type: "hills", weight: 6 }, { type: "wetland", weight: 4 }], transitions: [{ next: "Alpine", between: "Coastal fjord" }], shore: true }, + { id: "open-sea", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20, minPatches: 1 }], transitions: [] }, ]; /** A copy of a preset's fields (callers may change it). */ diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index ffb34f86..a6f923b0 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -266,6 +266,10 @@ export interface BiomeProfile { /** BiomeInfo.landShare / minIslands, carried for region generation. */ landShare?: number; minIslands?: number; + /** Type → fewest separate patches of it a region gets (the note's Min patches). */ + minPatches?: Map; + /** Land toward land-heavy neighbours, water toward the rest (the note's `shore`). */ + shore?: boolean; } /** Open sea has no shipped generator: deep water with a rim of ocean. */ @@ -448,7 +452,25 @@ export function profileFromMix(id: BiomeId, mix: BiomeMixRow[], palette: Terrain const list = byType.get(ty)!; names.set(ty, new Map(list.map((n) => [n, 1 / list.length]))); } - return { id, types, names }; + const profile: BiomeProfile = { id, types, names }; + // Min patches follow their type to the one the palette has (the same fallback as the mix). + const minPatches = new Map(); + for (const r of mix) { + if (!r.minPatches || r.weight <= 0) continue; + const to = [r.type, ...(TYPE_FALLBACKS[r.type] ?? [])].find((x) => types.has(x)); + if (to) minPatches.set(to, Math.max(minPatches.get(to) ?? 0, r.minPatches)); + } + if (minPatches.size) profile.minPatches = minPatches; + return profile; +} + +/** A biome note's profile on a palette: its mix, islands and shore settings. */ +export function profileFromFields(b: BiomeNoteFields, palette: TerrainColor[]): BiomeProfile { + const p = profileFromMix(b.id, b.mix, palette); + if (b.landShare !== undefined) p.landShare = b.landShare; + if (b.minIslands !== undefined) p.minIslands = b.minIslands; + if (b.shore) p.shore = true; + return p; } /** Profiles of every note biome with a mix the palette can show. */ @@ -456,9 +478,7 @@ export function noteBiomeProfiles(palette: TerrainColor[]): Map(); if (!source) return out; for (const b of source.biomes.values()) { - const p = profileFromMix(b.id, b.mix, palette); - if (b.landShare !== undefined) p.landShare = b.landShare; - if (b.minIslands !== undefined) p.minIslands = b.minIslands; + const p = profileFromFields(b, palette); if (p.types.size) out.set(b.id, p); } return out; diff --git a/src/overworld/regionGen.ts b/src/overworld/regionGen.ts index bb9480ab..412443d3 100644 --- a/src/overworld/regionGen.ts +++ b/src/overworld/regionGen.ts @@ -25,7 +25,8 @@ import { mulberry32 } from "../../packages/hex-wfc/src/rng"; import { SHORE_TYPES, WATER_TYPES, type BiomeId, type BiomeProfile } from "./biomes"; import { namesWithinType, typeMix, type BlendField } from "./blendField"; -import { childNeighbours, parentOf, regionCells, type RegionLayout } from "./layout"; +import { childNeighbours, childPoint, neighbourRegions, parentOf, regionCells, regionCentrePoint, regionSpacing, type RegionLayout } from "./layout"; +import { fbm, hash2 } from "./noise"; export interface RegionGenInput { layout: RegionLayout; @@ -144,7 +145,24 @@ export function generateRegion(input: RegionGenInput): Map { // land in a mostly water biome would otherwise vanish. const ownBiome = field.biomes.get(`${input.parent[0]}_${input.parent[1]}`); const profile = ownBiome ? profiles.get(ownBiome) : undefined; - if (ownBiome && profile && (profile.minIslands || profile.landShare)) { + if (ownBiome && profile?.shore) { + // A shoreline biome: its land share becomes a direction (land toward + // the land-heavy neighbours). Islands don't apply. + placeShore({ + layout, + parent: input.parent, + cells, + work, + terrainAt, + typeOf, + profile, + profiles, + field, + pinned, + sharpness: sharp, + seed: input.seed, + }); + } else if (ownBiome && profile && (profile.minIslands || profile.landShare)) { placeIslands({ layout, cells, @@ -157,6 +175,21 @@ export function generateRegion(input: RegionGenInput): Map { }); } + // 4. Min patches (the Mix table's column), after smoothing and islands: + // smoothing erases a type that's only a sprinkle (alpine peaks, a volcano). + if (ownBiome && profile?.minPatches?.size) { + placePatches({ + layout, + cells, + work, + terrainAt, + typeOf, + profile, + influence: (x, y) => field.at(x, y).get(ownBiome) ?? 0, + rng: mulberry32(cellSeed(input.seed ^ 0x3c6ef372, input.parent[0], input.parent[1])), + }); + } + const out = new Map(); for (const k of own) { const v = work.get(k); @@ -321,6 +354,291 @@ export function placeIslands(input: IslandInput): void { } } +interface PatchInput { + layout: RegionLayout; + /** The region's own (unpinned) cells: the only cells changed. */ + cells: [number, number][]; + work: Map; + terrainAt: (key: string) => string | undefined; + typeOf: (terrain: string) => string | undefined; + /** The region's own biome: its minPatches, shares and names. */ + profile: BiomeProfile; + /** The region biome's share of the field at a cell (patches go where it is strongest). */ + influence: (x: number, y: number) => number; + rng: () => number; +} + +/** + * Min patches per type (the biome note's Mix "Min patches" column): after + * smoothing, a type the biome has only a little of (alpine peaks, a + * volcano) is usually washed out. For each such type (in type order), the + * patches already inside the region are counted, and new ones grown from + * free cells where the biome is strongest (away from the edge, not + * touching that type) until there are enough. A patch is about the type's + * share of the region split between its patches, never over a quarter of + * it. Only the region's own cells change; cells of a type that has its + * own minimum are never painted over. Deterministic for a seed. + */ +export function placePatches(input: PatchInput): void { + const { layout, work, terrainAt, typeOf, profile, rng } = input; + const wants = [...(profile.minPatches ?? [])].filter(([t, n]) => n > 0 && profile.names.get(t)?.size).sort((a, b) => (a[0] < b[0] ? -1 : 1)); + if (!wants.length) return; + const own = new Set(input.cells.map(([x, y]) => `${x}_${y}`)); + const ownList = [...own].sort(); + const n = ownList.length; + if (!n) return; + const protectedTypes = new Set(wants.map(([t]) => t)); + const nbrs = (k: string): string[] => { + const [x, y] = k.split("_").map(Number); + return childNeighbours(layout, x, y).map(([a, b]) => `${a}_${b}`); + }; + const typeAt = (k: string) => { + const t = terrainAt(k); + return t ? typeOf(t) : undefined; + }; + const taken = new Set(); + for (const [type, min] of wants) { + // Patches of this type already in the region (own cells only). + const seen = new Set(); + let have = 0; + for (const k of ownList) { + if (seen.has(k) || typeAt(k) !== type) continue; + have++; + const stack = [k]; + seen.add(k); + while (stack.length) { + for (const m of nbrs(stack.pop()!)) { + if (own.has(m) && !seen.has(m) && typeAt(m) === type) { seen.add(m); stack.push(m); } + } + } + } + const free = (k: string) => own.has(k) && !taken.has(k) && !protectedTypes.has(typeAt(k) ?? ""); + const share = profile.types.get(type) ?? 0; + const size = Math.max(1, Math.min(Math.round((share * n) / min), Math.floor(n / (4 * min)))); + const names = profile.names.get(type)!; + for (let guard = 0; guard < n && have < min; guard++) { + let start: string | undefined, best = -1; + for (const k of ownList) { + if (!free(k)) continue; + const around = nbrs(k); + if (around.some((m) => typeAt(m) === type)) continue; + const [x, y] = k.split("_").map(Number); + const score = (input.influence(x, y) + 0.05) * (around.every((m) => own.has(m)) ? 1 : 0.3) * (0.5 + rng()); + if (score > best) { best = score; start = k; } + } + if (!start) break; + const patch = new Set(); + const add = (k: string) => { + work.set(k, pick(names, rng())!); + patch.add(k); + taken.add(k); + }; + add(start); + while (patch.size < size) { + // Grow onto a free cell that touches no other patch of this type. + const options = [...new Set([...patch].flatMap(nbrs))].filter((k) => free(k) && nbrs(k).every((m) => patch.has(m) || typeAt(m) !== type)).sort(); + if (!options.length) break; + add(options[Math.floor(rng() * options.length)]); + } + have++; + } + } +} + +interface ShoreInput { + layout: RegionLayout; + parent: [number, number]; + /** The region's own (unpinned) cells: the only cells changed. */ + cells: [number, number][]; + work: Map; + terrainAt: (key: string) => string | undefined; + typeOf: (terrain: string) => string | undefined; + /** The region's own (shore) biome. */ + profile: BiomeProfile; + profiles: ReadonlyMap; + field: BlendField; + pinned: ReadonlyMap; + sharpness: number; + seed: number; +} + +/** How sharply a cell leans toward the neighbour it faces: exp(SHORE_LEAN · projection), as in hex-wfc's directional blend. */ +const SHORE_LEAN = 1.6; +/** Raggedness of the coastline (noise added to a cell's landness). */ +const SHORE_RAGGED = 0.12; + +/** Land share of a biome profile: its landShare, else its non-water type shares. */ +function profileLand(p: BiomeProfile | undefined): number | undefined { + if (!p) return undefined; + if (p.landShare !== undefined) return p.landShare; + let land = 0; + for (const [t, v] of p.types) if (!WATER_TYPES.includes(t)) land += v; + return land; +} + +/** + * Each neighbouring region's land share, by parent hex: from its cells + * already painted (pinned) when there are some, else from its biome's mix. + */ +export function neighbourLand( + layout: RegionLayout, + parent: [number, number], + pinned: ReadonlyMap, + biomes: ReadonlyMap, + profiles: ReadonlyMap, + typeOf: (terrain: string) => string | undefined, +): { hex: [number, number]; land: number }[] { + const painted = new Map(); + for (const [k, t] of pinned) { + const [x, y] = k.split("_").map(Number); + const pk = parentOf(layout, x, y).join("_"); + const ty = typeOf(t); + if (!ty) continue; + const c = painted.get(pk) ?? { land: 0, all: 0 }; + c.all++; + if (!WATER_TYPES.includes(ty)) c.land++; + painted.set(pk, c); + } + const out: { hex: [number, number]; land: number }[] = []; + for (const [qx, qy] of neighbourRegions(layout, parent[0], parent[1])) { + const pk = `${qx}_${qy}`; + const c = painted.get(pk); + if (c && c.all >= 3) { out.push({ hex: [qx, qy], land: c.land / c.all }); continue; } + const b = biomes.get(pk); + const land = profileLand(b ? profiles.get(b) : undefined); + if (land !== undefined) out.push({ hex: [qx, qy], land }); + } + return out; +} + +/** + * A shoreline region (a biome with `shore`): the region's land goes toward + * its land-heavy neighbours and its water toward the others, with a coast + * band between. + * + * 1. Each neighbouring region's land share (neighbourLand). Each own cell's + * landness is those shares weighted by exp(1.6 · projection) of the cell + * onto the direction of each neighbour (hex-wfc's directional blend), so + * a cell leans toward the neighbour it faces; plus a little smooth noise + * so the coastline is ragged. + * 2. With no land neighbour to lean on (all within 0.15 of each other, or + * none known), one side picked from the seed is made land (a mostly + * water neighbourhood) or water (a mostly land one): a water region + * with a ragged coast along that side, never an island. + * 3. The most landward cells become land: the biome's land-share when set, + * else the mean landness (between 15% and 85%). + * 4. Land cells next to water take the biome's land shore type (coast), + * water cells next to land its water one (shallows); other land cells + * keep a land terrain or take one from the field (so they look like the + * land neighbour); other water cells likewise. + * + * Only the region's own cells change. Deterministic for a seed. + */ +export function placeShore(input: ShoreInput): void { + const { layout, parent, work, terrainAt, typeOf, profile, profiles, field } = input; + const own = new Set(input.cells.map(([x, y]) => `${x}_${y}`)); + const ownList = [...own].sort(); + if (!ownList.length) return; + const water = new Set(WATER_TYPES); + const isWaterType = (t: string | undefined) => t !== undefined && water.has(t); + + // 1–2. Neighbours and their land. + const sides = neighbourLand(layout, parent, input.pinned, field.biomes, profiles, typeOf); + const [cx, cy] = regionCentrePoint(layout, parent[0], parent[1]); + const dirs = sides.map((s) => { + const [qx, qy] = regionCentrePoint(layout, s.hex[0], s.hex[1]); + const len = Math.hypot(qx - cx, qy - cy) || 1; + return { ux: (qx - cx) / len, uy: (qy - cy) / len, land: s.land }; + }); + const lands = dirs.map((d) => d.land); + if (!dirs.length || Math.max(...lands) - Math.min(...lands) < 0.15) { + const mean = lands.length ? lands.reduce((a, b) => a + b, 0) / lands.length : 0; + const all = neighbourRegions(layout, parent[0], parent[1]); + const pickHex = all[Math.floor(hash2(input.seed >>> 0, parent[0], parent[1]) * all.length) % all.length]; + const [qx, qy] = regionCentrePoint(layout, pickHex[0], pickHex[1]); + const len = Math.hypot(qx - cx, qy - cy) || 1; + const towardLand = mean < 0.5; + if (!dirs.length) { + // Nothing known around: water everywhere but the one land side. + for (const [ax, ay] of all) { + if (ax === pickHex[0] && ay === pickHex[1]) continue; + const [bx, by] = regionCentrePoint(layout, ax, ay); + const l = Math.hypot(bx - cx, by - cy) || 1; + dirs.push({ ux: (bx - cx) / l, uy: (by - cy) / l, land: 0 }); + } + } + dirs.push({ ux: (qx - cx) / len, uy: (qy - cy) / len, land: towardLand ? 1 : 0 }); + } + + const radius = regionSpacing(layout) / 2 || 1; + const f = 1.4 / (radius * 2); + const landness = new Map(); + for (const k of ownList) { + const [x, y] = k.split("_").map(Number); + const [px, py] = childPoint(layout, x, y); + const vx = (px - cx) / radius, vy = (py - cy) / radius; + let sw = 0, sl = 0; + for (const d of dirs) { + const w = Math.exp(SHORE_LEAN * (vx * d.ux + vy * d.uy)); + sw += w; + sl += w * d.land; + } + const noise = (fbm((input.seed ^ 0x51ed) >>> 0, px * f, py * f, 2) - 0.5) * 2 * SHORE_RAGGED; + landness.set(k, sl / sw + noise); + } + + // 3. The most landward cells are land. + const mean = ownList.reduce((s, k) => s + landness.get(k)!, 0) / ownList.length; + const target = profile.landShare ?? Math.min(0.85, Math.max(0.15, mean)); + const order = [...ownList].sort((a, b) => landness.get(b)! - landness.get(a)! || (a < b ? -1 : 1)); + const landCount = Math.round(target * ownList.length); + const isLandCell = new Map(order.map((k, i) => [k, i < landCount])); + + // 4. Terrain for each cell. + const rng = mulberry32(cellSeed(input.seed ^ 0x1f83d9ab, parent[0], parent[1])); + const nbrs = (k: string): string[] => { + const [x, y] = k.split("_").map(Number); + return childNeighbours(layout, x, y).map(([a, b]) => `${a}_${b}`); + }; + /** Is a neighbouring cell land? Own cells by the plan, others by their terrain. */ + const landAt = (k: string): boolean | undefined => { + if (isLandCell.has(k)) return isLandCell.get(k); + const t = terrainAt(k); + const ty = t ? typeOf(t) : undefined; + return ty === undefined ? undefined : !water.has(ty); + }; + const has = (type: string) => !!profile.names.get(type)?.size; + const landShore = SHORE_TYPES.find((t) => !water.has(t) && has(t)); + const waterShore = SHORE_TYPES.find((t) => water.has(t) && has(t)); + const shoreSet = new Set(SHORE_TYPES); + const nameFor = (k: string, wantLand: boolean): string | undefined => { + const [x, y] = k.split("_").map(Number); + const phi = field.at(x, y); + const ok = (t: string) => t !== "settlement" && !shoreSet.has(t) && (wantLand ? !water.has(t) : water.has(t)); + let odds = new Map([...typeMix(phi, profiles)].filter(([t]) => ok(t))); + if (!odds.size) odds = new Map([...profile.types].filter(([t]) => ok(t))); + if (!odds.size) { + const fallback = wantLand ? landShore : waterShore; + return fallback ? pick(profile.names.get(fallback)!, rng()) : undefined; + } + const type = pick(odds, rng())!; + const names = namesWithinType(phi, profiles, type, input.sharpness); + return pick(names.size ? names : profile.names.get(type) ?? new Map(), rng()); + }; + for (const k of ownList) { + const land = isLandCell.get(k)!; + const around = nbrs(k).map(landAt); + const cur = work.get(k); + const curType = cur ? typeOf(cur) : undefined; + let next: string | undefined; + if (land && landShore && around.some((v) => v === false)) next = curType === landShore ? cur : pick(profile.names.get(landShore)!, rng()); + else if (!land && waterShore && around.some((v) => v === true)) next = curType === waterShore ? cur : pick(profile.names.get(waterShore)!, rng()); + else if (curType !== undefined && !shoreSet.has(curType) && curType !== "settlement" && isWaterType(curType) === !land) next = cur; + else next = nameFor(k, land); + if (next) work.set(k, next); + } +} + /** Spiral order from a centre hex: the order regions are generated in (each pins the earlier ones). */ export function spiralOrder(hexes: [number, number][], centre: [number, number], distance: (a: [number, number], b: [number, number]) => number): [number, number][] { return [...hexes].sort((a, b) => distance(a, centre) - distance(b, centre) || a[1] - b[1] || a[0] - b[0]); diff --git a/tests/biomeNotes.test.ts b/tests/biomeNotes.test.ts index 644c8583..bb5fc443 100644 --- a/tests/biomeNotes.test.ts +++ b/tests/biomeNotes.test.ts @@ -133,9 +133,10 @@ describe("biome note format", () => { // ── presets ────────────────────────────────────────────────────────────── describe("shipped biome presets", () => { - it("cover every built-in biome with the same label", () => { - expect(BIOME_PRESETS.map((b) => b.id)).toEqual(BIOMES.map((b) => b.id)); - for (const p of BIOME_PRESETS) expect(p.label).toBe(BIOMES.find((b) => b.id === p.id)!.label); + it("cover every built-in biome with the same label (Coast is note-only)", () => { + expect(BIOME_PRESETS.map((b) => b.id).filter((id) => id !== "coast")).toEqual(BIOMES.map((b) => b.id)); + for (const b of BIOMES) expect(BIOME_PRESETS.find((p) => p.id === b.id)!.label).toBe(b.label); + expect(BIOME_PRESETS.find((p) => p.id === "coast")!.shore).toBe(true); }); it("as notes, give the same transitions as the old table", () => { @@ -172,7 +173,7 @@ describe("shipped biome presets", () => { const before = representableBiomes(DEFAULT_TERRAIN_PALETTE); setBiomeSource(BIOME_PRESETS); try { - expect(representableBiomes(DEFAULT_TERRAIN_PALETTE)).toEqual(before); + expect(representableBiomes(DEFAULT_TERRAIN_PALETTE)).toEqual(new Set([...before, "coast"])); } finally { setBiomeSource(undefined); } @@ -411,10 +412,10 @@ describe("biome form model", () => { expect(fieldsFromForm(s)).toEqual({ id: "tundra", label: "Tundra", color: "#7a9a5a", mix: [{ type: "desert", weight: 5 }], transitions: [] }); }); - it("routes: blend, or a generator marked as waiting for generator regions", () => { + it("routes: blend, or the linked generator", () => { expect(regionGenerator({})).toEqual({ kind: "blend" }); - expect(regionGenerator(GLASS)).toEqual({ kind: "generator", generator: GLASS.generator, ready: false }); - expect(routeNote(GLASS)).toMatch(/^Uses Glass dunes: available once generator regions land/); + expect(regionGenerator(GLASS)).toEqual({ kind: "generator", generator: GLASS.generator, ready: true }); + expect(routeNote(GLASS)).toMatch(/^Made by Glass dunes/); expect(routeNote({})).toBeUndefined(); }); From d4822ed61bb6864a1a0bf6b91e75f996f9da5f24 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 00:37:12 -0400 Subject: [PATCH 261/558] feat(biomes #50): biome climates drive World biomes placement Biome notes get optional climate keys (temperature, moisture, elevation, coastal, chance, rare), read forgivingly with problems reported and written normalised (words when the ends fall on word bands). The shipped biomes carry today's placement rules as climate DATA in biomePresets.ts; worldBiomes picks from every biome with a climate (no names in the code), so a user biome with a climate is placed like a built-in and one without is only placed by hand. Built-in notes written before climates get the shipped climate once (biomeClimatesSeeded). Tests: parse/normalise, exact reproduction of the old placement (frozen copy in tests/fixtures) on Expanded and Limited, user biome placed in its band, no-climate biome never placed. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/overworld/BiomeStore.ts | 49 ++++ src/overworld/biomeClimate.ts | 254 ++++++++++++++++ src/overworld/biomeNote.ts | 13 +- src/overworld/biomePresets.ts | 42 +-- src/overworld/biomes.ts | 26 ++ src/overworld/worldBiomes.ts | 231 ++++++++++++--- src/types.ts | 10 +- tests/biomeClimate.test.ts | 238 +++++++++++++++ tests/fixtures/worldBiomesLegacy.ts | 433 ++++++++++++++++++++++++++++ tests/overworldBiomes.test.ts | 3 +- 11 files changed, 1231 insertions(+), 72 deletions(-) create mode 100644 src/overworld/biomeClimate.ts create mode 100644 tests/biomeClimate.test.ts create mode 100644 tests/fixtures/worldBiomesLegacy.ts diff --git a/package.json b/package.json index f66a1553..e1187b0c 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeClimate.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeClimate.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/overworld/BiomeStore.ts b/src/overworld/BiomeStore.ts index 738bc713..d86aa013 100644 --- a/src/overworld/BiomeStore.ts +++ b/src/overworld/BiomeStore.ts @@ -23,6 +23,7 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import { normalizeFolder } from "../utils"; import { writeJsonBackup } from "../backup"; import { + BIOME_NOTE_MARKER, biomeFileName, biomeSlug, buildBiomeNote, @@ -61,6 +62,28 @@ export function presetsToSeed( return { write, done }; } +/** + * Shipped biomes whose notes (written before biome climates) get their + * preset climate added: not done before, the note has the preset's id and + * no climate of its own. Once per biome, so clearing a climate by hand + * sticks (that biome is then only placed by hand). + */ +export function climatesToAdd( + done: readonly string[], + notes: readonly BiomeNoteFields[], + presets: readonly BiomeNoteFields[] = BIOME_PRESETS, +): { add: BiomeNoteFields[]; done: string[] } { + const add: BiomeNoteFields[] = []; + const now: string[] = []; + for (const p of presets) { + if (!p.climate || done.includes(p.id)) continue; + now.push(p.id); + const note = notes.find((n) => n.id === p.id); + if (note && !note.climate) add.push({ ...note, climate: biomePreset(p.id)?.climate }); + } + return { add, done: now }; +} + export class BiomeStore implements BiomeStoreApi { private entries = new Map(); private lastContent = new Map(); @@ -92,6 +115,7 @@ export class BiomeStore implements BiomeStoreApi { await this.enqueue(async () => { for (const f of this.files()) await this.load(f); await this.seed(); + await this.seedClimates(); this.ready = true; this.publish(); }); @@ -339,6 +363,31 @@ export class BiomeStore implements BiomeStoreApi { await this.plugin.saveSettings(); } + /** Add the shipped climates to built-in notes written before climates existed (climatesToAdd). */ + private async seedClimates(): Promise { + const s = this.plugin.settings; + const done = s.biomeClimatesSeeded ?? []; + const plan = climatesToAdd(done, this.active().map((e) => e.fields)); + if (!plan.done.length) return; + for (const fields of plan.add) { + const e = this.active().find((x) => x.fields.id === fields.id); + const f = e ? this.plugin.app.vault.getAbstractFileByPath(e.path) : null; + if (!(f instanceof TFile)) continue; + try { + const content = await this.plugin.app.vault.read(f); + // Only notes the plugin wrote (they carry its marker key); a note the user wrote by hand is theirs. + if (!new RegExp(`^${BIOME_NOTE_MARKER}\\s*:`, "m").test(content.split(/\r?\n---/)[0] ?? "")) continue; + const next = updateBiomeNote(content, fields); + if (next !== content) await this.plugin.app.vault.modify(f, next); + this.take(f.path, f.basename, next); + } catch (err) { + console.error("Hexmaker: couldn't add a climate to biome note", f.path, err); + } + } + s.biomeClimatesSeeded = [...done, ...plan.done]; + await this.plugin.saveSettings(); + } + private async ensureFolder(folder: string): Promise { const vault = this.plugin.app.vault; const parts = folder.split("/"); diff --git a/src/overworld/biomeClimate.ts b/src/overworld/biomeClimate.ts new file mode 100644 index 00000000..c84a64ff --- /dev/null +++ b/src/overworld/biomeClimate.ts @@ -0,0 +1,254 @@ +/** + * A biome's climate (#50): where World biomes may place it on a generated + * overworld. Optional plain keys in the biome note's frontmatter: + * + * temperature: cold–mild (cold, cool, mild, warm, hot, or 0.2–0.5) + * moisture: wet (dry, moderate, wet, or 0.6–1) + * elevation: low (sea, low, mid, high, or mouth) + * coastal: yes (only next to the coast) + * chance: 50% (share of the fitting hexes it takes) + * rare: yes (at most one hex per ~20) + * + * A biome with none of temperature / moisture / elevation / coastal is + * never placed by the generator, only by hand. Built-in biomes carry + * theirs as data (biomePresets.ts); nothing here knows any biome by name. + * + * How the generator uses it (worldBiomes.ts): each hex is in one band of + * height (high: the top of the land; mid: hills; low: the rest; sea; and + * the river's mouth). The biomes of a band whose temperature and moisture + * contain the hex's are tried rarest first, then narrowest: one roll per + * hex, and the first biome whose chance is above the roll takes it. When + * none does, the hex falls to the next band down. + * + * Reading is forgiving: en dash, hyphen, "to" or ".." between the ends; + * percents or 0–1; a range written backwards is turned round. Anything + * unreadable is reported and left out (the hex just isn't limited by it). + * + * Pure: no Obsidian imports. + */ + +export interface ClimateRange { + /** 0..1, inclusive. */ + lo: number; + /** 0..1, exclusive (inclusive at 1). */ + hi: number; +} + +export type ClimateElevation = "sea" | "low" | "mid" | "high" | "mouth"; +export const CLIMATE_ELEVATIONS: readonly ClimateElevation[] = ["sea", "low", "mid", "high", "mouth"]; + +export interface BiomeClimate { + /** Unset: any temperature. */ + temperature?: ClimateRange; + /** Unset: any moisture. */ + moisture?: ClimateRange; + /** Unset (with other climate keys set): low. */ + elevation?: ClimateElevation; + /** Only hexes next to the coast (land by the sea, or sea by land). */ + coastal?: boolean; + /** Share of the fitting hexes it takes, 0..1; unset = all of them. */ + chance?: number; + /** At most one hex per ~20 on an overworld. */ + rare?: boolean; +} + +export interface ClimateProblem { + key: string; + text: string; +} + +/** Word bands, cold → hot. */ +export const TEMPERATURE_WORDS: readonly [string, number, number][] = [ + ["cold", 0, 0.2], + ["cool", 0.2, 0.4], + ["mild", 0.4, 0.6], + ["warm", 0.6, 0.8], + ["hot", 0.8, 1], +]; +/** Word bands, dry → wet. */ +export const MOISTURE_WORDS: readonly [string, number, number][] = [ + ["dry", 0, 1 / 3], + ["moderate", 1 / 3, 2 / 3], + ["wet", 2 / 3, 1], +]; + +const ELEVATION_ALIASES: Record = { + sea: "sea", ocean: "sea", water: "sea", + low: "low", lowland: "low", lowlands: "low", plain: "low", plains: "low", + mid: "mid", middle: "mid", hills: "mid", hill: "mid", upland: "mid", uplands: "mid", + high: "high", peak: "high", peaks: "high", highland: "high", highlands: "high", + mouth: "mouth", "river mouth": "mouth", "river-mouth": "mouth", delta: "mouth", +}; + +const near = (a: number, b: number) => Math.abs(a - b) < 1e-6; +const fmtNum = (n: number) => String(Math.round(n * 1000) / 1000); + +/** One end of a range: a word band, or a number (percent, or 0–1). */ +function readEnd(raw: string, words: readonly [string, number, number][]): { lo: number; hi: number; word: boolean } | undefined { + const t = raw.trim().toLowerCase(); + const w = words.find(([name]) => name === t); + if (w) return { lo: w[1], hi: w[2], word: true }; + const pct = t.endsWith("%"); + const n = Number(t.replace(/%$/, "").trim()); + if (!t || !Number.isFinite(n)) return undefined; + const v = pct || n > 1 ? n / 100 : n; + return v >= 0 && v <= 1 ? { lo: v, hi: v, word: false } : undefined; +} + +/** + * "cold–mild", "wet", "0.2–0.5", "20% to 50%" → a range; "any" or blank → + * undefined with no problem. Problems name what was wrong. + */ +export function parseClimateRange(raw: string, words: readonly [string, number, number][]): { range?: ClimateRange; problem?: string } { + const t = raw.trim().toLowerCase(); + if (!t || t === "any") return {}; + const parts = t.split(/\s*(?:–|—|\.\.|\bto\b|(?<=[a-z%\d.])\s*-\s*(?=[a-z\d.]))\s*/).filter((p) => p !== ""); + const names = words.map(([n]) => n).join(", "); + if (parts.length > 2) return { problem: `"${raw.trim()}" should be one band or a range like ${words[0][0]}–${words[1][0]}` }; + const ends = parts.map((p) => readEnd(p, words)); + if (ends.some((e) => !e)) return { problem: `"${raw.trim()}" should use ${names}, or numbers from 0 to 1` }; + const [a, b] = ends as { lo: number; hi: number; word: boolean }[]; + if (!b) { + if (!a.word) return { problem: `"${raw.trim()}" needs two ends, like 0.2–0.5` }; + return { range: { lo: a.lo, hi: a.hi } }; + } + // Word ends span their whole band; number ends are the number. + let lo = a.lo, hi = b.hi; + let problem: string | undefined; + if (lo > hi) { + // Written backwards ("mild–cold"): turned round. + problem = `"${raw.trim()}" runs backwards; read the other way round`; + lo = b.lo; + hi = a.hi; + } + if (near(lo, hi)) return { problem: `"${raw.trim()}" is empty (both ends are the same)` }; + return { range: { lo, hi }, problem }; +} + +/** A range as written: words when its ends fall on word bands, else numbers. */ +export function formatClimateRange(r: ClimateRange, words: readonly [string, number, number][]): string { + const from = words.find(([, lo]) => near(lo, r.lo)); + const to = words.find(([, , hi]) => near(hi, r.hi)); + if (from && to) return from === to ? from[0] : `${from[0]}–${to[0]}`; + return `${fmtNum(r.lo)}–${fmtNum(r.hi)}`; +} + +/** Whether a range is the whole 0–1 (says nothing). */ +const isAll = (r: ClimateRange | undefined) => !r || (near(r.lo, 0) && near(r.hi, 1)); + +/** "yes" / "no" and friends; undefined when neither. */ +export function readYesNoWord(raw: string): boolean | undefined { + const t = raw.trim().toLowerCase(); + if (["yes", "y", "true", "on", "1"].includes(t)) return true; + if (["no", "n", "false", "off", "0"].includes(t)) return false; + return undefined; +} + +/** "50%", "0.5", "50" → 0.5; NaN when unreadable. */ +function readChance(raw: string): number { + const t = raw.trim(); + const pct = t.endsWith("%"); + const n = Number(t.replace(/%$/, "").trim()); + if (!t || !Number.isFinite(n)) return NaN; + const v = pct || n > 1 ? n / 100 : n; + return v >= 0 && v <= 1 ? v : NaN; +} + +/** The climate keys this file owns, in writing order. */ +export const CLIMATE_KEYS = ["temperature", "moisture", "elevation", "coastal", "chance", "rare"] as const; + +/** Read the climate keys from a note's (lower-cased) frontmatter. Undefined when none is set. */ +export function readClimate(fm: ReadonlyMap): { climate?: BiomeClimate; problems: ClimateProblem[] } { + const problems: ClimateProblem[] = []; + const c: BiomeClimate = {}; + const temp = fm.get("temperature"); + if (temp !== undefined) { + const r = parseClimateRange(temp, TEMPERATURE_WORDS); + if (r.range && !isAll(r.range)) c.temperature = r.range; + if (r.problem) problems.push({ key: "temperature", text: r.problem }); + } + const moist = fm.get("moisture"); + if (moist !== undefined) { + const r = parseClimateRange(moist, MOISTURE_WORDS); + if (r.range && !isAll(r.range)) c.moisture = r.range; + if (r.problem) problems.push({ key: "moisture", text: r.problem }); + } + const elev = fm.get("elevation")?.trim().toLowerCase(); + if (elev) { + const e = ELEVATION_ALIASES[elev]; + if (e) c.elevation = e; + else problems.push({ key: "elevation", text: `elevation should be sea, low, mid, high or mouth, not "${elev}"` }); + } + const coastal = fm.get("coastal"); + if (coastal) { + const v = readYesNoWord(coastal); + if (v === undefined) problems.push({ key: "coastal", text: `coastal should be yes or no, not "${coastal}"` }); + else if (v) c.coastal = true; + } + const chance = fm.get("chance"); + if (chance) { + const v = readChance(chance); + if (Number.isFinite(v)) { if (v < 1) c.chance = v; } + else problems.push({ key: "chance", text: `chance should be a share like 50%, not "${chance}"` }); + } + const rare = fm.get("rare"); + if (rare) { + const v = readYesNoWord(rare); + if (v === undefined) problems.push({ key: "rare", text: `rare should be yes or no, not "${rare}"` }); + else if (v) c.rare = true; + } + return { climate: Object.keys(c).length ? c : undefined, problems }; +} + +/** The climate keys' values as written (undefined = not written). */ +export function climateKeyValues(c: BiomeClimate | undefined): [string, string | undefined][] { + return [ + ["temperature", c?.temperature && !isAll(c.temperature) ? formatClimateRange(c.temperature, TEMPERATURE_WORDS) : undefined], + ["moisture", c?.moisture && !isAll(c.moisture) ? formatClimateRange(c.moisture, MOISTURE_WORDS) : undefined], + ["elevation", c?.elevation], + ["coastal", c?.coastal ? "yes" : undefined], + ["chance", c?.chance !== undefined && c.chance < 1 ? `${fmtNum(c.chance * 100)}%` : undefined], + ["rare", c?.rare ? "yes" : undefined], + ]; +} + +/** Whether a written climate value reads the same as another (keeps the user's spelling). */ +export function sameClimateValue(key: string, cur: string, want: string): boolean { + const one = (v: string) => { + const m = new Map([[key, v]]); + return JSON.stringify(climateKeyValues(readClimate(m).climate)); + }; + return one(cur) === one(want); +} + +/** Whether the generator may place this biome (any placement key set). */ +export function isPlaceable(c: BiomeClimate | undefined): boolean { + return !!c && (c.temperature !== undefined || c.moisture !== undefined || c.elevation !== undefined || !!c.coastal); +} + +/** Whether a value lies in a range (the top end counts at 1). */ +export function inClimateRange(r: ClimateRange | undefined, v: number): boolean { + if (!r) return true; + return v >= r.lo && (v < r.hi || (r.hi >= 1 - 1e-9 && v <= 1)); +} + +/** Area of a climate's temperature × moisture box (1 = any climate). */ +export function climateArea(c: BiomeClimate): number { + const span = (r?: ClimateRange) => (r ? Math.max(0, r.hi - r.lo) : 1); + return span(c.temperature) * span(c.moisture); +} + +/** The middle of a climate's box. */ +export function climateCentre(c: BiomeClimate): [number, number] { + const mid = (r?: ClimateRange) => (r ? (r.lo + r.hi) / 2 : 0.5); + return [mid(c.temperature), mid(c.moisture)]; +} + +/** A copy (callers may change it). */ +export function copyClimate(c: BiomeClimate | undefined): BiomeClimate | undefined { + if (!c) return undefined; + const out: BiomeClimate = { ...c }; + if (c.temperature) out.temperature = { ...c.temperature }; + if (c.moisture) out.moisture = { ...c.moisture }; + return out; +} diff --git a/src/overworld/biomeNote.ts b/src/overworld/biomeNote.ts index b186a557..ab93e913 100644 --- a/src/overworld/biomeNote.ts +++ b/src/overworld/biomeNote.ts @@ -51,6 +51,8 @@ * Pure: no Obsidian imports. */ +import { climateKeyValues, readClimate, sameClimateValue, type BiomeClimate } from "./biomeClimate"; + /** Frontmatter key written into every biome note (the format version). */ export const BIOME_NOTE_MARKER = "hexmaker-biome"; export const BIOME_NOTE_FORMAT = 1; @@ -90,6 +92,8 @@ export interface BiomeNoteFields { minIslands?: number; /** Link target of a generator note (no brackets), e.g. "world/generators/My tundra". */ generator?: string; + /** Where World biomes may place it (biomeClimate.ts); unset = only by hand. */ + climate?: BiomeClimate; } export interface BiomeNoteProblem { @@ -117,7 +121,7 @@ export function biomeFileName(label: string): string { export const BIOME_HELP = [ "> [!info] Biome", - "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `generator` links a generator note. Delete a row to drop it.", + "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `generator` links a generator note. For generated overworlds (optional): `temperature` (cold, cool, mild, warm, hot, or 0.2–0.5), `moisture` (dry, moderate, wet), `elevation` (sea, low, mid, high, mouth), `coastal: yes`, `chance` (like 50%) and `rare: yes`; without them the biome is only placed by hand. Delete a row to drop it.", ]; // ── reading ────────────────────────────────────────────────────────────── @@ -247,6 +251,9 @@ export function parseBiomeNote(content: string, basename: string): ParsedBiomeNo } const gen = fm.get("generator"); if (gen && linkTarget(gen)) fields.generator = linkTarget(gen); + const climate = readClimate(fm); + if (climate.climate) fields.climate = climate.climate; + for (const p of climate.problems) problems.push({ where: "settings", text: p.text }); const mix = findTable(lines, isMix); if (mix) { @@ -308,6 +315,7 @@ function ownKeys(f: BiomeNoteFields): [string, string | undefined][] { ["land-share", f.landShare !== undefined ? shareText(f.landShare) : undefined], ["min-islands", f.minIslands !== undefined ? String(f.minIslands) : undefined], ["generator", f.generator ? `"[[${f.generator}]]"` : undefined], + ...climateKeyValues(f.climate), ]; } @@ -368,12 +376,15 @@ export function updateBiomeNote(content: string, f: BiomeNoteFields): string { return out === content.replace(/\r\n?/g, "\n").split("\n").join(eol) ? content : out; } +const CLIMATE_KEY_SET = new Set(climateKeyValues(undefined).map(([k]) => k)); + function sameValue(key: string, cur: string, want: string): boolean { const w = unquote(want); if (key === "land-share") return parseShare(cur) === parseShare(w); if (key === "colour") return readColour(cur) === readColour(w); if (key === "generator") return linkTarget(cur) === linkTarget(w); if (key === "id") return biomeSlug(cur) === biomeSlug(w); + if (CLIMATE_KEY_SET.has(key)) return sameClimateValue(key, cur, w); return cur.trim() === w.trim(); } diff --git a/src/overworld/biomePresets.ts b/src/overworld/biomePresets.ts index 721232bf..905f3c52 100644 --- a/src/overworld/biomePresets.ts +++ b/src/overworld/biomePresets.ts @@ -14,29 +14,35 @@ */ import type { BiomeNoteFields } from "./biomeNote"; +import { copyClimate } from "./biomeClimate"; export const BIOME_PRESETS: readonly BiomeNoteFields[] = [ - { id: "tundra", label: "Tundra", color: "#e0f2fe", mix: [{ type: "snow", weight: 26 }, { type: "hills", weight: 21 }, { type: "grassland", weight: 21 }, { type: "water", weight: 10 }, { type: "peaks", weight: 6 }, { type: "wetland", weight: 6 }, { type: "desert", weight: 4 }, { type: "forest", weight: 3 }, { type: "mountains", weight: 3 }], transitions: [{ next: "Temperate forest", between: "Taiga" }, { next: "Deep forest", between: "Taiga" }, { next: "Grassland", between: "Taiga" }, { next: "Jungle", between: "Grassland" }, { next: "Savanna", between: "Grassland" }, { next: "Badlands", between: "Grassland" }] }, - { id: "taiga", label: "Taiga", color: "#428a5e", mix: [{ type: "forest", weight: 63 }, { type: "hills", weight: 13 }, { type: "water", weight: 12 }, { type: "wetland", weight: 7 }, { type: "snow", weight: 3 }, { type: "mountains", weight: 2 }], transitions: [{ next: "Jungle", between: "Temperate forest" }, { next: "Badlands", between: "Grassland" }] }, - { id: "temperate-forest", label: "Temperate forest", color: "#2d9553", mix: [{ type: "forest", weight: 67 }, { type: "hills", weight: 17 }, { type: "grassland", weight: 8 }, { type: "water", weight: 5 }, { type: "wetland", weight: 3 }], transitions: [] }, - { id: "deep-forest", label: "Deep forest", color: "#257445", mix: [{ type: "forest", weight: 80 }, { type: "hills", weight: 14 }, { type: "grassland", weight: 3 }, { type: "wetland", weight: 3 }], transitions: [] }, - { id: "grassland", label: "Grassland", color: "#69a168", mix: [{ type: "grassland", weight: 59 }, { type: "hills", weight: 17 }, { type: "forest", weight: 9 }, { type: "desert", weight: 4 }, { type: "water", weight: 4 }, { type: "wetland", weight: 4 }, { type: "mountains", weight: 4 }], transitions: [{ next: "Alpine", between: "Valley" }] }, - { id: "savanna", label: "Savanna", color: "#c4b25c", mix: [{ type: "grassland", weight: 46 }, { type: "desert", weight: 26 }, { type: "jungle", weight: 10 }, { type: "hills", weight: 7 }, { type: "forest", weight: 6 }, { type: "wetland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Alpine", between: "Valley" }] }, - { id: "jungle", label: "Jungle", color: "#15803d", mix: [{ type: "jungle", weight: 63 }, { type: "wetland", weight: 14 }, { type: "hills", weight: 11 }, { type: "mountains", weight: 6 }, { type: "water", weight: 4 }, { type: "grassland", weight: 2 }], transitions: [{ next: "Badlands", between: "Savanna" }] }, - { id: "badlands", label: "Badlands", color: "#c2410c", mix: [{ type: "badlands", weight: 42 }, { type: "desert", weight: 26 }, { type: "mountains", weight: 21 }, { type: "hills", weight: 7 }, { type: "coast", weight: 4 }], transitions: [] }, - { id: "swamp", label: "Swamp", color: "#909f23", mix: [{ type: "wetland", weight: 62 }, { type: "forest", weight: 21 }, { type: "water", weight: 10 }, { type: "grassland", weight: 6 }, { type: "shallows", weight: 2 }], transitions: [{ next: "Badlands", between: "Grassland" }, { next: "Alpine", between: "Valley" }] }, - { id: "river-delta", label: "River delta", color: "#5f9a7a", mix: [{ type: "wetland", weight: 39 }, { type: "water", weight: 32 }, { type: "shallows", weight: 13 }, { type: "grassland", weight: 10 }, { type: "coast", weight: 4 }, { type: "forest", weight: 2 }], transitions: [] }, - { id: "valley", label: "Valley", color: "#e0e8a1", mix: [{ type: "grassland", weight: 34 }, { type: "hills", weight: 21 }, { type: "mountains", weight: 18 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 11 }, { type: "water", weight: 3 }, { type: "wetland", weight: 2 }], transitions: [] }, - { id: "karst", label: "Karst", color: "#4ade80", mix: [{ type: "grassland", weight: 30 }, { type: "hills", weight: 24 }, { type: "mountains", weight: 18 }, { type: "forest", weight: 17 }, { type: "water", weight: 5 }, { type: "badlands", weight: 4 }, { type: "wetland", weight: 2 }], transitions: [] }, - { id: "alpine", label: "Alpine", color: "#bfdbfe", mix: [{ type: "mountains", weight: 44 }, { type: "peaks", weight: 20 }, { type: "hills", weight: 18 }, { type: "forest", weight: 9 }, { type: "snow", weight: 4 }, { type: "grassland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Jungle", between: "Karst" }] }, - { id: "volcanic", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1 }], transitions: [] }, - { id: "coastal-fjord", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [] }, - { id: "archipelago", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [], landShare: 0.3, minIslands: 2 }, - { id: "open-sea", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20 }], transitions: [] }, + { id: "tundra", label: "Tundra", color: "#e0f2fe", mix: [{ type: "snow", weight: 26 }, { type: "hills", weight: 21 }, { type: "grassland", weight: 21 }, { type: "water", weight: 10 }, { type: "peaks", weight: 6 }, { type: "wetland", weight: 6 }, { type: "desert", weight: 4 }, { type: "forest", weight: 3 }, { type: "mountains", weight: 3 }], transitions: [{ next: "Temperate forest", between: "Taiga" }, { next: "Deep forest", between: "Taiga" }, { next: "Grassland", between: "Taiga" }, { next: "Jungle", between: "Grassland" }, { next: "Savanna", between: "Grassland" }, { next: "Badlands", between: "Grassland" }], climate: { temperature: { lo: 0, hi: 0.36 }, elevation: "low" } }, + { id: "taiga", label: "Taiga", color: "#428a5e", mix: [{ type: "forest", weight: 63 }, { type: "hills", weight: 13 }, { type: "water", weight: 12 }, { type: "wetland", weight: 7 }, { type: "snow", weight: 3 }, { type: "mountains", weight: 2 }], transitions: [{ next: "Jungle", between: "Temperate forest" }, { next: "Badlands", between: "Grassland" }], climate: { temperature: { lo: 0.18, hi: 0.36 }, moisture: { lo: 0.45, hi: 1 }, elevation: "low" } }, + { id: "temperate-forest", label: "Temperate forest", color: "#2d9553", mix: [{ type: "forest", weight: 67 }, { type: "hills", weight: 17 }, { type: "grassland", weight: 8 }, { type: "water", weight: 5 }, { type: "wetland", weight: 3 }], transitions: [], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0.3, hi: 0.62 }, elevation: "low" } }, + { id: "deep-forest", label: "Deep forest", color: "#257445", mix: [{ type: "forest", weight: 80 }, { type: "hills", weight: 14 }, { type: "grassland", weight: 3 }, { type: "wetland", weight: 3 }], transitions: [], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0.62, hi: 0.8 }, elevation: "low" } }, + { id: "grassland", label: "Grassland", color: "#69a168", mix: [{ type: "grassland", weight: 59 }, { type: "hills", weight: 17 }, { type: "forest", weight: 9 }, { type: "desert", weight: 4 }, { type: "water", weight: 4 }, { type: "wetland", weight: 4 }, { type: "mountains", weight: 4 }], transitions: [{ next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0, hi: 0.3 }, elevation: "low" } }, + { id: "savanna", label: "Savanna", color: "#c4b25c", mix: [{ type: "grassland", weight: 46 }, { type: "desert", weight: 26 }, { type: "jungle", weight: 10 }, { type: "hills", weight: 7 }, { type: "forest", weight: 6 }, { type: "wetland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0.2, hi: 0.5 }, elevation: "low" } }, + { id: "jungle", label: "Jungle", color: "#15803d", mix: [{ type: "jungle", weight: 63 }, { type: "wetland", weight: 14 }, { type: "hills", weight: 11 }, { type: "mountains", weight: 6 }, { type: "water", weight: 4 }, { type: "grassland", weight: 2 }], transitions: [{ next: "Badlands", between: "Savanna" }], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0.5, hi: 0.85 }, elevation: "low" } }, + { id: "badlands", label: "Badlands", color: "#c2410c", mix: [{ type: "badlands", weight: 42 }, { type: "desert", weight: 26 }, { type: "mountains", weight: 21 }, { type: "hills", weight: 7 }, { type: "coast", weight: 4 }], transitions: [], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0, hi: 0.2 }, elevation: "low" } }, + { id: "swamp", label: "Swamp", color: "#909f23", mix: [{ type: "wetland", weight: 62 }, { type: "forest", weight: 21 }, { type: "water", weight: 10 }, { type: "grassland", weight: 6 }, { type: "shallows", weight: 2 }], transitions: [{ next: "Badlands", between: "Grassland" }, { next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.36, hi: 1 }, moisture: { lo: 0.8, hi: 1 }, elevation: "low" } }, + { id: "river-delta", label: "River delta", color: "#5f9a7a", mix: [{ type: "wetland", weight: 39 }, { type: "water", weight: 32 }, { type: "shallows", weight: 13 }, { type: "grassland", weight: 10 }, { type: "coast", weight: 4 }, { type: "forest", weight: 2 }], transitions: [], climate: { moisture: { lo: 0.55, hi: 1 }, elevation: "mouth", rare: true } }, + { id: "valley", label: "Valley", color: "#e0e8a1", mix: [{ type: "grassland", weight: 34 }, { type: "hills", weight: 21 }, { type: "mountains", weight: 18 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 11 }, { type: "water", weight: 3 }, { type: "wetland", weight: 2 }], transitions: [], climate: { elevation: "mid", chance: 0.55 } }, + { id: "karst", label: "Karst", color: "#4ade80", mix: [{ type: "grassland", weight: 30 }, { type: "hills", weight: 24 }, { type: "mountains", weight: 18 }, { type: "forest", weight: 17 }, { type: "water", weight: 5 }, { type: "badlands", weight: 4 }, { type: "wetland", weight: 2 }], transitions: [], climate: { temperature: { lo: 0.62, hi: 1 }, moisture: { lo: 0.6, hi: 1 }, elevation: "mid", chance: 0.55, rare: true } }, + { id: "alpine", label: "Alpine", color: "#bfdbfe", mix: [{ type: "mountains", weight: 44 }, { type: "peaks", weight: 20 }, { type: "hills", weight: 18 }, { type: "forest", weight: 9 }, { type: "snow", weight: 4 }, { type: "grassland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Jungle", between: "Karst" }], climate: { elevation: "high" } }, + { id: "volcanic", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1 }], transitions: [], climate: { elevation: "high", chance: 0.12, rare: true } }, + { id: "coastal-fjord", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [], climate: { temperature: { lo: 0, hi: 0.3 }, elevation: "low", coastal: true, chance: 0.5 } }, + { id: "archipelago", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [], landShare: 0.3, minIslands: 2, climate: { elevation: "sea", coastal: true, chance: 0.3 } }, + { id: "open-sea", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20 }], transitions: [], climate: { elevation: "sea" } }, ]; /** A copy of a preset's fields (callers may change it). */ export function biomePreset(id: string): BiomeNoteFields | undefined { const p = BIOME_PRESETS.find((b) => b.id === id); - return p ? { ...p, mix: p.mix.map((r) => ({ ...r })), transitions: p.transitions.map((t) => ({ ...t })) } : undefined; + if (!p) return undefined; + const out: BiomeNoteFields = { ...p, mix: p.mix.map((r) => ({ ...r })), transitions: p.transitions.map((t) => ({ ...t })) }; + const climate = copyClimate(p.climate); + if (climate) out.climate = climate; + else delete out.climate; + return out; } diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index ffb34f86..f87f9554 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -16,6 +16,7 @@ import { mapTerrainsByType, TYPE_FALLBACKS } from "../worldgen/builtinGenerators import { biomeSlug, mixShares, type BiomeMixRow, type BiomeNoteFields } from "./biomeNote"; import type { TerrainColor } from "../types"; import { typesInGroup } from "../terrainTypes"; +import { climateCentre, isPlaceable, type BiomeClimate, type ClimateElevation, type ClimateRange } from "./biomeClimate"; export type BiomeId = string; export const OPEN_SEA = "open-sea"; @@ -353,6 +354,23 @@ let sourceVersion = 0; /** Bumped on every setBiomeSource (for cache keys). */ export const biomeSourceVersion = (): number => sourceVersion; +/** The overworld zone a climate's elevation stands for (unset: lowland). */ +export function zoneOfElevation(e: ClimateElevation | undefined): BiomeInfo["zone"] { + return e === "sea" ? "sea" : e === "high" ? "peak" : e === "mid" ? "high" : "low"; +} + +/** + * A biome's ideal climate (T, M) for the generator's repairs: the shipped + * table's tuned value when the climate box still holds it, else the box's + * middle. Data only: a user's biome always gets its box's middle. + */ +export function climateIdeal(id: BiomeId, c: BiomeClimate): [number, number] { + const base = BY_ID.get(id); + const holds = (r: ClimateRange | undefined, v: number) => !r || (v >= r.lo - 1e-9 && v <= r.hi + 1e-9); + if (base && holds(c.temperature, base.temp) && holds(c.moisture, base.moist)) return [base.temp, base.moist]; + return climateCentre(c); +} + /** Load (or, with undefined, drop) the biomes read from notes. */ export function setBiomeSource(list: readonly BiomeNoteFields[] | undefined): void { sourceVersion++; @@ -372,6 +390,14 @@ export function setBiomeSource(list: readonly BiomeNoteFields[] | undefined): vo delete info.minIslands; if (b.landShare !== undefined) info.landShare = b.landShare; if (b.minIslands !== undefined) info.minIslands = b.minIslands; + // The note's climate (when set) says its zone, rarity and ideal climate. + if (isPlaceable(b.climate)) { + const c = b.climate!; + info.zone = zoneOfElevation(c.elevation); + if (c.rare) info.rare = true; + else delete info.rare; + [info.temp, info.moist] = climateIdeal(b.id, c); + } infos.set(b.id, info); } const ecotones: [BiomeId, BiomeId, BiomeId][] = []; diff --git a/src/overworld/worldBiomes.ts b/src/overworld/worldBiomes.ts index f97c0776..fa1920f8 100644 --- a/src/overworld/worldBiomes.ts +++ b/src/overworld/worldBiomes.ts @@ -6,6 +6,12 @@ * biomes, a mountain chain, few rare biomes, and transition biomes * (ecotones) between neighbours that shouldn't touch. * + * Which biome a hex gets is data, never a name: each biome's climate + * (temperature, moisture, elevation, coastal, chance, rare; biomeClimate.ts) + * from its note, the shipped ones' from biomePresets.ts. Biomes without a + * climate are only placed by hand (or, in a biome pool, where nothing else + * fits). + * * Each hex is painted with its biome's representative terrain on the given * palette, so the terrain is the biome signal regions read back (§4.1). * Biomes the palette can't show fall back to the nearest one it can, so a @@ -20,19 +26,24 @@ import { mulberry32 } from "../../packages/hex-wfc/src/rng"; import type { TerrainColor } from "../types"; import { fbm } from "./noise"; import { - BIOMES, - OPEN_SEA, SIMILAR, + allBiomeIds, biomeInfo, - climateMisfit, + biomeNoteOf, + biomeSourceActive, + climateIdeal, compatible, ecotoneBetween, - isSeaBiome, representableBiomes, representativeTerrain, resolveBiome, + zoneOfElevation, type BiomeId, + type BiomeInfo, } from "./biomes"; +import { climateArea, inClimateRange, isPlaceable, type BiomeClimate, type ClimateElevation } from "./biomeClimate"; +import type { BiomeNoteFields } from "./biomeNote"; +import { BIOME_PRESETS } from "./biomePresets"; export type Climate = "cold" | "temperate" | "warm" | "varied"; export type LandShape = "one" | "two" | "islands"; @@ -47,6 +58,11 @@ export interface WorldBiomesOptions { north?: NorthIs; /** Trace a river from the highest hex down to the sea (default true). */ river?: boolean; + /** + * A biome pool: only these are placed (placementPool). Unset: every + * biome with a climate. + */ + biomes?: readonly BiomeNoteFields[]; } export interface WorldBiomesResult { @@ -173,27 +189,66 @@ export function worldBiomes( moisture.set(k, Math.min(1, Math.max(0, m))); } - // 4. Biome per hex. - const shown = representableBiomes(palette); - const ok = (b: BiomeId) => resolveBiome(b, shown) ?? b; + // 4. Biome per hex, from the candidates' climates (biomeClimate.ts): the + // hex's band (high, mid, low; sea), then the band's biomes that fit its + // temperature and moisture, rarest and narrowest first, one roll. + const pool = placementPool(opts.biomes); + const { cands, byId } = pool; + const isRare = (b: BiomeId) => byId.get(b)?.rare ?? !!biomeInfo(b)?.rare; + const zoneOf = (b: BiomeId) => byId.get(b)?.zone ?? biomeInfo(b)?.zone; + const misfit = (b: BiomeId, t: number, m: number) => { + const c = byId.get(b); + return c ? Math.hypot(c.ideal[0] - t, c.ideal[1] - m) : 1; + }; + const allowed = new Set([...cands.map((c) => c.id), ...pool.fallback.map((f) => f.id)]); + const shown = new Set([...representableBiomes(palette)].filter((b) => allowed.has(b))); + /** A biome the palette can show: itself, else the nearest similar one in the pool; undefined when neither. */ + const ok = (b: BiomeId): BiomeId | undefined => resolveBiome(b, shown) ?? (allowed.has(b) ? b : undefined); + const band = (e: ClimateElevation) => pool.tryOrder.filter((c) => c.elevation === e); + const bands = { high: band("high"), mid: band("mid"), low: band("low"), sea: band("sea"), mouth: band("mouth") }; + /** The band's first biome (rarest, narrowest) that fits and takes the roll. */ + const pickFrom = (list: PlacementCandidate[], t: number, m: number, coast: boolean): BiomeId | undefined => { + const fit = list.filter((c) => inClimateRange(c.temperature, t) && inClimateRange(c.moisture, m) && (!c.coastal || coast)); + if (!fit.length) return undefined; + const roll = fit.some((c) => c.chance < 1) ? rng() : 0; + return fit.find((c) => roll < c.chance)?.id; + }; + /** Nearest-climate biome of a list (no roll). */ + const nearest = (list: { id: BiomeId }[], t: number, m: number): BiomeId | undefined => { + let best: BiomeId | undefined, score = Infinity; + for (const c of list) { + const s = misfit(c.id, t, m); + if (s < score) { score = s; best = c.id; } + } + return best; + }; + /** A hex no climate biome fits: the pool's biomes without a climate, else the nearest climate biome. */ + const fallbackFor = (seaHex: boolean, t: number, m: number): BiomeId | undefined => { + const own = pool.fallback.filter((f) => f.sea === seaHex); + if (own.length) return own.length === 1 ? own[0].id : own[Math.floor(rng() * own.length)].id; + const same = cands.filter((c) => (c.zone === "sea") === seaHex && c.elevation !== "mouth"); + return nearest(same.length ? same : cands, t, m) ?? pool.fallback[0]?.id; + }; const biomes = new Map(); const bigLand = landKeys.length >= 8; for (const k of keys) { const t = temperature.get(k)!, m = moisture.get(k)!; - let b: BiomeId; + let b: BiomeId | undefined; if (sea.has(k)) { - b = toLand.get(k) === 1 && rng() < 0.3 ? "archipelago" : OPEN_SEA; + b = pickFrom(bands.sea, t, m, toLand.get(k) === 1) ?? fallbackFor(true, t, m); } else { const r = rank.get(k)!; - if (bigLand && r > 0.86) b = rng() < 0.12 ? "volcanic" : "alpine"; - else if (r > 0.66 && rng() < 0.55) b = t > 0.62 && m > 0.6 ? "karst" : "valley"; - else if (toSea.get(k) === 1 && t < 0.3 && rng() < 0.5) b = "coastal-fjord"; - else b = lowland(t, m); + const coast = toSea.get(k) === 1; + if (bigLand && r > HIGH_RANK) b = pickFrom(bands.high, t, m, coast); + if (!b && r > MID_RANK) b = pickFrom(bands.mid, t, m, coast); + if (!b) b = pickFrom(bands.low, t, m, coast) ?? fallbackFor(false, t, m); } - biomes.set(k, ok(b)); + if (b) biomes.set(k, ok(b) ?? b); } + // Nothing in the pool can be placed: no biomes. + if (biomes.size < N) return { ...empty, elevation, temperature, moisture, sea }; - // River: highest land hex downhill to the sea; a wet mouth may be a delta. + // River: highest land hex downhill to the sea; its mouth may take a "mouth" biome. const river: string[] = []; if ((opts.river ?? true) && landKeys.length >= 4 && sea.size) { let cur = [...landKeys].sort((a, b) => rank.get(b)! - rank.get(a)!)[0]; @@ -209,7 +264,11 @@ export function worldBiomes( cur = next; } const mouth = river.filter((k) => !sea.has(k)).pop(); - if (mouth && moisture.get(mouth)! > 0.55 && biomeInfo(biomes.get(mouth)!)?.zone === "low") biomes.set(mouth, ok("river-delta")); + if (mouth && zoneOf(biomes.get(mouth)!) === "low") { + const b = pickFrom(bands.mouth, temperature.get(mouth)!, moisture.get(mouth)!, toSea.get(mouth) === 1); + const resolved = b ? ok(b) : undefined; + if (resolved) biomes.set(mouth, resolved); + } } // 5. Repairs. @@ -219,7 +278,12 @@ export function worldBiomes( ks.reduce((s, k) => s + moisture.get(k)!, 0) / ks.length, ]; const rareCap = Math.max(1, Math.floor(N / 20)); - const rareCount = () => [...biomes.values()].filter((b) => biomeInfo(b)?.rare).length; + const rareCount = () => [...biomes.values()].filter((b) => isRare(b)).length; + /** A common land biome for a hex when a rare one has to go and no similar one will do. */ + const commonNear = (k: string): BiomeId | undefined => nearest( + cands.filter((c) => !c.rare && c.zone !== "sea" && c.elevation !== "mouth" && shown.has(c.id)), + temperature.get(k)!, moisture.get(k)!, + ); /** Best replacement biome for a group of hexes now holding `from`. */ const alternative = (group: string[], from: BiomeId, avoid: Set = new Set()): BiomeId | undefined => { @@ -227,17 +291,17 @@ export function worldBiomes( const inGroup = new Set(group); const around = new Set(); for (const k of group) for (const n of nbrs.get(k)!) if (!inGroup.has(n) && isLand(n)) around.add(biomes.get(n)!); - const fromZone = biomeInfo(from)?.zone; + const fromZone = zoneOf(from); const similar = SIMILAR[from] ?? []; let best: BiomeId | undefined; let bestScore = Infinity; - for (const info of BIOMES) { - const b = info.id; - if (b === from || avoid.has(b) || !shown.has(b) || info.zone === "sea") continue; - if (info.zone === "peak" && fromZone !== "peak") continue; - if (info.rare && rareCount() >= rareCap) continue; + for (const c of cands) { + const b = c.id; + if (b === from || avoid.has(b) || !shown.has(b) || c.zone === "sea") continue; + if (c.zone === "peak" && fromZone !== "peak") continue; + if (c.rare && rareCount() >= rareCap) continue; if ([...around].some((a) => !compatible(a, b))) continue; - const score = climateMisfit(b, t, m) + (similar.includes(b) ? 0 : 0.35) + (around.has(b) ? 0.5 : 0) + rng() * 0.05; + const score = misfit(b, t, m) + (similar.includes(b) ? 0 : 0.35) + (around.has(b) ? 0.5 : 0) + rng() * 0.05; if (score < bestScore) { bestScore = score; best = b; } } return best; @@ -285,17 +349,19 @@ export function worldBiomes( for (const k of landKeys) { const counts = new Map(); for (const n of nbrs.get(k)!) if (isLand(n)) counts.set(biomes.get(n)!, (counts.get(biomes.get(n)!) ?? 0) + 1); - for (const [b, c] of counts) if (c >= 4 && b !== biomes.get(k) && !biomeInfo(b)?.rare) biomes.set(k, b); + for (const [b, c] of counts) if (c >= 4 && b !== biomes.get(k) && !isRare(b)) biomes.set(k, b); } - // b. A mountain chain from the ridge when there's room and none exists. - if (bigLand && shown.has("alpine") && ![...biomes.values()].includes("alpine")) { + // b. A mountain chain from the ridge when there's room and none exists: + // the commonest "high" biome (the highest chance). + const chainBiome = [...bands.high].sort((a, b) => b.chance - a.chance || a.order - b.order)[0]?.id; + if (bigLand && chainBiome !== undefined && shown.has(chainBiome) && ![...biomes.values()].includes(chainBiome)) { let cur = [...landKeys].sort((a, b) => rank.get(b)! - rank.get(a)!)[0]; const chain = new Set(); const len = 2 + Math.floor(rng() * 2); while (cur && chain.size < len) { chain.add(cur); - biomes.set(cur, "alpine"); + biomes.set(cur, chainBiome); cur = nbrs.get(cur)!.filter((n) => isLand(n) && !chain.has(n)).sort((a, b) => rank.get(b)! - rank.get(a)!)[0]; } } @@ -303,11 +369,14 @@ export function worldBiomes( // c. Rare biomes: at most one per ~20 hexes. for (const k of keys) { const b = biomes.get(k)!; - if (!biomeInfo(b)?.rare) continue; + if (!isRare(b)) continue; const before = rareCount(); if (before <= rareCap) continue; biomes.set(k, "__"); - if (!recolour([k], b)) biomes.set(k, ok(SIMILAR[b]?.find((s) => !biomeInfo(s)?.rare) ?? "grassland")); + if (!recolour([k], b)) { + const sim = SIMILAR[b]?.find((s) => !isRare(s)); + biomes.set(k, (sim !== undefined ? ok(sim) : undefined) ?? commonNear(k) ?? b); + } } const splitAndSpread = () => { @@ -355,13 +424,17 @@ export function worldBiomes( const eco = ecotoneBetween(a, b); if (!eco) continue; let target = ok(eco); - // Rare transitions (karst) count toward the rare cap too: past it, - // the nearest common biome stands in. - if (biomeInfo(target)?.rare && rareCount() > rareCap) { - target = ok(SIMILAR[target]?.find((s) => !biomeInfo(s)?.rare && shown.has(s)) ?? "grassland"); + if (target === undefined) continue; // the transition biome isn't in the pool + // Rare transitions count toward the rare cap too: past it, the + // nearest common biome stands in. + if (isRare(target) && rareCount() > rareCap) { + const sim = SIMILAR[target]?.find((s) => !isRare(s) && shown.has(s)); + const common = (sim !== undefined ? ok(sim) : undefined) ?? commonNear(k); + if (common === undefined) continue; + target = common; } - const fitK = climateMisfit(a, temperature.get(k)!, moisture.get(k)!); - const fitN = climateMisfit(b, temperature.get(n)!, moisture.get(n)!); + const fitK = misfit(a, temperature.get(k)!, moisture.get(k)!); + const fitN = misfit(b, temperature.get(n)!, moisture.get(n)!); const which = fitK >= fitN ? k : n; if (biomes.get(which) === target) continue; biomes.set(which, target); @@ -373,8 +446,13 @@ export function worldBiomes( } splitAndSpread(); - // Seas stay sea biomes whatever the repairs did nearby. - for (const k of sea) if (!isSeaBiome(biomes.get(k)!)) biomes.set(k, ok(OPEN_SEA)); + // Seas stay sea biomes whatever the repairs did nearby: the commonest sea biome. + const seaDefault = [...bands.sea].sort((a, b) => b.chance - a.chance || a.order - b.order)[0]?.id; + for (const k of sea) { + if (zoneOf(biomes.get(k)!) === "sea") continue; + const b = seaDefault !== undefined ? ok(seaDefault) : fallbackFor(true, temperature.get(k)!, moisture.get(k)!); + if (b !== undefined) biomes.set(k, b); + } const terrain = new Map(); for (const k of keys) { @@ -384,6 +462,75 @@ export function worldBiomes( return { biomes, terrain, elevation, temperature, moisture, sea, river, ecotones }; } +// ── the biomes it may place ────────────────────────────────────────────── + +/** Land height ranks above which a hex is "high" (on land of 8+ hexes) and "mid". */ +export const HIGH_RANK = 0.86; +export const MID_RANK = 0.66; + +export interface PlacementCandidate extends BiomeClimate { + id: BiomeId; + elevation: ClimateElevation; + chance: number; + rare: boolean; + zone: BiomeInfo["zone"]; + /** Ideal (temperature, moisture) for the repairs (biomes.climateIdeal). */ + ideal: [number, number]; + /** The shipped biomes in their preset order first, then the user's by id. */ + order: number; +} + +export interface PlacementPool { + /** Biomes with a climate, in `order` (the repairs walk them in it). */ + cands: PlacementCandidate[]; + /** The same, in the order a band tries them: rarest, then narrowest, then `order`. */ + tryOrder: PlacementCandidate[]; + byId: Map; + /** A pool's biomes without a climate: placed only where no climate biome fits. */ + fallback: { id: BiomeId; sea: boolean }[]; +} + +/** + * The biomes World biomes may place. With `list` (a biome pool) only those, + * and the pool's biomes without a climate fill hexes no climate biome fits. + * Without one: every biome note with a climate (the shipped presets before + * the notes load); biomes without a climate are never placed. + */ +export function placementPool(list?: readonly BiomeNoteFields[]): PlacementPool { + const notes: readonly BiomeNoteFields[] = list + ?? (biomeSourceActive() ? allBiomeIds().map((id) => biomeNoteOf(id)).filter((b): b is BiomeNoteFields => !!b) : BIOME_PRESETS); + const presetOrder = new Map(BIOME_PRESETS.map((p, i) => [p.id, i])); + const users = [...new Set(notes.filter((b) => !presetOrder.has(b.id)).map((b) => b.id))].sort(); + const orderOf = (id: BiomeId) => presetOrder.get(id) ?? BIOME_PRESETS.length + users.indexOf(id); + const seen = new Set(); + const cands: PlacementCandidate[] = []; + const fallback: { id: BiomeId; sea: boolean }[] = []; + for (const b of notes) { + if (seen.has(b.id)) continue; + seen.add(b.id); + const c = b.climate; + if (!c || !isPlaceable(c)) { + if (list) fallback.push({ id: b.id, sea: biomeInfo(b.id)?.zone === "sea" || (b.landShare !== undefined && b.landShare < 0.5) }); + continue; + } + const elevation = c.elevation ?? "low"; + cands.push({ + ...c, + id: b.id, + elevation, + chance: c.chance ?? 1, + rare: !!c.rare, + zone: zoneOfElevation(elevation), + ideal: climateIdeal(b.id, c), + order: orderOf(b.id), + }); + } + cands.sort((a, b) => a.order - b.order); + fallback.sort((a, b) => orderOf(a.id) - orderOf(b.id)); + const tryOrder = [...cands].sort((a, b) => a.chance - b.chance || climateArea(a) - climateArea(b) || a.order - b.order); + return { cands, tryOrder, byId: new Map(cands.map((c) => [c.id, c])), fallback }; +} + // ── as a generator (registry: "World biomes") ─────────────────────────── export const WORLD_BIOMES_ID = "procedural:world-biomes"; @@ -419,11 +566,3 @@ export function worldBiomesFromOptions( north: pick(options.north, ["colder", "warmer", "none"] as const, "colder"), }); } - -/** Lowland biome for a climate (Whittaker-style). */ -export function lowland(t: number, m: number): BiomeId { - if (t < 0.18) return "tundra"; - if (t < 0.36) return m > 0.45 ? "taiga" : "tundra"; - if (t < 0.66) return m < 0.3 ? "grassland" : m < 0.62 ? "temperate-forest" : m < 0.8 ? "deep-forest" : "swamp"; - return m < 0.2 ? "badlands" : m < 0.5 ? "savanna" : m < 0.85 ? "jungle" : "swamp"; -} diff --git a/src/types.ts b/src/types.ts index 605e558e..12a2e5de 100644 --- a/src/types.ts +++ b/src/types.ts @@ -341,10 +341,12 @@ export interface HexmakerPluginSettings { setupDismissed: boolean; /** Vault folder holding palette notes. Empty = "{worldFolder}/palettes". */ palettesFolder: string; - /** Vault folder holding biome notes (#50). Empty = "{worldFolder}/biomes". */ - biomesFolder?: string; - /** Shipped biomes already written into biome notes (ids): each is written once, so a deleted one stays deleted. */ - biomesSeeded?: string[]; + /** Vault folder holding biome notes (#50). Empty = "{worldFolder}/biomes". */ + biomesFolder?: string; + /** Shipped biomes already written into biome notes (ids): each is written once, so a deleted one stays deleted. */ + biomesSeeded?: string[]; + /** Shipped biomes whose notes got their climate added (ids): once each, so a climate cleared by hand stays cleared. */ + biomeClimatesSeeded?: string[]; /** True once settings-only palettes were written out as notes. */ palettesMigrated: boolean; /** diff --git a/tests/biomeClimate.test.ts b/tests/biomeClimate.test.ts new file mode 100644 index 00000000..db5230e2 --- /dev/null +++ b/tests/biomeClimate.test.ts @@ -0,0 +1,238 @@ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { hexDistance } from "../packages/hex-wfc/src/grid"; +import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { + MOISTURE_WORDS, + TEMPERATURE_WORDS, + formatClimateRange, + isPlaceable, + parseClimateRange, + readClimate, +} from "../src/overworld/biomeClimate"; +import { buildBiomeNote, parseBiomeNote, updateBiomeNote, type BiomeNoteFields } from "../src/overworld/biomeNote"; +import { BIOME_PRESETS, biomePreset } from "../src/overworld/biomePresets"; +import { BIOMES, biomeInfo, setBiomeSource } from "../src/overworld/biomes"; +import { placementPool, worldBiomes, type WorldBiomesOptions } from "../src/overworld/worldBiomes"; +import { lowland, worldBiomes as legacyWorldBiomes } from "./fixtures/worldBiomesLegacy"; +import { climatesToAdd } from "../src/overworld/BiomeStore"; + +const hexWorld = (R: number): [number, number][] => { + const out: [number, number][] = []; + for (let x = 0; x <= 2 * R; x++) for (let y = 0; y <= 2 * R; y++) if (hexDistance([x, y], [R, R], "flat", "odd") <= R) out.push([x, y]); + return out; +}; +const rectWorld = (c: number, r: number): [number, number][] => { + const out: [number, number][] = []; + for (let x = 0; x < c; x++) for (let y = 0; y < r; y++) out.push([x, y]); + return out; +}; +const sorted = (m: Map) => JSON.stringify([...m].sort()); + +afterEach(() => setBiomeSource(undefined)); + +describe("biome climate: reading and writing", () => { + it("reads words, word ranges and numbers", () => { + expect(parseClimateRange("cold–mild", TEMPERATURE_WORDS).range).toEqual({ lo: 0, hi: 0.6 }); + expect(parseClimateRange("Cold - Mild", TEMPERATURE_WORDS).range).toEqual({ lo: 0, hi: 0.6 }); + expect(parseClimateRange("cool to warm", TEMPERATURE_WORDS).range).toEqual({ lo: 0.2, hi: 0.8 }); + expect(parseClimateRange("wet", MOISTURE_WORDS).range).toEqual({ lo: 2 / 3, hi: 1 }); + expect(parseClimateRange("0.2–0.5", MOISTURE_WORDS).range).toEqual({ lo: 0.2, hi: 0.5 }); + expect(parseClimateRange("0.2-0.5", MOISTURE_WORDS).range).toEqual({ lo: 0.2, hi: 0.5 }); + expect(parseClimateRange("20% to 50%", MOISTURE_WORDS).range).toEqual({ lo: 0.2, hi: 0.5 }); + expect(parseClimateRange("wet..dry", MOISTURE_WORDS).problem).toBeDefined(); // backwards: turned round + expect(parseClimateRange("any", MOISTURE_WORDS)).toEqual({}); + }); + + it("reports what it can't read", () => { + expect(parseClimateRange("toasty", TEMPERATURE_WORDS).problem).toMatch(/cold, cool, mild, warm, hot/); + expect(parseClimateRange("0.4", TEMPERATURE_WORDS).problem).toMatch(/two ends/); + expect(parseClimateRange("150–200", TEMPERATURE_WORDS).problem).toBeDefined(); + const r = readClimate(new Map([["elevation", "orbit"], ["chance", "lots"], ["coastal", "maybe"], ["moisture", "wet"]])); + expect(r.problems.map((p) => p.key).sort()).toEqual(["chance", "coastal", "elevation"]); + expect(r.climate).toEqual({ moisture: { lo: 2 / 3, hi: 1 } }); + }); + + it("turns a backwards range round", () => { + expect(parseClimateRange("mild–cold", TEMPERATURE_WORDS).range).toEqual({ lo: 0, hi: 0.6 }); + expect(parseClimateRange("0.5–0.2", TEMPERATURE_WORDS).range).toEqual({ lo: 0.2, hi: 0.5 }); + }); + + it("writes words when the ends fall on word bands, else numbers", () => { + expect(formatClimateRange({ lo: 0, hi: 0.6 }, TEMPERATURE_WORDS)).toBe("cold–mild"); + expect(formatClimateRange({ lo: 0.4, hi: 0.6 }, TEMPERATURE_WORDS)).toBe("mild"); + expect(formatClimateRange({ lo: 0.36, hi: 0.66 }, TEMPERATURE_WORDS)).toBe("0.36–0.66"); + expect(formatClimateRange({ lo: 2 / 3, hi: 1 }, MOISTURE_WORDS)).toBe("wet"); + }); + + it("round-trips through a biome note and keeps the user's spelling", () => { + const f: BiomeNoteFields = { + id: "glass-wastes", label: "Glass wastes", mix: [{ type: "desert", weight: 3 }], transitions: [], + climate: { temperature: { lo: 0.6, hi: 1 }, moisture: { lo: 0, hi: 1 / 3 }, elevation: "low", coastal: true, chance: 0.4, rare: true }, + }; + const text = buildBiomeNote(f); + expect(text).toContain("temperature: warm–hot"); + expect(text).toContain("moisture: dry"); + expect(text).toContain("chance: 40%"); + const back = parseBiomeNote(text, "Glass wastes"); + expect(back.problems).toEqual([]); + expect(back.fields.climate).toEqual(f.climate); + // Same values, other spelling: left alone. + const hand = text.replace("temperature: warm–hot", "temperature: Warm to Hot").replace("chance: 40%", "chance: 0.4"); + expect(updateBiomeNote(hand, back.fields)).toBe(hand); + // Climate dropped: its keys go. + const none = updateBiomeNote(text, { ...back.fields, climate: undefined }); + expect(none.split("\n---")[0]).not.toMatch(/temperature:|moisture:|elevation:|coastal:|chance:|rare:/); + expect(parseBiomeNote(none, "Glass wastes").fields.climate).toBeUndefined(); + }); + + it("a note with no climate keys has no climate (only placed by hand)", () => { + const f = parseBiomeNote(buildBiomeNote({ id: "x", label: "X", mix: [{ type: "forest", weight: 1 }], transitions: [] }), "X").fields; + expect(f.climate).toBeUndefined(); + expect(isPlaceable(f.climate)).toBe(false); + }); + + it("every shipped biome has a climate, and its note round-trips it", () => { + for (const p of BIOME_PRESETS) { + expect(isPlaceable(p.climate)).toBe(true); + const back = parseBiomeNote(buildBiomeNote(p), p.label); + expect(back.problems).toEqual([]); + for (const k of ["temperature", "moisture"] as const) { + const a = back.fields.climate?.[k], b = p.climate?.[k]; + if (!b) { expect(a).toBeUndefined(); continue; } + expect(a!.lo).toBeCloseTo(b.lo, 6); + expect(a!.hi).toBeCloseTo(b.hi, 6); + } + expect(back.fields.climate?.elevation).toBe(p.climate?.elevation); + expect(back.fields.climate?.chance).toBe(p.climate?.chance); + expect(!!back.fields.climate?.rare).toBe(!!p.climate?.rare); + expect(!!back.fields.climate?.coastal).toBe(!!p.climate?.coastal); + } + expect(biomePreset("karst")!.climate).not.toBe(BIOME_PRESETS.find((p) => p.id === "karst")!.climate); + }); + + it("the shipped lowland boxes give the old lowland table's biome", () => { + const low = placementPool().tryOrder.filter((c) => c.elevation === "low" && !c.coastal); + for (let t = 0.005; t < 1; t += 0.01) { + for (let m = 0.005; m < 1; m += 0.01) { + const hit = low.find((c) => (!c.temperature || (t >= c.temperature.lo && t < c.temperature.hi + (c.temperature.hi >= 1 ? 1e-9 : 0))) + && (!c.moisture || (m >= c.moisture.lo && m < c.moisture.hi + (c.moisture.hi >= 1 ? 1e-9 : 0)))); + expect(hit?.id).toBe(lowland(t, m)); + } + } + }); + + it("adds the shipped climate to built-in notes written before climates, once", () => { + const old = BIOME_PRESETS.map((p) => ({ ...p, climate: undefined })); + const mine = { ...old[0], climate: { elevation: "high" as const } }; + const plan = climatesToAdd([], [mine, ...old.slice(1), { id: "mine", label: "Mine", mix: [], transitions: [] }]); + expect(plan.done.length).toBe(BIOME_PRESETS.length); + expect(plan.add.map((b) => b.id)).toEqual(BIOME_PRESETS.slice(1).map((p) => p.id)); // own climate kept, user biome untouched + expect(plan.add[0].climate).toEqual(BIOME_PRESETS[1].climate); + expect(climatesToAdd(plan.done, old).add).toEqual([]); + }); + + it("shipped zones and rarity match the old table", () => { + setBiomeSource(BIOME_PRESETS); + for (const b of BIOMES) { + expect(biomeInfo(b.id)?.zone).toBe(b.zone); + expect(!!biomeInfo(b.id)?.rare).toBe(!!b.rare); + expect(biomeInfo(b.id)?.temp).toBe(b.temp); + } + }); +}); + +describe("World biomes from climates", () => { + const SEEDS = [1, 2, 3, 7, 11, 42, 99, 123, 777, 2024, 31337, 65535]; + const cases: { cells: [number, number][]; o: Partial }[] = [ + { cells: hexWorld(2), o: {} }, + { cells: hexWorld(3), o: { climate: "varied" } }, + { cells: hexWorld(5), o: { climate: "varied", water: 0.25 } }, + { cells: rectWorld(10, 8), o: { climate: "cold", land: "two" } }, + { cells: rectWorld(12, 9), o: { climate: "warm", land: "islands", water: 0.5 } }, + { cells: rectWorld(7, 6), o: { climate: "temperate", north: "none", water: 0.1 } }, + { cells: hexWorld(6), o: { climate: "varied", north: "warmer", water: 0.4 } }, + ]; + + for (const [name, palette] of [["Expanded", DEFAULT_TERRAIN_PALETTE], ["Limited", LIMITED_TERRAIN_PALETTE]] as const) { + it(`reproduces the old placement exactly with only the shipped biomes (${name})`, () => { + for (const { cells, o } of cases) { + for (const seed of SEEDS) { + const opts = { seed, ...o }; + const old = legacyWorldBiomes(cells, "flat", "odd", palette, opts); + const now = worldBiomes(cells, "flat", "odd", palette, opts); + expect(sorted(now.biomes)).toBe(sorted(old.biomes)); + expect(sorted(now.terrain)).toBe(sorted(old.terrain)); + expect(now.river).toEqual(old.river); + expect([...now.ecotones].sort()).toEqual([...old.ecotones].sort()); + } + } + }); + } + + it("reproduces it with the shipped biomes loaded from notes, in any order", () => { + setBiomeSource([...BIOME_PRESETS].reverse()); + for (const { cells, o } of cases.slice(0, 4)) { + for (const seed of SEEDS.slice(0, 6)) { + const opts = { seed, ...o }; + setBiomeSource(undefined); + const old = legacyWorldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, opts); + setBiomeSource([...BIOME_PRESETS].reverse()); + expect(sorted(worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, opts).biomes)).toBe(sorted(old.biomes)); + } + } + }); + + const ASH: BiomeNoteFields = { + id: "ash-plains", label: "Ash plains", color: "#555555", mix: [{ type: "badlands", weight: 5 }, { type: "hills", weight: 1 }], transitions: [], + climate: { temperature: { lo: 0.4, hi: 0.6 }, moisture: { lo: 0.3, hi: 0.5 }, elevation: "low" }, + }; + + it("places a user biome with a narrow climate band in the hexes that fit it", () => { + setBiomeSource([...BIOME_PRESETS, ASH]); + let placed = 0, fitting = 0; + for (const seed of SEEDS) { + const r = worldBiomes(hexWorld(5), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed, climate: "temperate", river: false }); + for (const [k, b] of r.biomes) { + const t = r.temperature.get(k)!, m = r.moisture.get(k)!; + if (b === "ash-plains") { + placed++; + // Placed where it fits (repairs may spread it a step, never far). + expect(Math.abs(t - 0.5)).toBeLessThan(0.25); + } + if (!r.sea.has(k) && t >= 0.4 && t < 0.6 && m >= 0.3 && m < 0.5) fitting++; + } + } + expect(fitting).toBeGreaterThan(0); + expect(placed).toBeGreaterThan(fitting / 4); + // Painted with its own terrain (its heaviest type's). + const r = worldBiomes(hexWorld(5), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 42, climate: "temperate" }); + for (const [k, b] of r.biomes) if (b === "ash-plains") expect(DEFAULT_TERRAIN_PALETTE.find((t) => t.name === r.terrain.get(k))?.type).toBe("badlands"); + }); + + it("never places a biome without a climate", () => { + const plain = { ...ASH, id: "plain-ash", label: "Plain ash", climate: undefined }; + setBiomeSource([...BIOME_PRESETS, plain]); + for (const seed of SEEDS) { + const r = worldBiomes(hexWorld(4), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed, climate: "varied" }); + expect([...r.biomes.values()]).not.toContain("plain-ash"); + } + }); + + it("is deterministic with user biomes", () => { + setBiomeSource([...BIOME_PRESETS, ASH]); + const a = worldBiomes(hexWorld(4), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 9 }); + const b = worldBiomes(hexWorld(4), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 9 }); + expect(sorted(a.biomes)).toBe(sorted(b.biomes)); + }); + + it("a lower chance takes a share of the fitting hexes", () => { + const half = { ...ASH, climate: { ...ASH.climate!, chance: 0.5 } }; + setBiomeSource([...BIOME_PRESETS, ASH]); + const full = SEEDS.reduce((s, seed) => s + [...worldBiomes(hexWorld(5), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed, climate: "temperate", river: false }).biomes.values()].filter((b) => b === "ash-plains").length, 0); + setBiomeSource([...BIOME_PRESETS, half]); + const some = SEEDS.reduce((s, seed) => s + [...worldBiomes(hexWorld(5), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed, climate: "temperate", river: false }).biomes.values()].filter((b) => b === "ash-plains").length, 0); + expect(some).toBeGreaterThan(0); + expect(some).toBeLessThan(full); + }); +}); diff --git a/tests/fixtures/worldBiomesLegacy.ts b/tests/fixtures/worldBiomesLegacy.ts new file mode 100644 index 00000000..f5892964 --- /dev/null +++ b/tests/fixtures/worldBiomesLegacy.ts @@ -0,0 +1,433 @@ +/** + * FROZEN COPY of src/overworld/worldBiomes.ts before biome climates (be51ec5), + * kept so tests can check the data-driven placement reproduces it exactly. + * Never edit. + * + * "World biomes": lays out biomes on an overworld (plan-overworld-regions + * §4.4). Elevation, temperature and moisture fields give each hex a biome + * (Whittaker-style), then deterministic repairs make it interesting: + * patches of 1–5 hexes, no biome over 40% of the land, enough distinct + * biomes, a mountain chain, few rare biomes, and transition biomes + * (ecotones) between neighbours that shouldn't touch. + * + * Each hex is painted with its biome's representative terrain on the given + * palette, so the terrain is the biome signal regions read back (§4.1). + * Biomes the palette can't show fall back to the nearest one it can, so a + * small palette gives fewer, broader biomes. + * + * Seeded and pure: no Obsidian imports. Works on any set of hexes + * (rectangle or hex-shaped overworld). + */ + +import { hexCenter, hexNeighbors, type Orientation, type Stagger } from "../../packages/hex-wfc/src/grid"; +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; +import type { TerrainColor } from "../../src/types"; +import { fbm } from "../../src/overworld/noise"; +import { + BIOMES, + OPEN_SEA, + SIMILAR, + biomeInfo, + climateMisfit, + compatible, + ecotoneBetween, + isSeaBiome, + representableBiomes, + representativeTerrain, + resolveBiome, + type BiomeId, +} from "../../src/overworld/biomes"; + +export type Climate = "cold" | "temperate" | "warm" | "varied"; +export type LandShape = "one" | "two" | "islands"; +export type NorthIs = "colder" | "warmer" | "none"; + +export interface WorldBiomesOptions { + seed: number; + climate?: Climate; + /** Share of hexes that are sea, 0..0.9 (default 0.3). */ + water?: number; + land?: LandShape; + north?: NorthIs; + /** Trace a river from the highest hex down to the sea (default true). */ + river?: boolean; +} + +export interface WorldBiomesResult { + /** Hex key → biome. */ + biomes: Map; + /** Hex key → palette terrain (the biome's representative). */ + terrain: Map; + elevation: Map; + temperature: Map; + moisture: Map; + /** Hex keys that are sea. */ + sea: Set; + /** River hex keys from source to mouth (empty when none). */ + river: string[]; + /** Hexes turned into transition biomes. */ + ecotones: Set; +} + +/** Largest patch (connected same-biome land hexes) the repairs allow. */ +export const MAX_PATCH = 5; +/** No land biome may cover more than this share of the land. */ +export const MAX_SHARE = 0.4; + +const key = (x: number, y: number) => `${x}_${y}`; + +// ── generator ──────────────────────────────────────────────────────────── + +export function worldBiomes( + cells: Iterable<[number, number]>, + orientation: Orientation, + stagger: Stagger, + palette: TerrainColor[], + opts: WorldBiomesOptions, +): WorldBiomesResult { + const seed = opts.seed >>> 0; + const rng = mulberry32(seed ^ 0x5eed); + const list = [...cells].sort((a, b) => a[1] - b[1] || a[0] - b[0]); + const keys = list.map(([x, y]) => key(x, y)); + const N = keys.length; + const inMap = new Set(keys); + const nbrs = new Map(); + for (const [x, y] of list) { + nbrs.set(key(x, y), hexNeighbors(x, y, orientation, stagger).map(([a, b]) => key(a, b)).filter((k) => inMap.has(k))); + } + const empty: WorldBiomesResult = { + biomes: new Map(), terrain: new Map(), elevation: new Map(), temperature: new Map(), moisture: new Map(), + sea: new Set(), river: [], ecotones: new Set(), + }; + if (!N) return empty; + + // Positions normalised to the unit square (keeping proportions). + const pts = list.map(([x, y]) => hexCenter(x, y, orientation, stagger)); + const minX = Math.min(...pts.map((p) => p[0])), maxX = Math.max(...pts.map((p) => p[0])); + const minY = Math.min(...pts.map((p) => p[1])), maxY = Math.max(...pts.map((p) => p[1])); + const span = Math.max(maxX - minX, maxY - minY, 1e-9); + const pos = new Map(); + keys.forEach((k, i) => pos.set(k, [(pts[i][0] - minX) / span, (pts[i][1] - minY) / span])); + const cxm = (maxX - minX) / span / 2, cym = (maxY - minY) / span / 2; + // Noise frequency grows with map size so a 400-hex map isn't one blob. + const freq = 1.6 + Math.sqrt(N) / 6; + + // 1. Elevation: fBm × continent mask; sea = lowest `water` share. + const land = opts.land ?? "one"; + const angle = rng() * Math.PI * 2; + const lobes: [number, number][] = land === "two" + ? [[cxm + Math.cos(angle) * 0.24, cym + Math.sin(angle) * 0.24], [cxm - Math.cos(angle) * 0.24, cym - Math.sin(angle) * 0.24]] + : [[cxm, cym]]; + const elevation = new Map(); + for (const k of keys) { + const [u, v] = pos.get(k)!; + const n = fbm(seed, u * freq, v * freq); + const d = Math.min(...lobes.map(([a, b]) => Math.hypot(u - a, v - b))) / (land === "two" ? 0.36 : 0.62); + const mask = land === "islands" ? 0.5 : Math.max(0, 1 - d * d); + const w = land === "islands" ? 0.85 : 0.5; + elevation.set(k, w * n + (1 - w) * mask); + } + const water = Math.min(0.9, Math.max(0, opts.water ?? 0.3)); + const bySea = [...keys].sort((a, b) => elevation.get(a)! - elevation.get(b)! || (a < b ? -1 : 1)); + const seaCount = Math.round(water * N); + const sea = new Set(bySea.slice(0, seaCount)); + const landKeys = keys.filter((k) => !sea.has(k)); + // Land height as a rank 0..1 (lowest land 0, highest 1). + const rank = new Map(); + bySea.slice(seaCount).forEach((k, i, arr) => rank.set(k, arr.length > 1 ? i / (arr.length - 1) : 0.5)); + + // Distance to the sea / to land (BFS over hexes). + const bfs = (from: Iterable) => { + const dist = new Map(); + const q: string[] = []; + for (const k of from) { dist.set(k, 0); q.push(k); } + for (let i = 0; i < q.length; i++) { + for (const m of nbrs.get(q[i])!) if (!dist.has(m)) { dist.set(m, dist.get(q[i])! + 1); q.push(m); } + } + return dist; + }; + const toSea = bfs(sea); + const toLand = bfs(landKeys); + + // 2. Temperature: latitude, minus height, plus a little noise. + const climate = opts.climate ?? "temperate"; + const north = opts.north ?? "colder"; + const temperature = new Map(); + const ySpan = Math.max(1e-9, (maxY - minY) / span); + for (const k of keys) { + const [, v] = pos.get(k)!; + const lat = north === "none" ? 0.5 : north === "colder" ? v / ySpan : 1 - v / ySpan; + let t = climate === "varied" ? 0.05 + lat * 0.9 : 0.5 + (lat - 0.5) * 0.45; + if (climate === "cold") t -= 0.28; + if (climate === "warm") t += 0.28; + t -= 0.3 * Math.max(0, (rank.get(k) ?? 0) - 0.5); + t += 0.16 * (fbm(seed + 77, pos.get(k)![0] * 2, pos.get(k)![1] * 2) - 0.5) * (north === "none" ? 3 : 1); + temperature.set(k, Math.min(1, Math.max(0, t))); + } + + // 3. Moisture: noise + nearness to the sea − rain shadow (wind from the west). + const high = (k: string) => (rank.get(k) ?? 0) > 0.8; + const moisture = new Map(); + for (const k of keys) { + const [x, y] = k.split("_").map(Number); + let shadow = 0; + for (let s = 1; s <= 3; s++) if (high(key(x - s, y))) shadow++; + const nearSea = sea.size ? 1 - Math.min(toSea.get(k) ?? 4, 4) / 4 : 0.4; + const m = 0.55 * fbm(seed + 991, pos.get(k)![0] * freq, pos.get(k)![1] * freq) + 0.45 * nearSea - 0.15 * shadow; + moisture.set(k, Math.min(1, Math.max(0, m))); + } + + // 4. Biome per hex. + const shown = representableBiomes(palette); + const ok = (b: BiomeId) => resolveBiome(b, shown) ?? b; + const biomes = new Map(); + const bigLand = landKeys.length >= 8; + for (const k of keys) { + const t = temperature.get(k)!, m = moisture.get(k)!; + let b: BiomeId; + if (sea.has(k)) { + b = toLand.get(k) === 1 && rng() < 0.3 ? "archipelago" : OPEN_SEA; + } else { + const r = rank.get(k)!; + if (bigLand && r > 0.86) b = rng() < 0.12 ? "volcanic" : "alpine"; + else if (r > 0.66 && rng() < 0.55) b = t > 0.62 && m > 0.6 ? "karst" : "valley"; + else if (toSea.get(k) === 1 && t < 0.3 && rng() < 0.5) b = "coastal-fjord"; + else b = lowland(t, m); + } + biomes.set(k, ok(b)); + } + + // River: highest land hex downhill to the sea; a wet mouth may be a delta. + const river: string[] = []; + if ((opts.river ?? true) && landKeys.length >= 4 && sea.size) { + let cur = [...landKeys].sort((a, b) => rank.get(b)! - rank.get(a)!)[0]; + const seen = new Set(); + while (cur && !seen.has(cur)) { + seen.add(cur); + river.push(cur); + if (sea.has(cur)) break; + // Downhill toward the sea: fewest steps to the sea, then lowest. + const next = nbrs.get(cur)!.filter((n) => !seen.has(n)) + .sort((a, b) => (toSea.get(a)! - toSea.get(b)!) || (elevation.get(a)! - elevation.get(b)!))[0]; + if (!next) break; + cur = next; + } + const mouth = river.filter((k) => !sea.has(k)).pop(); + if (mouth && moisture.get(mouth)! > 0.55 && biomeInfo(biomes.get(mouth)!)?.zone === "low") biomes.set(mouth, ok("river-delta")); + } + + // 5. Repairs. + const isLand = (k: string) => !sea.has(k); + const climateOf = (ks: string[]) => [ + ks.reduce((s, k) => s + temperature.get(k)!, 0) / ks.length, + ks.reduce((s, k) => s + moisture.get(k)!, 0) / ks.length, + ]; + const rareCap = Math.max(1, Math.floor(N / 20)); + const rareCount = () => [...biomes.values()].filter((b) => biomeInfo(b)?.rare).length; + + /** Best replacement biome for a group of hexes now holding `from`. */ + const alternative = (group: string[], from: BiomeId, avoid: Set = new Set()): BiomeId | undefined => { + const [t, m] = climateOf(group); + const inGroup = new Set(group); + const around = new Set(); + for (const k of group) for (const n of nbrs.get(k)!) if (!inGroup.has(n) && isLand(n)) around.add(biomes.get(n)!); + const fromZone = biomeInfo(from)?.zone; + const similar = SIMILAR[from] ?? []; + let best: BiomeId | undefined; + let bestScore = Infinity; + for (const info of BIOMES) { + const b = info.id; + if (b === from || avoid.has(b) || !shown.has(b) || info.zone === "sea") continue; + if (info.zone === "peak" && fromZone !== "peak") continue; + if (info.rare && rareCount() >= rareCap) continue; + if ([...around].some((a) => !compatible(a, b))) continue; + const score = climateMisfit(b, t, m) + (similar.includes(b) ? 0 : 0.35) + (around.has(b) ? 0.5 : 0) + rng() * 0.05; + if (score < bestScore) { bestScore = score; best = b; } + } + return best; + }; + + /** Connected same-biome land patches. */ + const patches = (): string[][] => { + const seen = new Set(); + const out: string[][] = []; + for (const k of landKeys) { + if (seen.has(k)) continue; + const b = biomes.get(k)!; + const group = [k]; + seen.add(k); + for (let i = 0; i < group.length; i++) { + for (const n of nbrs.get(group[i])!) if (!seen.has(n) && isLand(n) && biomes.get(n) === b) { seen.add(n); group.push(n); } + } + out.push(group); + } + return out; + }; + + /** 2–4 hexes of a patch, grown from its most exposed hex. */ + const rimChunk = (patch: string[], max: number): string[] => { + const inPatch = new Set(patch); + const exposure = (k: string) => nbrs.get(k)!.filter((n) => !inPatch.has(n)).length + (6 - nbrs.get(k)!.length); + const start = [...patch].sort((a, b) => exposure(b) - exposure(a) || (a < b ? -1 : 1))[0]; + const size = Math.min(max, 2 + Math.floor(rng() * 3)); + const chunk = [start]; + const taken = new Set(chunk); + for (let i = 0; i < chunk.length && chunk.length < size; i++) { + for (const n of nbrs.get(chunk[i])!) if (inPatch.has(n) && !taken.has(n) && chunk.length < size) { taken.add(n); chunk.push(n); } + } + return chunk; + }; + + const recolour = (group: string[], from: BiomeId, avoid?: Set): boolean => { + const alt = alternative(group, from, avoid); + if (!alt) return false; + for (const k of group) biomes.set(k, alt); + return true; + }; + + // a. Majority filter: a land hex surrounded (4+ of 6) by one compatible biome joins it. + for (const k of landKeys) { + const counts = new Map(); + for (const n of nbrs.get(k)!) if (isLand(n)) counts.set(biomes.get(n)!, (counts.get(biomes.get(n)!) ?? 0) + 1); + for (const [b, c] of counts) if (c >= 4 && b !== biomes.get(k) && !biomeInfo(b)?.rare) biomes.set(k, b); + } + + // b. A mountain chain from the ridge when there's room and none exists. + if (bigLand && shown.has("alpine") && ![...biomes.values()].includes("alpine")) { + let cur = [...landKeys].sort((a, b) => rank.get(b)! - rank.get(a)!)[0]; + const chain = new Set(); + const len = 2 + Math.floor(rng() * 2); + while (cur && chain.size < len) { + chain.add(cur); + biomes.set(cur, "alpine"); + cur = nbrs.get(cur)!.filter((n) => isLand(n) && !chain.has(n)).sort((a, b) => rank.get(b)! - rank.get(a)!)[0]; + } + } + + // c. Rare biomes: at most one per ~20 hexes. + for (const k of keys) { + const b = biomes.get(k)!; + if (!biomeInfo(b)?.rare) continue; + const before = rareCount(); + if (before <= rareCap) continue; + biomes.set(k, "__"); + if (!recolour([k], b)) biomes.set(k, ok(SIMILAR[b]?.find((s) => !biomeInfo(s)?.rare) ?? "grassland")); + } + + const splitAndSpread = () => { + // d. No biome above MAX_SHARE of the land. + for (let guard = 0; guard < 60 && landKeys.length >= 5; guard++) { + const counts = new Map(); + for (const k of landKeys) counts.set(biomes.get(k)!, (counts.get(biomes.get(k)!) ?? 0) + 1); + const [top, c] = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))[0]; + if (c / landKeys.length <= MAX_SHARE) break; + const patch = patches().filter((p) => biomes.get(p[0]) === top).sort((a, b) => b.length - a.length)[0]; + const excess = c - Math.floor(MAX_SHARE * landKeys.length); + if (!recolour(rimChunk(patch, Math.max(1, excess)), top)) break; + } + // e. Patches of at most MAX_PATCH hexes. + for (let guard = 0; guard < 200; guard++) { + const big = patches().filter((p) => p.length > MAX_PATCH).sort((a, b) => b.length - a.length)[0]; + if (!big) break; + if (!recolour(rimChunk(big, Math.min(4, big.length - 1)), biomes.get(big[0])!)) break; + } + }; + splitAndSpread(); + + // f. Enough distinct land biomes: min(5, N/4). + const wantDistinct = Math.min(5, Math.floor(N / 4), landKeys.length); + for (let guard = 0; guard < 20; guard++) { + const used = new Set(landKeys.map((k) => biomes.get(k)!)); + if (used.size >= wantDistinct) break; + const counts = new Map(); + for (const k of landKeys) counts.set(biomes.get(k)!, (counts.get(biomes.get(k)!) ?? 0) + 1); + const top = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))[0][0]; + const patch = patches().filter((p) => biomes.get(p[0]) === top).sort((a, b) => b.length - a.length)[0]; + if (patch.length < 2 && counts.get(top)! < 2) break; + if (!recolour(rimChunk(patch, Math.max(1, Math.min(3, patch.length - 1))), top, used)) break; + } + + // g. Ecotones between neighbours that shouldn't touch: the hex that suits + // its own biome less becomes the transition biome. + const ecotones = new Set(); + for (let pass = 0; pass < 3; pass++) { + let changed = false; + for (const k of landKeys) { + for (const n of nbrs.get(k)!) { + if (!isLand(n)) continue; + const a = biomes.get(k)!, b = biomes.get(n)!; + const eco = ecotoneBetween(a, b); + if (!eco) continue; + let target = ok(eco); + // Rare transitions (karst) count toward the rare cap too: past it, + // the nearest common biome stands in. + if (biomeInfo(target)?.rare && rareCount() > rareCap) { + target = ok(SIMILAR[target]?.find((s) => !biomeInfo(s)?.rare && shown.has(s)) ?? "grassland"); + } + const fitK = climateMisfit(a, temperature.get(k)!, moisture.get(k)!); + const fitN = climateMisfit(b, temperature.get(n)!, moisture.get(n)!); + const which = fitK >= fitN ? k : n; + if (biomes.get(which) === target) continue; + biomes.set(which, target); + ecotones.add(which); + changed = true; + } + } + if (!changed) break; + } + splitAndSpread(); + + // Seas stay sea biomes whatever the repairs did nearby. + for (const k of sea) if (!isSeaBiome(biomes.get(k)!)) biomes.set(k, ok(OPEN_SEA)); + + const terrain = new Map(); + for (const k of keys) { + const t = representativeTerrain(biomes.get(k)!, palette); + if (t) terrain.set(k, t); + } + return { biomes, terrain, elevation, temperature, moisture, sea, river, ecotones }; +} + +// ── as a generator (registry: "World biomes") ─────────────────────────── + +export const WORLD_BIOMES_ID = "procedural:world-biomes"; + +export const WORLD_BIOMES_OPTIONS: { key: string; label: string; choices: { value: string; label: string }[]; default: string }[] = [ + { key: "climate", label: "Climate", default: "varied", choices: [ + { value: "varied", label: "Varied" }, { value: "cold", label: "Cold" }, { value: "temperate", label: "Temperate" }, { value: "warm", label: "Warm" }, + ] }, + { key: "water", label: "Water %", default: "25", choices: ["10", "25", "40", "60"].map((v) => ({ value: v, label: `${v}%` })) }, + { key: "land", label: "Land", default: "one", choices: [ + { value: "one", label: "One continent" }, { value: "two", label: "Two" }, { value: "islands", label: "Islands" }, + ] }, + { key: "north", label: "North is", default: "colder", choices: [ + { value: "colder", label: "Colder" }, { value: "warmer", label: "Warmer" }, { value: "none", label: "No gradient" }, + ] }, +]; + +/** worldBiomes from a generator's option strings. */ +export function worldBiomesFromOptions( + cells: Iterable<[number, number]>, + orientation: Orientation, + stagger: Stagger, + palette: TerrainColor[], + seed: number, + options: Record, +): WorldBiomesResult { + const pick = (v: string | undefined, ok: readonly T[], d: T): T => (ok.includes(v as T) ? (v as T) : d); + return worldBiomes(cells, orientation, stagger, palette, { + seed, + climate: pick(options.climate, ["cold", "temperate", "warm", "varied"] as const, "varied"), + water: Math.min(90, Math.max(0, Number(options.water ?? 25) || 0)) / 100, + land: pick(options.land, ["one", "two", "islands"] as const, "one"), + north: pick(options.north, ["colder", "warmer", "none"] as const, "colder"), + }); +} + +/** Lowland biome for a climate (Whittaker-style). */ +export function lowland(t: number, m: number): BiomeId { + if (t < 0.18) return "tundra"; + if (t < 0.36) return m > 0.45 ? "taiga" : "tundra"; + if (t < 0.66) return m < 0.3 ? "grassland" : m < 0.62 ? "temperate-forest" : m < 0.8 ? "deep-forest" : "swamp"; + return m < 0.2 ? "badlands" : m < 0.5 ? "savanna" : m < 0.85 ? "jungle" : "swamp"; +} diff --git a/tests/overworldBiomes.test.ts b/tests/overworldBiomes.test.ts index 33d2c577..13f3e94e 100644 --- a/tests/overworldBiomes.test.ts +++ b/tests/overworldBiomes.test.ts @@ -13,7 +13,8 @@ import { representativeTerrain, resolveBiome, } from "../src/overworld/biomes"; -import { MAX_PATCH, MAX_SHARE, lowland, worldBiomes, type WorldBiomesOptions } from "../src/overworld/worldBiomes"; +import { MAX_PATCH, MAX_SHARE, worldBiomes, type WorldBiomesOptions } from "../src/overworld/worldBiomes"; +import { lowland } from "./fixtures/worldBiomesLegacy"; import { BUILTIN_GENERATORS } from "../src/worldgen/builtinGenerators"; const EXP = DEFAULT_TERRAIN_PALETTE; From 22667087b03386470eb9de5fd15b17080e2255c2 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 00:38:14 -0400 Subject: [PATCH 262/558] feat(biomes #50): generateBiomeRegion, generator-backed regions, biome page on the generator tab - worldgen/biomeRegion.ts: generateBiomeRegion(plugin, req) runs a learned, blend, preset or registry generator joined to the pinned cells (solveWithRing, shared with generateConnected); throws a readable BiomeRegionError when it doesn't fit; paths via toPathsOn. - regionsVault: planRegionWithGenerator routes through regionGenerator; create/regenerate use it; previews follow the route. - Generator page: Biome (blend field) view (BiomePanel) for openTerrainGenerator({ biome }), 'Used by biome' line on generators; GENERATOR_PAGE_TAKES_BIOMES on. Co-Authored-By: Claude Opus 5.5 --- src/HexmakerPlugin.ts | 19 +- src/hex-map/BiomeLibraryModal.ts | 11 +- src/hex-map/BiomeModals.ts | 15 +- src/overworld/regionGen.ts | 2 +- src/overworld/regionsVault.ts | 82 ++++++- src/worldgen/BiomePanel.ts | 404 +++++++++++++++++++++++++++++++ src/worldgen/GeneratorPanel.ts | 39 ++- src/worldgen/GeneratorView.ts | 2 + src/worldgen/WalkRegionModal.ts | 11 +- src/worldgen/biomeRegion.ts | 198 +++++++++++++++ src/worldgen/generators.ts | 42 +++- src/worldgen/neighbours.ts | 65 +++-- 12 files changed, 844 insertions(+), 46 deletions(-) create mode 100644 src/worldgen/BiomePanel.ts create mode 100644 src/worldgen/biomeRegion.ts diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index c7b9e8f1..cee31d81 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -637,9 +637,11 @@ export default class HexmakerPlugin extends Plugin { /** * Open the terrain generator page (or bring it forward), optionally with a - * region and generator selected. + * region and generator selected, or a biome (#50): a blend-field biome + * opens as "Biome (blend field)", a generator-backed one opens its + * generator (the page says which biomes use it). */ - async openTerrainGenerator(select: { mapName?: string; generatorPath?: string; paletteName?: string } = {}): Promise { + async openTerrainGenerator(select: { mapName?: string; generatorPath?: string; paletteName?: string; biome?: string } = {}): Promise { // An Advanced feature: in Simple, offer to turn it on first. if (!hasFeature(this.settings, "generators")) { new EnableFeatureModal(this.app, this, "generators", () => void this.openTerrainGenerator(select)).open(); @@ -647,7 +649,18 @@ export default class HexmakerPlugin extends Plugin { } if (select.mapName) GeneratorPanel.mapName = select.mapName; if (select.paletteName) GeneratorPanel.paletteName = select.paletteName; - if (select.generatorPath) GeneratorPanel.selectedPath = select.generatorPath; + if (select.generatorPath) { + GeneratorPanel.selectedPath = select.generatorPath; + GeneratorPanel.biome = ""; + } + if (select.biome) { + const b = this.biomeStore.get(select.biome); + const file = b?.generator ? this.app.vault.getAbstractFileByPath(`${b.generator}.md`) ?? this.app.vault.getAbstractFileByPath(b.generator) ?? this.app.metadataCache.getFirstLinkpathDest(b.generator, "") : null; + if (b && file) { + GeneratorPanel.selectedPath = file.path; + GeneratorPanel.biome = ""; + } else if (b && !b.generator) GeneratorPanel.biome = b.id; + } const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_GENERATOR)[0]; if (existing) { await this.app.workspace.revealLeaf(existing); diff --git a/src/hex-map/BiomeLibraryModal.ts b/src/hex-map/BiomeLibraryModal.ts index 3f6e0b60..c1a3a7a1 100644 --- a/src/hex-map/BiomeLibraryModal.ts +++ b/src/hex-map/BiomeLibraryModal.ts @@ -30,11 +30,8 @@ export function biomeEditLock(plugin: HexmakerPlugin, overworldName: string): st return canAdd(plugin.getMap(overworldName)) ? undefined : "Switch to Build to add or edit biomes."; } -/** - * Whether the generator page can open a biome (`openTerrainGenerator({ biome })`). - * TODO(#50): set true once the generator page takes biomes (other session). - */ -const GENERATOR_PAGE_TAKES_BIOMES = false; +/** Whether the generator page can open a biome (`openTerrainGenerator({ biome })`). */ +const GENERATOR_PAGE_TAKES_BIOMES = true; /** * "Edit generator…" for a biome, in one place: a biome with a generator @@ -49,7 +46,7 @@ export async function openBiomeGenerator(plugin: HexmakerPlugin, biome: string): if (file) { await plugin.openTerrainGenerator({ generatorPath: file.path }); return; } new Notice(`Generator ${generatorName(b.generator)} wasn't found; opening the biome's note.`); } else if (GENERATOR_PAGE_TAKES_BIOMES) { - await (plugin.openTerrainGenerator as (s: { biome: string }) => Promise)({ biome: b.id }); + await plugin.openTerrainGenerator({ biome: b.id }); return; } const path = plugin.biomeStore.pathOf(b.id); @@ -165,7 +162,7 @@ export class BiomeFormModal extends HexmakerModal { if (state.generator && ![...gen.options].some((o) => o.value === state.generator)) gen.createEl("option", { text: generatorName(state.generator), value: state.generator }); gen.value = state.generator; const genNote = form.createEl("p", { cls: "setting-item-description" }); - const showGenNote = () => genNote.setText(routeNote({ generator: state.generator || undefined }) ?? "Blend mixes the terrain types below, and blends into the biomes next to it. A temporary stand-in until generator regions land."); + const showGenNote = () => genNote.setText(routeNote({ generator: state.generator || undefined }) ?? "Blend mixes the terrain types below, and blends into the biomes next to it."); showGenNote(); gen.addEventListener("change", () => { state.generator = gen.value; showGenNote(); }); diff --git a/src/hex-map/BiomeModals.ts b/src/hex-map/BiomeModals.ts index 7f1327e9..9b29d10f 100644 --- a/src/hex-map/BiomeModals.ts +++ b/src/hex-map/BiomeModals.ts @@ -28,6 +28,7 @@ import { regionBiomeStatus, overworldOf, planRegionAt, + planRegionWithGenerator, regenerateRegion, reshapeLock, setBiomeAt, @@ -243,10 +244,18 @@ export class RegionGenModal extends HexmakerModal { return this.opts.biome ? representativeTerrain(this.opts.biome, plugin.getMapPalette(this.parentName)) : undefined; } + private redrawToken = 0; + private redraw(): void { - // Preview with the chosen biome on the hex (nothing is written). - const plan = planRegionAt(this.host.plugin, this.parentName, this.px, this.py, { ...this.opts, hexTerrain: this.biomeTerrain() }); - drawRegionPlan(this.canvas, this.host.plugin, this.parentName, this.px, this.py, plan); + // Preview with the chosen biome on the hex (nothing is written), made + // the way the region will be (a generator-backed biome by its generator). + const token = ++this.redrawToken; + const opts = { ...this.opts, hexTerrain: this.biomeTerrain() }; + void planRegionWithGenerator(this.host.plugin, this.parentName, this.px, this.py, opts) + .catch(() => planRegionAt(this.host.plugin, this.parentName, this.px, this.py, opts)) + .then((plan) => { + if (token === this.redrawToken) drawRegionPlan(this.canvas, this.host.plugin, this.parentName, this.px, this.py, plan); + }); } private async apply(): Promise { diff --git a/src/overworld/regionGen.ts b/src/overworld/regionGen.ts index 412443d3..61ea1424 100644 --- a/src/overworld/regionGen.ts +++ b/src/overworld/regionGen.ts @@ -623,7 +623,7 @@ export function placeShore(input: ShoreInput): void { } const type = pick(odds, rng())!; const names = namesWithinType(phi, profiles, type, input.sharpness); - return pick(names.size ? names : profile.names.get(type) ?? new Map(), rng()); + return pick(names.size ? names : profile.names.get(type) ?? new Map(), rng()); }; for (const k of ownList) { const land = isLandCell.get(k)!; diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index d5a73d0d..98ed093f 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -8,8 +8,13 @@ * writes the plugin's maps. */ +import { Notice } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; -import type { MapData, RegionSettings, TerrainColor } from "../types"; +import type { MapData, MapPath, RegionSettings, TerrainColor, TerrainPalette } from "../types"; +import { addGeneratedPaths } from "../worldgen/generators"; +import { BiomeRegionError, generateBiomeRegion } from "../worldgen/biomeRegion"; +import { regionGenerator } from "./biomeForm"; +import { inRegion, regionBox } from "./layout"; import { slugify } from "../utils"; import { newWorldId } from "../worldgen/world"; import { BUILTIN_GENERATORS, builtinModel } from "../worldgen/builtinGenerators"; @@ -169,6 +174,11 @@ export interface RegionGenOptions { * are and blended around. */ export function planRegionAt(plugin: HexmakerPlugin, parentName: string, px: number, py: number, opts: RegionGenOptions = {}): RegionPlan | undefined { + return regionInputs(plugin, parentName, px, py, opts)?.plan(); +} + +/** Everything a region of hex (px, py) is made from (planRegionAt, planRegionWithGenerator). */ +function regionInputs(plugin: HexmakerPlugin, parentName: string, px: number, py: number, opts: RegionGenOptions) { const ow = overworldOf(plugin, parentName); if (!ow) return undefined; const palette = regionPalette(plugin, ow.map); @@ -183,7 +193,8 @@ export function planRegionAt(plugin: HexmakerPlugin, parentName: string, px: num const pinned = pinnedAround(plugin, parentName, ow.layout, px, py); const own = regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`); if (own) for (const [k, h] of plugin.mapStore.all(own.name)) if (h.locked && h.terrain) pinned.set(k, h.terrain); - return planRegion({ + const seed = opts.seed ?? own?.regionSeed ?? ws; + const plan = () => planRegion({ layout: ow.layout, parent: [px, py], biomes, @@ -191,10 +202,59 @@ export function planRegionAt(plugin: HexmakerPlugin, parentName: string, px: num pinned, typeOf: paletteTypeOf(palette), worldSeed: ws, - seed: opts.seed ?? own?.regionSeed ?? ws, + seed, blend: opts.blend ?? (ownBiome ? biomeNoteOf(ownBiome)?.blend : undefined) ?? ow.settings.blend, warp: opts.warp, }); + return { ow, palette, ownBiome, pinned, seed, plan }; +} + +/** A region plan, with the paths and note a generator-made region may bring. */ +export type RegionPlanOut = RegionPlan & { paths?: MapPath[]; note?: string }; + +/** + * What the region of hex (px, py) would be, made the way its biome says + * (biomeForm.regionGenerator): a biome with a generator link has its + * region made by that generator (generateBiomeRegion), joined to the cells + * painted around it; every other biome blends (planRegionAt). Throws + * BiomeRegionError when the generator can't make it (not found, doesn't + * fit the palette). + */ +export async function planRegionWithGenerator(plugin: HexmakerPlugin, parentName: string, px: number, py: number, opts: RegionGenOptions = {}): Promise { + const inputs = regionInputs(plugin, parentName, px, py, opts); + if (!inputs) return undefined; + const { ow, palette, ownBiome, pinned, seed } = inputs; + const plan = inputs.plan(); + const note = ownBiome ? biomeNoteOf(ownBiome) : undefined; + const route = regionGenerator(note); + if (route.kind !== "generator" || !route.ready) return plan; + const box = regionBox(ow.layout, px, py); + const name = ow.settings.palette ?? ow.map.paletteName; + const pal: TerrainPalette = { ...(plugin.getPaletteByName(name) ?? { name }), terrains: palette }; + const made = await generateBiomeRegion(plugin, { + generator: { path: route.generator }, + palette: pal, + bounds: { cols: box.cols, rows: box.rows, offset: { x: box.x, y: box.y }, stagger: ow.layout.childStagger }, + mask: (k) => { + const [x, y] = k.split("_").map(Number); + return inRegion(ow.layout, px, py, x, y); + }, + pinned, + seed, + }); + // Locked own cells stay out of the plan, as with the blend (they aren't rewritten). + const cells = new Map([...made.cells].filter(([k]) => !pinned.has(k))); + return { ...plan, cells, ...(made.paths ? { paths: made.paths } : {}), ...(made.note ? { note: made.note } : {}) }; +} + +/** planRegionWithGenerator, with a generator's error as a message instead of a throw. */ +async function planOrError(plugin: HexmakerPlugin, parentName: string, px: number, py: number, opts: RegionGenOptions): Promise { + try { + return await planRegionWithGenerator(plugin, parentName, px, py, opts); + } catch (e) { + if (e instanceof BiomeRegionError) return { error: e.message }; + throw e; + } } /** The palette regions of this overworld are painted with. */ @@ -225,7 +285,9 @@ export async function createRegion(plugin: HexmakerPlugin, parentName: string, p const settings = await ensureMeshFields(plugin, parent); const layout = regionLayoutOf(parent, gridRulesOf(plugin))!; const slot = regionSlot(layout, settings.worldId!, px, py); - const plan = opts.fill === "match" ? planRegionAt(plugin, parentName, px, py, opts) : undefined; + const planned = opts.fill === "match" ? await planOrError(plugin, parentName, px, py, opts) : undefined; + if (planned && "error" in planned) return planned; + const plan = planned; const paletteName = settings.palette ?? parent.paletteName; const taken = (n: string) => plugin.settings.maps.some((m) => m.name === slugify(n)); const name = opts.name?.trim() || defaultRegionName(plugin.mapLabel(parentName), px, py, plugin.mapStore.get(parentName, hex)?.name, taken); @@ -238,6 +300,8 @@ export async function createRegion(plugin: HexmakerPlugin, parentName: string, p child.world = slot.world; if (plan?.biome) child.biome = plan.biome; if (opts.seed !== undefined) child.regionSeed = opts.seed; + if (plan?.paths?.length) addGeneratedPaths(plugin, res.name, plan.paths); + if (plan?.note) new Notice(`${plugin.mapLabel(res.name)}: ${plan.note}`); await plugin.linkRegion(parentName, px, py, res.name); await fillBlankParent(plugin, parentName, px, py, res.name); return res; @@ -336,12 +400,20 @@ export async function regenerateRegion(plugin: HexmakerPlugin, regionName: strin if (region?.submapKind !== "region" || !region.parent) return 0; if (!canReshape(plugin.getMap(region.parent.map))) return 0; // see reshapeGate const [px, py] = region.parent.hex.split("_").map(Number); - const plan = planRegionAt(plugin, region.parent.map, px, py, opts); + const planned = await planOrError(plugin, region.parent.map, px, py, opts); + if (planned && "error" in planned) { + new Notice(planned.error); + return 0; + } + const plan = planned; if (!plan) return 0; const cur = plugin.mapStore.all(regionName); const cells: [string, { terrain: string }][] = []; for (const [k, t] of plan.cells) if (cur.get(k)?.terrain !== t) cells.push([k, { terrain: t }]); plugin.mapStore.setMany(regionName, cells); + // A generator's paths replace the ones of the same types it drew before. + if (plan.paths?.length) addGeneratedPaths(plugin, regionName, plan.paths, new Set(plan.paths.map((p) => p.typeName))); + if (plan.note) new Notice(`${plugin.mapLabel(regionName)}: ${plan.note}`); if (plan.biome) region.biome = plan.biome; if (opts.seed !== undefined) region.regionSeed = opts.seed; await plugin.saveSettings(); diff --git a/src/worldgen/BiomePanel.ts b/src/worldgen/BiomePanel.ts new file mode 100644 index 00000000..3f9dd7d2 --- /dev/null +++ b/src/worldgen/BiomePanel.ts @@ -0,0 +1,404 @@ +/** + * The generator page for a blend-field biome (#50): "Biome (blend field)". + * Opened with `plugin.openTerrainGenerator({ biome })` (the biome form's + * and Edit region's "Edit generator…"). Tunes what the biome's note says, + * with a live preview of a sample region made by the blend field + * (regionWorld.planRegion): + * + * - the type mix (weights) and min patches per type; + * - blend width, land share, min islands and shore; + * - transitions. + * + * Every change is written through `biomeStore.update` (the note's prose is + * kept); "Restore default" calls `restoreDefault` for shipped biomes. A + * hand edit to the note while the page is open re-renders it. + */ + +import { Notice, TFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { TerrainColor } from "../types"; +import { BIOME_BLENDS, type BiomeBlend, type BiomeNoteFields } from "../overworld/biomeNote"; +import { formTypes } from "../overworld/biomeForm"; +import { OPEN_SEA, profileFromFields, type BiomeId } from "../overworld/biomes"; +import { profilesForPalette } from "../overworld/regionsVault"; +import { paletteTypeOf, planRegion } from "../overworld/regionWorld"; +import { neighbourRegions, regionBox, type RegionLayout } from "../overworld/layout"; +import { drawPreview } from "./preview"; +import { renderPreviewLegend } from "../hex-map/terrainLegend"; +import { getIconUrl } from "../utils"; +import { randomSeed } from "../../packages/hex-wfc/src"; + +export interface BiomePanelHost { + rerender(): void; + /** A titled, foldable group of controls (GeneratorPanel.section). */ + section(el: HTMLElement, title: string): HTMLElement; + /** Leave the biome page for the generator list. */ + back(): void; +} + +/** What the preview puts around the sample region. */ +export type PreviewSurround = "same" | "land-west"; + +/** The note fields the page edits (everything but id, label, colour and generator). */ +export function biomePagePatch(f: BiomeNoteFields): Partial> { + return { + mix: f.mix.map((r) => ({ ...r })), + transitions: f.transitions.map((t) => ({ ...t })), + blend: f.blend, + landShare: f.landShare, + minIslands: f.minIslands, + shore: f.shore ? true : undefined, + }; +} + +/** Set a type's weight (0 drops it from the mix) or min patches (undefined clears it). Pure. */ +export function setMixRow(f: BiomeNoteFields, type: string, change: { weight?: number; minPatches?: number | null }): void { + let row = f.mix.find((r) => r.type === type); + if (change.weight !== undefined) { + const w = Math.max(0, Number.isFinite(change.weight) ? change.weight : 0); + if (w === 0) { f.mix = f.mix.filter((r) => r.type !== type); return; } + if (row) row.weight = w; + else { row = { type, weight: w }; f.mix.push(row); } + } + if (change.minPatches !== undefined && row) { + if (change.minPatches === null || !(change.minPatches > 0)) delete row.minPatches; + else row.minPatches = Math.round(change.minPatches); + } +} + +/** + * A sample region of a biome on a palette: the region of hex (0, 0) with + * its neighbours the same biome, or (`land-west`) land biomes on its + * west, open sea on its east and the biome itself north and south (to see + * a shore biome turn its land toward the land). + */ +export function biomeSamplePlan( + layout: RegionLayout, + palette: TerrainColor[], + fields: BiomeNoteFields, + seed: number, + surround: PreviewSurround, + landBiome: BiomeId, + others = profilesForPalette(palette), +) { + const biomes = new Map([["0_0", fields.id]]); + for (const [x, y] of neighbourRegions(layout, 0, 0)) { + // West of it land, east of it sea, north and south more of the biome. + biomes.set(`${x}_${y}`, surround === "same" || x === 0 ? fields.id : x < 0 ? landBiome : OPEN_SEA); + } + const profiles = new Map(others); + profiles.set(fields.id, profileFromFields(fields, palette)); + return planRegion({ + layout, + parent: [0, 0], + biomes, + profiles, + typeOf: paletteTypeOf(palette), + worldSeed: seed, + seed, + blend: fields.blend, + }); +} + +export class BiomePanel { + /** The store listener of the page on show (one at a time). */ + private static off: (() => void) | undefined; + static seed = randomSeed(); + static surround: PreviewSurround = "same"; + static size = 10; + + private fields: BiomeNoteFields; + private writing = 0; + private writeTimer: number | null = null; + private drawTimer: number | null = null; + + constructor( + private plugin: HexmakerPlugin, + private host: BiomePanelHost, + private id: string, + private paletteName: () => string, + ) { + const b = plugin.biomeStore.get(id)!; + this.fields = { ...b, mix: b.mix.map((r) => ({ ...r })), transitions: b.transitions.map((t) => ({ ...t })) }; + } + + /** Drop the page's store listener (the page closed or shows something else). */ + static dispose(): void { + BiomePanel.off?.(); + BiomePanel.off = undefined; + } + + private palette(): TerrainColor[] { + return this.plugin.getPaletteOrPresetTerrains(this.paletteName()); + } + + render(main: HTMLElement, side: HTMLElement): void { + const { plugin } = this; + const f = this.fields; + BiomePanel.dispose(); + BiomePanel.off = plugin.biomeStore.onChange(() => { + if (this.writing) return; + const now = plugin.biomeStore.get(this.id); + if (!now) { this.host.back(); return; } + if (JSON.stringify(biomePagePatch(now)) !== JSON.stringify(biomePagePatch(this.fields))) this.host.rerender(); + }); + + // Header: which biome, its note, restore, back. + let el = this.host.section(main, "Biome (blend field)"); + const head = el.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + head.createSpan({ text: "Biome", cls: "duckmage-map-origin-label" }); + const pick = head.createEl("select", { attr: { "aria-label": "Biome" } }); + for (const b of plugin.biomeStore.list()) { + if (b.generator) continue; + pick.createEl("option", { text: b.label, value: b.id }); + } + pick.value = this.id; + pick.addEventListener("change", () => { + void plugin.openTerrainGenerator({ biome: pick.value }); + }); + const path = plugin.biomeStore.pathOf(this.id); + head.createEl("button", { text: "Open note" }).addEventListener("click", () => { + const file = path ? plugin.app.vault.getAbstractFileByPath(path) : null; + if (file instanceof TFile) void plugin.app.workspace.getLeaf("tab").openFile(file); + }); + if (plugin.biomeStore.hasDefault(this.id)) { + head.createEl("button", { text: "Restore default", attr: { title: "Rewrite this biome's note from the shipped preset (the old note is backed up)" } }).addEventListener("click", () => { + void plugin.biomeStore.restoreDefault(this.id).then((ok) => { + if (!ok) return; + new Notice(`${f.label} is back to its default (the old note is in the plugin's backups folder).`); + this.host.rerender(); + }); + }); + } + head.createEl("button", { text: "Back to generators" }).addEventListener("click", () => this.host.back()); + el.createEl("p", { + cls: "duckmage-map-origin-desc", + text: `${f.label}'s regions mix these terrain types and blend into the biomes next to them. Changes are saved to its note${path ? ` (${path})` : ""}.`, + }); + + // Type mix. + el = this.host.section(main, "Type mix"); + const palette = this.palette(); + const present = new Set(palette.map((t) => t.type)); + const grid = el.createDiv({ cls: "duckmage-biome-page-mix" }); + const headRow = grid.createDiv({ cls: "duckmage-biome-page-row is-head" }); + for (const h of ["Type", "Weight", "", "Min patches"]) headRow.createSpan({ text: h }); + for (const type of formTypes(palette, f)) { + const row = grid.createDiv({ cls: "duckmage-biome-page-row" }); + if (!present.has(type)) row.addClass("is-missing"); + row.createSpan({ text: type, attr: { title: present.has(type) ? type : `${type}: not in this palette` } }); + const cur = () => f.mix.find((r) => r.type === type); + const slider = row.createEl("input", { type: "range", attr: { min: "0", max: "100", step: "1", "aria-label": `${type} weight` } }); + const num = row.createEl("input", { type: "number", cls: "duckmage-wfc-num", attr: { min: "0", step: "1", "aria-label": `${type} weight value` } }); + const patches = row.createEl("input", { type: "number", cls: "duckmage-wfc-num", attr: { min: "0", step: "1", placeholder: "—", "aria-label": `${type} min patches` } }); + const show = () => { + const r = cur(); + slider.value = String(Math.min(100, r?.weight ?? 0)); + num.value = String(r?.weight ?? 0); + patches.value = r?.minPatches !== undefined ? String(r.minPatches) : ""; + patches.disabled = !r; + }; + show(); + slider.addEventListener("input", () => { + setMixRow(f, type, { weight: Number(slider.value) }); + num.value = slider.value; + patches.disabled = !cur(); + this.schedulePreview(); + }); + slider.addEventListener("change", () => this.save()); + num.addEventListener("change", () => { + setMixRow(f, type, { weight: Number(num.value) }); + show(); + this.schedulePreview(); + this.save(); + }); + patches.addEventListener("change", () => { + setMixRow(f, type, { minPatches: patches.value.trim() === "" ? null : Number(patches.value) }); + show(); + this.schedulePreview(); + this.save(); + }); + } + el.createEl("p", { cls: "duckmage-map-origin-desc", text: "Weights are relative (any scale). Min patches: the fewest separate patches of that type a region gets, so a sprinkle (peaks, a volcano) isn't smoothed away." }); + + // Blend, land and shore. + el = this.host.section(main, "Blend and land"); + const field = (label: string) => { + const row = el.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + row.createSpan({ text: label, cls: "duckmage-map-origin-label" }); + return row; + }; + const blend = field("Blend width").createEl("select", { attr: { "aria-label": "Blend width" } }); + blend.createEl("option", { text: "Overworld setting", value: "" }); + for (const b of BIOME_BLENDS) blend.createEl("option", { text: b, value: b }); + blend.value = f.blend ?? ""; + blend.addEventListener("change", () => { + if (blend.value) f.blend = blend.value as BiomeBlend; + else delete f.blend; + this.schedulePreview(); + this.save(); + }); + const landRow = field("Land share"); + const landOn = landRow.createEl("input", { type: "checkbox", attr: { "aria-label": "Set a land share" } }); + const land = landRow.createEl("input", { type: "range", attr: { min: "0", max: "100", step: "5", "aria-label": "Land share" } }); + const landVal = landRow.createSpan(); + const showLand = () => { + landOn.checked = f.landShare !== undefined; + land.disabled = f.landShare === undefined; + land.value = String(Math.round((f.landShare ?? 0.5) * 100)); + landVal.setText(f.landShare !== undefined ? `${Math.round(f.landShare * 100)}%` : "Not set"); + }; + showLand(); + landOn.addEventListener("change", () => { + if (landOn.checked) f.landShare = Number(land.value) / 100; + else delete f.landShare; + showLand(); + this.schedulePreview(); + this.save(); + }); + land.addEventListener("input", () => { f.landShare = Number(land.value) / 100; showLand(); this.schedulePreview(); }); + land.addEventListener("change", () => this.save()); + const isl = field("Min islands").createEl("input", { type: "number", cls: "duckmage-wfc-num", attr: { min: "0", step: "1", placeholder: "—", "aria-label": "Min islands" } }); + isl.value = f.minIslands !== undefined ? String(f.minIslands) : ""; + isl.addEventListener("change", () => { + if (isl.value.trim() === "") delete f.minIslands; + else f.minIslands = Math.max(0, Math.round(Number(isl.value) || 0)); + this.schedulePreview(); + this.save(); + }); + const shoreRow = field("Shore"); + const shore = shoreRow.createEl("input", { type: "checkbox", attr: { "aria-label": "Shore" } }); + shore.checked = !!f.shore; + shoreRow.createSpan({ cls: "duckmage-map-origin-desc", text: "Land faces the land-heavy neighbours, water the rest, with a coast between." }); + shore.addEventListener("change", () => { + if (shore.checked) f.shore = true; + else delete f.shore; + this.schedulePreview(); + this.save(); + }); + el.createEl("p", { cls: "duckmage-map-origin-desc", text: "Land share and min islands are for watery biomes (islands), or with shore on, how much of a region is land." }); + + // Transitions. + el = this.host.section(main, "Transitions"); + el.createEl("p", { cls: "duckmage-map-origin-desc", text: "Biomes this one shouldn't touch on an overworld, and the biome put between them." }); + const trList = el.createDiv(); + const renderTr = () => { + trList.empty(); + f.transitions.forEach((t, i) => { + const row = trList.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + const sel = (value: string, label: string) => { + const s = row.createEl("select", { attr: { "aria-label": label } }); + s.createEl("option", { text: "—", value: "" }); + for (const b of plugin.biomeStore.list()) s.createEl("option", { text: b.label, value: b.label }); + const hit = [...s.options].find((o) => o.value.toLowerCase() === value.toLowerCase()); + if (!hit && value) s.createEl("option", { text: `${value} (unknown)`, value }); + s.value = hit?.value ?? value; + return s; + }; + row.createSpan({ text: "Next to" }); + const next = sel(t.next, "Next to"); + row.createSpan({ text: "put" }); + const between = sel(t.between, "Put between"); + const changed = () => { + t.next = next.value; + t.between = between.value; + if (t.next && t.between) this.save(); + }; + next.addEventListener("change", changed); + between.addEventListener("change", changed); + row.createEl("button", { text: "Remove", attr: { "aria-label": "Remove transition" } }).addEventListener("click", () => { + f.transitions.splice(i, 1); + renderTr(); + this.save(); + }); + }); + trList.createEl("button", { text: "Add transition" }).addEventListener("click", () => { + f.transitions.push({ next: "", between: "" }); + renderTr(); + }); + }; + renderTr(); + + // Preview (sticky side column). + const box = side.createDiv({ cls: "duckmage-wfc-section" }); + box.createEl("h4", { text: "Preview" }); + const canvas = box.createEl("canvas", { cls: "duckmage-wfc-preview" }); + const legend = box.createDiv(); + const status = box.createEl("p", { cls: "duckmage-map-origin-desc" }); + const seedRow = box.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + seedRow.createSpan({ text: "Seed", cls: "duckmage-map-origin-label" }); + const seed = seedRow.createEl("input", { type: "number", cls: "duckmage-wfc-seed", value: String(BiomePanel.seed) }); + seed.addEventListener("change", () => { BiomePanel.seed = Number(seed.value) >>> 0; this.drawPreview(canvas, legend, status, side); }); + seedRow.createEl("button", { text: "Re-roll" }).addEventListener("click", () => { + BiomePanel.seed = randomSeed(); + seed.value = String(BiomePanel.seed); + this.drawPreview(canvas, legend, status, side); + }); + seedRow.createSpan({ text: "Size", cls: "duckmage-map-origin-label" }); + const size = seedRow.createEl("input", { type: "number", cls: "duckmage-wfc-num", value: String(BiomePanel.size), attr: { min: "2", max: "32", "aria-label": "Region size" } }); + size.addEventListener("change", () => { + BiomePanel.size = Math.max(2, Math.min(32, Math.round(Number(size.value) || 10))); + size.value = String(BiomePanel.size); + this.drawPreview(canvas, legend, status, side); + }); + const aroundRow = box.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + aroundRow.createSpan({ text: "Around it", cls: "duckmage-map-origin-label" }); + const around = aroundRow.createEl("select", { attr: { "aria-label": "Around it" } }); + around.createEl("option", { text: "The same biome", value: "same" }); + around.createEl("option", { text: "Land to the west, sea to the east", value: "land-west" }); + around.value = BiomePanel.surround; + around.addEventListener("change", () => { BiomePanel.surround = around.value as PreviewSurround; this.drawPreview(canvas, legend, status, side); }); + const palRow = box.createDiv({ cls: "duckmage-region-row duckmage-wfc-map-row" }); + palRow.createSpan({ text: "Palette", cls: "duckmage-map-origin-label" }); + const palSel = palRow.createEl("select", { attr: { "aria-label": "Preview palette" } }); + for (const p of plugin.settings.terrainPalettes) palSel.createEl("option", { text: p.name, value: p.name }); + palSel.value = this.paletteName(); + palSel.addEventListener("change", () => { this.onPalette(palSel.value); }); + this.redrawPreview = () => this.drawPreview(canvas, legend, status, side); + this.drawPreview(canvas, legend, status, side); + } + + /** Called with a new preview palette (the page keeps it). */ + onPalette: (name: string) => void = () => {}; + + private redrawPreview: () => void = () => {}; + + private schedulePreview(): void { + if (this.drawTimer !== null) window.clearTimeout(this.drawTimer); + this.drawTimer = window.setTimeout(() => { this.drawTimer = null; this.redrawPreview(); }, 120); + } + + private drawPreview(canvas: HTMLCanvasElement, legend: HTMLElement, status: HTMLElement, side: HTMLElement): void { + const { plugin } = this; + const palette = this.palette(); + const stagger = plugin.settings.staggerOffset ?? "odd"; + const layout: RegionLayout = { footprint: "rect", size: BiomePanel.size, orientation: plugin.settings.hexOrientation, parentStagger: stagger, childStagger: stagger }; + if (!this.fields.mix.length) { + status.setText("Give at least one terrain type a weight."); + return; + } + const landBiome = plugin.biomeStore.list().find((b) => b.id !== this.fields.id && !b.generator && !b.shore && (b.landShare === undefined || b.landShare > 0.5) && b.mix.some((r) => r.type === "forest" || r.type === "grassland"))?.id ?? "grassland"; + const t0 = activeWindow.performance.now(); + const plan = biomeSamplePlan(layout, palette, this.fields, BiomePanel.seed, BiomePanel.surround, landBiome); + const b = regionBox(layout, 0, 0); + const colors = new Map(palette.map((t) => [t.name, t.color])); + const dpr = activeWindow.devicePixelRatio || 1; + drawPreview(canvas, plan.cells, { cols: b.cols, rows: b.rows, offset: { x: b.x, y: b.y }, stagger }, plugin.settings.hexOrientation, colors, undefined, [], new Map(), Math.max(420, side.clientWidth) * dpr, 40 * dpr); + renderPreviewLegend(legend, plugin, palette, plan.cells.values(), (i) => getIconUrl(plugin, i)); + status.setText(`One ${layout.size}×${layout.size} region · ${Math.round(activeWindow.performance.now() - t0)} ms`); + } + + /** Write the page's fields to the biome's note (debounced). */ + private save(): void { + if (this.writeTimer !== null) window.clearTimeout(this.writeTimer); + this.writeTimer = window.setTimeout(() => { + this.writeTimer = null; + this.writing++; + void this.plugin.biomeStore.update(this.id, biomePagePatch(this.fields)) + .then((ok) => { + if (ok) this.plugin.refreshHexMap(); + }) + .finally(() => { this.writing--; }); + }, 300); + } +} diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 2a577608..58af5176 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -42,6 +42,7 @@ import { isImpassable } from "../impassable"; import { SIDES, hexRangeText, type Side } from "./world"; import { blendFromNeighbours, regionBiome, generateConnected, neighbourSpec, NEIGHBOUR_SHARE, occupiedSides, placeNewRegion, regionNameAt, regionNeighbourNames, type NewRegion } from "./neighbours"; import { GeneratorLibrary } from "./GeneratorLibrary"; +import { BiomePanel } from "./BiomePanel"; import { hasFeature } from "../featureLevel"; import { renderAdvancedHint } from "../advancedHints"; import { generatorMapKind, isGeneratorShown, isSpacePalette } from "../mapKinds"; @@ -75,6 +76,17 @@ import { } from "../../packages/hex-wfc/src"; import type { TFile } from "obsidian"; +/** Labels of the biomes whose `generator:` link resolves to the generator note at `path`. */ +export function biomesUsing(plugin: HexmakerPlugin, path: string): string[] { + const out: string[] = []; + for (const b of plugin.biomeStore?.list() ?? []) { + if (!b.generator) continue; + const hit = plugin.app.vault.getAbstractFileByPath(b.generator) ?? plugin.app.vault.getAbstractFileByPath(`${b.generator}.md`) ?? plugin.app.metadataCache.getFirstLinkpathDest(b.generator, ""); + if (hit?.path === path) out.push(b.label); + } + return out; +} + export interface GeneratorPanelHost { /** Re-render the whole page (e.g. after learning a new generator). */ rerender(): void; @@ -119,6 +131,8 @@ export class GeneratorPanel { * the generators folder. */ static draft: HexWfcModel | null = null; + /** A blend-field biome shown instead of a generator (its id; "" = none). See BiomePanel. */ + static biome = ""; private seed = randomSeed(); private previewCols = 30; private previewRows = 20; @@ -182,6 +196,19 @@ export class GeneratorPanel { const show = () => { body.empty(); side.empty(); + BiomePanel.dispose(); + const biome = GeneratorPanel.biome ? this.plugin.biomeStore.get(GeneratorPanel.biome) : undefined; + if (biome && !biome.generator) { + const panel = new BiomePanel(this.plugin, { + rerender: () => this.host.rerender(), + section: (e, t) => this.section(e, t), + back: () => { GeneratorPanel.biome = ""; BiomePanel.dispose(); show(); }, + }, biome.id, () => GeneratorPanel.paletteName); + panel.onPalette = (name) => { GeneratorPanel.paletteName = name; show(); }; + panel.render(body, side); + return; + } + GeneratorPanel.biome = ""; const g = current(); if (g) this.renderGenerator(body, side, g); else { @@ -191,6 +218,7 @@ export class GeneratorPanel { } }; const choose = (g: GeneratorFile) => { + GeneratorPanel.biome = ""; GeneratorPanel.selectedPath = g.file.path; const source = sourceMapsOf(g.model)[0]; if (source && this.plugin.getMap(source)) GeneratorPanel.mapName = source; @@ -224,6 +252,7 @@ export class GeneratorPanel { selectedPath: () => GeneratorPanel.selectedPath, load: choose, loadDraft: (draft) => { + GeneratorPanel.biome = ""; GeneratorPanel.draft = draft; GeneratorPanel.selectedPath = DRAFT_PATH; show(); @@ -264,6 +293,14 @@ export class GeneratorPanel { cls: "duckmage-map-origin-desc", }); summary.setAttr("title", [...detail, ...g.warnings].join("\n")); + // Biomes whose regions this generator makes (their note links it). + const usedBy = file ? biomesUsing(this.plugin, file.path) : []; + if (usedBy.length) { + el.createEl("p", { + cls: "duckmage-map-origin-desc duckmage-wfc-used-by", + text: `Used by biome${usedBy.length === 1 ? "" : "s"} ${usedBy.join(", ")}: ${usedBy.length === 1 ? "its" : "their"} overworld regions are made by this generator.`, + }); + } // Current settings, kept in sync with the file. const s = () => generatorSettings(model, this.plugin.getPaletteByName(GeneratorPanel.paletteName)?.terrains ?? []); @@ -1373,7 +1410,7 @@ export class GeneratorPanel { * A titled group of controls; click the title to fold it away. Folded * sections stay folded across re-renders. Returns the section's body. */ - private section(el: HTMLElement, text: string): HTMLElement { + section(el: HTMLElement, text: string): HTMLElement { const box = el.createDiv({ cls: "duckmage-wfc-group" }); const title = box.createEl("h5", { cls: "duckmage-wfc-heading is-collapsible", attr: { role: "button", tabindex: "0" } }); setIcon(title.createSpan({ cls: "duckmage-wfc-fold" }), "chevron-down"); diff --git a/src/worldgen/GeneratorView.ts b/src/worldgen/GeneratorView.ts index ce8864ca..401ea648 100644 --- a/src/worldgen/GeneratorView.ts +++ b/src/worldgen/GeneratorView.ts @@ -2,6 +2,7 @@ import { ItemView, type WorkspaceLeaf } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import { VIEW_TYPE_GENERATOR } from "../constants"; import { GeneratorPanel } from "./GeneratorPanel"; +import { BiomePanel } from "./BiomePanel"; /** Full-page terrain generator (wave function collapse). */ export class GeneratorView extends ItemView { @@ -40,6 +41,7 @@ export class GeneratorView extends ItemView { } async onClose(): Promise { + BiomePanel.dispose(); this.contentEl.empty(); } } diff --git a/src/worldgen/WalkRegionModal.ts b/src/worldgen/WalkRegionModal.ts index 1ff1f4bc..4a978b5f 100644 --- a/src/worldgen/WalkRegionModal.ts +++ b/src/worldgen/WalkRegionModal.ts @@ -7,7 +7,7 @@ import { createWalkRegion, planWalk, previewWalk, regionBiome, type WalkPlan } f import { drawPreview } from "./preview"; import type { Side } from "./world"; import { biomeForTerrain, biomeInfo, representativeTerrain } from "../overworld/biomes"; -import { regionHome, inOverworldGrid, planRegionAt, walkIntoHex, walkLock } from "../overworld/regionsVault"; +import { regionHome, inOverworldGrid, planRegionAt, planRegionWithGenerator, walkIntoHex, walkLock } from "../overworld/regionsVault"; import { defaultRegionName, rollBiome } from "../overworld/regionWorld"; import { drawRegionPlan, lockButton, paintableBiomes } from "../hex-map/BiomeModals"; import { ADD_REGION_LOCKED_HINT, canAdd } from "../workMode"; @@ -131,8 +131,15 @@ export class WalkRegionModal extends HexmakerModal { const labelOf = (id: string) => biomeInfo(id)?.label ?? id; let rolled = ""; + let token = 0; const refresh = () => { - const plan = planRegionAt(plugin, walk.overworld, px, py, { seed: this.seed, hexTerrain: representativeTerrain(biome, owPalette) }); + const mine = ++token; + const opts = { seed: this.seed, hexTerrain: representativeTerrain(biome, owPalette), biome }; + void planRegionWithGenerator(plugin, walk.overworld, px, py, opts) + .catch(() => planRegionAt(plugin, walk.overworld, px, py, opts)) + .then((plan) => { if (mine === token) show(plan); }); + }; + const show = (plan: ReturnType) => { drawRegionPlan(canvas, plugin, walk.overworld, px, py, plan); // The biomes it blends from: the field's, plus the one walked from. const fromIds = new Set((plan?.biome?.from ?? []).filter((b) => b !== biome)); diff --git a/src/worldgen/biomeRegion.ts b/src/worldgen/biomeRegion.ts new file mode 100644 index 00000000..2989e368 --- /dev/null +++ b/src/worldgen/biomeRegion.ts @@ -0,0 +1,198 @@ +/** + * Regions made by a generator (#50, the generator side of custom biomes): + * a biome whose note links a generator (`generator: [[…]]`) has its + * overworld regions made by that generator instead of the blend field. + * biomeForm.regionGenerator is the routing point; regionsVault calls + * generateBiomeRegion for such biomes. + * + * The region is solved with a one-hex ring around its bounding box, every + * pinned cell in reach fixed (the neighbouring regions' painted cells and + * the region's own locked ones), then cropped to the region's mask, so the + * seams join up the same way a neighbouring map's edge does + * (neighbours.ts solveWithRing, shared with generateConnected). + */ + +import { TFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { HexKey, MapPath, PathType, TerrainPalette } from "../types"; +import { isModelMarkdown, parseModelMarkdown, type HexWfcModel } from "../../packages/hex-wfc/src"; +import { blendSourcesOf, drawnPathType, generatorFitsPalette, toPathsOn, type GridSpec } from "./generators"; +import { BUILTIN_GENERATORS, BUILTIN_PREFIX, builtinModel, builtinPathType, fitBuiltinModel } from "./builtinGenerators"; +import { solveWithRing } from "./neighbours"; +import { listGeneratorKinds, optionsWithDefaults } from "./registry"; +import type { GenerationContext } from "./procedural/common"; +import { mapRouteContext } from "../paths/mapContext"; +import { impassableNames } from "../impassable"; + +/** + * Which generator makes the region: + * - `{ path }`: a generator note (learned or blend), by vault path or link + * target (`world/generators/My tundra`, with or without `.md`); a shipped + * generator's slug or label is accepted too (no file needed); + * - `{ builtin }`: a shipped preset generator by slug (`preset-volcanic`); + * - `{ id }`: a generator id from the registry (`wfc:`, + * `builtin:`, or a procedural one such as `overland`); + * - `{ model, source }`: a generator already in memory (the generator page, + * tests). Preset models are fitted to the palette first. + */ +export type GeneratorRef = + | { path: string } + | { builtin: string } + | { id: string } + | { model: HexWfcModel; source: "learned" | "blend" | "preset" }; + +export interface BiomeRegionRequest { + generator: GeneratorRef; + /** The palette the region is painted with. */ + palette: TerrainPalette; + /** The region's bounding box in the shared grid (stagger: default the plugin's). */ + bounds: { cols: number; rows: number; offset: { x: number; y: number }; stagger?: "odd" | "even" }; + /** Which cells of the box are the region's (hex flowers); default all. */ + mask?: (key: HexKey) => boolean; + /** Cells already painted (neighbouring regions, the region's locked cells): never changed. */ + pinned: Map; + seed: number; + /** Parent hex / neighbours, for procedural generators that read it. */ + context?: GenerationContext; +} + +export interface BiomeRegionResult { + /** The region's cells (pinned ones inside it come out as they were). */ + cells: Map; + /** Paths the generator drew, anchored on the region's own terrain; only when it made some. */ + paths?: MapPath[]; + /** Anything worth telling the user (edge pins dropped, path types missing). */ + note?: string; +} + +/** Thrown when a region can't be made; `message` says why, for the user. */ +export class BiomeRegionError extends Error {} + +interface Loaded { + name: string; + /** A hex-wfc model (learned, blend or fitted preset), or a registry kind id. */ + model?: HexWfcModel; + kindId?: string; + preset: boolean; +} + +const nameOf = (target: string) => target.slice(target.lastIndexOf("/") + 1).replace(/\.md$/i, ""); + +/** A shipped generator by slug or label (case-insensitive). */ +function builtinBy(name: string): string | undefined { + const k = name.trim().toLowerCase(); + return BUILTIN_GENERATORS.find((d) => d.slug === k || d.label.toLowerCase() === k)?.slug; +} + +async function load(plugin: HexmakerPlugin, ref: GeneratorRef): Promise { + if ("model" in ref) return { name: ref.model.name, model: ref.model, preset: ref.source === "preset" }; + if ("builtin" in ref) { + const model = builtinModel(ref.builtin); + if (!model) throw new BiomeRegionError(`There's no shipped generator called ${ref.builtin}.`); + return { name: BUILTIN_GENERATORS.find((d) => d.slug === ref.builtin)?.label ?? ref.builtin, model, preset: true }; + } + if ("id" in ref) { + if (ref.id.startsWith("wfc:")) return load(plugin, { path: ref.id.slice(4) }); + if (ref.id.startsWith(BUILTIN_PREFIX)) return load(plugin, { builtin: ref.id.slice(BUILTIN_PREFIX.length) }); + return { name: ref.id, kindId: ref.id, preset: false }; + } + const target = ref.path.trim(); + const vault = plugin.app.vault; + const file = vault.getAbstractFileByPath(target) ?? vault.getAbstractFileByPath(`${target}.md`) ?? plugin.app.metadataCache.getFirstLinkpathDest(target, ""); + if (file instanceof TFile) { + const text = await vault.cachedRead(file); + if (!isModelMarkdown(text)) throw new BiomeRegionError(`${file.basename} isn't a generator note.`); + try { + return { name: file.basename, model: parseModelMarkdown(text, file.basename).model, preset: false }; + } catch (e) { + throw new BiomeRegionError(`Couldn't read generator ${file.basename}: ${e instanceof Error ? e.message : String(e)}`); + } + } + const slug = builtinBy(nameOf(target)); + if (slug) return load(plugin, { builtin: slug }); + throw new BiomeRegionError(`Generator ${nameOf(target)} wasn't found.`); +} + +/** What kind of generator a ref is, for the page and the report: learned, blend or preset. */ +export function generatorSource(model: HexWfcModel, preset: boolean): "learned" | "blend" | "preset" { + return preset ? "preset" : blendSourcesOf(model).length ? "blend" : "learned"; +} + +/** + * Make one overworld region with a generator, joined to the cells already + * painted around it. Pinned cells come out unchanged; the same seed gives + * the same region. Throws BiomeRegionError (readable message) when the + * generator can't be found or doesn't fit the palette. + */ +export async function generateBiomeRegion(plugin: HexmakerPlugin, req: BiomeRegionRequest): Promise { + const loaded = await load(plugin, req.generator); + const terrains = req.palette.terrains; + const names = terrains.map((t) => t.name); + const stagger = req.bounds.stagger ?? plugin.settings.staggerOffset ?? "odd"; + const grid: GridSpec = { cols: req.bounds.cols, rows: req.bounds.rows, offset: { ...req.bounds.offset }, stagger }; + const inBox = (k: string) => { + const [x, y] = k.split("_").map(Number); + return x >= grid.offset.x && x < grid.offset.x + grid.cols && y >= grid.offset.y && y < grid.offset.y + grid.rows; + }; + const mine = (k: string) => inBox(k) && (!req.mask || req.mask(k)); + const pathTypes: readonly PathType[] = req.palette.pathTypes ?? plugin.getPathTypes(req.palette.name); + + let cells: Map; + let raw: { type: string; route?: string; hexes: string[] }[] = []; + let model: HexWfcModel | undefined; + const warnings: string[] = []; + + if (loaded.kindId) { + const kind = (await listGeneratorKinds(plugin)).find((k) => k.id === loaded.kindId); + if (!kind) throw new BiomeRegionError(`There's no generator ${loaded.kindId}.`); + if (!kind.fits(terrains)) throw new BiomeRegionError(`${kind.label} doesn't fit palette ${req.palette.name}.`); + const out = kind.generate({ terrains, grid, seed: req.seed, options: optionsWithDefaults(kind), pathTypes, context: req.context }); + if (!out.ok) throw new BiomeRegionError(`${kind.label}: ${out.message}`); + cells = out.cells; + raw = out.paths; + warnings.push(...out.warnings); + } else { + model = loaded.model!; + if (loaded.preset) { + const fit = fitBuiltinModel(model, terrains); + if (!fit) throw new BiomeRegionError(`${loaded.name} doesn't fit palette ${req.palette.name}: it has too few terrains with a type for it.`); + model = fit; + } else if (!generatorFitsPalette(model, names)) { + const missing = model.terrains.filter((t) => t.weight > 0 && !names.includes(t.name)).map((t) => t.name); + throw new BiomeRegionError( + missing.length + ? `${loaded.name} doesn't fit palette ${req.palette.name}: it uses ${missing.join(", ")}, which the palette doesn't have.` + : `${loaded.name} has no terrains to place.`, + ); + } + const r = solveWithRing(plugin, model, names, grid, req.pinned, req.seed, req.mask); + if (!r.ok) throw new BiomeRegionError(`${loaded.name} couldn't make this region: ${r.message}`); + cells = r.cells; + raw = r.paths; + warnings.push(...r.warnings); + } + + // The region's cells; pinned ones as they were. + const out = new Map(); + for (const [k, t] of cells) if (mine(k)) out.set(k, req.pinned.get(k) ?? t); + for (const [k, t] of req.pinned) if (mine(k)) out.set(k, t); + + const result: BiomeRegionResult = { cells: out }; + if (raw.length) { + // Shipped generators' path types draw as the palette's type that behaves like them. + const typed = loaded.preset ? raw.map((p) => ({ type: builtinPathType(drawnPathType(model, p), pathTypes), hexes: p.hexes })) : raw; + const route = mapRouteContext({ + orientation: plugin.settings.hexOrientation, + stagger, + gridSize: { cols: grid.cols, rows: grid.rows }, + gridOffset: grid.offset, + terrainOf: [...out].map(([k, t]): [string, { terrain: string }] => [k, { terrain: t }]), + impassable: impassableNames(terrains), + }); + const { paths, missing } = toPathsOn(typed, loaded.preset ? undefined : model, { pathTypes, route }); + if (paths.length) result.paths = paths; + if (missing.length) warnings.push(`No path type named ${missing.join(", ")}, so those paths were skipped`); + } + if (warnings.length) result.note = warnings.join(". ") + "."; + return result; +} diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index fd175d12..fb19f107 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -16,8 +16,11 @@ import { getFrontMatter, getTerrainFromFile, setTerrainInFile } from "../frontma import { normalizeFolder, slugify } from "../utils"; import { VERSION_KEY, pluginVersion } from "../compat"; import { isImpassable } from "../impassable"; -import type { MapPath, TerrainColor } from "../types"; +import type { MapPath, PathType, TerrainColor } from "../types"; import { generatedToMapPaths } from "../paths/fromGenerated"; +import { pathTypeStyleFor } from "../paths/mapContext"; +import type { RouteContext } from "../paths/router"; +import type { StyleFor } from "../paths/resolve"; import { learnModel, mergeModels, @@ -165,15 +168,40 @@ export function toMapPaths( taken?: Iterable, ): { paths: MapPath[]; missing: string[] } { const map = plugin.getMap(mapName); - const known = new Set(plugin.getMapPathTypes(mapName).map((t) => t.name)); - const typed = paths.map((p) => ({ typeName: drawnPathType(model, p), hexes: [...p.hexes] })); - const missing = [...new Set(typed.map((p) => p.typeName).filter((t) => !known.has(t)))]; - if (!map) return { paths: [], missing }; + const pathTypes = plugin.getMapPathTypes(mapName); + if (!map) return { paths: [], missing: missingPathTypes(paths, model, pathTypes) }; const store = plugin.mapStore; + return toPathsOn(paths, model, { + pathTypes, + route: store.routeContext(map), + styleFor: store.pathStyleFor(map), + taken: taken ?? store.paths(mapName).map((p) => p.name), + }); +} + +/** Path types generated paths are drawn as that `pathTypes` doesn't have. */ +function missingPathTypes(paths: readonly { type: string; route?: string }[], model: HexWfcModel | undefined, pathTypes: readonly PathType[]): string[] { + const known = new Set(pathTypes.map((t) => t.name)); + return [...new Set(paths.map((p) => drawnPathType(model, p)).filter((t) => !known.has(t)))]; +} + +/** + * toMapPaths against any routing context: a map that doesn't exist yet + * (an overworld region being generated) passes its own bounds and terrain + * (paths/mapContext.ts mapRouteContext) and its palette's path types. + */ +export function toPathsOn( + paths: readonly { type: string; route?: string; hexes: readonly string[] }[], + model: HexWfcModel | undefined, + target: { pathTypes: readonly PathType[]; route: RouteContext; styleFor?: StyleFor; taken?: Iterable }, +): { paths: MapPath[]; missing: string[] } { + const known = new Set(target.pathTypes.map((t) => t.name)); + const typed = paths.map((p) => ({ typeName: drawnPathType(model, p), hexes: [...p.hexes] })); + const missing = missingPathTypes(paths, model, target.pathTypes); const { paths: out } = generatedToMapPaths( typed.filter((p) => known.has(p.typeName)), - store.routeContext(map), - { styleFor: store.pathStyleFor(map), taken: taken ?? store.paths(mapName).map((p) => p.name) }, + target.route, + { styleFor: target.styleFor ?? pathTypeStyleFor(target.pathTypes), taken: target.taken ?? [] }, ); return { paths: out, missing }; } diff --git a/src/worldgen/neighbours.ts b/src/worldgen/neighbours.ts index c90902e8..640b39e0 100644 --- a/src/worldgen/neighbours.ts +++ b/src/worldgen/neighbours.ts @@ -155,41 +155,72 @@ export function generateConnected( const shadowInfo = neighbourShadow(plugin, region); const shadow = new Map(); for (const [k, v] of shadowInfo) if (v.terrain) shadow.set(k, v.terrain); - const { cols, rows, offset } = region; - const inside = (key: string) => { + return { ...solveWithRing(plugin, model, paletteTerrains, { cols: region.cols, rows: region.rows, offset: region.offset, stagger: region.stagger }, shadow, seed), shadow }; +} + +/** + * Solve `grid` so it carries on from `around` (hex key → terrain): the grid + * is solved with a one-hex ring around it, every `around` cell inside that + * ring (or the grid itself) pinned, then cropped to the grid (and to + * `inside`, when given). Pins that clash with the generator's rules are + * dropped one at a time (up to 40); if it still can't fit, the grid is + * generated on its own, keeping only the pins inside it, with a warning. + * Shared by generateConnected (a neighbour's edge) and generateBiomeRegion + * (an overworld region's painted neighbours). + */ +export function solveWithRing( + plugin: HexmakerPlugin, + model: HexWfcModel, + paletteTerrains: string[], + grid: GridSpec, + around: ReadonlyMap, + seed: number, + inside?: (key: string) => boolean, +): SolveResult { + const { cols, rows, offset } = grid; + const inGrid = (key: string) => { const [x, y] = key.split("_").map(Number); return x >= offset.x && x < offset.x + cols && y >= offset.y && y < offset.y + rows; }; - // The ring one hex out, where a neighbour is. + const keep = inside ? (key: string) => inGrid(key) && inside(key) : inGrid; + // The ring one hex out (and the grid itself), where a pin is. const fixed = new Map(); - for (const [k, t] of shadow) { + for (const [k, t] of around) { const [x, y] = k.split("_").map(Number); if (x >= offset.x - 1 && x <= offset.x + cols && y >= offset.y - 1 && y <= offset.y + rows) fixed.set(k, t); } - if (!fixed.size) { - const grid: GridSpec = { cols, rows, offset, stagger: region.stagger }; - return { ...generateTerrain(plugin, model, paletteTerrains, grid, seed), shadow }; - } - const grid: GridSpec = { cols: cols + 2, rows: rows + 2, offset: { x: offset.x - 1, y: offset.y - 1 }, stagger: region.stagger }; + const crop = (r: SolveResult): SolveResult => { + if (!r.ok || !inside) return r; + return { + ...r, + cells: new Map([...r.cells].filter(([k]) => keep(k))), + featureCells: new Set([...r.featureCells].filter(keep)), + paths: r.paths.map((p) => ({ ...p, hexes: cropPath(p.hexes, keep) })).filter((p) => p.hexes.length >= 2), + }; + }; + if (!fixed.size) return crop(generateTerrain(plugin, model, paletteTerrains, grid, seed)); + const ringGrid: GridSpec = { cols: cols + 2, rows: rows + 2, offset: { x: offset.x - 1, y: offset.y - 1 }, stagger: grid.stagger }; let dropped = 0; - let r = generateTerrain(plugin, model, paletteTerrains, grid, seed, fixed); + let r = generateTerrain(plugin, model, paletteTerrains, ringGrid, seed, fixed); while (!r.ok && r.at && fixed.size && dropped < 40) { const key = `${r.at.x}_${r.at.y}`; if (!fixed.delete(key)) break; dropped++; - r = generateTerrain(plugin, model, paletteTerrains, grid, seed, fixed); + r = generateTerrain(plugin, model, paletteTerrains, ringGrid, seed, fixed); } if (!r.ok) { - const alone = generateTerrain(plugin, model, paletteTerrains, { cols, rows, offset, stagger: region.stagger }, seed); + const own = new Map([...around].filter(([k]) => inGrid(k))); + let alone = generateTerrain(plugin, model, paletteTerrains, grid, seed, own.size ? own : undefined); + if (!alone.ok && own.size) alone = generateTerrain(plugin, model, paletteTerrains, grid, seed); if (alone.ok) alone.warnings.unshift("Couldn't fit this map to its neighbours' edges, so it was generated on its own"); - return { ...alone, shadow }; + return crop(alone); } - const cells = new Map([...r.cells].filter(([k]) => inside(k))); - const featureCells = new Set([...r.featureCells].filter(inside)); - const paths = r.paths.map((p) => ({ ...p, hexes: cropPath(p.hexes, inside) })).filter((p) => p.hexes.length >= 2); + const cells = new Map([...r.cells].filter(([k]) => keep(k))); + const featureCells = new Set([...r.featureCells].filter(keep)); + const paths = r.paths.map((p) => ({ ...p, hexes: cropPath(p.hexes, keep) })).filter((p) => p.hexes.length >= 2); const warnings = [...r.warnings]; if (dropped) warnings.push(`${dropped} edge hex${dropped === 1 ? "" : "es"} couldn't be matched to the neighbouring map's terrain`); - return { ...r, cells, featureCells, paths, warnings, shadow }; + return { ...r, cells, featureCells, paths, warnings }; } /** Name of the map on `side` of a region that's about to be made. */ From 340dc0a0b03f73d5afc6f2cf7d436e1876314bcd Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 00:40:55 -0400 Subject: [PATCH 263/558] feat(biomes #50): Climate section in the biome form A folded 'Climate (optional, for generated overworlds)' section: temperature and moisture as typed (words or numbers), height, chance, coast only, rare. Blank = only placed by hand; unreadable values block Save with the reason. Co-Authored-By: Claude Opus 5.5 --- src/hex-map/BiomeLibraryModal.ts | 35 +++++++++++++++++++++++-- src/overworld/biomeForm.ts | 45 ++++++++++++++++++++++++++++++++ styles.css | 7 ++++- tests/biomeClimate.test.ts | 27 +++++++++++++++++++ 4 files changed, 111 insertions(+), 3 deletions(-) diff --git a/src/hex-map/BiomeLibraryModal.ts b/src/hex-map/BiomeLibraryModal.ts index 3f6e0b60..62bbb65b 100644 --- a/src/hex-map/BiomeLibraryModal.ts +++ b/src/hex-map/BiomeLibraryModal.ts @@ -18,7 +18,7 @@ import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { canAdd } from "../workMode"; import { BIOME_BLENDS, type BiomeBlend, type BiomeNoteFields } from "../overworld/biomeNote"; -import { fieldsFromForm, formFromFields, formProblem, formTypes, generatorName, previewRegion, routeNote, type BiomeFormState } from "../overworld/biomeForm"; +import { fieldsFromForm, formFromFields, formProblem, formTypes, generatorName, previewRegion, routeNote, type BiomeFormState, type ClimateFormState } from "../overworld/biomeForm"; import { overworldOf, regionPalette } from "../overworld/regionsVault"; import { cellsBox, composeAffine, drawRegionCells, type RegionCell } from "../overworld/overworldRender"; import { regionCells } from "../overworld/layout"; @@ -224,6 +224,37 @@ export class BiomeFormModal extends HexmakerModal { isl.addEventListener("change", () => { state.minIslands = isl.value.trim() === "" ? undefined : Math.max(0, Math.round(Number(isl.value) || 0)); this.schedule(); }); isles.createEl("p", { cls: "setting-item-description", text: "For archipelagos: how much of a region is land, and the fewest islands it gets." }); + // Climate (optional): where World biomes may place it. + const cl = state.climate; + const clBox = form.createEl("details", { cls: "duckmage-biome-climate" }); + clBox.open = !!(cl.temperature || cl.moisture || cl.elevation || cl.coastal); + clBox.createEl("summary", { text: "Climate (optional, for generated overworlds)" }); + const clGrid = clBox.createDiv({ cls: "duckmage-biome-mix-grid" }); + const text = (label: string, value: string, placeholder: string, set: (v: string) => void) => { + const input = field(label, clGrid).createEl("input", { type: "text", attr: { "aria-label": label, placeholder } }); + input.value = value; + input.addEventListener("input", () => { set(input.value); this.check(); }); + }; + text("Temperature", cl.temperature, "Any (e.g. cold–mild)", (v) => { cl.temperature = v; }); + text("Moisture", cl.moisture, "Any (e.g. wet, 0.2–0.5)", (v) => { cl.moisture = v; }); + const elev = field("Height", clGrid).createEl("select", { attr: { "aria-label": "Height" } }); + for (const [v, t] of [["", "Not set (low)"], ["low", "Low"], ["mid", "Mid (hills)"], ["high", "High (peaks)"], ["sea", "Sea"], ["mouth", "River mouth"]] as const) elev.createEl("option", { value: v, text: t }); + elev.value = cl.elevation; + elev.addEventListener("change", () => { cl.elevation = elev.value as ClimateFormState["elevation"]; this.check(); }); + const chance = field("Chance %", clGrid).createEl("input", { type: "number", attr: { min: "0", max: "100", step: "5", placeholder: "100", "aria-label": "Chance" } }); + chance.value = cl.chancePercent !== undefined ? String(cl.chancePercent) : ""; + chance.addEventListener("change", () => { cl.chancePercent = chance.value.trim() === "" ? undefined : Math.min(100, Math.max(0, Number(chance.value) || 0)); this.check(); }); + const tick = (label: string, on: boolean, set: (v: boolean) => void) => { + const row = clGrid.createEl("label", { cls: "duckmage-region-gen-row" }); + const box = row.createEl("input", { type: "checkbox" }); + box.checked = on; + row.createSpan({ text: label }); + box.addEventListener("change", () => { set(box.checked); this.check(); }); + }; + tick("Coast only", cl.coastal, (v) => { cl.coastal = v; }); + tick("Rare", cl.rare, (v) => { cl.rare = v; }); + clBox.createEl("p", { cls: "setting-item-description", text: "When set, World biomes can place this biome where the climate fits, like a built-in one. Left blank, it's only placed by hand. Temperature: cold, cool, mild, warm, hot; moisture: dry, moderate, wet; or numbers from 0 to 1." }); + // Transitions. const trBox = form.createEl("details", { cls: "duckmage-biome-transitions" }); trBox.open = state.transitions.length > 0; @@ -339,7 +370,7 @@ export class BiomeFormModal extends HexmakerModal { const fields = fieldsFromForm(this.state, existing?.id); if (existing) { // Unset optional fields are written as removed. - const full: Partial = { color: undefined, generator: undefined, blend: undefined, landShare: undefined, minIslands: undefined, ...fields }; + const full: Partial = { color: undefined, generator: undefined, blend: undefined, landShare: undefined, minIslands: undefined, climate: undefined, ...fields }; delete full.id; if (!(await plugin.biomeStore.update(existing.id, full))) return; } else { diff --git a/src/overworld/biomeForm.ts b/src/overworld/biomeForm.ts index 504381aa..812a0706 100644 --- a/src/overworld/biomeForm.ts +++ b/src/overworld/biomeForm.ts @@ -9,6 +9,7 @@ import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; import type { TerrainColor } from "../types"; import { biomeSlug, type BiomeBlend, type BiomeNoteFields, type BiomeTransition } from "./biomeNote"; +import { climateKeyValues, readClimate, type BiomeClimate, type ClimateElevation } from "./biomeClimate"; import { profileFromMix, type BiomeId } from "./biomes"; import { planRegion, paletteTypeOf, type RegionPlan } from "./regionWorld"; import type { RegionLayout } from "./layout"; @@ -57,6 +58,45 @@ export interface BiomeFormState { landPercent?: number; minIslands?: number; transitions: BiomeTransition[]; + /** Climate for generated overworlds, as typed (blank = not set). */ + climate: ClimateFormState; +} + +/** The form's climate fields: text as typed for the ranges, so any spelling the note accepts works. */ +export interface ClimateFormState { + temperature: string; + moisture: string; + elevation: ClimateElevation | ""; + coastal: boolean; + /** 0..100, or undefined (every fitting hex). */ + chancePercent?: number; + rare: boolean; +} + +/** The form's climate fields filled from a biome's climate. */ +export function climateFormFrom(c: BiomeClimate | undefined): ClimateFormState { + const values = new Map(climateKeyValues(c)); + return { + temperature: values.get("temperature") ?? "", + moisture: values.get("moisture") ?? "", + elevation: c?.elevation ?? "", + coastal: !!c?.coastal, + chancePercent: c?.chance !== undefined ? Math.round(c.chance * 100) : undefined, + rare: !!c?.rare, + }; +} + +/** The climate the form says, and what in it couldn't be read. */ +export function climateFromForm(s: ClimateFormState): { climate?: BiomeClimate; problems: string[] } { + const fm = new Map(); + if (s.temperature.trim()) fm.set("temperature", s.temperature); + if (s.moisture.trim()) fm.set("moisture", s.moisture); + if (s.elevation) fm.set("elevation", s.elevation); + if (s.coastal) fm.set("coastal", "yes"); + if (s.chancePercent !== undefined) fm.set("chance", `${Math.min(100, Math.max(0, s.chancePercent))}%`); + if (s.rare) fm.set("rare", "yes"); + const r = readClimate(fm); + return { climate: r.climate, problems: r.problems.map((p) => p.text) }; } /** The types a form offers: the palette's (in order, settlements left out), then any others the biome already uses. */ @@ -80,6 +120,7 @@ export function formFromFields(fields: BiomeNoteFields | undefined, types: strin landPercent: fields?.landShare !== undefined ? Math.round(fields.landShare * 100) : undefined, minIslands: fields?.minIslands, transitions: (fields?.transitions ?? []).map((t) => ({ ...t })), + climate: climateFormFrom(fields?.climate), }; } @@ -97,6 +138,8 @@ export function fieldsFromForm(s: BiomeFormState, id?: string): BiomeNoteFields if (s.blend) f.blend = s.blend; if (s.landPercent !== undefined) f.landShare = Math.min(100, Math.max(0, s.landPercent)) / 100; if (s.minIslands !== undefined) f.minIslands = Math.max(0, Math.round(s.minIslands)); + const climate = s.climate ? climateFromForm(s.climate).climate : undefined; + if (climate) f.climate = climate; return f; } @@ -108,6 +151,8 @@ export function formProblem(s: BiomeFormState, others: { id: string; label: stri if (!k) return "Use some letters or numbers in the name."; if (others.some((o) => o.id === k || biomeSlug(o.label) === k)) return `There's already a biome called ${label}.`; if (![...s.mix.values()].some((w) => w > 0)) return "Give at least one terrain type a weight."; + const climate = s.climate ? climateFromForm(s.climate).problems : []; + if (climate.length) return `Climate: ${climate[0]}.`; return undefined; } diff --git a/styles.css b/styles.css index 86ab6015..b1abb9ab 100644 --- a/styles.css +++ b/styles.css @@ -8578,7 +8578,12 @@ textarea.duckmage-edit-region-notes-input { flex: 1 1 auto; min-width: 3em; } -.duckmage-biome-islands { +.duckmage-biome-islands, +.duckmage-biome-climate { display: grid; gap: 4px; } +.duckmage-biome-climate input[type="text"] { + flex: 1 1 auto; + min-width: 6em; +} diff --git a/tests/biomeClimate.test.ts b/tests/biomeClimate.test.ts index db5230e2..7c9df2fa 100644 --- a/tests/biomeClimate.test.ts +++ b/tests/biomeClimate.test.ts @@ -5,6 +5,7 @@ import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constan import { MOISTURE_WORDS, TEMPERATURE_WORDS, + climateKeyValues, formatClimateRange, isPlaceable, parseClimateRange, @@ -16,6 +17,7 @@ import { BIOMES, biomeInfo, setBiomeSource } from "../src/overworld/biomes"; import { placementPool, worldBiomes, type WorldBiomesOptions } from "../src/overworld/worldBiomes"; import { lowland, worldBiomes as legacyWorldBiomes } from "./fixtures/worldBiomesLegacy"; import { climatesToAdd } from "../src/overworld/BiomeStore"; +import { climateFromForm, fieldsFromForm, formFromFields, formProblem, formTypes } from "../src/overworld/biomeForm"; const hexWorld = (R: number): [number, number][] => { const out: [number, number][] = []; @@ -142,6 +144,31 @@ describe("biome climate: reading and writing", () => { }); }); +describe("biome form: climate section", () => { + it("round-trips every shipped climate through the form", () => { + for (const p of BIOME_PRESETS) { + const s = formFromFields(p, formTypes(DEFAULT_TERRAIN_PALETTE, p)); + const back = fieldsFromForm(s, p.id).climate; + expect(climateKeyValues(back)).toEqual(climateKeyValues(p.climate)); + } + }); + + it("blank climate fields mean no climate; bad ones block saving", () => { + const s = formFromFields(undefined, formTypes(DEFAULT_TERRAIN_PALETTE)); + s.label = "Ash"; + s.mix.set("badlands", 3); + expect(fieldsFromForm(s).climate).toBeUndefined(); + s.climate.temperature = "toasty"; + expect(formProblem(s, [])).toMatch(/^Climate: /); + s.climate.temperature = "warm–hot"; + s.climate.elevation = "low"; + s.climate.chancePercent = 50; + expect(formProblem(s, [])).toBeUndefined(); + expect(fieldsFromForm(s).climate).toEqual({ temperature: { lo: 0.6, hi: 1 }, elevation: "low", chance: 0.5 }); + expect(climateFromForm(s.climate).problems).toEqual([]); + }); +}); + describe("World biomes from climates", () => { const SEEDS = [1, 2, 3, 7, 11, 42, 99, 123, 777, 2024, 31337, 65535]; const cases: { cells: [number, number][]; o: Partial }[] = [ From 460662511ea0fb8102879eeee936bfa53618c3e2 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 00:45:53 -0400 Subject: [PATCH 264/558] test(biomes #50): generateBiomeRegion, biome page round trip, min patches over 200 seeds, shore biomes Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- tests/biomeGenerators.test.ts | 460 ++++++++++++++++++++++++++++++++++ 2 files changed, 462 insertions(+), 2 deletions(-) create mode 100644 tests/biomeGenerators.test.ts diff --git a/package.json b/package.json index f66a1553..defd7cc7 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/tests/biomeGenerators.test.ts b/tests/biomeGenerators.test.ts new file mode 100644 index 00000000..7bf54c94 --- /dev/null +++ b/tests/biomeGenerators.test.ts @@ -0,0 +1,460 @@ +/** + * Custom biomes, the generator side (#50): generateBiomeRegion (a region + * made by a learned, blend or preset generator, joined to pinned cells), + * the biome page's edits through the store, min patches per type, and the + * shore setting (land toward the land-heavy neighbours). + */ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { hexDistance, hexNeighbors } from "../packages/hex-wfc/src/grid"; +import { learnModel, mergeModels, modelToMarkdown, type HexWfcModel } from "../packages/hex-wfc/src"; +import { DEFAULT_PATH_TYPES, DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { parseBuiltin } from "../src/worldgen/builtinGenerators"; +import { BiomeRegionError, generateBiomeRegion, type BiomeRegionRequest, type GeneratorRef } from "../src/worldgen/biomeRegion"; +import { biomePagePatch, biomeSamplePlan, setMixRow } from "../src/worldgen/BiomePanel"; +import { buildBiomeNote, parseBiomeNote, updateBiomeNote, type BiomeNoteFields } from "../src/overworld/biomeNote"; +import { BIOME_PRESETS, biomePreset } from "../src/overworld/biomePresets"; +import { BiomeStore } from "../src/overworld/BiomeStore"; +import { WATER_TYPES, noteBiomeProfiles, profileFromFields, setBiomeSource, type BiomeProfile } from "../src/overworld/biomes"; +import { fieldsFromForm, formFromFields, formTypes, regionGenerator } from "../src/overworld/biomeForm"; +import { BlendField, REGION_WARP } from "../src/overworld/blendField"; +import { regionCells, type RegionLayout } from "../src/overworld/layout"; +import { generateRegion } from "../src/overworld/regionGen"; +import type { TerrainPalette } from "../src/types"; +import { MemVault } from "./helpers/memVault"; + +(globalThis as Record).window ??= globalThis; + +const PALETTE: TerrainPalette = { name: "Expanded", terrains: DEFAULT_TERRAIN_PALETTE, pathTypes: DEFAULT_PATH_TYPES }; +const typeOfMap = new Map(DEFAULT_TERRAIN_PALETTE.map((t) => [t.name, t.type])); +const typeOf = (n: string) => typeOfMap.get(n); +const water = new Set(WATER_TYPES); +const isLand = (t: string) => { const ty = typeOf(t); return ty !== undefined && !water.has(ty); }; + +// ── generateBiomeRegion ────────────────────────────────────────────────── + +function fakePlugin(vault?: MemVault) { + return { + app: { ...(vault?.app() ?? {}), metadataCache: { getFirstLinkpathDest: () => null } }, + settings: { hexOrientation: "flat", staggerOffset: "odd", terrainPalettes: [PALETTE] }, + getPathTypes: () => DEFAULT_PATH_TYPES, + }; +} + +/** A painted 12×10 map: forest with a lake and a band of hills. */ +function painted(): Map { + const m = new Map(); + for (let x = 0; x < 12; x++) for (let y = 0; y < 10; y++) { + const d = Math.hypot(x - 4, y - 4); + m.set(`${x}_${y}`, d < 2.2 ? "water" : x > 8 ? "hills" : (x + y) % 5 === 0 ? "grass" : "forest"); + } + return m; +} + +const learned = (): HexWfcModel => learnModel(painted(), { name: "my-woods", orientation: "flat", meta: { palette: "Expanded" } }); +const otherLearned = (): HexWfcModel => { + const m = new Map(); + for (let x = 0; x < 10; x++) for (let y = 0; y < 8; y++) m.set(`${x}_${y}`, y < 3 ? "hills" : (x * y) % 7 === 0 ? "forest" : "grass"); + return learnModel(m, { name: "my-hills", orientation: "flat", meta: { palette: "Expanded" } }); +}; +const preset = (slug: string) => parseBuiltin(readFileSync(join(__dirname, "../src/worldgen/builtin", `${slug}.md`), "utf8"), slug)!; + +const BOUNDS = { cols: 8, rows: 8, offset: { x: 16, y: 8 }, stagger: "odd" as const }; +const inBounds = (k: string) => { + const [x, y] = k.split("_").map(Number); + return x >= 16 && x < 24 && y >= 8 && y < 16; +}; + +/** A neighbour's column of forest just west, and two locked cells inside. */ +function pins(): Map { + const p = new Map(); + for (let y = 8; y < 16; y++) p.set(`15_${y}`, "forest"); + p.set("18_10", "hills"); + p.set("20_13", "water"); + return p; +} + +const req = (generator: GeneratorRef, seed: number, extra: Partial = {}): BiomeRegionRequest => ({ + generator, palette: PALETTE, bounds: BOUNDS, pinned: pins(), seed, ...extra, +}); + +describe("generateBiomeRegion", () => { + const refs: [string, () => GeneratorRef][] = [ + ["a learned generator", () => ({ model: learned(), source: "learned" })], + ["a blend", () => ({ model: mergeModels([learned(), otherLearned()], "woods-to-hills", { "blend-of": "my-woods + my-hills" }, [50, 50], ["W", "E"]), source: "blend" })], + ["a preset", () => ({ model: preset("preset-volcanic"), source: "preset" })], + ]; + for (const [label, ref] of refs) { + it(`${label}: fills the region, keeps pinned cells, same seed same region`, async () => { + const plugin = fakePlugin() as never; + for (const seed of [1, 7, 42]) { + const a = await generateBiomeRegion(plugin, req(ref(), seed)); + const b = await generateBiomeRegion(plugin, req(ref(), seed)); + expect([...a.cells]).toEqual([...b.cells]); + expect(a.cells.size).toBe(64); + for (const k of a.cells.keys()) expect(inBounds(k)).toBe(true); + // Pinned cells inside come out as they were; neighbours' cells aren't in the result. + expect(a.cells.get("18_10")).toBe("hills"); + expect(a.cells.get("20_13")).toBe("water"); + expect(a.cells.has("15_9")).toBe(false); + for (const t of a.cells.values()) expect(DEFAULT_TERRAIN_PALETTE.some((p) => p.name === t)).toBe(true); + } + }); + } + + it("a different seed gives a different region", async () => { + const plugin = fakePlugin() as never; + const a = await generateBiomeRegion(plugin, req({ model: learned(), source: "learned" }, 1)); + const b = await generateBiomeRegion(plugin, req({ model: learned(), source: "learned" }, 2)); + expect([...a.cells]).not.toEqual([...b.cells]); + }); + + it("only the mask's cells (hex flowers)", async () => { + const mask = (k: string) => { const [x] = k.split("_").map(Number); return x < 20; }; + const r = await generateBiomeRegion(fakePlugin() as never, req({ model: learned(), source: "learned" }, 3, { mask })); + expect(r.cells.size).toBe(32); + for (const k of r.cells.keys()) expect(mask(k)).toBe(true); + }); + + it("carries a neighbour's edge on (a hills column west pulls hills to the region's west edge)", async () => { + const edge = (terrain: string) => { + const p = new Map(); + for (let y = 8; y < 16; y++) p.set(`15_${y}`, terrain); + return p; + }; + const share = async (pinned: Map) => { + let hit = 0, n = 0; + for (let seed = 1; seed <= 20; seed++) { + const r = await generateBiomeRegion(fakePlugin() as never, req({ model: learned(), source: "learned" }, seed, { pinned })); + for (let y = 8; y < 16; y++) { n++; if (r.cells.get(`16_${y}`) === "hills") hit++; } + } + return hit / n; + }; + expect(await share(edge("hills"))).toBeGreaterThan((await share(edge("water"))) + 0.2); + }); + + it("throws a readable error when the generator doesn't fit the palette", async () => { + const alien = learnModel({ "0_0": "lava", "0_1": "glass", "1_0": "lava", "1_1": "glass" }, { name: "alien", orientation: "flat" }); + const p = generateBiomeRegion(fakePlugin() as never, req({ model: alien, source: "learned" }, 1)); + await expect(p).rejects.toBeInstanceOf(BiomeRegionError); + await expect(generateBiomeRegion(fakePlugin() as never, req({ model: alien, source: "learned" }, 1))).rejects.toThrow(/alien doesn't fit palette Expanded: it uses (lava, glass|glass, lava)/); + const tiny: TerrainPalette = { name: "Tiny", terrains: [{ name: "grass", color: "#0f0", type: "grassland" }] }; + await expect(generateBiomeRegion(fakePlugin() as never, { ...req({ model: preset("preset-volcanic"), source: "preset" }, 1), palette: tiny })).rejects.toThrow(/doesn't fit palette Tiny/); + }); + + it("reads a generator note by link target (a biome's generator: [[…]])", async () => { + const v = new MemVault({ "world/generators/my-woods.md": modelToMarkdown(learned()) }); + const plugin = fakePlugin(v) as never; + const byLink = await generateBiomeRegion(plugin, req({ path: "world/generators/my-woods" }, 5)); + const byModel = await generateBiomeRegion(plugin, req({ model: learned(), source: "learned" }, 5)); + expect(byLink.cells.size).toBe(64); + expect([...byLink.cells.values()].every((t) => DEFAULT_TERRAIN_PALETTE.some((p) => p.name === t))).toBe(true); + expect(byModel.cells.size).toBe(64); + await expect(generateBiomeRegion(plugin, req({ path: "world/generators/nope" }, 5))).rejects.toThrow(/nope wasn't found/); + }); + + it("routing: a biome with a generator link goes to its generator, the rest blend", () => { + expect(regionGenerator({ generator: "world/generators/my-woods" })).toEqual({ kind: "generator", generator: "world/generators/my-woods", ready: true }); + expect(regionGenerator({})).toEqual({ kind: "blend" }); + }); +}); + +// ── the biome page through the store ───────────────────────────────────── + +function storePlugin(vault: MemVault) { + return { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { worldFolder: "world", biomesFolder: "" } as Record, + saveSettings: async () => {}, + }; +} + +describe("biome page edits round-trip through the store", () => { + afterEach(() => setBiomeSource(undefined)); + + it("mix, min patches, blend, land, islands, shore and transitions are written to the note and read back", async () => { + const v = new MemVault(); + const store = new BiomeStore(storePlugin(v) as never); + await store.init(); + const path = "world/biomes/Alpine.md"; + v.files.set(path, v.files.get(path)! + "\nMy notes about the peaks.\n"); + store.onModify(v.app().vault.getAbstractFileByPath(path)!); + const f = structuredClone(store.get("alpine")!); + setMixRow(f, "peaks", { weight: 30, minPatches: 3 }); + setMixRow(f, "snow", { weight: 0 }); + setMixRow(f, "hills", { minPatches: null }); + f.blend = "wide"; + f.landShare = 0.8; + f.minIslands = 1; + f.shore = true; + f.transitions = [{ next: "Jungle", between: "Karst" }, { next: "Swamp", between: "Valley" }]; + expect(await store.update("alpine", biomePagePatch(f))).toBe(true); + const text = v.files.get(path)!; + expect(text).toContain("My notes about the peaks."); + expect(text).toContain("| Type | Weight | Min patches |"); + expect(text).toMatch(/\| peaks \| 30 \| 3 \|/); + expect(text).toContain("shore: yes"); + const back = parseBiomeNote(text, "Alpine").fields; + expect(back.mix).toEqual(f.mix); + expect(back.transitions).toEqual(f.transitions); + expect([back.blend, back.landShare, back.minIslands, back.shore]).toEqual(["wide", 0.8, 1, true]); + expect(store.get("alpine")!.mix.find((r) => r.type === "peaks")).toEqual({ type: "peaks", weight: 30, minPatches: 3 }); + // Turning things off removes them. + const g = structuredClone(store.get("alpine")!); + delete g.shore; delete g.blend; delete g.landShare; delete g.minIslands; + expect(await store.update("alpine", biomePagePatch(g))).toBe(true); + expect(v.files.get(path)).not.toMatch(/^(shore|blend|land-share|min-islands):/m); + // Restore default brings the shipped preset back (min patches included). + expect(store.hasDefault("alpine")).toBe(true); + expect(await store.restoreDefault("alpine")).toBe(true); + expect(store.get("alpine")!.mix).toEqual(biomePreset("alpine")!.mix); + expect(store.get("alpine")!.shore).toBeUndefined(); + }); + + it("the Coast preset is seeded, listed, and restorable", async () => { + const v = new MemVault(); + const store = new BiomeStore(storePlugin(v) as never); + await store.init(); + expect(store.get("coast")?.shore).toBe(true); + expect(v.files.get("world/biomes/Coast.md")).toContain("shore: yes"); + await store.update("coast", { shore: undefined }); + expect(store.get("coast")?.shore).toBeUndefined(); + await store.restoreDefault("coast"); + expect(store.get("coast")?.shore).toBe(true); + }); + + it("the Add / Edit biome form keeps min patches and shore", () => { + const coast = biomePreset("coast")!; + const alpine = biomePreset("alpine")!; + for (const b of [coast, alpine]) { + const back = fieldsFromForm(formFromFields(b, formTypes(DEFAULT_TERRAIN_PALETTE, b)), b.id); + const byType = (m: { type: string }[]) => [...m].sort((x, y) => (x.type < y.type ? -1 : 1)); + expect(byType(back.mix)).toEqual(byType(b.mix)); + expect(!!back.shore).toBe(!!b.shore); + } + }); +}); + +// ── the note's Min patches column ──────────────────────────────────────── + +describe("Min patches in the biome note", () => { + it("reads forgivingly (header spelling, blanks, bad values reported, row kept)", () => { + const text = "| Type | Weight | Patches |\n| --- | --- | --- |\n| peaks | 20 | 2 |\n| hills | 10 | |\n| snow | 5 | lots |\n"; + const { fields, problems } = parseBiomeNote(text, "Crags"); + expect(fields.mix).toEqual([{ type: "peaks", weight: 20, minPatches: 2 }, { type: "hills", weight: 10 }, { type: "snow", weight: 5 }]); + expect(problems).toHaveLength(1); + expect(problems[0].text).toMatch(/min patches "lots"/); + }); + + it("notes without the column are left exactly as written", () => { + const old = buildBiomeNote({ ...biomePreset("tundra")!, mix: [{ type: "snow", weight: 2 }, { type: "hills", weight: 1 }] }); + expect(old).not.toContain("| Min patches |"); + const f = parseBiomeNote(old, "Tundra").fields; + expect(updateBiomeNote(old, f)).toBe(old); + }); + + it("round-trips through build and parse", () => { + const f: BiomeNoteFields = { id: "crags", label: "Crags", mix: [{ type: "peaks", weight: 20, minPatches: 2 }, { type: "hills", weight: 10 }], transitions: [], shore: true }; + expect(parseBiomeNote(buildBiomeNote(f), "Crags").fields).toEqual(f); + }); +}); + +// ── min patches in region generation ───────────────────────────────────── + +const brick = (size: number): RegionLayout => ({ footprint: "rect", size, orientation: "flat", parentStagger: "odd", childStagger: "odd" }); + +function ringed(centre: string, around: string): Map { + const m = new Map(); + for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) m.set(`${x}_${y}`, hexDistance([x, y], [2, 2], "flat", "odd") === 0 ? centre : around); + return m; +} + +/** Separate patches of `type` among a region's cells. */ +function patches(l: RegionLayout, cells: Map, type: string): number { + const of = new Set([...cells].filter(([, t]) => typeOf(t) === type).map(([k]) => k)); + const seen = new Set(); + let n = 0; + for (const k of of) { + if (seen.has(k)) continue; + n++; + const stack = [k]; + seen.add(k); + while (stack.length) { + const [x, y] = stack.pop()!.split("_").map(Number); + for (const [a, b] of hexNeighbors(x, y, l.orientation, l.childStagger)) { + const nk = `${a}_${b}`; + if (of.has(nk) && !seen.has(nk)) { seen.add(nk); stack.push(nk); } + } + } + } + return n; +} + +const strip = (p: BiomeProfile): BiomeProfile => { const q = { ...p }; delete q.minPatches; return q; }; + +describe("min patches per type (regionGen)", () => { + setBiomeSource(BIOME_PRESETS); + const profiles = noteBiomeProfiles(DEFAULT_TERRAIN_PALETTE); + setBiomeSource(undefined); + const l = brick(8); + const gen = (centre: string, around: string, seed: number, ps: Map = profiles) => + generateRegion({ layout: l, parent: [2, 2], field: new BlendField(l, ringed(centre, around), "normal", { warp: REGION_WARP, seed }), profiles: ps, typeOf, seed }); + + for (const [biome, around] of [["alpine", "alpine"], ["alpine", "grassland"], ["volcanic", "volcanic"], ["volcanic", "grassland"], ["taiga", "taiga"], ["jungle", "jungle"]] as const) { + it(`${biome} ringed by ${around}: every min-patches type is there on 200 seeds`, () => { + const wants = [...profiles.get(biome)!.minPatches!]; + expect(wants.length).toBeGreaterThan(0); + for (let seed = 1; seed <= 200; seed++) { + const out = gen(biome, around, seed); + for (const [type, min] of wants) expect({ seed, type, ok: patches(l, out, type) >= min }).toEqual({ seed, type, ok: true }); + } + }); + } + + it("the presets ask for alpine peaks and a volcano", () => { + expect(profiles.get("alpine")!.minPatches!.get("peaks")).toBeGreaterThanOrEqual(1); + expect(profiles.get("volcanic")!.minPatches!.get("volcanic")).toBe(1); + }); + + it("a biome without the setting comes out exactly as before (200 seeds)", () => { + const without = new Map([...profiles].map(([id, p]) => [id, strip(p)])); + for (const biome of ["archipelago", "coastal-fjord", "grassland"]) { + const ps = new Map(without); + if (biome !== "grassland") ps.set(biome, without.get(biome)!); + for (let seed = 1; seed <= 200; seed++) { + // The neighbours' min patches never touch this region; an empty setting changes nothing. + const a = gen(biome, "alpine", seed, ps); + const b = gen(biome, "alpine", seed, new Map([...ps, [biome, { ...without.get(biome)!, minPatches: new Map() }]])); + const c = gen(biome, "alpine", seed, new Map([...profiles, [biome, without.get(biome)!]])); + expect(b).toEqual(a); + expect(c).toEqual(a); + } + } + }); + + it("never changes pinned cells or the neighbours'", () => { + const pinned = new Map(); + for (const [x, y] of regionCells(l, 1, 2)) pinned.set(`${x}_${y}`, "grass"); + const own = regionCells(l, 2, 2).map(([x, y]) => `${x}_${y}`); + pinned.set(own[20], "grass"); + pinned.set(own[30], "grass"); + for (let seed = 1; seed <= 50; seed++) { + const out = generateRegion({ layout: l, parent: [2, 2], field: new BlendField(l, ringed("alpine", "alpine"), "normal", { warp: REGION_WARP, seed }), profiles, typeOf, seed, pinned }); + for (const k of pinned.keys()) expect(out.has(k)).toBe(false); + expect(out.size).toBe(own.length - 2); + } + }); +}); + +// ── shore biomes ───────────────────────────────────────────────────────── + +describe("shore biomes (Coast)", () => { + setBiomeSource(BIOME_PRESETS); + const profiles = noteBiomeProfiles(DEFAULT_TERRAIN_PALETTE); + setBiomeSource(undefined); + const l = brick(8); + /** A 5×5 overworld: coast at 2,2; `west` on columns 0–1, `east` on 3–4, coast above and below. */ + const layout = (west: string, east: string) => { + const m = new Map(); + for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) m.set(`${x}_${y}`, x < 2 ? west : x > 2 ? east : "coast"); + return m; + }; + const gen = (west: string, east: string, seed: number, pinned?: Map) => + generateRegion({ layout: l, parent: [2, 2], field: new BlendField(l, layout(west, east), "normal", { warp: REGION_WARP, seed }), profiles, typeOf, seed, pinned }); + const cells = regionCells(l, 2, 2); + const xs = cells.map(([x]) => x); + const mid = (Math.min(...xs) + Math.max(...xs)) / 2; + const landShare = (out: Map, side: "west" | "east") => { + const keys = cells.filter(([x]) => (side === "west" ? x < mid : x > mid)).map(([x, y]) => `${x}_${y}`).filter((k) => out.has(k)); + return keys.filter((k) => isLand(out.get(k)!)).length / keys.length; + }; + + it("Coast is a shore biome, by its setting", () => { + expect(profiles.get("coast")!.shore).toBe(true); + expect(profileFromFields({ ...biomePreset("coast")!, shore: undefined }, DEFAULT_TERRAIN_PALETTE).shore).toBeUndefined(); + }); + + it("forest to the west, open sea to the east: land-heavy west, water east (100 seeds)", () => { + let west = 0, east = 0; + for (let seed = 1; seed <= 100; seed++) { + const out = gen("temperate-forest", "open-sea", seed); + const w = landShare(out, "west"), e = landShare(out, "east"); + expect({ seed, ok: w > e + 0.3 }).toEqual({ seed, ok: true }); + west += w; east += e; + } + expect(west / 100).toBeGreaterThan(0.7); + expect(east / 100).toBeLessThan(0.25); + }); + + it("the land side follows the land neighbour (sea west, forest east)", () => { + for (let seed = 1; seed <= 100; seed++) { + const out = gen("open-sea", "temperate-forest", seed); + expect({ seed, ok: landShare(out, "east") > landShare(out, "west") + 0.3 }).toEqual({ seed, ok: true }); + } + }); + + it("a coast band sits between land and water", () => { + const out = gen("temperate-forest", "open-sea", 11); + expect([...out.values()].some((t) => typeOf(t) === "coast")).toBe(true); + expect([...out.values()].some((t) => typeOf(t) === "shallows")).toBe(true); + }); + + it("with no land around: mostly water, with land along one side picked by the seed", () => { + const sides = new Set(); + for (let seed = 1; seed <= 60; seed++) { + const out = gen("open-sea", "open-sea", seed); + const land = [...out.values()].filter(isLand).length / out.size; + expect({ seed, ok: land > 0.05 && land < 0.5 }).toEqual({ seed, ok: true }); + sides.add(landShare(out, "west") > landShare(out, "east") ? "west" : "east"); + } + expect(sides.size).toBe(2); + }); + + it("already painted neighbours count: a land region painted to the east pulls the land there", () => { + const pinned = new Map(); + for (const [qx, qy] of hexNeighbors(2, 2, "flat", "odd")) { + if (qx <= 2) continue; + for (const [x, y] of regionCells(l, qx, qy)) pinned.set(`${x}_${y}`, "forest"); + } + // The overworld says sea everywhere, but the painted cells say land to the east. + for (let seed = 1; seed <= 30; seed++) { + const out = gen("open-sea", "open-sea", seed, pinned); + expect({ seed, ok: landShare(out, "east") > landShare(out, "west") }).toEqual({ seed, ok: true }); + } + }); + + it("pinned and neighbour cells unchanged; deterministic", () => { + const pinned = new Map(); + for (const [x, y] of regionCells(l, 1, 2)) pinned.set(`${x}_${y}`, "forest"); + const own = cells.map(([x, y]) => `${x}_${y}`); + pinned.set(own[5], "ocean"); + for (let seed = 1; seed <= 30; seed++) { + const a = gen("temperate-forest", "open-sea", seed, pinned); + const b = gen("temperate-forest", "open-sea", seed, pinned); + expect([...a]).toEqual([...b]); + for (const k of pinned.keys()) expect(a.has(k)).toBe(false); + for (const k of a.keys()) expect(own.includes(k)).toBe(true); + } + }); + + it("the biome page's sample shows the shore turning toward the land", () => { + const coast = biomePreset("coast")!; + setBiomeSource(BIOME_PRESETS); + try { + const plan = biomeSamplePlan(brick(10), DEFAULT_TERRAIN_PALETTE, coast, 9, "land-west", "temperate-forest", profiles); + const own = regionCells(brick(10), 0, 0); + const m = (Math.min(...own.map(([x]) => x)) + Math.max(...own.map(([x]) => x))) / 2; + const share = (west: boolean) => { + const ks = own.filter(([x]) => (west ? x < m : x > m)).map(([x, y]) => `${x}_${y}`); + return ks.filter((k) => isLand(plan.cells.get(k)!)).length / ks.length; + }; + expect(share(true)).toBeGreaterThan(share(false)); + } finally { + setBiomeSource(undefined); + } + }); +}); + From 3176124d185138f19273c26ed16e9a2bc260ffe1 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 00:56:35 -0400 Subject: [PATCH 265/558] feat(biomes #50): biome pools and the Generate overworld first pass - Biome pool notes (/biome-pools/.md, setting 'Biome pools folder'): a Biome | Weight | Notes table, read forgivingly (bad rows reported, kept). 'All biomes' (every built-in) is written once. - Weight scales a biome's climate chance; 0 leaves it out. A pool biome without a climate only fills hexes no climate biome of the pool fits. - Generate overworld: New overworld... now picks/edits a pool (add or remove any biome, generator-backed ones marked), with live preview; Create lays the pool out, records user biomes in the overworld's new optional Biome column, and makes every region through regionGenerator. - Map menu > Regions: Generate overworld... regenerates the whole map (God only): locked hexes and their regions stay, other regions are remade in place (locked cells, names and notes kept). The map note records biome-pool: "[[...]]". Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerSettingTab.ts | 23 ++ src/constants.ts | 1 + src/hex-map/BiomeLibraryModal.ts | 2 +- src/hex-map/MapModal.ts | 12 +- src/hex-map/OverworldModals.ts | 355 +++++++++++++++++++++++++------ src/maps/mapNote.ts | 26 ++- src/overworld/biomePool.ts | 219 +++++++++++++++++++ src/overworld/overworldGen.ts | 268 +++++++++++++++++++++++ src/overworld/overworldPass.ts | 47 ++++ src/overworld/regionsVault.ts | 24 ++- src/types.ts | 6 + styles.css | 36 ++++ tests/biomePool.test.ts | 192 +++++++++++++++++ 14 files changed, 1134 insertions(+), 81 deletions(-) create mode 100644 src/overworld/biomePool.ts create mode 100644 src/overworld/overworldGen.ts create mode 100644 src/overworld/overworldPass.ts create mode 100644 tests/biomePool.test.ts diff --git a/package.json b/package.json index e1187b0c..b14002ce 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeClimate.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeClimate.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index 6c177e44..70cc1b2c 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -16,6 +16,9 @@ const PALETTES_FOLDER_DESC = const BIOMES_FOLDER_DESC = "Vault-relative folder for overworld biome notes (one note per biome: its mix of terrain types, colour and transitions). Defaults to a biomes folder inside the world folder."; +const BIOME_POOLS_FOLDER_DESC = + "Vault-relative folder for biome pool notes (each lists the biomes a generated overworld may use). Defaults to a biome-pools folder inside the world folder."; + // --------------------------------------------------------------------------- // Obsidian 1.13 declarative settings API — local structural types. // @@ -125,6 +128,7 @@ const FOLDER_PATH_KEYS = new Set([ "templatesFolder", "palettesFolder", "biomesFolder", + "biomePoolsFolder", ]); /** Settings keys whose change should re-render open hex map views. */ @@ -666,6 +670,12 @@ export class HexmakerSettingTab extends PluginSettingTab { "World/biomes", BIOMES_FOLDER_DESC, ), + folderText( + "Biome pools folder", + "biomePoolsFolder", + "World/biome-pools", + BIOME_POOLS_FOLDER_DESC, + ), { type: "group", heading: "Map types", @@ -1578,6 +1588,19 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); + new Setting(containerEl) + .setName("Biome pools folder") + .setDesc(BIOME_POOLS_FOLDER_DESC) + .addText((text) => + text + .setPlaceholder("World/biome-pools") + .setValue(this.plugin.settings.biomePoolsFolder ?? "") + .onChange(async (value) => { + this.plugin.settings.biomePoolsFolder = normalizeFolder(value ?? ""); + await this.plugin.saveSettings(); + }), + ); + new Setting(containerEl).setName("Map types").setHeading(); for (const k of MAP_KINDS) { new Setting(containerEl) diff --git a/src/constants.ts b/src/constants.ts index 9bb9ee84..200fad9c 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -401,6 +401,7 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { setupDismissed: false, palettesFolder: "", biomesFolder: "", + biomePoolsFolder: "", palettesMigrated: false, // Space is opt-in (setup wizard / settings → Map types). Upgrades without // the setting get space too if they already have space palettes diff --git a/src/hex-map/BiomeLibraryModal.ts b/src/hex-map/BiomeLibraryModal.ts index 62bbb65b..c2ebcfeb 100644 --- a/src/hex-map/BiomeLibraryModal.ts +++ b/src/hex-map/BiomeLibraryModal.ts @@ -253,7 +253,7 @@ export class BiomeFormModal extends HexmakerModal { }; tick("Coast only", cl.coastal, (v) => { cl.coastal = v; }); tick("Rare", cl.rare, (v) => { cl.rare = v; }); - clBox.createEl("p", { cls: "setting-item-description", text: "When set, World biomes can place this biome where the climate fits, like a built-in one. Left blank, it's only placed by hand. Temperature: cold, cool, mild, warm, hot; moisture: dry, moderate, wet; or numbers from 0 to 1." }); + clBox.createEl("p", { cls: "setting-item-description", text: "When set, the overworld generator can place this biome where the climate fits, like a built-in one. Left blank, it's only placed by hand. Temperature: cold, cool, mild, warm, hot; moisture: dry, moderate, wet; or numbers from 0 to 1." }); // Transitions. const trBox = form.createEl("details", { cls: "duckmage-biome-transitions" }); diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 5bd1eff2..6565ea60 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -23,7 +23,9 @@ import { hasFeature } from "../featureLevel"; import { renderAdvancedHint, withFeature } from "../advancedHints"; import { regionsOf, removeMapPatch } from "../maps/submaps"; import { RegionSettingsModal } from "./newChildMap"; -import { GenerateRegionsModal } from "./OverworldModals"; +import { GenerateRegionsModal, NewOverworldModal } from "./OverworldModals"; +import { REGENERATE_LOCKED_HINT } from "../overworld/overworldGen"; +import { canReshape } from "../workMode"; import { meshes } from "../overworld/regionWorld"; import { missingRegionHexes } from "../overworld/regionsVault"; import { renderRegionSettingsForm } from "./regionSettingsForm"; @@ -161,6 +163,14 @@ export class MapModal extends HexmakerModal { this.onChanged(); }).open(); }); + // The first pass again, over the whole map (God only; locked hexes kept). + const genRow = el.createDiv({ cls: "duckmage-region-row" }); + const gen = genRow.createEl("button", { text: "Generate overworld…" }); + genRow.createSpan({ cls: "duckmage-map-origin-desc", text: canReshape(map) ? "Lay out biomes from a pool again and remake the regions. Locked hexes stay." : REGENERATE_LOCKED_HINT }); + gen.addEventListener("click", () => { + this.close(); + new NewOverworldModal(this.app, this.plugin, () => this.onChanged(), map.name).open(); + }); } if (!regions.length) return; el.createEl("h4", { text: `Regions (${regions.length})` }); diff --git a/src/hex-map/OverworldModals.ts b/src/hex-map/OverworldModals.ts index c1dd8745..3918edd2 100644 --- a/src/hex-map/OverworldModals.ts +++ b/src/hex-map/OverworldModals.ts @@ -1,15 +1,16 @@ /** * Making an overworld (plan-overworld-regions §4.4, §5.4; phase 3): * - * - NewOverworldModal: a new map laid out by World biomes (a hex's terrain - * is its biome), rectangular or hex-shaped, with its region settings, - * previewed the way the overworld preview page draws its minimap, and - * optionally every region made straight away. + * - NewOverworldModal: "Generate overworld", the first pass (#50): a biome + * pool laid out by World biomes (a hex's terrain is its biome, plus the + * Biome column for a user's biome), rectangular or hex-shaped, previewed + * the way the overworld preview page draws its minimap, then every + * region made. Also regenerates an existing overworld (God only). * - GenerateRegionsModal: "Make the missing regions": one per painted hex * that has none, centre-out, with progress and a Stop button. */ -import { App, Notice } from "obsidian"; +import { App, Notice, setIcon } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { hexDistance } from "../../packages/hex-wfc/src/grid"; @@ -17,12 +18,26 @@ import { biomeInfo } from "../overworld/biomes"; import { drawMiniOverworld, miniLayout, type MiniHex } from "../overworld/overworldRender"; import { formatBiomeRiver, withMeshFields } from "../overworld/regionWorld"; import { generateMissingRegions } from "../overworld/regionsVault"; -import { worldBiomes, type Climate, type LandShape, type NorthIs, type WorldBiomesResult } from "../overworld/worldBiomes"; +import { type Climate, type LandShape, type NorthIs, type WorldBiomesResult } from "../overworld/worldBiomes"; import { RECT_SIDES } from "../maps/submaps"; import { newWorldId } from "../worldgen/world"; import { isSpacePalette } from "../mapKinds"; import { ecotoneHexes } from "../overworld/regionWorld"; -import { ADD_REGION_LOCKED_HINT, canAdd } from "../workMode"; +import { ADD_REGION_LOCKED_HINT, canAdd, canReshape } from "../workMode"; +import { ALL_BIOMES_POOL, type BiomePoolRow } from "../overworld/biomePool"; +import { + REGENERATE_LOCKED_HINT, + layOutBiomes, + listBiomePools, + overworldCells, + poolRowFor, + regenerateOverworld, + regionPass, + resolvePool, + saveBiomePool, + writeOverworldBiomes, + type PoolNote, +} from "../overworld/overworldGen"; export class GenerateRegionsModal extends HexmakerModal { private stop = false; @@ -92,6 +107,14 @@ export function overworldShapeCells(shape: "rect" | "hex", cols: number, rows: n return { cols: n, rows: n, cells }; } +/** + * "Generate overworld" (#50), the first pass: a biome pool laid out by + * World biomes, previewed live, then every region made with its biome. + * New (the "New overworld…" command): name, shape, size, palette and + * region settings too. Regenerate (the map menu, `regenerate` = the map): + * God only; locked hexes and their regions stay, the other regions are + * remade in place. + */ export class NewOverworldModal extends HexmakerModal { private name = "Overworld"; private shape: "rect" | "hex" = "hex"; @@ -109,67 +132,132 @@ export class NewOverworldModal extends HexmakerModal { private makeAll = true; private result: WorldBiomesResult | null = null; private canvas!: HTMLCanvasElement; + /** The pool: its note (undefined = a new, unsaved one) and its rows as edited. */ + private pools: PoolNote[] = []; + private poolPath: string | undefined; + private poolRows: BiomePoolRow[] = []; + private poolDirty = false; + private poolBox!: HTMLDetailsElement; + private poolNote!: HTMLElement; - constructor(app: App, private plugin: HexmakerPlugin, private onCreated: (name: string) => void) { + constructor(app: App, private plugin: HexmakerPlugin, private onCreated: (name: string) => void, private regenerate?: string) { super(app); } onOpen(): void { this.makeDraggable(); - this.titleEl.setText("New overworld"); + const regen = this.regenerate ? this.plugin.getMap(this.regenerate) : undefined; + this.titleEl.setText(regen ? `Generate overworld: ${this.plugin.mapLabel(regen.name)}` : "New overworld"); this.modalEl.addClass("duckmage-new-overworld-modal"); const world = this.plugin.settings.terrainPalettes.filter((p) => !isSpacePalette(p.terrains)); - this.palette = world[0]?.name ?? this.plugin.settings.terrainPalettes[0]?.name ?? ""; + this.palette = regen?.paletteName ?? world[0]?.name ?? this.plugin.settings.terrainPalettes[0]?.name ?? ""; const { contentEl } = this; contentEl.createEl("p", { cls: "setting-item-description", - text: "A map of biomes: each hex is one biome, and each opens into a region map that blends with its neighbours.", + text: regen + ? "A first pass over the whole map: biomes from the pool, laid out by climate, then every region remade. Locked hexes and their regions stay as they are; region notes are never touched." + : "A first pass: each hex is one biome from the pool, laid out by climate, and each opens into a region map that blends with its neighbours. Edit, reroll or swap any region afterwards.", }); const form = contentEl.createDiv({ cls: "duckmage-region-gen-form" }); - const field = (label: string) => { - const row = form.createDiv({ cls: "duckmage-region-gen-row" }); + const field = (label: string, parent: HTMLElement = form) => { + const row = parent.createDiv({ cls: "duckmage-region-gen-row" }); row.createSpan({ cls: "duckmage-region-gen-label", text: label }); return row; }; - const nameIn = field("Name").createEl("input", { type: "text", value: this.name, attr: { "aria-label": "Name" } }); - nameIn.addEventListener("input", () => { this.name = nameIn.value; }); + if (!regen) { + const nameIn = field("Name").createEl("input", { type: "text", value: this.name, attr: { "aria-label": "Name" } }); + nameIn.addEventListener("input", () => { this.name = nameIn.value; }); - const shapeRow = field("Shape"); - const shapeSel = shapeRow.createEl("select", { attr: { "aria-label": "Shape" } }); - shapeSel.createEl("option", { value: "hex", text: "Hex-shaped" }); - shapeSel.createEl("option", { value: "rect", text: "Rectangle" }); - shapeSel.value = this.shape; - const sizeBox = shapeRow.createSpan({ cls: "duckmage-ow-shape-size" }); - const drawSize = () => { - sizeBox.empty(); - if (this.shape === "hex") { - const r = sizeBox.createEl("select", { attr: { "aria-label": "Hexes" } }); - for (const n of [1, 2, 3, 4, 5, 6, 8, 10]) r.createEl("option", { value: String(n), text: `${3 * n * n + 3 * n + 1} hexes` }); - r.value = String(this.radius); - r.addEventListener("change", () => { this.radius = Number(r.value); this.regen(); }); - } else { - const c = sizeBox.createEl("input", { type: "number", value: String(this.cols), attr: { min: "2", max: "60", "aria-label": "Columns" } }); - sizeBox.createSpan({ text: " × " }); - const rr = sizeBox.createEl("input", { type: "number", value: String(this.rows), attr: { min: "2", max: "60", "aria-label": "Rows" } }); - const upd = () => { - this.cols = Math.max(2, Math.min(60, Math.round(Number(c.value) || 2))); - this.rows = Math.max(2, Math.min(60, Math.round(Number(rr.value) || 2))); - this.regen(); - }; - c.addEventListener("change", upd); - rr.addEventListener("change", upd); - } - }; - shapeSel.addEventListener("change", () => { this.shape = shapeSel.value as "rect" | "hex"; drawSize(); this.regen(); }); - drawSize(); + const shapeRow = field("Shape"); + const shapeSel = shapeRow.createEl("select", { attr: { "aria-label": "Shape" } }); + shapeSel.createEl("option", { value: "hex", text: "Hex-shaped" }); + shapeSel.createEl("option", { value: "rect", text: "Rectangle" }); + shapeSel.value = this.shape; + const sizeBox = shapeRow.createSpan({ cls: "duckmage-ow-shape-size" }); + const drawSize = () => { + sizeBox.empty(); + if (this.shape === "hex") { + const r = sizeBox.createEl("select", { attr: { "aria-label": "Hexes" } }); + for (const n of [1, 2, 3, 4, 5, 6, 8, 10]) r.createEl("option", { value: String(n), text: `${3 * n * n + 3 * n + 1} hexes` }); + r.value = String(this.radius); + r.addEventListener("change", () => { this.radius = Number(r.value); this.regen(); }); + } else { + const c = sizeBox.createEl("input", { type: "number", value: String(this.cols), attr: { min: "2", max: "60", "aria-label": "Columns" } }); + sizeBox.createSpan({ text: " × " }); + const rr = sizeBox.createEl("input", { type: "number", value: String(this.rows), attr: { min: "2", max: "60", "aria-label": "Rows" } }); + const upd = () => { + this.cols = Math.max(2, Math.min(60, Math.round(Number(c.value) || 2))); + this.rows = Math.max(2, Math.min(60, Math.round(Number(rr.value) || 2))); + this.regen(); + }; + c.addEventListener("change", upd); + rr.addEventListener("change", upd); + } + }; + shapeSel.addEventListener("change", () => { this.shape = shapeSel.value as "rect" | "hex"; drawSize(); this.regen(); }); + drawSize(); - const pal = field("Palette").createEl("select", { attr: { "aria-label": "Palette" } }); - for (const p of world) pal.createEl("option", { value: p.name, text: p.name }); - pal.value = this.palette; - pal.addEventListener("change", () => { this.palette = pal.value; this.regen(); }); + const pal = field("Palette").createEl("select", { attr: { "aria-label": "Palette" } }); + for (const p of world) pal.createEl("option", { value: p.name, text: p.name }); + pal.value = this.palette; + pal.addEventListener("change", () => { this.palette = pal.value; this.regen(); }); + } + + // The pool. + const poolRow = field("Biome pool"); + const poolSel = poolRow.createEl("select", { attr: { "aria-label": "Biome pool" } }); + const saveBtn = poolRow.createEl("button", { text: "Save", attr: { title: "Save the pool's biomes to its note" } }); + const saveAs = poolRow.createEl("button", { text: "Save as…", attr: { title: "Save as a new pool note" } }); + this.poolBox = form.createEl("details", { cls: "duckmage-ow-pool" }); + this.poolNote = form.createEl("p", { cls: "setting-item-description" }); + const fillPools = () => { + poolSel.empty(); + for (const p of this.pools) poolSel.createEl("option", { value: p.path, text: p.name }); + if (this.poolPath === undefined) poolSel.createEl("option", { value: "", text: "Unsaved pool" }); + poolSel.value = this.poolPath ?? ""; + saveBtn.disabled = !this.poolDirty || this.poolPath === undefined; + }; + const pickPool = (path: string | undefined) => { + const p = this.pools.find((x) => x.path === path); + this.poolPath = p?.path; + this.poolRows = p ? p.rows.map((r) => ({ ...r })) : this.plugin.biomeStore.list().filter((b) => b.climate).map((b) => poolRowFor(this.plugin, b)); + this.poolDirty = false; + fillPools(); + this.drawPool(); + this.regen(); + }; + poolSel.addEventListener("change", () => pickPool(poolSel.value || undefined)); + saveBtn.addEventListener("click", () => { + if (!this.poolPath) return; + void saveBiomePool(this.plugin, { path: this.poolPath }, this.poolRows).then((res) => { + if ("error" in res) { new Notice(res.error); return; } + this.poolDirty = false; + fillPools(); + new Notice("Pool saved."); + }); + }); + saveAs.addEventListener("click", () => { + new PoolNameModal(this.app, (name) => { + void saveBiomePool(this.plugin, { name }, this.poolRows).then(async (res) => { + if ("error" in res) { new Notice(res.error); return; } + this.pools = await listBiomePools(this.plugin); + this.poolPath = res.path; + this.poolDirty = false; + fillPools(); + }); + }).open(); + }); + this.onPoolChanged = () => { this.poolDirty = true; fillPools(); }; + void listBiomePools(this.plugin).then((pools) => { + this.pools = pools; + const want = regen?.biomePool && pools.some((p) => p.path === regen.biomePool) ? regen.biomePool : pools.find((p) => p.name === ALL_BIOMES_POOL)?.path ?? pools[0]?.path; + pickPool(want); + }); + // World biomes knobs. + const knobs = form.createDiv({ cls: "duckmage-biome-mix-grid" }); const sel = (label: string, opts: [T, string][], get: () => T, set: (v: T) => void) => { - const s = field(label).createEl("select", { attr: { "aria-label": label } }); + const s = field(label, knobs).createEl("select", { attr: { "aria-label": label } }); for (const [v, t] of opts) s.createEl("option", { value: v, text: t }); s.value = get(); s.addEventListener("change", () => { set(s.value as T); this.regen(); }); @@ -177,7 +265,7 @@ export class NewOverworldModal extends HexmakerModal { sel("Climate", [["varied", "Varied"], ["cold", "Cold"], ["temperate", "Temperate"], ["warm", "Warm"]], () => this.climate, (v) => { this.climate = v; }); sel("Land", [["one", "One continent"], ["two", "Two"], ["islands", "Islands"]], () => this.land, (v) => { this.land = v; }); sel("North is", [["colder", "Colder"], ["warmer", "Warmer"], ["none", "No gradient"]], () => this.north, (v) => { this.north = v; }); - const waterRow = field("Water"); + const waterRow = field("Water", knobs); const water = waterRow.createEl("input", { type: "range", attr: { min: "0", max: "60", step: "5", "aria-label": "Water" } }); water.value = String(this.water); const wv = waterRow.createSpan({ text: `${this.water}%` }); @@ -196,49 +284,135 @@ export class NewOverworldModal extends HexmakerModal { this.canvas.width = 420; this.canvas.height = 300; - form.createEl("h4", { text: "Regions" }); - const regRow = field("Each hex opens into"); - const size = regRow.createEl("select", { attr: { "aria-label": "Region size" } }); - for (const n of RECT_SIDES) size.createEl("option", { value: String(n), text: `${n} × ${n} hexes` }); - size.value = String(this.regionSize); - size.addEventListener("change", () => { this.regionSize = Number(size.value); }); - const blend = field("Blend").createEl("select", { attr: { "aria-label": "Blend" } }); - for (const b of ["narrow", "normal", "wide"]) blend.createEl("option", { value: b, text: b }); - blend.value = this.blend; - blend.addEventListener("change", () => { this.blend = blend.value as typeof this.blend; }); + if (!regen) { + form.createEl("h4", { text: "Regions" }); + const regRow = field("Each hex opens into"); + const size = regRow.createEl("select", { attr: { "aria-label": "Region size" } }); + for (const n of RECT_SIDES) size.createEl("option", { value: String(n), text: `${n} × ${n} hexes` }); + size.value = String(this.regionSize); + size.addEventListener("change", () => { this.regionSize = Number(size.value); }); + const blend = field("Blend").createEl("select", { attr: { "aria-label": "Blend" } }); + for (const b of ["narrow", "normal", "wide"]) blend.createEl("option", { value: b, text: b }); + blend.value = this.blend; + blend.addEventListener("change", () => { this.blend = blend.value as typeof this.blend; }); + } const allRow = form.createEl("label", { cls: "duckmage-region-gen-row" }); const all = allRow.createEl("input", { type: "checkbox" }); all.checked = this.makeAll; - allRow.createSpan({ text: "Make every region now" }); + allRow.createSpan({ text: regen ? "Remake the regions too" : "Make every region now" }); all.addEventListener("change", () => { this.makeAll = all.checked; }); const status = contentEl.createEl("p", { cls: "duckmage-ow-progress" }); const row = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); row.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); - const create = row.createEl("button", { text: "Create", cls: "mod-cta" }); + const create = row.createEl("button", { text: regen ? "Regenerate" : "Create", cls: "mod-cta" }); + if (regen && !canReshape(regen)) { + create.disabled = true; + create.addClass("is-locked"); + create.setAttr("title", REGENERATE_LOCKED_HINT); + status.setText(REGENERATE_LOCKED_HINT); + status.addClass("duckmage-locked-hint"); + } create.addEventListener("click", () => { create.disabled = true; - void this.create(status).finally(() => { create.disabled = false; }); + void (regen ? this.regenerateMap(status) : this.create(status)).finally(() => { create.disabled = false; }); }); this.regen(); } + private onPoolChanged = (): void => {}; + + /** The pool's biomes: each row with its weight and remove button, then "Add". */ + private drawPool(): void { + const box = this.poolBox; + const wasOpen = box.open; + box.empty(); + const { biomes, unknown } = resolvePool(this.plugin, this.poolRows); + box.createEl("summary", { text: `Biomes in the pool (${biomes.length})` }); + const list = box.createDiv({ cls: "duckmage-ow-pool-list" }); + this.poolRows.forEach((r, i) => { + const b = this.plugin.biomeStore.get(r.biome) ?? this.plugin.biomeStore.get(r.biome.slice(r.biome.lastIndexOf("/") + 1)); + const item = list.createDiv({ cls: "duckmage-ow-pool-item" }); + if (b?.color) item.createSpan({ cls: "duckmage-ow-pool-swatch" }).setCssProps({ "--duckmage-swatch": b.color }); + item.createSpan({ cls: "duckmage-ow-pool-name", text: b?.label ?? `${r.biome} (no such biome)` }); + const tags: string[] = []; + if (b && !b.climate) tags.push("fills gaps"); + if (b?.generator) tags.push("generator"); + if (tags.length) item.createSpan({ cls: "duckmage-ow-pool-tag", text: tags.join(", "), attr: { title: b && !b.climate ? "No climate: only placed where no other biome in the pool fits." : "Its regions are made by its generator once generator regions land; blends until then." } }); + const w = item.createEl("input", { type: "number", cls: "duckmage-biome-weight", attr: { min: "0", step: "0.5", placeholder: "1", "aria-label": `${b?.label ?? r.biome} weight`, title: "Weight: how often it's chosen where it fits (1 = as its note says)" } }); + w.value = r.weight !== undefined ? String(r.weight) : ""; + w.addEventListener("change", () => { + const v = Number(w.value); + if (w.value.trim() === "" || !Number.isFinite(v) || v < 0) delete r.weight; else r.weight = v; + this.onPoolChanged(); + this.regen(); + }); + const rm = item.createEl("button", { cls: "clickable-icon", attr: { "aria-label": `Remove ${b?.label ?? r.biome}` } }); + setIcon(rm, "x"); + rm.addEventListener("click", () => { + this.poolRows.splice(i, 1); + this.onPoolChanged(); + this.drawPool(); + this.regen(); + }); + }); + const addRow = box.createDiv({ cls: "duckmage-region-gen-row" }); + const inPool = new Set(biomes.map((b) => b.id)); + const add = addRow.createEl("select", { attr: { "aria-label": "Add a biome" } }); + add.createEl("option", { value: "", text: "Add a biome…" }); + for (const b of this.plugin.biomeStore.list()) { + if (inPool.has(b.id)) continue; + add.createEl("option", { value: b.id, text: `${b.label}${b.generator ? " (generator)" : ""}${b.climate ? "" : " (no climate)"}` }); + } + add.addEventListener("change", () => { + const b = this.plugin.biomeStore.get(add.value); + if (!b) return; + this.poolRows.push(poolRowFor(this.plugin, b)); + this.onPoolChanged(); + this.drawPool(); + this.regen(); + }); + box.open = wasOpen; + const placeable = biomes.filter((b) => b.climate).length; + this.poolNote.setText([ + unknown.length ? `Not found: ${unknown.join(", ")}.` : "", + placeable ? "" : "No biome in this pool has a climate: add one, or give one a climate in its biome note.", + ].filter(Boolean).join(" ")); + } + private terrains() { + if (this.regenerate) return this.plugin.getMapPalette(this.regenerate); return this.plugin.getPaletteOrPresetTerrains(this.palette); } + private cells(): [number, number][] { + if (this.regenerate) return overworldCells(this.plugin, this.regenerate); + return overworldShapeCells(this.shape, this.cols, this.rows, this.radius, this.plugin).cells; + } + + private poolBiomes() { + return resolvePool(this.plugin, this.poolRows).biomes; + } + private regen(): void { - const { cells } = overworldShapeCells(this.shape, this.cols, this.rows, this.radius, this.plugin); - const o = this.plugin.settings.hexOrientation, s = this.plugin.settings.staggerOffset ?? "odd"; + if (!this.canvas) return; + const cells = this.cells(); + const o = this.plugin.settings.hexOrientation; + const s = (this.regenerate ? this.plugin.getMap(this.regenerate)?.staggerOffset : undefined) ?? this.plugin.settings.staggerOffset ?? "odd"; // River: kept as biome data (a delta at its mouth), never a path (paths come later). - this.result = worldBiomes(cells, o, s, this.terrains(), { seed: this.seed, climate: this.climate, water: this.water / 100, land: this.land, north: this.north }); + this.result = layOutBiomes(this.plugin, cells, this.terrains(), { seed: this.seed, climate: this.climate, water: this.water / 100, land: this.land, north: this.north }, this.poolBiomes(), s); const ctx = this.canvas.getContext("2d"); if (!ctx) return; ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); const colour = new Map(this.terrains().map((t) => [t.name, t.color])); const eco = ecotoneHexes(this.result.biomes, o, s); + const locked = (k: string) => (this.regenerate ? this.plugin.mapStore.get(this.regenerate, k)?.locked : false); const hexes: MiniHex[] = cells.map(([x, y]) => { const k = `${x}_${y}`; + if (locked(k)) { + const t = this.plugin.mapStore.get(this.regenerate!, k)?.terrain; + return { x, y, color: colour.get(t ?? "") ?? "#333", label: "locked" }; + } const b = this.result!.biomes.get(k); return { x, y, color: colour.get(this.result!.terrain.get(k) ?? "") ?? "#333", label: b ? biomeInfo(b)?.label : undefined, ecotone: eco.has(k) }; }); @@ -247,6 +421,7 @@ export class NewOverworldModal extends HexmakerModal { private async create(status: HTMLElement): Promise { if (!this.result) return; + if (!this.result.biomes.size) { status.setText("No biome in this pool can be placed: give some a climate."); return; } const { cols, rows } = overworldShapeCells(this.shape, this.cols, this.rows, this.radius, this.plugin); const stagger = this.plugin.settings.staggerOffset ?? "odd"; status.setText("Creating the overworld…"); @@ -255,18 +430,64 @@ export class NewOverworldModal extends HexmakerModal { const map = this.plugin.getMap(res.name)!; map.regions = withMeshFields({ footprint: "rect", size: this.regionSize, blend: this.blend, palette: this.palette }, stagger, newWorldId); if (this.result.river.length > 1) map.biomeRiver = formatBiomeRiver(this.result.river); + if (this.poolPath) map.biomePool = this.poolPath; await this.plugin.saveSettings(); + // Biomes their terrain can't say (a user's) go in the Biome column. + await writeOverworldBiomes(this.plugin, res.name, this.result); if (this.makeAll) { const t0 = performance.now(); - const { made, errors } = await generateMissingRegions(this.plugin, res.name, { + const r = await regionPass(this.plugin, res.name, this.cells(), { + remake: false, onProgress: (done, total) => status.setText(`Making regions: ${done} of ${total}…`), }); - new Notice(`Made ${made.length} regions in ${((performance.now() - t0) / 1000).toFixed(1)} s.${errors.length ? ` ${errors.length} failed.` : ""}`); + new Notice(`Made ${r.made.length} regions in ${((performance.now() - t0) / 1000).toFixed(1)} s.${r.errors.length ? ` ${r.errors.length} failed.` : ""}${r.waiting ? ` ${r.waiting} blend until generator regions land.` : ""}`); } this.close(); this.onCreated(res.name); } + private async regenerateMap(status: HTMLElement): Promise { + const name = this.regenerate!; + status.setText("Regenerating…"); + const t0 = performance.now(); + const res = await regenerateOverworld(this.plugin, name, { + seed: this.seed, climate: this.climate, water: this.water / 100, land: this.land, north: this.north, + pool: this.poolBiomes(), poolPath: this.poolPath, regions: this.makeAll, + }, { onProgress: (done, total) => status.setText(`Regions: ${done} of ${total}…`) }); + if ("error" in res) { status.setText(res.error); return; } + new Notice(`Overworld regenerated in ${((performance.now() - t0) / 1000).toFixed(1)} s: ${res.written} hexes, ${res.kept} locked kept, ${res.made} regions made, ${res.remade} remade.${res.errors.length ? ` ${res.errors.length} failed.` : ""}`); + this.close(); + this.onCreated(name); + } + + onClose(): void { + this.contentEl.empty(); + } +} + +/** Name for a new biome pool. */ +class PoolNameModal extends HexmakerModal { + constructor(app: App, private onName: (name: string) => void) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + this.titleEl.setText("Save pool as"); + const input = this.contentEl.createEl("input", { type: "text", attr: { "aria-label": "Pool name", placeholder: "Cold north" } }); + const row = this.contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); + row.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); + const ok = row.createEl("button", { text: "Save", cls: "mod-cta" }); + const go = () => { + if (!input.value.trim()) return; + this.onName(input.value.trim()); + this.close(); + }; + ok.addEventListener("click", go); + input.addEventListener("keydown", (e) => { if (e.key === "Enter") go(); }); + input.focus(); + } + onClose(): void { this.contentEl.empty(); } diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index a2e818a5..54b8e32d 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -98,6 +98,12 @@ export interface HexData { /** Location maps opened from this hex (towns, dungeons…), in the user's order. */ locations?: string[]; locked?: boolean; + /** + * The hex's biome (an id or name of a biome note), on an overworld: set + * when its terrain alone can't say it (a user's biome paints a terrain + * that reads back as a built-in one). The optional "Biome" column. + */ + biome?: string; /** * Cells of Hexes-table columns this build doesn't know (header → value), * in the table's column order. Kept opaque and written back unchanged, so @@ -380,6 +386,7 @@ const SIMPLE_KEYS: [keyof MapSettings, string, Kind, string[]?][] = [ // Work mode: play, build or god (src/workMode.ts). ["workMode", "mode", "str"], ["biomeRiver", "biome-river", "str"], + ["biomePool", "biome-pool", "note"], ["showCoords", "show-coords", "bool"], ["showTerrainIcons", "show-terrain-icons", "bool"], ["showIconOverrides", "show-icon-overrides", "bool"], @@ -888,9 +895,12 @@ const FRONTMATTER = /^---[ \t]*\n(?:([\s\S]*?)\n)?---[ \t]*(\n|$)/; // ── tables ─────────────────────────────────────────────────────────────── -const HEX_HEADERS = ["Hex", "Name", "Terrain", "Icon", "GM icons", "Region", "Region map", "Locations", "Locked"]; -/** Known columns written only when the table has them or some row needs them. */ -const OPTIONAL_HEX_HEADERS = new Set(["region map"]); +const HEX_HEADERS = ["Hex", "Name", "Terrain", "Biome", "Icon", "GM icons", "Region", "Region map", "Locations", "Locked"]; +/** Known columns written only when the table has them or some row needs them (column → does a row need it). */ +const OPTIONAL_HEX_HEADERS: Record boolean> = { + "region map": (h) => !!h.regionMap, + biome: (h) => !!h.biome, +}; /** `## Paths` (format 5): what each path is. Route is derived. */ const PATH_HEADERS = ["Path", "Type", "Route", "Notes"]; /** `## Path routes`: where each path goes. Pure input, nothing derived. */ @@ -912,6 +922,7 @@ const HEX_COL_ALIASES: Record = { // Format 2's one-submap column: read as Locations, renamed on write. submap: "locations", submaps: "locations", locked: "locked", + biome: "biome", }; const PATH_COL_ALIASES: Record = { path: "path", paths: "path", pathname: "path", @@ -1031,7 +1042,7 @@ export function compareHexKeys(a: string, b: string): number { /** Anything besides terrain set on a hex. */ function hasNonTerrainData(h: HexData): boolean { - return !!(h.name || h.icon || (h.gmIcons && h.gmIcons.length) || h.region || h.regionMap || (h.locations && h.locations.length) || h.locked + return !!(h.name || h.icon || (h.gmIcons && h.gmIcons.length) || h.region || h.regionMap || (h.locations && h.locations.length) || h.locked || h.biome || (h.extra && Object.values(h.extra).some(Boolean))); } @@ -1098,6 +1109,7 @@ const HEX_CELL: Record string | undefined> = hex: (k) => k, name: (_k, h) => h.name, terrain: (_k, h) => h.terrain, + biome: (_k, h) => h.biome, icon: (_k, h) => h.icon, "gm icons": (_k, h) => h.gmIcons?.join(", "), region: (_k, h) => (h.region ? regionLinkText(h.region) : undefined), @@ -1108,7 +1120,7 @@ const HEX_CELL: Record string | undefined> = function hexTable(hexes: Map, baseTerrain?: string, existing?: string[], keptRows: string[] = []): string { const rows = hexRowsToWrite(hexes, baseTerrain); - const skip = new Set([...OPTIONAL_HEX_HEADERS].filter((c) => c !== "region map" || !rows.some(([, h]) => h.regionMap))); + const skip = new Set(Object.entries(OPTIONAL_HEX_HEADERS).filter(([, needs]) => !rows.some(([, h]) => needs(h))).map(([c]) => c)); const headers = columnOrder(HEX_HEADERS, HEX_COL_ALIASES, existing, extraHeaders(rows.map(([, h]) => h)), skip); const lines = tableHead(headers); for (const [k, h] of rows) { @@ -1264,7 +1276,7 @@ function readHexTable(lines: string[], t: Table | null): TableRead t.cols.indexOf(name); - const ci = { hex: col("hex"), name: col("name"), terrain: col("terrain"), icon: col("icon"), gm: col("gm icons"), region: col("region"), regionMap: col("region map"), locked: col("locked") }; + const ci = { hex: col("hex"), name: col("name"), terrain: col("terrain"), icon: col("icon"), gm: col("gm icons"), region: col("region"), regionMap: col("region map"), locked: col("locked"), biome: col("biome") }; // Locations may sit in more than one column (a Submap column next to a // Locations one): all are read, in column order. const locCols = t.cols.flatMap((c, i) => (c === "locations" ? [i] : [])); @@ -1286,6 +1298,8 @@ function readHexTable(lines: string[], t: Table | null): TableRead s.trim()).filter(Boolean); diff --git a/src/overworld/biomePool.ts b/src/overworld/biomePool.ts new file mode 100644 index 00000000..47eb71d4 --- /dev/null +++ b/src/overworld/biomePool.ts @@ -0,0 +1,219 @@ +/** + * Biome pools (#50): the biomes a generated overworld may use, one plain + * note per pool at `/.md`: + * + * --- + * hexmaker-biome-pool: 1 + * --- + * + * # Cold north + * + * > [!info] Biome pool + * > … (short help) + * + * | Biome | Weight | Notes | + * | --- | ---: | --- | + * | [[Tundra]] | | | + * | [[Taiga]] | 2 | twice as likely where it fits | + * | [[Glass wastes]] | 0.5 | | + * + * - *Biome* links a biome note (built-in or the user's, generator-backed + * ones too). + * - *Weight* (optional, default 1) scales how often the biome takes a hex + * where its climate fits: 0.5 = half its chance, 2 = twice it (up to + * always), 0 = never placed by the generator. + * - *Notes* is free text, kept as written. + * + * Placement uses each biome's climate (biomeClimate.ts). A biome in the + * pool WITHOUT a climate is placed only on hexes no climate biome of the + * pool fits (a pool of just such biomes paints them by chance). + * + * Reading is forgiving: columns by header name in any order, a plain name + * instead of a link, weights like `2` or `50%`. Rows that can't be read + * are reported and left in the note as written; rewriting replaces only + * the table (prose and other frontmatter stay). + * + * Pure: no Obsidian imports. + */ + +import { biomeFileName, linkTarget, type BiomeNoteFields } from "./biomeNote"; + +export const BIOME_POOL_MARKER = "hexmaker-biome-pool"; +export const BIOME_POOL_FORMAT = 1; +/** The shipped pool's name. */ +export const ALL_BIOMES_POOL = "All biomes"; + +export interface BiomePoolRow { + /** Link target as written (no brackets), e.g. "Tundra" or "world/biomes/Tundra". */ + biome: string; + /** Default 1. */ + weight?: number; + notes?: string; +} + +export interface BiomePoolProblem { + text: string; +} + +export interface ParsedBiomePool { + rows: BiomePoolRow[]; + problems: BiomePoolProblem[]; +} + +export const BIOME_POOL_HELP = [ + "> [!info] Biome pool", + "> The biomes a generated overworld may use. **Biome** links a biome note. **Weight** (optional, 1 if blank) scales how often it's chosen where its climate fits: 0.5 is half as often, 2 twice (up to always), 0 never. Biomes without a climate are only placed where no other biome in the pool fits. Add or delete rows freely.", +]; + +function splitRow(line: string): string[] { + let s = line.trim(); + if (s.startsWith("|")) s = s.slice(1); + if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1); + const cells: string[] = []; + let cur = ""; + let depth = 0; + for (let i = 0; i < s.length; i++) { + // A `|` inside [[link|alias]] belongs to the link. + if (s[i] === "[" && s[i + 1] === "[") { depth++; cur += "[["; i++; continue; } + if (s[i] === "]" && s[i + 1] === "]" && depth) { depth--; cur += "]]"; i++; continue; } + if (s[i] === "\\" && s[i + 1] === "|") { cur += "|"; i++; } + else if (s[i] === "|" && !depth) { cells.push(cur.trim()); cur = ""; } + else cur += s[i]; + } + cells.push(cur.trim()); + return cells; +} + +const SEPARATOR_ROW = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/; +const norm = (h: string) => h.trim().toLowerCase().replace(/\s+/g, " "); + +interface Span { start: number; end: number; headers: string[] } + +function findTable(lines: string[]): Span | null { + for (let i = 0; i < lines.length - 1; i++) { + if (!lines[i].trim().startsWith("|") || !SEPARATOR_ROW.test(lines[i + 1])) continue; + const headers = splitRow(lines[i]).map(norm); + if (!headers.includes("biome") && !headers.includes("biomes")) continue; + let end = i + 2; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { start: i, end, headers }; + } + return null; +} + +/** "2", "50%", "0.5" → a weight ≥ 0, or NaN. */ +function readWeight(raw: string): number { + const t = raw.trim(); + const pct = t.endsWith("%"); + const n = Number(t.replace(/%$/, "").trim()); + if (!t || !Number.isFinite(n) || n < 0) return NaN; + return pct ? n / 100 : n; +} + +/** Read a pool note. Never throws. */ +export function parseBiomePool(content: string): ParsedBiomePool { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const rows: BiomePoolRow[] = []; + const problems: BiomePoolProblem[] = []; + const t = findTable(lines); + if (!t) return { rows, problems: [{ text: "no table with a Biome column" }] }; + const bi = t.headers.includes("biome") ? t.headers.indexOf("biome") : t.headers.indexOf("biomes"); + const wi = ["weight", "chance", "share"].map((h) => t.headers.indexOf(h)).find((i) => i >= 0) ?? -1; + const ni = ["notes", "note", "comment"].map((h) => t.headers.indexOf(h)).find((i) => i >= 0) ?? -1; + for (let i = t.start + 2; i < t.end; i++) { + const cells = splitRow(lines[i]); + if (cells.every((c) => c === "")) continue; + const biome = linkTarget(cells[bi] ?? ""); + if (!biome) { problems.push({ text: `row ${i + 1}: no biome` }); continue; } + const row: BiomePoolRow = { biome }; + const rawW = wi >= 0 ? (cells[wi] ?? "").trim() : ""; + if (rawW) { + const w = readWeight(rawW); + if (Number.isFinite(w)) row.weight = w; + else problems.push({ text: `row ${i + 1}: weight "${rawW}" isn't a number (read as 1)` }); + } + const notes = ni >= 0 ? (cells[ni] ?? "").trim() : ""; + if (notes) row.notes = notes; + rows.push(row); + } + return { rows, problems }; +} + +const esc = (s: string) => s.replace(/\|/g, "\\|"); +const fmt = (n: number) => String(Math.round(n * 1000) / 1000); + +function poolTable(rows: BiomePoolRow[]): string[] { + return [ + "| Biome | Weight | Notes |", + "| --- | ---: | --- |", + ...rows.map((r) => `| [[${r.biome}]] | ${r.weight !== undefined && r.weight !== 1 ? fmt(r.weight) : ""} | ${esc(r.notes ?? "")} |`), + ]; +} + +/** A fresh pool note. */ +export function buildBiomePool(name: string, rows: BiomePoolRow[]): string { + return [ + "---", `${BIOME_POOL_MARKER}: ${BIOME_POOL_FORMAT}`, "---", "", + `# ${name}`, "", + ...BIOME_POOL_HELP, "", + ...poolTable(rows), "", + ].join("\n"); +} + +/** + * The note with its table set to `rows` (everything else kept; rows the + * plugin reads the same are left as written). Same string when unchanged. + */ +export function updateBiomePool(content: string, rows: BiomePoolRow[]): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const t = findTable(lines); + const same = (a: BiomePoolRow[], b: BiomePoolRow[]) => JSON.stringify(a.map(key)) === JSON.stringify(b.map(key)); + if (t && same(parseBiomePool(content).rows, rows) && !parseBiomePool(content).problems.length) return content; + const table = poolTable(rows); + let out: string[]; + if (t) out = [...lines.slice(0, t.start), ...table, ...lines.slice(t.end)]; + else { + out = [...lines]; + while (out.length && out[out.length - 1].trim() === "") out.pop(); + out.push("", ...table, ""); + } + return out.join(eol); +} + +const key = (r: BiomePoolRow) => [r.biome.toLowerCase(), r.weight ?? 1, r.notes ?? ""]; + +/** The shipped pool: every built-in biome, linked by its note's name. */ +export function allBiomesPool(presets: readonly BiomeNoteFields[]): BiomePoolRow[] { + return presets.map((p) => ({ biome: biomeFileName(p.label) })); +} + +/** + * A pool's biomes as placement input: each row's biome (looked up by + * `find`, which takes a link target), with its climate chance scaled by the + * row's weight. Weight 0 drops a biome; a row naming no known biome is + * reported. Repeats: the first row counts. + */ +export function poolBiomes( + rows: readonly BiomePoolRow[], + find: (ref: string) => BiomeNoteFields | undefined, +): { biomes: BiomeNoteFields[]; unknown: string[] } { + const biomes: BiomeNoteFields[] = []; + const unknown: string[] = []; + const seen = new Set(); + for (const r of rows) { + const b = find(r.biome) ?? find(r.biome.slice(r.biome.lastIndexOf("/") + 1)); + if (!b) { unknown.push(r.biome); continue; } + if (seen.has(b.id)) continue; + seen.add(b.id); + const w = r.weight ?? 1; + if (w <= 0) continue; + if (w === 1 || !b.climate) { biomes.push(b); continue; } + const chance = Math.min(1, (b.climate.chance ?? 1) * w); + const climate = { ...b.climate }; + if (chance >= 1) delete climate.chance; + else climate.chance = chance; + biomes.push({ ...b, climate }); + } + return { biomes, unknown }; +} diff --git a/src/overworld/overworldGen.ts b/src/overworld/overworldGen.ts new file mode 100644 index 00000000..bda080b0 --- /dev/null +++ b/src/overworld/overworldGen.ts @@ -0,0 +1,268 @@ +/** + * "Generate overworld" (#50): the first pass. Biome pools in the vault, + * laying a pool's biomes out with World biomes, and making (or remaking) + * every region with its biome. Only a first pass: afterwards each region + * is edited, rerolled or swapped as usual (within the work-mode gates). + * + * - Pools: `/.md` (biomePool.ts). The shipped + * "All biomes" pool is written once (settings.biomePoolSeeded). + * - Regenerating an existing overworld needs God; locked (hand-painted) + * hexes keep their terrain and biome, and their regions are left alone. + * Regions are remade in place (their notes, names and locked cells stay). + * - Every region goes through regionGenerator(biome), the single routing + * point: generator-backed biomes use their generator once generator + * regions are ready; until then they blend like the rest. + */ + +import { TFile, TFolder } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { normalizeFolder } from "../utils"; +import { canAdd, canReshape } from "../workMode"; +import { regionMapAt } from "../maps/submaps"; +import { + ALL_BIOMES_POOL, + allBiomesPool, + buildBiomePool, + parseBiomePool, + poolBiomes, + updateBiomePool, + type BiomePoolProblem, + type BiomePoolRow, +} from "./biomePool"; +import { biomeFileName, type BiomeNoteFields } from "./biomeNote"; +import { BIOME_PRESETS } from "./biomePresets"; +import { biomeForTerrain, biomeNoteOf, type BiomeId } from "./biomes"; +import { regionGenerator } from "./biomeForm"; +import { firstPassWrites } from "./overworldPass"; +import { formatBiomeRiver, regionOrder } from "./regionWorld"; +import { createRegion, overworldOf, regenerateRegion } from "./regionsVault"; +import { worldBiomes, type WorldBiomesOptions, type WorldBiomesResult } from "./worldBiomes"; + +/** Hint shown where regenerating a whole overworld is locked. */ +export const REGENERATE_LOCKED_HINT = "Switch to God to regenerate the whole overworld."; + +// ── pools in the vault ─────────────────────────────────────────────────── + +export function biomePoolsFolder(plugin: HexmakerPlugin): string { + const configured = normalizeFolder(plugin.settings.biomePoolsFolder ?? ""); + if (configured) return configured; + const world = normalizeFolder(plugin.settings.worldFolder ?? ""); + return world ? `${world}/biome-pools` : "biome-pools"; +} + +export interface PoolNote { + path: string; + name: string; + rows: BiomePoolRow[]; + problems: BiomePoolProblem[]; +} + +async function ensureFolder(plugin: HexmakerPlugin, folder: string): Promise { + const parts = folder.split("/"); + for (let i = 1; i <= parts.length; i++) { + const p = parts.slice(0, i).join("/"); + if (!plugin.app.vault.getAbstractFileByPath(p)) { + try { await plugin.app.vault.createFolder(p); } catch { /* made meanwhile */ } + } + } +} + +/** Write the shipped "All biomes" pool, once (never over a note, never again once deleted). */ +export async function ensureDefaultPool(plugin: HexmakerPlugin): Promise { + if (plugin.settings.biomePoolSeeded) return; + const folder = biomePoolsFolder(plugin); + const path = `${folder}/${ALL_BIOMES_POOL}.md`; + if (!plugin.app.vault.getAbstractFileByPath(path)) { + await ensureFolder(plugin, folder); + try { + await plugin.app.vault.create(path, buildBiomePool(ALL_BIOMES_POOL, allBiomesPool(BIOME_PRESETS))); + } catch (e) { + console.error("Hexmaker: couldn't write the biome pool", path, e); + return; + } + } + plugin.settings.biomePoolSeeded = true; + await plugin.saveSettings(); +} + +/** Every pool note (names starting with "_" left out), by name. Seeds the default first. */ +export async function listBiomePools(plugin: HexmakerPlugin): Promise { + await ensureDefaultPool(plugin); + const root = plugin.app.vault.getAbstractFileByPath(biomePoolsFolder(plugin)); + if (!(root instanceof TFolder)) return []; + const files: TFile[] = []; + const walk = (f: TFolder) => { + for (const c of f.children) { + if (c instanceof TFolder) walk(c); + else if (c instanceof TFile && c.extension === "md" && !c.basename.startsWith("_")) files.push(c); + } + }; + walk(root); + const out: PoolNote[] = []; + for (const f of files.sort((a, b) => a.basename.localeCompare(b.basename))) { + const { rows, problems } = parseBiomePool(await plugin.app.vault.read(f)); + out.push({ path: f.path, name: f.basename, rows, problems }); + } + return out; +} + +/** Save a pool's rows: into its note (`path`), or a new note named `name`. */ +export async function saveBiomePool(plugin: HexmakerPlugin, target: { path: string } | { name: string }, rows: BiomePoolRow[]): Promise<{ path: string } | { error: string }> { + if ("path" in target) { + const f = plugin.app.vault.getAbstractFileByPath(target.path); + if (!(f instanceof TFile)) return { error: "That pool's note is gone." }; + const content = await plugin.app.vault.read(f); + const next = updateBiomePool(content, rows); + if (next !== content) await plugin.app.vault.modify(f, next); + return { path: f.path }; + } + const name = biomeFileName(target.name.trim()); + if (!target.name.trim()) return { error: "Give the pool a name." }; + const folder = biomePoolsFolder(plugin); + const path = `${folder}/${name}.md`; + if (plugin.app.vault.getAbstractFileByPath(path)) return { error: `There's already a pool called ${name}.` }; + await ensureFolder(plugin, folder); + await plugin.app.vault.create(path, buildBiomePool(name, rows)); + return { path }; +} + +/** A pool's biomes, looked up in the biome notes. */ +export function resolvePool(plugin: HexmakerPlugin, rows: readonly BiomePoolRow[]): { biomes: BiomeNoteFields[]; unknown: string[] } { + return poolBiomes(rows, (ref) => plugin.biomeStore.get(ref)); +} + +/** A pool row for a biome (linked by its note's name). */ +export function poolRowFor(plugin: HexmakerPlugin, biome: BiomeNoteFields): BiomePoolRow { + const path = plugin.biomeStore.pathOf(biome.id); + return { biome: path ? path.slice(path.lastIndexOf("/") + 1).replace(/\.md$/, "") : biomeFileName(biome.label) }; +} + +// ── the pass ───────────────────────────────────────────────────────────── + +/** The hexes an existing overworld covers: painted or with a region (else its whole grid). */ +export function overworldCells(plugin: HexmakerPlugin, mapName: string): [number, number][] { + const map = plugin.getMap(mapName); + if (!map) return []; + const keys = new Set(); + for (const [k, h] of plugin.mapStore.all(mapName)) if (h.terrain || h.regionMap) keys.add(k); + for (const m of plugin.settings.maps) if (m.submapKind === "region" && m.parent?.map === mapName) keys.add(m.parent.hex); + if (!keys.size) { + for (let y = map.gridOffset.y; y < map.gridOffset.y + map.gridSize.rows; y++) { + for (let x = map.gridOffset.x; x < map.gridOffset.x + map.gridSize.cols; x++) keys.add(`${x}_${y}`); + } + } + return [...keys].map((k) => k.split("_").map(Number) as [number, number]); +} + +/** World biomes for an overworld's cells from a pool. */ +export function layOutBiomes( + plugin: HexmakerPlugin, + cells: [number, number][], + palette: Parameters[3], + opts: Omit, + pool: readonly BiomeNoteFields[] | undefined, + stagger?: "odd" | "even", +): WorldBiomesResult { + const o = plugin.settings.hexOrientation, s = stagger ?? plugin.settings.staggerOffset ?? "odd"; + return worldBiomes(cells, o, s, palette, { ...opts, biomes: pool }); +} + +/** Write a result into the overworld (locked hexes kept). Returns the hexes kept. */ +export async function writeOverworldBiomes(plugin: HexmakerPlugin, mapName: string, result: WorldBiomesResult): Promise<{ written: number; kept: string[] }> { + const palette = plugin.getMapPalette(mapName); + const current = new Map([...plugin.mapStore.all(mapName)].map(([k, h]) => [k, { terrain: h.terrain, biome: h.biome, locked: h.locked }])); + const { cells, kept } = firstPassWrites(current, result, (t) => biomeForTerrain(t, palette)); + for (const [k, patch] of cells) plugin.mapStore.set(mapName, k, patch); + await plugin.mapStore.flush(); + return { written: cells.length, kept }; +} + +export interface RegionPassHooks { + onProgress?: (done: number, total: number, name: string) => void; + cancelled?: () => boolean; +} + +/** + * Make every missing region, and (God, `remake`) regenerate the existing + * ones, centre-out, each through regionGenerator(biome). Hexes in `skip` + * (locked) are left alone. Returns what happened. + */ +export async function regionPass( + plugin: HexmakerPlugin, + mapName: string, + cells: [number, number][], + opts: { remake: boolean; skip?: ReadonlySet } & RegionPassHooks, +): Promise<{ made: string[]; remade: string[]; waiting: number; errors: string[] }> { + const out = { made: [] as string[], remade: [] as string[], waiting: 0, errors: [] as string[] }; + const ow = overworldOf(plugin, mapName); + if (!ow) { out.errors.push("This map has no rectangle region settings."); return out; } + const order = regionOrder(cells.filter(([x, y]) => !opts.skip?.has(`${x}_${y}`)), ow.layout.orientation, ow.layout.parentStagger); + let done = 0; + for (const [px, py] of order) { + if (opts.cancelled?.()) break; + const hex = `${px}_${py}`; + const terrain = plugin.mapStore.get(mapName, hex)?.terrain; + const existing = regionMapAt(plugin.settings.maps, mapName, hex); + const biome = biomeOfHex(plugin, mapName, hex, terrain); + // The routing point: every region of every biome goes through here. + const route = regionGenerator(biome ? biomeNoteOf(biome) : undefined); + if (route.kind === "generator" && !route.ready) out.waiting++; + let name = ""; + if (existing) { + if (opts.remake) { + await regenerateRegion(plugin, existing.name, biome ? { biome } : {}); + out.remade.push(existing.name); + name = existing.name; + } + } else if (terrain) { + const res = await createRegion(plugin, mapName, px, py, { fill: "match", ...(biome ? { biome } : {}) }); + if ("error" in res) out.errors.push(`${px}, ${py}: ${res.error}`); + else { out.made.push(res.name); name = res.name; } + } + opts.onProgress?.(++done, order.length, name); + } + return out; +} + +function biomeOfHex(plugin: HexmakerPlugin, mapName: string, hex: string, terrain: string | undefined): BiomeId | undefined { + const own = plugin.mapStore.get(mapName, hex)?.biome; + if (own) return plugin.biomeStore.get(own)?.id; + return terrain ? biomeForTerrain(terrain, plugin.getMapPalette(mapName)) : undefined; +} + +export interface RegenerateOptions extends Omit { + /** The pool's note (recorded on the map), and its biomes. */ + poolPath?: string; + pool?: readonly BiomeNoteFields[]; + /** Make the missing regions and remake the rest (default true). */ + regions?: boolean; +} + +/** + * Regenerate a whole overworld (God only): lay the pool's biomes out again, + * keep locked hexes, then remake the regions (theirs too, locked cells + * kept) and make the missing ones. + */ +export async function regenerateOverworld( + plugin: HexmakerPlugin, + mapName: string, + opts: RegenerateOptions, + hooks: RegionPassHooks = {}, +): Promise<{ written: number; kept: number; made: number; remade: number; waiting: number; errors: string[] } | { error: string }> { + const map = plugin.getMap(mapName); + if (!map) return { error: "Map not found." }; + if (!canReshape(map)) return { error: REGENERATE_LOCKED_HINT }; + const cells = overworldCells(plugin, mapName); + const result = layOutBiomes(plugin, cells, plugin.getMapPalette(mapName), opts, opts.pool, map.staggerOffset); + if (!result.biomes.size) return { error: "No biome in this pool can be placed: give some a climate." }; + const { written, kept } = await writeOverworldBiomes(plugin, mapName, result); + map.biomeRiver = result.river.length > 1 ? formatBiomeRiver(result.river) : undefined; + if (opts.poolPath) map.biomePool = opts.poolPath; + await plugin.saveSettings(); + let regions = { made: [] as string[], remade: [] as string[], waiting: 0, errors: [] as string[] }; + if ((opts.regions ?? true) && overworldOf(plugin, mapName) && canAdd(map)) { + regions = await regionPass(plugin, mapName, cells, { remake: true, skip: new Set(kept), ...hooks }); + } + plugin.refreshHexMap(); + return { written, kept: kept.length, made: regions.made.length, remade: regions.remade.length, waiting: regions.waiting, errors: regions.errors }; +} diff --git a/src/overworld/overworldPass.ts b/src/overworld/overworldPass.ts new file mode 100644 index 00000000..ce19d34a --- /dev/null +++ b/src/overworld/overworldPass.ts @@ -0,0 +1,47 @@ +/** + * The overworld first pass (#50), pure part: what a World biomes result + * writes into an overworld's hexes. Hand-painted (locked) hexes are never + * written; every other hex gets its biome's terrain, and its biome in the + * Biome column when the terrain can't say it (a user's biome). + * + * Pure: no Obsidian imports. + */ + +import type { BiomeId } from "./biomes"; + +export interface PassHex { + terrain?: string; + biome?: string; + locked?: boolean; +} + +export interface PassWrites { + /** Hex → patch (`biome: null` clears the column). */ + cells: [string, { terrain: string; biome: string | null }][]; + /** Locked hexes left as they were. */ + kept: string[]; +} + +/** + * The writes for a result. `readsAs(terrain)` is the biome a terrain stands + * for on the overworld's palette (biomeForTerrain). Hexes whose biome has + * no terrain on the palette are left alone. + */ +export function firstPassWrites( + current: ReadonlyMap, + result: { biomes: ReadonlyMap; terrain: ReadonlyMap }, + readsAs: (terrain: string) => BiomeId | undefined, +): PassWrites { + const cells: PassWrites["cells"] = []; + const kept: string[] = []; + for (const [k, biome] of result.biomes) { + if (current.get(k)?.locked) { kept.push(k); continue; } + const terrain = result.terrain.get(k); + if (!terrain) continue; + const want = readsAs(terrain) === biome ? null : biome; + const cur = current.get(k); + if (cur?.terrain === terrain && (cur.biome ?? null) === want) continue; + cells.push([k, { terrain, biome: want }]); + } + return { cells, kept }; +} diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index d5a73d0d..71ff0d5b 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -102,11 +102,28 @@ export function placedBiomes(plugin: HexmakerPlugin, overworldName: string): Map const id = biomeByRef(m.biome?.generator); if (id) out.set(m.parent.hex, id); } + // The overworld's own Biome column wins (set with the biome, before any region exists). + for (const [k, h] of plugin.mapStore.all(overworldName)) { + const id = biomeByRef(h.biome); + if (id) out.set(k, id); + } return out; } +/** + * Record hex `hex`'s biome in the overworld's Biome column when its + * terrain can't say it (a user's biome), else clear it. Not flushed. + */ +export function recordHexBiome(plugin: HexmakerPlugin, overworldName: string, hex: string, biome: BiomeId, terrain: string | undefined): void { + const reads = terrain ? biomeForTerrain(terrain, plugin.getMapPalette(overworldName)) : undefined; + const want = reads === biome ? undefined : biome; + if ((plugin.mapStore.get(overworldName, hex)?.biome ?? undefined) !== want) plugin.mapStore.set(overworldName, hex, { biome: want ?? null }); +} + /** One overworld hex's biome: its placed biome, else read from its terrain. */ export function hexBiomeAt(plugin: HexmakerPlugin, overworldName: string, hex: string): BiomeId | undefined { + const own = biomeByRef(plugin.mapStore.get(overworldName, hex)?.biome); + if (own) return own; const region = regionMapAt(plugin.settings.maps, overworldName, hex); const placed = region ? biomeByRef(region.biome?.generator) : undefined; if (placed) return placed; @@ -370,10 +387,9 @@ export async function setBiomeAt( const hex = `${px}_${py}`; const lock = reshapeLock(plugin, parentName, px, py); if (lock) return { error: lock }; - if (plugin.mapStore.get(parentName, hex)?.terrain !== terrain) { - plugin.mapStore.set(parentName, hex, { terrain }); - await plugin.mapStore.flush(); - } + if (plugin.mapStore.get(parentName, hex)?.terrain !== terrain) plugin.mapStore.set(parentName, hex, { terrain }); + recordHexBiome(plugin, parentName, hex, biome, terrain); + await plugin.mapStore.flush(); const existing = regionMapAt(plugin.settings.maps, parentName, hex); if (existing) { await regenerateRegion(plugin, existing.name, { ...opts, biome }); diff --git a/src/types.ts b/src/types.ts index 12a2e5de..09aa0bde 100644 --- a/src/types.ts +++ b/src/types.ts @@ -221,6 +221,8 @@ export interface MapData { /** Overworlds made by World biomes: the river's hexes, source to mouth, * as "x,y > x,y > …" (biome data drawn on the overworld; not a path). */ biomeRiver?: string; + /** Overworlds: the biome pool note (vault path) its biomes were placed from (`biome-pool: "[[…]]"`). */ + biomePool?: string; backgroundImage?: MapBackgroundImage; /** Optional independent transform applied to the hex grid container, * used during background-image calibration so the user can resize/shift @@ -347,6 +349,10 @@ export interface HexmakerPluginSettings { biomesSeeded?: string[]; /** Shipped biomes whose notes got their climate added (ids): once each, so a climate cleared by hand stays cleared. */ biomeClimatesSeeded?: string[]; + /** Vault folder for biome pool notes; blank = `/biome-pools`. */ + biomePoolsFolder?: string; + /** True once the shipped "All biomes" pool note was written (once, so a deleted one stays deleted). */ + biomePoolSeeded?: boolean; /** True once settings-only palettes were written out as notes. */ palettesMigrated: boolean; /** diff --git a/styles.css b/styles.css index b1abb9ab..141deff7 100644 --- a/styles.css +++ b/styles.css @@ -8587,3 +8587,39 @@ textarea.duckmage-edit-region-notes-input { flex: 1 1 auto; min-width: 6em; } +/* Generate overworld: the biome pool list (compact, scrolls when long). */ +.duckmage-ow-pool-list { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(15em, 1fr)); + gap: 2px 10px; + max-height: 14em; + overflow-y: auto; + margin: 4px 0; +} +.duckmage-ow-pool-item { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.duckmage-ow-pool-swatch { + width: 0.9em; + height: 0.9em; + border-radius: 2px; + flex: none; + background: var(--duckmage-swatch, transparent); +} +.duckmage-ow-pool-name { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.duckmage-ow-pool-tag { + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} +.duckmage-ow-pool-item .duckmage-biome-weight { + width: 3.5em; +} diff --git a/tests/biomePool.test.ts b/tests/biomePool.test.ts new file mode 100644 index 00000000..39ac3550 --- /dev/null +++ b/tests/biomePool.test.ts @@ -0,0 +1,192 @@ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { hexDistance } from "../packages/hex-wfc/src/grid"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { + ALL_BIOMES_POOL, + allBiomesPool, + buildBiomePool, + parseBiomePool, + poolBiomes, + updateBiomePool, +} from "../src/overworld/biomePool"; +import { biomeFileName, type BiomeNoteFields } from "../src/overworld/biomeNote"; +import { BIOME_PRESETS } from "../src/overworld/biomePresets"; +import { biomeForTerrain, setBiomeSource } from "../src/overworld/biomes"; +import { worldBiomes } from "../src/overworld/worldBiomes"; +import { firstPassWrites } from "../src/overworld/overworldPass"; +import { buildMapNote, parseMapNote, type HexData, type MapNoteData } from "../src/maps/mapNote"; + +const hexWorld = (R: number): [number, number][] => { + const out: [number, number][] = []; + for (let x = 0; x <= 2 * R; x++) for (let y = 0; y <= 2 * R; y++) if (hexDistance([x, y], [R, R], "flat", "odd") <= R) out.push([x, y]); + return out; +}; +const sorted = (m: Map) => JSON.stringify([...m].sort()); +const byId = new Map(BIOME_PRESETS.map((p) => [p.id, p])); +const preset = (id: string) => byId.get(id)!; +/** Lookup like the plugin's (biome store): id, label or note name. */ +const finder = (list: BiomeNoteFields[]) => (ref: string) => { + const k = ref.trim().toLowerCase().replace(/\s+/g, "-"); + return list.find((b) => b.id === k || b.label.toLowerCase().replace(/\s+/g, "-") === k); +}; + +afterEach(() => setBiomeSource(undefined)); + +describe("biome pool notes", () => { + it("round-trips and keeps prose", () => { + const rows = [{ biome: "Tundra" }, { biome: "Taiga", weight: 2, notes: "more | pines" }, { biome: "Glass wastes", weight: 0.5 }]; + const note = buildBiomePool("Cold north", rows); + expect(note).toContain("hexmaker-biome-pool: 1"); + expect(note).toContain("| [[Taiga]] | 2 | more \\| pines |"); + expect(parseBiomePool(note)).toEqual({ rows, problems: [] }); + const withProse = note.replace("# Cold north", "# Cold north\n\nMy notes on the north."); + expect(updateBiomePool(withProse, rows)).toBe(withProse); + const next = updateBiomePool(withProse, rows.slice(1)); + expect(next).toContain("My notes on the north."); + expect(parseBiomePool(next).rows).toEqual(rows.slice(1)); + }); + + it("reads forgivingly and reports what it can't", () => { + const note = [ + "| Notes | Biome | Chance |", + "| --- | --- | --- |", + "| a | [[world/biomes/Tundra|cold one]] | 50% |", + "| | Taiga | lots |", + "| orphan | | 1 |", + "", + ].join("\n"); + const { rows, problems } = parseBiomePool(note); + expect(rows).toEqual([{ biome: "world/biomes/Tundra", weight: 0.5, notes: "a" }, { biome: "Taiga" }]); + expect(problems.map((p) => p.text)).toEqual([expect.stringMatching(/weight "lots"/), expect.stringMatching(/no biome/)]); + expect(parseBiomePool("no table here").problems.length).toBe(1); + }); + + it("ships one pool with every built-in biome", () => { + const rows = allBiomesPool(BIOME_PRESETS); + expect(ALL_BIOMES_POOL).toBe("All biomes"); + expect(rows.map((r) => r.biome)).toEqual(BIOME_PRESETS.map((p) => biomeFileName(p.label))); + const { biomes, unknown } = poolBiomes(parseBiomePool(buildBiomePool(ALL_BIOMES_POOL, rows)).rows, finder([...BIOME_PRESETS])); + expect(unknown).toEqual([]); + expect(biomes.map((b) => b.id)).toEqual(BIOME_PRESETS.map((p) => p.id)); + }); + + it("weights scale a biome's chance; 0 leaves it out; unknown biomes are reported", () => { + const { biomes, unknown } = poolBiomes( + [{ biome: "Karst", weight: 0.5 }, { biome: "Valley", weight: 3 }, { biome: "Tundra", weight: 0 }, { biome: "Nowhere" }, { biome: "karst" }], + finder([...BIOME_PRESETS]), + ); + expect(unknown).toEqual(["Nowhere"]); + expect(biomes.map((b) => b.id)).toEqual(["karst", "valley"]); + expect(biomes[0].climate!.chance).toBeCloseTo(0.275, 6); + expect(biomes[1].climate!.chance).toBeUndefined(); // 0.55 × 3 → always + expect(preset("karst").climate!.chance).toBe(0.55); // the note's own data untouched + }); +}); + +describe("placement from a pool", () => { + const SEEDS = [1, 5, 42, 99, 2024]; + const cells = hexWorld(4); + + it("places only the pool's biomes", () => { + const pool = ["tundra", "taiga", "temperate-forest", "grassland", "alpine", "open-sea"].map(preset); + const ids = new Set(pool.map((b) => b.id)); + for (const seed of SEEDS) { + const r = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed, climate: "varied", biomes: pool }); + expect(r.biomes.size).toBe(cells.length); + for (const b of r.biomes.values()) expect(ids.has(b)).toBe(true); + } + }); + + it("the full shipped pool places exactly what World biomes does", () => { + for (const seed of SEEDS) { + const a = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed }); + const b = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed, biomes: BIOME_PRESETS }); + expect(sorted(b.biomes)).toBe(sorted(a.biomes)); + } + }); + + const ASH: BiomeNoteFields = { id: "ash", label: "Ash", mix: [{ type: "badlands", weight: 1 }], transitions: [] }; + + it("a pool biome without a climate fills only the hexes no climate biome fits", () => { + setBiomeSource([...BIOME_PRESETS, ASH]); + // With lowland biomes covering every climate, it never gets a hex. + for (const seed of SEEDS) { + const r = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed, biomes: [...BIOME_PRESETS, ASH] }); + expect([...r.biomes.values()]).not.toContain("ash"); + } + // With no lowland biome in the pool, the lowlands are it. + const pool = [preset("alpine"), preset("open-sea"), ASH]; + const r = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 42, biomes: pool, river: false }); + const land = [...r.biomes].filter(([k]) => !r.sea.has(k)); + expect(land.filter(([, b]) => b === "ash").length).toBeGreaterThan(land.length / 2); + for (const b of r.biomes.values()) expect(["alpine", "open-sea", "ash"]).toContain(b); + }); + + it("is deterministic for a seed and a pool", () => { + setBiomeSource([...BIOME_PRESETS, ASH]); + const pool = [preset("alpine"), preset("open-sea"), preset("taiga"), ASH]; + const a = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 7, biomes: pool }); + const b = worldBiomes([...cells].reverse(), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 7, biomes: [...pool] }); + expect(sorted(a.biomes)).toBe(sorted(b.biomes)); + expect(sorted(a.terrain)).toBe(sorted(b.terrain)); + }); + + it("a pool with nothing placeable places nothing", () => { + const r = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 1, biomes: [] }); + expect(r.biomes.size).toBe(0); + expect(r.terrain.size).toBe(0); + }); +}); + +describe("the first pass writes", () => { + const readsAs = (t: string) => biomeForTerrain(t, DEFAULT_TERRAIN_PALETTE); + + it("never touches locked hexes; records a biome its terrain can't say", () => { + setBiomeSource([...BIOME_PRESETS, { id: "ash", label: "Ash", mix: [{ type: "badlands", weight: 1 }], transitions: [], climate: { elevation: "low" } }]); + const r = worldBiomes(hexWorld(3), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 3 }); + const keys = [...r.biomes.keys()]; + const current = new Map([ + [keys[0], { terrain: "my painted", locked: true }], + [keys[1], { terrain: "old", biome: "old-one" }], + ]); + const w = firstPassWrites(current, r, readsAs); + expect(w.kept).toEqual([keys[0]]); + expect(w.cells.some(([k]) => k === keys[0])).toBe(false); + for (const [k, patch] of w.cells) { + expect(patch.terrain).toBe(r.terrain.get(k)); + expect(patch.biome).toBe(readsAs(patch.terrain) === r.biomes.get(k) ? null : r.biomes.get(k)); + } + // Nothing to do the second time round (beyond the locked hex). + const after = new Map(current); + for (const [k, p] of w.cells) after.set(k, { terrain: p.terrain, biome: p.biome ?? undefined }); + expect(firstPassWrites(after, r, readsAs).cells).toEqual([]); + }); + + it("regenerating keeps locked hexes across seeds", () => { + const cells = hexWorld(3); + const first = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 1 }); + const state = new Map(); + for (const [k, p] of firstPassWrites(state, first, readsAs).cells) state.set(k, { terrain: p.terrain }); + const lockedKey = [...state.keys()][4]; + state.set(lockedKey, { terrain: "hand painted", locked: true }); + const second = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 2 }); + for (const [k, p] of firstPassWrites(state, second, readsAs).cells) state.set(k, { ...state.get(k), terrain: p.terrain }); + expect(state.get(lockedKey)).toEqual({ terrain: "hand painted", locked: true }); + }); +}); + +describe("map note: Biome column", () => { + it("is written only when a hex has a biome, and reads back", () => { + const hexes = new Map([["0_0", { terrain: "forest" }], ["1_0", { terrain: "hills", biome: "ash" }]]); + const data: MapNoteData = { settings: { paletteName: "Default", biomePool: "world/biome-pools/All biomes.md" }, hexes, paths: [] }; + const note = buildMapNote("ow", data); + expect(note).toContain("| Hex | Name | Terrain | Biome |"); + expect(note).toContain('biome-pool: "[[world/biome-pools/All biomes]]"'); + const back = parseMapNote(note)!; + expect(back.hexes.get("1_0")).toEqual({ terrain: "hills", biome: "ash" }); + expect(back.settings.biomePool).toBe("world/biome-pools/All biomes.md"); + const plain = buildMapNote("ow", { ...data, hexes: new Map([["0_0", { terrain: "forest" }]]) }); + expect(plain).not.toContain("Biome |"); + }); +}); From 52ebe087a7f7fdf1cd866683c98a2329489f5e44 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 00:57:26 -0400 Subject: [PATCH 266/558] docs(biomes #50): biome climates, biome pools and Generate overworld in README and help Co-Authored-By: Claude Opus 5.5 --- README.md | 7 ++++++- src/hex-map/help.md | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e145bbb5..c80d3dbf 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,10 @@ Which biome a hex is comes from its terrain's **Type**, never its name: forest-t **Your own biomes.** Every biome is a plain note in the biomes folder (default `{world folder}/biomes`, see Settings). The built-in ones are written there once when the plugin starts, so you can edit them like any other note; delete one and it stays deleted. A biome note has a name, a colour, a **Mix** table of terrain *types* with weights (never terrain names, so it works on any palette with types), a **Transitions** table (biomes it shouldn't touch and the biome put between them), and in its frontmatter `blend` (narrow, normal or wide), `land-share` and `min-islands` (for watery biomes) and an optional `generator: [[…]]` link. Rows that can't be read are reported and left as you wrote them; your own text in the note is kept. On an overworld's **Biomes** view, **Biomes…** lists them: **Add biome…** opens a form (pick **Blend (built-in mixing)** or one of your generators, name, colour, type weights, blend, land share, fewest islands, transitions) with a live preview of one region, and **Save** writes the note. **Edit…** opens the same form for an existing biome (built-in ones also have **Restore default**, which backs up the old note first). **Edit generator…** (also in **Edit region…**) opens the biome's generator, or its note for now. Biomes linked to a generator say "available once generator regions land" and blend until then. Your biomes appear in the biome picker and make regions with the blend field straight away. Adding and editing biomes needs Build or God. A region keeps its biome when you rename the biome's note; if you delete the note, the region keeps its terrain and **Edit region…** shows "Unknown biome". Inside a region, click the middle of the hex flower to open **Edit region…** for it; the overworld's right-click menu has **Create token here** to mark the party. +**Biome climates.** A biome note can say where generated overworlds put it, with optional plain keys: `temperature` (cold, cool, mild, warm, hot, a range like `cold–mild`, or numbers like `0.2–0.5`), `moisture` (dry, moderate, wet, or numbers), `elevation` (`low`, `mid` for hills, `high` for peaks, `sea`, or `mouth` for the river's mouth), `coastal: yes` (only next to the coast), `chance` (like `50%`: the share of fitting hexes it takes) and `rare: yes` (at most one hex in about 20). With any of them set, World biomes can choose the biome like a built-in one; left blank, the biome is only placed by hand. The built-in biomes carry their climates in their notes too (older built-in notes get them added once), so you can see and change why tundra goes north. Where several biomes fit a hex, the rarer and then the narrower one is tried first. The biome form has the same fields in a folded **Climate (optional, for generated overworlds)** section. Values the plugin can't read are reported and ignored. + +**Generate overworld (first pass).** **New overworld…** lays out the biomes of a **biome pool**: a plain note in the biome pools folder (default `{world folder}/biome-pools`) with a `Biome | Weight | Notes` table linking biome notes. **All biomes** (every built-in) is written there once. In the form, pick a pool and add or remove biomes (built-in, your own, or ones made by a generator), set a weight (1 as its note says, 0.5 half as often, 2 twice, 0 never), and **Save** or **Save as…** a new pool; the preview updates as you go. Climate, land, which way is colder, water and seed are the World biomes settings. A biome in the pool without a climate is only placed where no other biome in the pool fits. **Create** makes the map (it remembers its pool as `biome-pool: "[[…]]"`) and every region with its biome; a biome whose terrain doesn't tell it apart (one of yours) is kept in the overworld's optional **Biome** column. It's only a first pass: edit, reroll or swap any region afterwards. To redo the whole map, open the map menu → **Regions** → **Generate overworld…** (God only): locked hexes keep their terrain and their regions are left alone, every other region is remade in place (its name, notes and locked hexes stay), and missing regions are made. + A small **minimap** of the overworld (bottom right) shows on the overworld and on each of its regions, with the region you're in outlined; click a hex on it to go there. **Neighbouring maps** (below) and overworlds both stay available: pick per map. A map can have N/E/S/W neighbours and regions at once; a region itself joins its neighbours by itself, so it doesn't offer the neighbour tools. **Neighbouring maps.** In **Maps → New map…**, **Next to** makes the new map a region beside an existing one (same size and palette, lined up hex for hex); **Properties → New region here…** opens the form already placed. The generators marked *Continues … edge* (Overland and learned generators) carry the neighbour's terrain on across the shared border, and the preview shows the neighbour's edge faded around the new map. Region detail is only offered for submaps, since it zooms into a parent hex. @@ -290,7 +294,7 @@ Every command, as it appears in the command palette: | **Hexmap World Creator: Open random tables** | Opens the random tables and workflows view. | | **Hexmap World Creator: Open terrain generator** | Opens the terrain generator (learn, blend and run generators). | | **Hexmap World Creator: Open palette editor** | Opens the terrain palette editor. | -| **Hexmap World Creator: New overworld…** | A map of biomes (World biomes) whose hexes open into regions that join up; can make every region at once. Advanced: Regions and overworlds. | +| **Hexmap World Creator: New overworld…** | Generate overworld (first pass): a map of biomes from a biome pool, laid out by climate, whose hexes open into regions that join up; can make every region at once. Advanced: Regions and overworlds. | | **Hexmap World Creator: Go up to parent map** | From a submap, back to the map it belongs to. | | **Hexmap World Creator: Go back to previous map** | Returns to the map you were on before. | | **Hexmap World Creator: Go forward to the next map** | After going back, forward again (like a browser). | @@ -329,6 +333,7 @@ Open **Settings → Hexmap World Creator** to configure: | **Path types** | Named path types used by the Path drawing tool. Each type has a name, colour, width, line style, and routing mode. Manage them from the Path button on the hex map toolbar. | | **Palettes folder** | Folder holding one note per terrain palette (default `{world folder}/palettes`). | | **Biomes folder** | Folder holding one note per overworld biome (default `{world folder}/biomes`). | +| **Biome pools folder** | Folder holding the biome pool notes used by Generate overworld (default `{world folder}/biome-pools`). | | **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | | **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 630d51af..4d70f4be 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -142,6 +142,10 @@ Turn on any one of them from the hint (✦) where it would appear, or all of the **Your own biomes.** Each biome is a note in the biomes folder (default `{world folder}/biomes`); the built-in ones are written there once, so you can edit them. A note lists terrain *types* with weights (**Mix**), **Transitions** (biomes it shouldn't touch, and what goes between), and `blend`, `land-share`, `min-islands` and an optional `generator` link. In the **Biomes** view, **Biomes…** lists them with **Add biome…**, **Edit…** (built-ins also have **Restore default**) and **Edit generator…**; the form has a live preview of one region. Needs Build or God. Inside a region, click the middle of the hex flower for **Edit region…**; right-click an overworld hex for **Create token here**. +**Biome climates.** Optional keys in a biome note (or the form's folded **Climate** section) say where generated overworlds put it: `temperature` (cold, cool, mild, warm, hot, or `0.2–0.5`), `moisture` (dry, moderate, wet), `elevation` (low, mid, high, sea, mouth), `coastal: yes`, `chance` (like `50%`) and `rare: yes`. Set, World biomes can choose it like a built-in; blank, it's only placed by hand. + +**Generate overworld.** **New overworld…** lays out a **biome pool** (a note in `{world folder}/biome-pools` listing biomes, with an optional weight each; **All biomes** ships). Add or remove biomes, save the pool, watch the preview, then **Create**: the map and every region are made. A pool biome without a climate only fills hexes nothing else fits. It's a first pass; edit any region afterwards. Map menu → **Regions** → **Generate overworld…** redoes the whole map (God only): locked hexes and their regions stay, other regions are remade in place. + **Walking into new land.** In a region, the hex flower on the toolbar shows a **+** on each neighbour that has no region yet ("New region to the east"). Click it, pick the biome that lies there or **Roll** for one (the seed is shown; the same seed rolls the same biome), watch the preview of the new region blended with the regions around it, then **Create and go**. A different biome makes border country in between. Past the overworld's edge, the overworld grows by a hex to fit the new region. The hex editor's neighbour flower does the same on the hexes past the region's edge, and maps joined side by side get a **+** on the empty sides of their arrow pad. Needs Build or God: in Play the **+** says "Switch to Build to make a region." Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. From 6169dfae1a9ffb8f094dbd8632e1fe92432179d4 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 01:00:02 -0400 Subject: [PATCH 267/558] style(biomes #50): biome page mix grid, used-by line Co-Authored-By: Claude Opus 5.5 --- styles.css | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/styles.css b/styles.css index 86ab6015..76567dc4 100644 --- a/styles.css +++ b/styles.css @@ -8582,3 +8582,27 @@ textarea.duckmage-edit-region-notes-input { display: grid; gap: 4px; } +/* Generator page: Biome (blend field) type mix. */ +.duckmage-biome-page-mix { + display: grid; + grid-template-columns: minmax(6em, max-content) minmax(6em, 1fr) 5em 6em; + gap: 2px 8px; + align-items: center; +} +.duckmage-biome-page-row { + display: contents; +} +.duckmage-biome-page-row input[type="range"] { + width: 100%; +} +.duckmage-biome-page-row.is-head span { + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} +.duckmage-biome-page-row.is-missing > span:first-child { + color: var(--text-faint); + font-style: italic; +} +.duckmage-wfc-used-by { + font-style: italic; +} From acbe5e347920f741669e84217d0656823b09133f Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 01:04:36 -0400 Subject: [PATCH 268/558] fix(biomes #50): biome page preview puts the most lowland biome beside a shore Co-Authored-By: Claude Opus 5.5 --- src/worldgen/BiomePanel.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/worldgen/BiomePanel.ts b/src/worldgen/BiomePanel.ts index 3f9dd7d2..15a6c878 100644 --- a/src/worldgen/BiomePanel.ts +++ b/src/worldgen/BiomePanel.ts @@ -377,7 +377,13 @@ export class BiomePanel { status.setText("Give at least one terrain type a weight."); return; } - const landBiome = plugin.biomeStore.list().find((b) => b.id !== this.fields.id && !b.generator && !b.shore && (b.landShare === undefined || b.landShare > 0.5) && b.mix.some((r) => r.type === "forest" || r.type === "grassland"))?.id ?? "grassland"; + // The land beside it: the biome most made of lowland (forest, grassland) types. + const lowland = (b: BiomeNoteFields) => { + const total = b.mix.reduce((s, r) => s + r.weight, 0) || 1; + return b.mix.filter((r) => r.type === "forest" || r.type === "grassland").reduce((s, r) => s + r.weight, 0) / total; + }; + const candidates = plugin.biomeStore.list().filter((b) => b.id !== this.fields.id && !b.generator && !b.shore); + const landBiome = candidates.sort((a, b) => lowland(b) - lowland(a))[0]?.id ?? this.fields.id; const t0 = activeWindow.performance.now(); const plan = biomeSamplePlan(layout, palette, this.fields, BiomePanel.seed, BiomePanel.surround, landBiome); const b = regionBox(layout, 0, 0); From a602df38b668eb06b0038a2a466af71edd24cbde Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 01:40:05 -0400 Subject: [PATCH 269/558] feat(world-types): interface - WorldTypeRow/Table, pickWorldType, note parse/build/update, Default space data src/space/worldTypes.ts is the API the space generators call (Star scatter, Orbits, planet submap defaults): pickWorldType(table, ctx) is a deterministic weighted pick that respects map/zone/ring/star/temperature filters and takes exactly one draw from a caller's stream; worldTypeWeights / worldTypeFor / orbitZone / worldTypeSubmapDefault for mixing with fallbacks and submap setup. worldTypePresets.ts holds the shipped Default space rows as data. Co-Authored-By: Claude Opus 5.5 --- src/space/worldTypePresets.ts | 82 +++++ src/space/worldTypes.ts | 629 ++++++++++++++++++++++++++++++++++ 2 files changed, 711 insertions(+) create mode 100644 src/space/worldTypePresets.ts create mode 100644 src/space/worldTypes.ts diff --git a/src/space/worldTypePresets.ts b/src/space/worldTypePresets.ts new file mode 100644 index 00000000..3be81aab --- /dev/null +++ b/src/space/worldTypePresets.ts @@ -0,0 +1,82 @@ +/** + * The shipped "Default space" world types table, as DATA: written into a + * note once (WorldTypeStore), then the note is what counts. Nothing here + * is read at run time except to seed a missing note and for "Restore + * default". + * + * It reproduces, exactly, the world odds Star scatter and Orbits had built + * in (their name tables for the shipped Space palettes) and the shipped + * palettes' submap defaults: + * - sector rows: Star scatter's mainworld weights (garden 3, ocean 2, …), + * each opening as a 13×13 Orbits system on Space - System; + * - system rows: Orbits' zone weights per body (a body a zone didn't list + * weighed 0.5 there), the rocky ones opening as 20×14 Planet surface + * maps tuned to the planet; + * - the moon (weight 0: Orbits puts moons beside planets, it never rolls + * them) for its map setup. + * tests/worldTypes.test.ts holds a frozen copy of the old tables and + * checks this against it. + * + * Pure: no Obsidian imports. + */ + +import type { OrbitZone, WorldTypeRow } from "./worldTypes"; + +const SYSTEM_PALETTE = "Space - System"; +const SURFACE_PALETTE = "Expanded"; + +const system = (world: string, weight: number): WorldTypeRow => ({ + world, + weight, + map: "sector", + size: { cols: { lo: 13, hi: 13 }, rows: { lo: 13, hi: 13 } }, + generator: { id: "procedural:orbits" }, + palette: SYSTEM_PALETTE, + baseTerrain: "void", +}); + +type Surface = Pick; +const surface = (water: string, climate: string, base: string, relief = "normal"): Surface => ({ + size: { cols: { lo: 20, hi: 20 }, rows: { lo: 14, hi: 14 } }, + generator: { id: "procedural:planet-surface" }, + options: { water, climate, relief }, + palette: SURFACE_PALETTE, + baseTerrain: base, +}); + +/** One body's rows: its weight per zone (zones with the same weight share a row). */ +function body(world: string, w: Record, setup: Surface = {}): WorldTypeRow[] { + const zones: OrbitZone[] = ["inner", "habitable", "outer"]; + const out: WorldTypeRow[] = []; + const done = new Set(); + for (const z of zones) { + if (done.has(z)) continue; + const same = zones.filter((o) => !done.has(o) && w[o] === w[z]); + same.forEach((o) => done.add(o)); + out.push({ world, weight: w[z], map: "system", zones: same, ...setup }); + } + return out; +} + +export const DEFAULT_WORLD_TYPE_ROWS: readonly WorldTypeRow[] = [ + // Sector: a hex's star system, typed by its mainworld (Star scatter). + system("garden world", 3), + system("ocean world", 2), + system("desert world", 3), + system("ice world", 2), + system("barren world", 3.5), + system("molten world", 1), + system("asteroid belt", 1.5), + system("gas giant", 1), + // System: one body per orbit, by zone (Orbits). + ...body("terrestrial planet", { inner: 0.5, habitable: 4, outer: 0.5 }, surface("65", "temperate", "ocean")), + ...body("ocean planet", { inner: 0.5, habitable: 3, outer: 0.5 }, surface("85", "lush", "ocean")), + ...body("desert planet", { inner: 2, habitable: 3, outer: 0.5 }, surface("10", "arid", "desert")), + ...body("ice planet", { inner: 0.5, habitable: 0.5, outer: 3 }, surface("30", "frozen", "ocean")), + ...body("rocky planet", { inner: 4, habitable: 2, outer: 1 }, surface("10", "arid", "desert", "rugged")), + ...body("molten planet", { inner: 4, habitable: 0.5, outer: 0.5 }, surface("10", "volcanic", "desert", "rugged")), + ...body("gas giant", { inner: 0.5, habitable: 0.5, outer: 4 }), + ...body("ice giant", { inner: 0.5, habitable: 0.5, outer: 3 }), + ...body("asteroid belt", { inner: 0.5, habitable: 1, outer: 1.5 }), + { world: "moon", weight: 0, map: "system", ...surface("10", "frozen", "desert", "rugged"), notes: "placed beside planets, never rolled" }, +]; diff --git a/src/space/worldTypes.ts b/src/space/worldTypes.ts new file mode 100644 index 00000000..bc37c094 --- /dev/null +++ b/src/space/worldTypes.ts @@ -0,0 +1,629 @@ +/** + * World types: which worlds space generators place, how often, and what a + * world's own map (its submap) is made with. One plain note per table at + * `/.md`: + * + * --- + * hexmaker-world-types: 1 + * --- + * + * # Default space + * + * > [!info] World types + * > … (short help) + * + * | World | Weight | Map | Orbit | Stars | Temperature | Size | Generator | Options | Palette | Base | Notes | + * | --- | ---: | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | + * | ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush | Expanded | ocean | | + * + * - *World*: the terrain the row places (matched to the palette's terrain + * names, any case). The same world may have several rows (different + * odds, sizes or generators per zone, star or temperature). + * - *Weight* (blank = 1): relative odds among the rows that fit. 0 = never + * rolled (the row still gives that world's map setup). + * - Filters, each optional (blank or "any" = no limit). A filter only + * applies when the generator knows that thing: + * *Map* `sector` (a sector's star systems: Star scatter) or `system` + * (an orbit around a star: Orbits); *Orbit* zone words `inner`, + * `habitable`, `outer` and/or ring distances like `2–4` (hexes from the + * star); *Stars* a list of star terrains (`red dwarf, white dwarf`); + * *Temperature* cold, cool, mild, warm, hot or 0.2–0.5 (as on biomes). + * - Map setup for the world's submap, each optional: *Size* `20×14` or a + * range `16–24 × 10–14` (rolled per world); *Generator* a generator note + * link (`[[My desert]]`), a generator id (`procedural:planet-surface`, + * `wfc:`, `builtin:`) or a shipped generator's slug + * (`preset-volcanic`); *Options* the generator's choices + * (`water=85, climate=lush`); *Palette* and *Base* (base terrain). + * - *Notes*: free text, kept as written. + * + * Reading is forgiving: columns by header name in any order, missing + * columns are fine, en dash / hyphen / "to" in ranges, × / x / "by" in + * sizes, weights like `2` or `50%`. A row that can't be read is never + * used, is reported, and stays in the note exactly as written (rewriting + * keeps it, after the rows the plugin wrote). + * + * Picking (pickWorldType) is deterministic for a seed and works like the + * generators' weighted pick: one draw over the fitting worlds, in palette + * order when a palette is given, so the shipped "Default space" table + * gives exactly the odds (and, for the same random stream, the same + * choices) Star scatter and Orbits had built in. + * + * Pure: no Obsidian imports. + */ + +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; +import { + TEMPERATURE_WORDS, + formatClimateRange, + inClimateRange, + parseClimateRange, + type ClimateRange, +} from "../overworld/biomeClimate"; + +export const WORLD_TYPES_MARKER = "hexmaker-world-types"; +export const WORLD_TYPES_FORMAT = 1; +/** The shipped table's name (and note name). */ +export const DEFAULT_WORLD_TYPES = "Default space"; + +export type OrbitZone = "inner" | "habitable" | "outer"; +export const ORBIT_ZONES: readonly OrbitZone[] = ["inner", "habitable", "outer"]; + +/** Which kind of space map picks: a sector's systems, or a system's orbits. */ +export type WorldTypeMap = "sector" | "system"; +export const WORLD_TYPE_MAPS: readonly WorldTypeMap[] = ["sector", "system"]; + +/** + * The generator a world's submap is made with. Assignable to + * worldgen/biomeRegion's GeneratorRef (minus the in-memory form): + * `{ path }` a generator note, `{ builtin }` a shipped generator's slug, + * `{ id }` a registry id (`procedural:planet-surface`, `wfc:`, …). + */ +export type WorldGeneratorRef = { path: string } | { builtin: string } | { id: string }; + +/** Inclusive integer range. */ +export interface IntRange { + lo: number; + hi: number; +} + +export interface WorldSizeRange { + cols: IntRange; + rows: IntRange; +} + +export interface WorldTypeRow { + /** The terrain this row places, as written ("ocean planet"). */ + world: string; + /** Relative odds among the fitting rows; default 1; 0 = never rolled. */ + weight?: number; + /** Only on this kind of map. Unset: any. */ + map?: WorldTypeMap; + /** Only in these orbit zones. Unset: any. */ + zones?: OrbitZone[]; + /** Only this many hexes from the star (inclusive). Unset: any. */ + distance?: IntRange; + /** Only around these stars (terrain names, as written). Unset: any. */ + stars?: string[]; + /** Only at this temperature (0 cold … 1 hot). Unset: any. */ + temperature?: ClimateRange; + /** The world's submap size. Unset: no preference. */ + size?: WorldSizeRange; + /** The world's submap generator. Unset: no preference. */ + generator?: WorldGeneratorRef; + /** The generator's options (`water` → `85`). */ + options?: Record; + /** The submap's palette. */ + palette?: string; + /** The submap's base terrain. */ + baseTerrain?: string; + notes?: string; +} + +export interface WorldTypeTable { + name: string; + rows: WorldTypeRow[]; +} + +export interface WorldTypeProblem { + /** 1-based line in the note, when it's a row. */ + line?: number; + text: string; +} + +export interface ParsedWorldTypes { + rows: WorldTypeRow[]; + problems: WorldTypeProblem[]; + /** Table rows that couldn't be read, exactly as written (kept on rewrite). */ + unreadable: string[]; +} + +/** What the generator knows where it is placing a world. Every field but `seed` is optional. */ +export interface WorldTypeContext { + map?: WorldTypeMap; + zone?: OrbitZone; + /** Hexes from the star (the orbit's ring). */ + distance?: number; + /** The system's star terrain. */ + starType?: string; + /** 0 (cold) … 1 (hot). */ + temperature?: number; + seed: number; + /** + * The generator's own random stream. When given, the pick takes exactly + * one draw from it (like weightedPick), so a generator's later rolls are + * unchanged; sizes and ties between rows use a stream made from `seed`. + */ + rand?: () => number; + /** + * The palette's terrains (names, or terrains with a name): only rows + * whose world is in it are picked, and the pick runs over them in + * palette order (the generators' order). + */ + palette?: readonly (string | { name: string })[]; +} + +export interface WorldTypePick { + row: WorldTypeRow; + /** The palette's own name for the world (its case), else the row's. */ + terrain: string; + /** Rolled from the row's size range; unset when the row has none. */ + size?: { cols: number; rows: number }; + generator?: WorldGeneratorRef; + options?: Record; + palette?: string; + baseTerrain?: string; +} + +// ── zones ──────────────────────────────────────────────────────────────── + +/** + * The orbit zone of ring `d` when orbits run from ring `first` to `last`: + * the first 30% inner, up to 60% habitable, the rest outer (Orbits' rule). + */ +export function orbitZone(d: number, first: number, last: number): OrbitZone { + const t = (d - first) / Math.max(1, last - first); + return t < 0.3 ? "inner" : t < 0.6 ? "habitable" : "outer"; +} + +// ── matching and picking ───────────────────────────────────────────────── + +const lc = (s: string) => s.trim().toLowerCase(); + +/** Whether a row's filters allow this context (filters the context doesn't speak to pass). */ +export function worldTypeFits(row: WorldTypeRow, ctx: Omit & { seed?: number }): boolean { + if (row.map && ctx.map && row.map !== ctx.map) return false; + if (row.zones?.length && ctx.zone && !row.zones.includes(ctx.zone)) return false; + if (row.distance && ctx.distance !== undefined && (ctx.distance < row.distance.lo || ctx.distance > row.distance.hi)) return false; + if (row.stars?.length && ctx.starType && !row.stars.some((s) => lc(s) === lc(ctx.starType!))) return false; + if (row.temperature && ctx.temperature !== undefined && !inClimateRange(row.temperature, ctx.temperature)) return false; + return true; +} + +const paletteNames = (p: WorldTypeContext["palette"]) => p?.map((t) => (typeof t === "string" ? t : t.name)); + +/** + * The rows that fit the context (weight > 0), in pick order: palette order + * of their world when a palette is given (rows of worlds not in it left + * out), else table order. + */ +export function matchingWorldTypes(table: WorldTypeTable, ctx: Omit & { seed?: number }): WorldTypeRow[] { + const fit = table.rows.filter((r) => (r.weight ?? 1) > 0 && r.world.trim() && worldTypeFits(r, ctx)); + const names = paletteNames(ctx.palette); + if (!names) return fit; + const order = new Map(); + names.forEach((n, i) => { if (!order.has(lc(n))) order.set(lc(n), i); }); + return fit + .filter((r) => order.has(lc(r.world))) + .map((r, i) => ({ r, i })) + .sort((a, b) => order.get(lc(a.r.world))! - order.get(lc(b.r.world))! || a.i - b.i) + .map((x) => x.r); +} + +/** + * Each fitting world's total weight (lower-case name → weight), for a + * generator that mixes the table with its own weights for terrains the + * table doesn't name. + */ +export function worldTypeWeights(table: WorldTypeTable, ctx: Omit & { seed?: number }): Record { + const out: Record = {}; + for (const r of matchingWorldTypes(table, ctx)) out[lc(r.world)] = (out[lc(r.world)] ?? 0) + (r.weight ?? 1); + return out; +} + +/** Weighted pick of an index, the generators' way (one draw). */ +function pickIndex(rand: () => number, weights: number[]): number { + const total = weights.reduce((a, b) => a + b, 0); + if (total <= 0) return Math.floor(rand() * weights.length); + let r = rand() * total; + for (let i = 0; i < weights.length; i++) { + r -= weights[i]; + if (r < 0) return i; + } + return weights.length - 1; +} + +const rollInt = (rand: () => number, r: IntRange) => r.lo + Math.floor(rand() * (r.hi - r.lo + 1)); + +/** + * Pick a world for the context: one weighted draw over the fitting worlds + * (a world's rows add up), then, when that world has several fitting rows, + * one of them by weight, and its size within its range. Null when nothing + * fits. Deterministic for a seed (or for the given random stream). + */ +export function pickWorldType(table: WorldTypeTable, ctx: WorldTypeContext): WorldTypePick | null { + const rows = matchingWorldTypes(table, ctx); + if (!rows.length) return null; + const worlds: string[] = []; + const weight = new Map(); + for (const r of rows) { + const k = lc(r.world); + if (!weight.has(k)) worlds.push(k); + weight.set(k, (weight.get(k) ?? 0) + (r.weight ?? 1)); + } + const rand = ctx.rand ?? mulberry32(ctx.seed >>> 0); + const world = worlds[pickIndex(rand, worlds.map((k) => weight.get(k)!))]; + // Its own stream, so the caller's stream sees exactly one draw. + const side = mulberry32(((ctx.seed ^ 0x51e3d7a1) >>> 0)); + const own = rows.filter((r) => lc(r.world) === world); + const row = own.length === 1 ? own[0] : own[pickIndex(side, own.map((r) => r.weight ?? 1))]; + const names = paletteNames(ctx.palette); + const out: WorldTypePick = { row, terrain: names?.find((n) => lc(n) === world) ?? row.world.trim() }; + if (row.size) out.size = { cols: rollInt(side, row.size.cols), rows: rollInt(side, row.size.rows) }; + if (row.generator) out.generator = { ...row.generator }; + if (row.options) out.options = { ...row.options }; + if (row.palette) out.palette = row.palette; + if (row.baseTerrain) out.baseTerrain = row.baseTerrain; + return out; +} + +/** + * The row giving a world's map setup (for a submap made from a hex of that + * world): the first row naming it that fits the context, weight 0 rows + * included. + */ +export function worldTypeFor(table: WorldTypeTable, world: string, ctx: Omit & { seed?: number } = {}): WorldTypeRow | undefined { + return table.rows.find((r) => lc(r.world) === lc(world) && worldTypeFits(r, ctx)); +} + +/** A generator ref as a registry id (`{ path }` → `wfc:.md`, `{ builtin }` → `builtin:`). */ +export function generatorRefId(ref: WorldGeneratorRef): string { + if ("id" in ref) return ref.id; + if ("builtin" in ref) return `builtin:${ref.builtin}`; + return `wfc:${/\.md$/i.test(ref.path) ? ref.path : `${ref.path}.md`}`; +} + +/** A row's map setup in the palette's submap-default shape (types.ts SubmapDefault). */ +export function worldTypeSubmapDefault(row: WorldTypeRow, size?: { cols: number; rows: number }): { + palette?: string; cols?: number; rows?: number; generator?: string; options?: Record; baseTerrain?: string; +} { + const out: ReturnType = {}; + if (row.palette) out.palette = row.palette; + const s = size ?? (row.size ? { cols: row.size.cols.lo, rows: row.size.rows.lo } : undefined); + if (s) { out.cols = s.cols; out.rows = s.rows; } + if (row.generator) out.generator = generatorRefId(row.generator); + if (row.options && Object.keys(row.options).length) out.options = { ...row.options }; + if (row.baseTerrain) out.baseTerrain = row.baseTerrain; + return out; +} + +// ── cells ──────────────────────────────────────────────────────────────── + +/** "2", "50%", "0.5" → a weight ≥ 0, or NaN. */ +export function readWeight(raw: string): number { + const t = raw.trim(); + const pct = t.endsWith("%"); + const n = Number(t.replace(/%$/, "").trim()); + if (!t || !Number.isFinite(n) || n < 0) return NaN; + return pct ? n / 100 : n; +} + +const RANGE_SPLIT = /\s*(?:–|—|\.\.|\bto\b|-)\s*/; + +/** "20", "16–24", "16 to 24" → an integer range ≥ 1 (turned round when backwards). */ +export function readIntRange(raw: string): IntRange | undefined { + const parts = raw.trim().split(RANGE_SPLIT).filter((p) => p !== ""); + if (parts.length < 1 || parts.length > 2) return undefined; + const nums = parts.map((p) => Number(p)); + if (nums.some((n) => !Number.isInteger(n) || n < 1)) return undefined; + const lo = Math.min(...nums), hi = Math.max(...nums); + return { lo, hi }; +} + +/** "20×14", "20x14", "16–24 × 10–14", "20 by 14" → a size range. */ +export function readSize(raw: string): WorldSizeRange | undefined { + const parts = raw.trim().toLowerCase().split(/\s*(?:×|\*|\bby\b|(?<=[\d\s])x(?=[\s\d]))\s*/).filter((p) => p !== ""); + if (parts.length !== 2) return undefined; + const cols = readIntRange(parts[0]), rows = readIntRange(parts[1]); + return cols && rows ? { cols, rows } : undefined; +} + +const fmtInt = (r: IntRange) => (r.lo === r.hi ? String(r.lo) : `${r.lo}–${r.hi}`); +export const formatSize = (s: WorldSizeRange) => `${fmtInt(s.cols)}×${fmtInt(s.rows)}`; + +const ZONE_ALIASES: Record = { + inner: "inner", hot: "inner", close: "inner", + habitable: "habitable", hab: "habitable", middle: "habitable", mid: "habitable", goldilocks: "habitable", + outer: "outer", cold: "outer", far: "outer", +}; + +/** "inner, habitable", "2–4", "habitable, 3-5" → zones and/or a ring band. */ +export function readOrbit(raw: string): { zones?: OrbitZone[]; distance?: IntRange } | undefined { + const t = raw.trim().toLowerCase(); + if (!t || t === "any") return {}; + const out: { zones?: OrbitZone[]; distance?: IntRange } = {}; + for (const tok of t.split(/\s*[,;/]\s*|\s+and\s+/).filter((p) => p !== "")) { + const z = ZONE_ALIASES[tok.replace(/\s*zone$/, "")]; + if (z) { + out.zones = [...(out.zones ?? []).filter((x) => x !== z), z]; + continue; + } + const d = readIntRange(tok.replace(/^(?:rings?|distance)\s*/, "")); + if (!d || out.distance) return undefined; + out.distance = d; + } + if (out.zones) out.zones = ORBIT_ZONES.filter((z) => out.zones!.includes(z)); + return out; +} + +export function formatOrbit(row: Pick): string { + const parts: string[] = [...(row.zones ?? [])]; + if (row.distance) parts.push(fmtInt(row.distance)); + return parts.join(", "); +} + +/** "sector", "systems", "any", "" → the map kind (undefined = any); null when unreadable. */ +export function readMap(raw: string): WorldTypeMap | undefined | null { + const t = raw.trim().toLowerCase().replace(/s$/, ""); + if (!t || t === "any" || t === "both") return undefined; + if (t === "sector") return "sector"; + if (t === "system" || t === "star system" || t === "orbit") return "system"; + return null; +} + +/** "[[My gen]]" → path; "procedural:x" → id; "preset-volcanic" → builtin; "" / "none" → undefined. */ +export function readGenerator(raw: string): WorldGeneratorRef | undefined { + const t = raw.trim(); + if (!t || /^(none|-|—)$/i.test(t)) return undefined; + const link = /\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]/.exec(t); + if (link) return { path: link[1].trim() }; + if (t.includes(":")) return { id: t }; + return { builtin: t.toLowerCase() }; +} + +export function formatGenerator(g: WorldGeneratorRef | undefined): string { + if (!g) return ""; + if ("path" in g) return `[[${g.path}]]`; + if ("id" in g) return g.id; + return g.builtin; +} + +/** "water=85, climate=lush" (or "water: 85; climate: lush") → options; undefined when unreadable. */ +export function readOptions(raw: string): Record | undefined { + const out: Record = {}; + const t = raw.trim(); + if (!t) return out; + for (const pair of t.split(/\s*[,;]\s*/).filter((p) => p !== "")) { + const m = /^([^=:]+?)\s*[=:]\s*(.+)$/.exec(pair); + if (!m) return undefined; + out[m[1].trim()] = m[2].trim(); + } + return out; +} + +export const formatOptions = (o: Record | undefined) => + o ? Object.entries(o).map(([k, v]) => `${k}=${v}`).join(", ") : ""; + +const readList = (raw: string) => { + const t = raw.trim(); + if (!t || t.toLowerCase() === "any") return []; + return t.split(/\s*[,;]\s*/).map((s) => s.trim()).filter((s) => s !== ""); +}; + +// ── the note ───────────────────────────────────────────────────────────── + +export const WORLD_TYPES_HELP = [ + "> [!info] World types", + "> Which worlds the space generators place and how often, and what each world's own map is made with. **World** is a terrain of the palette. **Weight** (1 if blank) is its odds against the other rows that fit; 0 never rolls it. Limits, all optional: **Map** sector (Star scatter's systems) or system (Orbits), **Orbit** inner, habitable, outer or rings like 2–4, **Stars** a list of star terrains, **Temperature** cold, cool, mild, warm, hot or 0.2–0.5. For the world's map: **Size** like 20×14 or 16–24 × 10–14, **Generator** a generator note link or id, **Options** like water=85, climate=lush, **Palette** and **Base** terrain. The same world can have several rows. Add, edit or delete rows freely.", +]; + +const COLUMNS = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; +type Column = (typeof COLUMNS)[number]; +const HEADER_ALIASES: Record = { + world: "World", worlds: "World", "world type": "World", type: "World", body: "World", terrain: "World", + weight: "Weight", odds: "Weight", chance: "Weight", + map: "Map", scale: "Map", + orbit: "Orbit", zone: "Orbit", orbits: "Orbit", "orbit zone": "Orbit", + stars: "Stars", star: "Stars", "star types": "Stars", + temperature: "Temperature", temp: "Temperature", + size: "Size", + generator: "Generator", preset: "Generator", + options: "Options", + palette: "Palette", + base: "Base", "base terrain": "Base", + notes: "Notes", note: "Notes", comment: "Notes", +}; + +function splitRow(line: string): string[] { + let s = line.trim(); + if (s.startsWith("|")) s = s.slice(1); + if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1); + const cells: string[] = []; + let cur = ""; + let depth = 0; + for (let i = 0; i < s.length; i++) { + // A `|` inside [[link|alias]] belongs to the link. + if (s[i] === "[" && s[i + 1] === "[") { depth++; cur += "[["; i++; continue; } + if (s[i] === "]" && s[i + 1] === "]" && depth) { depth--; cur += "]]"; i++; continue; } + if (s[i] === "\\" && s[i + 1] === "|") { cur += "|"; i++; } + else if (s[i] === "|" && !depth) { cells.push(cur.trim()); cur = ""; } + else cur += s[i]; + } + cells.push(cur.trim()); + return cells; +} + +const SEPARATOR_ROW = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/; +const normHeader = (h: string) => h.trim().toLowerCase().replace(/[*_]/g, "").replace(/\s+/g, " "); + +interface Span { start: number; end: number; cols: (Column | undefined)[] } + +function findTable(lines: string[]): Span | null { + for (let i = 0; i < lines.length - 1; i++) { + if (!lines[i].trim().startsWith("|") || !SEPARATOR_ROW.test(lines[i + 1])) continue; + const cols = splitRow(lines[i]).map((h) => HEADER_ALIASES[normHeader(h)]); + if (!cols.includes("World")) continue; + let end = i + 2; + while (end < lines.length && lines[end].trim().startsWith("|")) end++; + return { start: i, end, cols }; + } + return null; +} + +/** One table row → a row, or why it can't be read. */ +function readRow(cells: string[], cols: (Column | undefined)[]): { row?: WorldTypeRow; problem?: string } { + const cell = (c: Column) => { + const i = cols.indexOf(c); + return i >= 0 ? (cells[i] ?? "").trim() : ""; + }; + const worldRaw = cell("World"); + const world = (/\[\[([^\]|#]+)/.exec(worldRaw)?.[1] ?? worldRaw).trim(); + if (!world) return { problem: "no world" }; + const row: WorldTypeRow = { world }; + const w = cell("Weight"); + if (w) { + const n = readWeight(w); + if (!Number.isFinite(n)) return { problem: `weight "${w}" isn't a number` }; + row.weight = n; + } + const m = readMap(cell("Map")); + if (m === null) return { problem: `map "${cell("Map")}" should be sector or system` }; + if (m) row.map = m; + const o = readOrbit(cell("Orbit")); + if (!o) return { problem: `orbit "${cell("Orbit")}" should be inner, habitable, outer or rings like 2–4` }; + if (o.zones?.length) row.zones = o.zones; + if (o.distance) row.distance = o.distance; + const stars = readList(cell("Stars")); + if (stars.length) row.stars = stars; + const t = cell("Temperature"); + if (t) { + // Any doubt (even a range written backwards) leaves the row as written. + const r = parseClimateRange(t, TEMPERATURE_WORDS); + if (r.problem) return { problem: `temperature ${r.problem}` }; + if (r.range) row.temperature = r.range; + } + const s = cell("Size"); + if (s) { + const size = readSize(s); + if (!size) return { problem: `size "${s}" should look like 20×14 or 16–24 × 10–14` }; + row.size = size; + } + const g = readGenerator(cell("Generator")); + if (g) row.generator = g; + const opts = readOptions(cell("Options")); + if (!opts) return { problem: `options "${cell("Options")}" should look like water=85, climate=lush` }; + if (Object.keys(opts).length) row.options = opts; + if (cell("Palette")) row.palette = cell("Palette"); + if (cell("Base")) row.baseTerrain = cell("Base"); + if (cell("Notes")) row.notes = cell("Notes"); + return { row }; +} + +/** Read a world types note. Never throws. */ +export function parseWorldTypes(content: string): ParsedWorldTypes { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const rows: WorldTypeRow[] = []; + const problems: WorldTypeProblem[] = []; + const unreadable: string[] = []; + const t = findTable(lines); + if (!t) return { rows, problems: [{ text: "no table with a World column" }], unreadable }; + for (let i = t.start + 2; i < t.end; i++) { + const cells = splitRow(lines[i]); + if (cells.every((c) => c === "")) continue; + const { row, problem } = readRow(cells, t.cols); + if (row) rows.push(row); + else { + problems.push({ line: i + 1, text: `row ${i + 1}: ${problem ?? "can't be read"} (left as written, not used)` }); + unreadable.push(lines[i]); + } + } + return { rows, problems, unreadable }; +} + +const esc = (s: string) => s.replace(/\|/g, "\\|"); +const fmtNum = (n: number) => String(Math.round(n * 1000) / 1000); + +/** A row as the note's table cells, in COLUMNS order. */ +export function worldTypeCells(r: WorldTypeRow): string[] { + return [ + r.world, + r.weight === undefined ? "" : fmtNum(r.weight), + r.map ?? "", + formatOrbit(r), + (r.stars ?? []).join(", "), + r.temperature ? formatClimateRange(r.temperature, TEMPERATURE_WORDS) : "", + r.size ? formatSize(r.size) : "", + formatGenerator(r.generator), + formatOptions(r.options), + r.palette ?? "", + r.baseTerrain ?? "", + r.notes ?? "", + ]; +} + +function tableLines(rows: readonly WorldTypeRow[], keep: readonly string[] = []): string[] { + return [ + `| ${COLUMNS.join(" | ")} |`, + `| ${COLUMNS.map((c) => (c === "Weight" ? "---:" : "---")).join(" | ")} |`, + ...rows.map((r) => `| ${worldTypeCells(r).map((c) => (c.startsWith("[[") ? c : esc(c))).join(" | ")} |`), + ...keep, + ]; +} + +/** A fresh table note. */ +export function buildWorldTypes(name: string, rows: readonly WorldTypeRow[]): string { + return [ + "---", `${WORLD_TYPES_MARKER}: ${WORLD_TYPES_FORMAT}`, "---", "", + `# ${name}`, "", + ...WORLD_TYPES_HELP, "", + ...tableLines(rows), "", + ].join("\n"); +} + +const rowKey = (r: WorldTypeRow) => JSON.stringify(worldTypeCells(r).map((c, i) => (i === 0 ? c.toLowerCase() : c))); + +/** + * The note with its table set to `rows`; everything else is kept, and so + * are rows that couldn't be read (after the new rows, as written). Same + * string when nothing changes. + */ +export function updateWorldTypes(content: string, rows: readonly WorldTypeRow[]): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const t = findTable(lines); + const parsed = parseWorldTypes(content); + if (t && parsed.rows.length === rows.length && parsed.rows.every((r, i) => rowKey(r) === rowKey(rows[i]))) return content; + const table = tableLines(rows, parsed.unreadable); + let out: string[]; + if (t) out = [...lines.slice(0, t.start), ...table, ...lines.slice(t.end)]; + else { + out = [...lines]; + while (out.length && out[out.length - 1].trim() === "") out.pop(); + out.push("", ...table, ""); + } + return out.join(eol); +} + +/** A deep copy of rows (callers may change it). */ +export function copyWorldTypeRows(rows: readonly WorldTypeRow[]): WorldTypeRow[] { + return rows.map((r) => { + const c: WorldTypeRow = { ...r }; + if (r.zones) c.zones = [...r.zones]; + if (r.distance) c.distance = { ...r.distance }; + if (r.stars) c.stars = [...r.stars]; + if (r.temperature) c.temperature = { ...r.temperature }; + if (r.size) c.size = { cols: { ...r.size.cols }, rows: { ...r.size.rows } }; + if (r.generator) c.generator = { ...r.generator }; + if (r.options) c.options = { ...r.options }; + return c; + }); +} From 96fa541b9bc3b2d662b55f5a86306bfee2882a0d Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 01:59:31 -0400 Subject: [PATCH 270/558] feat(world-types): WorldTypeStore, World types editor with preview, setting, command, tests, docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - WorldTypeStore: one note per table in /world-types (setting in both settings paths), Default space written once (worldTypesSeeded + note marker), hand edits read live, unreadable rows reported and kept, Restore default with a backup, create/list/get/update. - World types modal: rows edited as their note cells (add, remove, reorder, weight, map, orbit, stars, temperature, size, generator, options, palette, base), table picker, New table, Restore default, and a preview rolling the table for a map/orbit/star/temperature (counts next to exact odds). Gated on Build/God (canAdd); opened from Star scatter / Orbits options in the new-map form and the 'Edit world types…' command (Advanced: generators). - Tests: parse/build round trip + tolerance, pick determinism, filters and weights, frozen copy of the old Orbits / Star scatter tables and submap defaults matched exactly (same stream, same picks), store seeding/restore. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 + package.json | 4 +- src/HexmakerPlugin.ts | 21 ++ src/HexmakerSettingTab.ts | 25 ++ src/constants.ts | 1 + src/hex-map/help.md | 2 + src/space/WorldTypeStore.ts | 327 ++++++++++++++++++++++++++ src/space/WorldTypesModal.ts | 378 +++++++++++++++++++++++++++++++ src/space/worldTypes.ts | 36 ++- src/types.ts | 4 + src/worldgen/NewMapSetupModal.ts | 11 + styles.css | 102 +++++++++ tests/worldTypes.test.ts | 327 ++++++++++++++++++++++++++ 13 files changed, 1237 insertions(+), 4 deletions(-) create mode 100644 src/space/WorldTypeStore.ts create mode 100644 src/space/WorldTypesModal.ts create mode 100644 tests/worldTypes.test.ts diff --git a/README.md b/README.md index c80d3dbf..e80b061d 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it. - **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). +- **World types** (Advanced: Terrain generators) — which worlds the space generators place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types` (**Default space** ships, with the odds Star scatter and Orbits have always used; **Restore default** puts them back). Each row is a world (a terrain of your palette) with a **Weight** and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature**. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows, and a preview rolls the table for a map, orbit, star and temperature and shows how often each world comes up next to its odds. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. @@ -294,6 +295,7 @@ Every command, as it appears in the command palette: | **Hexmap World Creator: Open random tables** | Opens the random tables and workflows view. | | **Hexmap World Creator: Open terrain generator** | Opens the terrain generator (learn, blend and run generators). | | **Hexmap World Creator: Open palette editor** | Opens the terrain palette editor. | +| **Hexmap World Creator: Edit world types…** | Opens the world types table editor (which worlds the space generators place, how often, and how each world's map is made), with a preview. Advanced: Terrain generators; space maps on. | | **Hexmap World Creator: New overworld…** | Generate overworld (first pass): a map of biomes from a biome pool, laid out by climate, whose hexes open into regions that join up; can make every region at once. Advanced: Regions and overworlds. | | **Hexmap World Creator: Go up to parent map** | From a submap, back to the map it belongs to. | | **Hexmap World Creator: Go back to previous map** | Returns to the map you were on before. | @@ -334,6 +336,7 @@ Open **Settings → Hexmap World Creator** to configure: | **Palettes folder** | Folder holding one note per terrain palette (default `{world folder}/palettes`). | | **Biomes folder** | Folder holding one note per overworld biome (default `{world folder}/biomes`). | | **Biome pools folder** | Folder holding the biome pool notes used by Generate overworld (default `{world folder}/biome-pools`). | +| **World types folder** | Folder holding the world types tables used by the space generators (default `{world folder}/world-types`). | | **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | | **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | diff --git a/package.json b/package.json index 6beb69d3..f9a1f2f5 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index cee31d81..dc58ed8b 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -33,6 +33,8 @@ import { } from "./constants"; import { SetupWizardView } from "./SetupWizardView"; import { BiomeStore } from "./overworld/BiomeStore"; +import { WorldTypeStore } from "./space/WorldTypeStore"; +import { WorldTypesModal } from "./space/WorldTypesModal"; import { PaletteStore } from "./palettes/PaletteStore"; import { PathsService } from "./paths/PathsService"; import { RoutePins } from "./paths/routePins"; @@ -101,6 +103,8 @@ export default class HexmakerPlugin extends Plugin { paletteStore = new PaletteStore(this); /** Overworld biome notes (#50). */ biomeStore = new BiomeStore(this); + /** World types tables for the space generators (src/space). */ + worldTypeStore = new WorldTypeStore(this); /** Per-hex map data, backed by one map note per map (src/maps). */ mapStore = new MapStore(this); /** Terrain names that have (or were offered) tables; new ones get theirs (HG5). */ @@ -147,6 +151,7 @@ export default class HexmakerPlugin extends Plugin { // Palettes first (maps reference them), then map notes — which may // migrate per-hex data out of hex notes on the first run. void this.biomeStore.init(); + void this.worldTypeStore.init(); void this.paletteStore.init().then(() => this.mapStore.init()).then(() => this.ensureTablesForNewTerrains()); // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. void this.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { @@ -189,6 +194,7 @@ export default class HexmakerPlugin extends Plugin { if (isIconFile(f.path)) this.loadAvailableIcons(); this.paletteStore.onModify(f); this.biomeStore.onModify(f); + this.worldTypeStore.onModify(f); }), ); this.registerEvent( @@ -196,6 +202,7 @@ export default class HexmakerPlugin extends Plugin { if (isIconFile(f.path)) this.loadAvailableIcons(); this.paletteStore.onDelete(f); this.biomeStore.onDelete(f); + this.worldTypeStore.onDelete(f); }), ); this.registerEvent( @@ -203,6 +210,7 @@ export default class HexmakerPlugin extends Plugin { if (isIconFile(f.path) || isIconFile(oldPath)) this.loadAvailableIcons(); this.paletteStore.onRename(f, oldPath); this.biomeStore.onRename(f, oldPath); + this.worldTypeStore.onRename(f, oldPath); if (f instanceof TFile) void this.onRegionNoteRenamed(f, oldPath); }), ); @@ -217,6 +225,7 @@ export default class HexmakerPlugin extends Plugin { this.app.vault.on("modify", (f) => { this.paletteStore.onModify(f); this.biomeStore.onModify(f); + this.worldTypeStore.onModify(f); this.mapStore.onModify(f); }), ); @@ -264,6 +273,18 @@ export default class HexmakerPlugin extends Plugin { name: "Open palette editor", callback: () => void this.openPaletteEditor(), }); + this.addCommand({ + id: "edit-world-types", + name: "Edit world types…", + checkCallback: (checking) => { + if (!hasFeature(this.settings, "generators") || !enabledKinds(this.settings).has("space")) return false; + if (!checking) { + const open = this.app.workspace.getActiveViewOfType(HexMapView); + new WorldTypesModal(this.app, this, open?.activeMapName).open(); + } + return true; + }, + }); this.addCommand({ id: "new-overworld", name: "New overworld…", diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index 70cc1b2c..b8f7320b 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -16,6 +16,9 @@ const PALETTES_FOLDER_DESC = const BIOMES_FOLDER_DESC = "Vault-relative folder for overworld biome notes (one note per biome: its mix of terrain types, colour and transitions). Defaults to a biomes folder inside the world folder."; +const WORLD_TYPES_FOLDER_DESC = + "Vault-relative folder for world types notes (which worlds the space generators place, and how each world's map is made). Defaults to a world-types folder inside the world folder."; + const BIOME_POOLS_FOLDER_DESC = "Vault-relative folder for biome pool notes (each lists the biomes a generated overworld may use). Defaults to a biome-pools folder inside the world folder."; @@ -129,6 +132,7 @@ const FOLDER_PATH_KEYS = new Set([ "palettesFolder", "biomesFolder", "biomePoolsFolder", + "worldTypesFolder", ]); /** Settings keys whose change should re-render open hex map views. */ @@ -676,6 +680,12 @@ export class HexmakerSettingTab extends PluginSettingTab { "World/biome-pools", BIOME_POOLS_FOLDER_DESC, ), + folderText( + "World types folder", + "worldTypesFolder", + "World/world-types", + WORLD_TYPES_FOLDER_DESC, + ), { type: "group", heading: "Map types", @@ -801,6 +811,7 @@ export class HexmakerSettingTab extends PluginSettingTab { return this.plugin.saveSettings().then(() => { if (MAP_REFRESH_KEYS.has(key)) this.plugin.refreshHexMap(); if (key === "biomesFolder") void this.plugin.biomeStore.reload(); + if (key === "worldTypesFolder") void this.plugin.worldTypeStore.reload(); if (key === "iconsFolder") this.plugin.loadAvailableIcons(); }); } @@ -1601,6 +1612,20 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); + new Setting(containerEl) + .setName("World types folder") + .setDesc(WORLD_TYPES_FOLDER_DESC) + .addText((text) => + text + .setPlaceholder("World/world-types") + .setValue(this.plugin.settings.worldTypesFolder ?? "") + .onChange(async (value) => { + this.plugin.settings.worldTypesFolder = normalizeFolder(value ?? ""); + await this.plugin.saveSettings(); + void this.plugin.worldTypeStore.reload(); + }), + ); + new Setting(containerEl).setName("Map types").setHeading(); for (const k of MAP_KINDS) { new Setting(containerEl) diff --git a/src/constants.ts b/src/constants.ts index 200fad9c..6c089f54 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -402,6 +402,7 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { palettesFolder: "", biomesFolder: "", biomePoolsFolder: "", + worldTypesFolder: "", palettesMigrated: false, // Space is opt-in (setup wizard / settings → Map types). Upgrades without // the setting get space too if they already have space palettes diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 4d70f4be..2c2970d3 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -152,6 +152,8 @@ Neighbouring regions share one set of hex numbers: a new region carries on from A road or river that ends on the edge of a region, next to where the neighbour's road of the same type ends, is drawn on to the shared edge on both maps, so the two join up. +**World types** (space; Advanced: Terrain generators). Which worlds Star scatter and Orbits place, how often, and how each world's own map is made, is a table note in `{world folder}/world-types` (**Default space** ships with the usual odds; **Restore default** puts them back). Each row: a **World** (a terrain of the palette), a **Weight**, optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base**. **Edit world types…** (in the Star scatter and Orbits options, or the command) edits the rows and previews how often each world comes up. Needs Build or God. + With generators on, new maps can also use the built-in **biomes and presets** (Grassland, Taiga, Swamp, Archipelago, Volcanic and more). They place terrain by type, so they work with any palette whose terrains have types. **New map…** (in Maps) is one form: generator cards with a live preview, Next to (Advanced), and **More** for starting coordinates, stagger and a background image (pick one from the vault, or drop one from your computer). A new map starts on Overland; pick Blank to paint by hand. diff --git a/src/space/WorldTypeStore.ts b/src/space/WorldTypeStore.ts new file mode 100644 index 00000000..5debaf83 --- /dev/null +++ b/src/space/WorldTypeStore.ts @@ -0,0 +1,327 @@ +/** + * World types tables in the vault: `/.md`, one + * note per table (worldTypes.ts has the format). The notes are the only + * copy; data.json only remembers that the shipped "Default space" table + * was written (`worldTypesSeeded`), so a deleted one isn't written again + * (Restore default brings it back). + * + * - init(): reads every note, then writes the shipped table once when + * space maps are on (ensureDefault() does it on demand otherwise). + * - Hand edits are read back live (vault events); rows that can't be read + * are reported once per edit, never used, and kept as written. + * - Every change is told to onChange listeners. + */ + +import { Notice, TAbstractFile, TFile, TFolder } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { normalizeFolder } from "../utils"; +import { writeJsonBackup } from "../backup"; +import { enabledKinds } from "../mapKinds"; +import { biomeFileName } from "../overworld/biomeNote"; +import { + DEFAULT_WORLD_TYPES, + buildWorldTypes, + copyWorldTypeRows, + parseWorldTypes, + updateWorldTypes, + type WorldTypeProblem, + type WorldTypeRow, + type WorldTypeTable, +} from "./worldTypes"; +import { DEFAULT_WORLD_TYPE_ROWS } from "./worldTypePresets"; + +interface Entry { + path: string; + name: string; + rows: WorldTypeRow[]; + problems: WorldTypeProblem[]; +} + +/** Settings the store reads (a subset of the plugin's). */ +interface StoreSettings { + worldFolder?: string; + worldTypesFolder?: string; + worldTypesSeeded?: boolean; + mapKinds?: string[]; +} + +/** The folder for world types notes: the setting, else `/world-types`. */ +export function worldTypesFolder(settings: StoreSettings): string { + const configured = normalizeFolder(settings.worldTypesFolder ?? ""); + if (configured) return configured; + const world = normalizeFolder(settings.worldFolder ?? ""); + return world ? `${world}/world-types` : "world-types"; +} + +export class WorldTypeStore { + private entries = new Map(); + private lastContent = new Map(); + private reported = new Map(); + private listeners = new Set<() => void>(); + private ready = false; + private queue: Promise = Promise.resolve(); + + constructor(private plugin: HexmakerPlugin) {} + + private get settings(): StoreSettings { + return this.plugin.settings; + } + + isReady(): boolean { + return this.ready; + } + + folder(): string { + return worldTypesFolder(this.settings); + } + + /** Call `fn` after every change. Returns an unsubscribe. */ + onChange(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + async init(): Promise { + await this.enqueue(async () => { + for (const f of this.files()) await this.load(f); + if (enabledKinds(this.settings).has("space")) await this.seed(); + this.ready = true; + this.publish(); + }); + } + + /** Re-read every note (the folder setting changed). */ + async reload(): Promise { + await this.enqueue(async () => { + this.entries.clear(); + this.lastContent.clear(); + for (const f of this.files()) await this.load(f); + this.publish(); + }); + } + + /** Write the shipped table if it never was (once). */ + async ensureDefault(): Promise { + await this.enqueue(() => this.seed()); + } + + // ── API ──────────────────────────────────────────────────────────────── + + /** Every table, by name. */ + list(): WorldTypeTable[] { + return this.sorted().map((e) => ({ name: e.name, rows: copyWorldTypeRows(e.rows) })); + } + + /** A table by name (any case) or note path. */ + get(name: string): WorldTypeTable | undefined { + const e = this.find(name); + return e ? { name: e.name, rows: copyWorldTypeRows(e.rows) } : undefined; + } + + pathOf(name: string): string | undefined { + return this.find(name)?.path; + } + + /** What couldn't be read in a table's note. */ + problemsOf(name: string): WorldTypeProblem[] { + return this.find(name)?.problems ?? []; + } + + hasDefault(name: string): boolean { + return name.trim().toLowerCase() === DEFAULT_WORLD_TYPES.toLowerCase(); + } + + /** Set a table's rows (rows the note has that can't be read are kept as written). */ + async update(name: string, rows: readonly WorldTypeRow[]): Promise { + await this.queue; // hand edits read first + const e = this.find(name); + if (!e) return false; + const f = this.plugin.app.vault.getAbstractFileByPath(e.path); + if (!(f instanceof TFile)) return false; + await this.enqueue(async () => { + const content = await this.plugin.app.vault.read(f); + const next = updateWorldTypes(content, rows); + if (next !== content) await this.plugin.app.vault.modify(f, next); + this.take(f.path, next); + this.publish(); + }); + return true; + } + + /** A new table note (rows default to a copy of the shipped table). Returns its name, or an error. */ + async create(name: string, rows: readonly WorldTypeRow[] = DEFAULT_WORLD_TYPE_ROWS): Promise<{ name: string } | { error: string }> { + const clean = name.trim() ? biomeFileName(name.trim()) : ""; + if (!clean) return { error: "Give the table a name." }; + const folder = this.folder(); + const path = `${folder}/${clean}.md`; + if (this.find(clean) || this.plugin.app.vault.getAbstractFileByPath(path)) return { error: `There's already a table called ${clean}.` }; + await this.enqueue(async () => { + await this.ensureFolder(folder); + const text = buildWorldTypes(clean, copyWorldTypeRows(rows)); + await this.plugin.app.vault.create(path, text); + this.take(path, text); + this.publish(); + }); + return { name: clean }; + } + + /** + * Put the shipped rows back into the "Default space" note (the old note + * is backed up first), or write the note again if it was deleted. + */ + async restoreDefault(name: string = DEFAULT_WORLD_TYPES): Promise { + if (!this.hasDefault(name)) return false; + await this.queue; + const e = this.find(DEFAULT_WORLD_TYPES); + const f = e ? this.plugin.app.vault.getAbstractFileByPath(e.path) : null; + await this.enqueue(async () => { + if (f instanceof TFile) { + const content = await this.plugin.app.vault.read(f); + await this.backup("default-space", { [f.path]: content }); + const next = updateWorldTypes(content, DEFAULT_WORLD_TYPE_ROWS); + if (next !== content) await this.plugin.app.vault.modify(f, next); + this.take(f.path, next); + } else { + await this.writeDefault(); + } + this.publish(); + }); + return true; + } + + // ── vault events ─────────────────────────────────────────────────────── + + onModify(f: TAbstractFile): void { + if (!this.isTableFile(f)) return; + void this.enqueue(async () => { + if (await this.load(f)) this.publish(); + }); + } + + onDelete(f: TAbstractFile): void { + if (!this.entries.has(f.path)) return; + this.entries.delete(f.path); + this.lastContent.delete(f.path); + this.publish(); + } + + onRename(f: TAbstractFile, oldPath: string): void { + const had = this.entries.delete(oldPath); + this.lastContent.delete(oldPath); + if (!this.isTableFile(f)) { + if (had) this.publish(); + return; + } + void this.enqueue(async () => { + await this.load(f); + this.publish(); + }); + } + + // ── internals ────────────────────────────────────────────────────────── + + private sorted(): Entry[] { + return [...this.entries.values()].sort((a, b) => a.name.localeCompare(b.name) || a.path.localeCompare(b.path)); + } + + private find(name: string): Entry | undefined { + const k = name.trim().replace(/\.md$/i, "").toLowerCase(); + const list = this.sorted(); + return list.find((e) => e.path.toLowerCase() === `${k}.md` || e.path.toLowerCase() === k) + ?? list.find((e) => e.name.toLowerCase() === k); + } + + private publish(): void { + for (const fn of this.listeners) fn(); + } + + private isTableFile(f: TAbstractFile): f is TFile { + return f instanceof TFile && f.extension === "md" && !f.basename.startsWith("_") + && f.path.startsWith(this.folder() + "/"); + } + + private files(): TFile[] { + const root = this.plugin.app.vault.getAbstractFileByPath(this.folder()); + if (!(root instanceof TFolder)) return []; + const out: TFile[] = []; + const walk = (folder: TFolder) => { + for (const child of folder.children) { + if (child instanceof TFolder) walk(child); + else if (child instanceof TFile && child.path.endsWith(".md") && !child.name.startsWith("_")) out.push(child); + } + }; + walk(root); + return out.sort((a, b) => a.path.localeCompare(b.path)); + } + + /** Read one note. True when what it says changed. */ + private async load(f: TFile): Promise { + const content = await this.plugin.app.vault.read(f); + if (this.lastContent.get(f.path) === content && this.entries.has(f.path)) return false; + this.take(f.path, content); + return true; + } + + private take(path: string, content: string): void { + const { rows, problems } = parseWorldTypes(content); + const name = path.slice(path.lastIndexOf("/") + 1).replace(/\.md$/i, ""); + this.entries.set(path, { path, name, rows, problems }); + this.lastContent.set(path, content); + this.report(path, name, problems); + } + + private report(path: string, name: string, problems: WorldTypeProblem[]): void { + const key = problems.map((p) => p.text).join("; "); + if (this.reported.get(path) === key) return; + this.reported.set(path, key); + if (key && this.ready) new Notice(`World types ${name}: couldn't read ${key}.`, 8000); + } + + private async seed(): Promise { + if (this.settings.worldTypesSeeded) return; + if (!this.find(DEFAULT_WORLD_TYPES)) await this.writeDefault(); + this.settings.worldTypesSeeded = true; + await this.plugin.saveSettings(); + } + + private async writeDefault(): Promise { + const folder = this.folder(); + const path = `${folder}/${DEFAULT_WORLD_TYPES}.md`; + if (this.plugin.app.vault.getAbstractFileByPath(path)) return; + await this.ensureFolder(folder); + const text = buildWorldTypes(DEFAULT_WORLD_TYPES, copyWorldTypeRows(DEFAULT_WORLD_TYPE_ROWS)); + try { + await this.plugin.app.vault.create(path, text); + this.take(path, text); + } catch (e) { + console.error("Hexmaker: couldn't write the world types note", path, e); + } + } + + private async ensureFolder(folder: string): Promise { + const vault = this.plugin.app.vault; + const parts = folder.split("/"); + for (let i = 1; i <= parts.length; i++) { + const p = parts.slice(0, i).join("/"); + if (!vault.getAbstractFileByPath(p)) { + try { await vault.createFolder(p); } catch { /* made meanwhile */ } + } + } + } + + private async backup(base: string, notes: Record): Promise { + try { + const dir = `${this.plugin.manifest.dir}/backups/world-types-${new Date().toISOString().slice(0, 10)}`; + await writeJsonBackup(this.plugin.app.vault.adapter, dir, base, JSON.stringify({ savedAt: new Date().toISOString(), notes })); + } catch (e) { + console.error("Hexmaker: world types backup failed", e); + } + } + + private enqueue(task: () => Promise): Promise { + this.queue = this.queue.then(task).catch((e) => { + console.error("Hexmaker: world types", e); + }); + return this.queue; + } +} diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts new file mode 100644 index 00000000..5a7fcaa0 --- /dev/null +++ b/src/space/WorldTypesModal.ts @@ -0,0 +1,378 @@ +/** + * "World types": edit a world types table (worldTypes.ts) — which worlds + * the space generators place, how often, and what each world's own map is + * made with — with a small preview that rolls the table for a chosen map, + * orbit zone, star and temperature and shows what comes up. + * + * Rows are edited as their note cells (the same reading as the note), so + * anything typed here reads back the same from the note. Rows the note + * has that can't be read are listed, never touched. + * + * Opened from the space generators' options (New map / submap setup) and + * the "Edit world types…" command. Editing follows the map's work mode: + * Build and God (canAdd), not Play. + */ + +import { App, Notice, TFile } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { canAdd } from "../workMode"; +import { + DEFAULT_WORLD_TYPES, + ORBIT_ZONES, + WORLD_TYPE_COLUMNS, + readWorldTypeCells, + rollWorldTypes, + worldTypeCells, + worldTypeOdds, + type OrbitZone, + type WorldTypeColumn, + type WorldTypeContext, + type WorldTypeMap, + type WorldTypeRow, +} from "./worldTypes"; + +/** Why world types can't be edited from this map now, or undefined. */ +export function worldTypesEditLock(plugin: HexmakerPlugin, mapName: string | undefined): string | undefined { + const map = mapName ? plugin.getMap(mapName) : undefined; + return canAdd(map) ? undefined : "Switch to Build to edit world types."; +} + +/** A button that can't be used in this work mode (like the biome editor's). */ +function lockButton(btn: HTMLButtonElement, hint: string): void { + btn.disabled = true; + btn.addClass("is-locked"); + btn.setAttr("title", hint); + btn.setAttr("aria-label", `${btn.getText()} (${hint})`); +} + +const PLACEHOLDERS: Partial> = { + World: "ocean planet", + Weight: "1", + Orbit: "any", + Stars: "any", + Temperature: "any", + Size: "20×14", + Generator: "none", + Options: "water=85, climate=lush", + Palette: "same", + Base: "none", + Notes: "", +}; + +/** Columns shown on a row's first line (what is picked, and where); the rest are its map setup. */ +const PICK_COLUMNS: WorldTypeColumn[] = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature"]; +const SETUP_COLUMNS: WorldTypeColumn[] = ["Size", "Generator", "Options", "Palette", "Base", "Notes"]; + +const col = (c: WorldTypeColumn) => WORLD_TYPE_COLUMNS.indexOf(c); + +export class WorldTypesModal extends HexmakerModal { + private tableName: string; + /** The rows being edited, as note cells. */ + private cells: string[][] = []; + private dirty = false; + private off: (() => void) | undefined; + private rowsEl!: HTMLElement; + private previewEl!: HTMLElement; + private saveBtn!: HTMLButtonElement; + private statusEl!: HTMLElement; + private preview: { map: WorldTypeMap | ""; zone: OrbitZone | ""; star: string; temperature: string; n: number } = { map: "", zone: "", star: "", temperature: "", n: 200 }; + + /** `mapName`: the map it was opened for (work mode, preview's map kind). */ + constructor(app: App, private plugin: HexmakerPlugin, private mapName?: string, table?: string, previewMap?: WorldTypeMap) { + super(app); + this.tableName = table ?? DEFAULT_WORLD_TYPES; + if (previewMap) this.preview.map = previewMap; + } + + onOpen(): void { + this.makeDraggable(); + this.modalEl.addClass("duckmage-world-types-modal"); + this.titleEl.setText("World types"); + void this.plugin.worldTypeStore.ensureDefault().then(() => { + const store = this.plugin.worldTypeStore; + if (!store.get(this.tableName)) this.tableName = store.list()[0]?.name ?? this.tableName; + this.loadRows(); + this.render(); + // Hand edits to the note show up here (unless there are unsaved changes here). + this.off = store.onChange(() => { + if (this.dirty) return; + this.loadRows(); + this.render(); + }); + }); + } + + onClose(): void { + this.off?.(); + if (this.dirty && !this.lock() && !this.firstProblem()) void this.save(); + this.contentEl.empty(); + } + + private lock(): string | undefined { + return worldTypesEditLock(this.plugin, this.mapName); + } + + private loadRows(): void { + const t = this.plugin.worldTypeStore.get(this.tableName); + this.cells = (t?.rows ?? []).map((r) => worldTypeCells(r)); + this.dirty = false; + } + + private rows(): WorldTypeRow[] { + return this.cells.map((c) => readWorldTypeCells(c).row).filter((r): r is WorldTypeRow => !!r); + } + + private firstProblem(): string | undefined { + for (let i = 0; i < this.cells.length; i++) { + const { problem } = readWorldTypeCells(this.cells[i]); + if (problem) return `Row ${i + 1}: ${problem}.`; + } + return undefined; + } + + private async save(): Promise { + const problem = this.firstProblem(); + if (problem) { new Notice(problem); return; } + if (await this.plugin.worldTypeStore.update(this.tableName, this.rows())) this.dirty = false; + } + + // ── rendering ────────────────────────────────────────────────────────── + + private render(): void { + const { contentEl, plugin } = this; + const store = plugin.worldTypeStore; + contentEl.empty(); + const lock = this.lock(); + + // Table picker and note actions. + const head = contentEl.createDiv({ cls: "duckmage-world-types-head" }); + const sel = head.createEl("select", { attr: { "aria-label": "Table" } }); + for (const t of store.list()) sel.createEl("option", { value: t.name, text: t.name }); + sel.value = this.tableName; + sel.addEventListener("change", () => { + if (this.dirty) void this.save(); + this.tableName = sel.value; + this.loadRows(); + this.render(); + }); + const newBtn = head.createEl("button", { text: "New table…" }); + if (lock) lockButton(newBtn, lock); + newBtn.addEventListener("click", () => this.newTable(head)); + head.createEl("button", { text: "Open note" }).addEventListener("click", () => { + const path = store.pathOf(this.tableName); + const f = path ? plugin.app.vault.getAbstractFileByPath(path) : null; + if (f instanceof TFile) { this.close(); void plugin.app.workspace.getLeaf("tab").openFile(f); } + }); + if (store.hasDefault(this.tableName)) { + const restore = head.createEl("button", { text: "Restore default" }); + if (lock) lockButton(restore, lock); + restore.addEventListener("click", () => { + if (this.lock()) return; + void store.restoreDefault(this.tableName).then((ok) => { + if (!ok) return; + this.loadRows(); + this.render(); + new Notice("World types restored (the old note was backed up)."); + }); + }); + } + + contentEl.createEl("p", { + cls: "setting-item-description", + text: `Which worlds the space generators place and how often, and what each world's own map is made with. Each table is a note in ${store.folder()}. Weight is the odds against the other rows that fit; blank limits mean any.`, + }); + if (lock) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); + const problems = store.problemsOf(this.tableName); + if (problems.length) { + contentEl.createEl("p", { + cls: "duckmage-world-types-problems", + text: `${problems.length} row${problems.length === 1 ? "" : "s"} in the note can't be read and ${problems.length === 1 ? "is" : "are"} kept as written: ${problems.map((p) => p.text).join("; ")}`, + }); + } + + this.rowsEl = contentEl.createDiv({ cls: "duckmage-world-types-rows" }); + this.renderRows(); + + const buttons = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); + const add = buttons.createEl("button", { text: "Add row" }); + if (lock) lockButton(add, lock); + add.addEventListener("click", () => { + if (this.lock()) return; + const blank = WORLD_TYPE_COLUMNS.map(() => ""); + if (this.preview.map) blank[col("Map")] = this.preview.map; + this.cells.push(blank); + this.changed(); + this.renderRows(); + }); + this.statusEl = buttons.createSpan({ cls: "duckmage-world-types-status" }); + this.saveBtn = buttons.createEl("button", { text: "Save", cls: "mod-cta" }); + if (lock) lockButton(this.saveBtn, lock); + this.saveBtn.addEventListener("click", () => void this.save().then(() => this.updateStatus())); + + contentEl.createEl("h4", { text: "Preview" }); + this.previewEl = contentEl.createDiv({ cls: "duckmage-world-types-preview" }); + this.renderPreview(); + this.updateStatus(); + } + + private newTable(head: HTMLElement): void { + if (this.lock()) return; + const box = head.createDiv({ cls: "duckmage-world-types-new" }); + const input = box.createEl("input", { type: "text", attr: { placeholder: "Table name", "aria-label": "New table name" } }); + const ok = box.createEl("button", { text: "Create", cls: "mod-cta" }); + input.focus(); + const go = () => { + void this.plugin.worldTypeStore.create(input.value, this.rows()).then((res) => { + if ("error" in res) { new Notice(res.error); return; } + this.tableName = res.name; + this.loadRows(); + this.render(); + }); + }; + ok.addEventListener("click", go); + input.addEventListener("keydown", (e) => { if (e.key === "Enter") go(); }); + } + + private changed(): void { + this.dirty = true; + this.updateStatus(); + this.renderPreview(); + } + + private updateStatus(): void { + if (!this.statusEl) return; + const problem = this.firstProblem(); + this.statusEl.setText(problem ?? (this.dirty ? "Unsaved changes" : "")); + this.statusEl.toggleClass("is-error", !!problem); + if (!this.lock()) this.saveBtn.disabled = !!problem || !this.dirty; + } + + /** Terrain names (all palettes) for the World / Stars / Base suggestions. */ + private suggestions(types: string[] | undefined): string[] { + const out = new Set(); + for (const p of this.plugin.settings.terrainPalettes) { + for (const t of p.terrains) if (!types || types.includes(t.type ?? "")) out.add(t.name); + } + return [...out].sort((a, b) => a.localeCompare(b)); + } + + private datalist(id: string, values: string[]): string { + const full = `duckmage-world-types-${id}`; + activeDocument.getElementById(full)?.remove(); + const dl = this.contentEl.createEl("datalist", { attr: { id: full } }); + for (const v of values) dl.createEl("option", { value: v }); + return full; + } + + private renderRows(): void { + const el = this.rowsEl; + el.empty(); + const lock = this.lock(); + const worldList = this.datalist("worlds", this.suggestions(["world", "gas-giant", "asteroids", "moon", "star-system", "station", "starport", "anomaly"])); + const starList = this.datalist("stars", this.suggestions(["star"])); + const baseList = this.datalist("base", this.suggestions(undefined)); + const paletteList = this.datalist("palettes", this.plugin.settings.terrainPalettes.map((p) => p.name)); + const lists: Partial> = { World: worldList, Stars: starList, Base: baseList, Palette: paletteList }; + if (!this.cells.length) el.createDiv({ cls: "setting-item-description", text: "No rows yet." }); + this.cells.forEach((cells, i) => { + const row = el.createDiv({ cls: "duckmage-world-types-row" }); + const problem = readWorldTypeCells(cells).problem; + row.toggleClass("is-invalid", !!problem); + if (problem) row.setAttr("title", problem); + const line = (cls: string, columns: WorldTypeColumn[]) => { + const l = row.createDiv({ cls }); + for (const c of columns) this.cellInput(l, cells, c, lists[c], !!lock, row); + return l; + }; + const top = line("duckmage-world-types-line", PICK_COLUMNS); + line("duckmage-world-types-line is-setup", SETUP_COLUMNS); + const tools = top.createDiv({ cls: "duckmage-world-types-tools" }); + const btn = (text: string, label: string, fn: () => void, disabled: boolean) => { + const b = tools.createEl("button", { text, attr: { "aria-label": label, title: label } }); + if (lock) lockButton(b, lock); + else b.disabled = disabled; + b.addEventListener("click", () => { + if (this.lock()) return; + fn(); + this.changed(); + this.renderRows(); + }); + }; + btn("↑", "Move up", () => { [this.cells[i - 1], this.cells[i]] = [this.cells[i], this.cells[i - 1]]; }, i === 0); + btn("↓", "Move down", () => { [this.cells[i + 1], this.cells[i]] = [this.cells[i], this.cells[i + 1]]; }, i === this.cells.length - 1); + btn("✕", "Remove row", () => { this.cells.splice(i, 1); }, false); + }); + } + + private cellInput(parent: HTMLElement, cells: string[], c: WorldTypeColumn, list: string | undefined, locked: boolean, row: HTMLElement): void { + const i = col(c); + const wrap = parent.createEl("label", { cls: `duckmage-world-types-cell is-${c.toLowerCase()}` }); + wrap.createSpan({ cls: "duckmage-world-types-cell-label", text: c }); + if (c === "Map") { + const sel = wrap.createEl("select"); + for (const [v, text] of [["", "Any"], ["sector", "Sector"], ["system", "System"]]) sel.createEl("option", { value: v, text }); + // A value the select doesn't list (typed in the note) stays as it was. + if (cells[i] && !["sector", "system"].includes(cells[i])) sel.createEl("option", { value: cells[i], text: cells[i] }); + sel.value = cells[i] ?? ""; + sel.disabled = locked; + sel.addEventListener("change", () => { cells[i] = sel.value; this.cellChanged(cells, row); }); + return; + } + const input = wrap.createEl("input", { type: "text", value: cells[i] ?? "", attr: { placeholder: PLACEHOLDERS[c] ?? "" } }); + if (list) input.setAttr("list", list); + input.disabled = locked; + input.addEventListener("input", () => { cells[i] = input.value; this.cellChanged(cells, row); }); + } + + private cellChanged(cells: string[], row: HTMLElement): void { + const problem = readWorldTypeCells(cells).problem; + row.toggleClass("is-invalid", !!problem); + if (problem) row.setAttr("title", problem); + else row.removeAttribute("title"); + this.changed(); + } + + private renderPreview(): void { + const el = this.previewEl; + if (!el) return; + el.empty(); + const p = this.preview; + const controls = el.createDiv({ cls: "duckmage-world-types-preview-controls" }); + const select = (label: string, options: [string, string][], value: string, set: (v: string) => void) => { + const l = controls.createEl("label", { text: `${label} ` }); + const s = l.createEl("select"); + for (const [v, t] of options) s.createEl("option", { value: v, text: t }); + s.value = value; + s.addEventListener("change", () => { set(s.value); this.renderPreview(); }); + }; + select("Map", [["", "Any"], ["sector", "Sector"], ["system", "System"]], p.map, (v) => { p.map = v as WorldTypeMap | ""; }); + select("Orbit", [["", "Any"], ...ORBIT_ZONES.map((z): [string, string] => [z, z[0].toUpperCase() + z.slice(1)])], p.zone, (v) => { p.zone = v as OrbitZone | ""; }); + select("Star", [["", "Any"], ...this.suggestions(["star"]).map((s): [string, string] => [s, s])], p.star, (v) => { p.star = v; }); + select("Temperature", [["", "Any"], ["0.1", "Cold"], ["0.3", "Cool"], ["0.5", "Mild"], ["0.7", "Warm"], ["0.9", "Hot"]], p.temperature, (v) => { p.temperature = v; }); + select("Rolls", [["100", "100"], ["200", "200"], ["1000", "1000"]], String(p.n), (v) => { p.n = Number(v); }); + + const ctx: Omit = {}; + if (p.map) ctx.map = p.map; + if (p.zone) ctx.zone = p.zone; + if (p.star) ctx.starType = p.star; + if (p.temperature) ctx.temperature = Number(p.temperature); + const table = { name: this.tableName, rows: this.rows() }; + const odds = worldTypeOdds(table, ctx); + if (!odds.length) { + el.createDiv({ cls: "setting-item-description", text: "No row fits: nothing would be placed here." }); + return; + } + const rolled = new Map(rollWorldTypes(table, ctx, p.n).map((r) => [r.world.toLowerCase(), r.count])); + const list = el.createDiv({ cls: "duckmage-world-types-dist" }); + for (const o of odds) { + const n = rolled.get(o.world.toLowerCase()) ?? 0; + const r = list.createDiv({ cls: "duckmage-world-types-dist-row" }); + r.createSpan({ cls: "duckmage-world-types-dist-name", text: o.world }); + const bar = r.createSpan({ cls: "duckmage-world-types-dist-bar" }); + bar.createSpan({ cls: "duckmage-world-types-dist-fill" }).setCssProps({ "--duckmage-dist": `${Math.round((n / p.n) * 100)}%` }); + r.createSpan({ cls: "duckmage-world-types-dist-num", text: `${n} of ${p.n}` }); + r.createSpan({ cls: "duckmage-world-types-dist-odds", text: `odds ${Math.round(o.odds * 1000) / 10}%` }); + } + } +} diff --git a/src/space/worldTypes.ts b/src/space/worldTypes.ts index bc37c094..fd386eef 100644 --- a/src/space/worldTypes.ts +++ b/src/space/worldTypes.ts @@ -426,8 +426,11 @@ export const WORLD_TYPES_HELP = [ "> Which worlds the space generators place and how often, and what each world's own map is made with. **World** is a terrain of the palette. **Weight** (1 if blank) is its odds against the other rows that fit; 0 never rolls it. Limits, all optional: **Map** sector (Star scatter's systems) or system (Orbits), **Orbit** inner, habitable, outer or rings like 2–4, **Stars** a list of star terrains, **Temperature** cold, cool, mild, warm, hot or 0.2–0.5. For the world's map: **Size** like 20×14 or 16–24 × 10–14, **Generator** a generator note link or id, **Options** like water=85, climate=lush, **Palette** and **Base** terrain. The same world can have several rows. Add, edit or delete rows freely.", ]; -const COLUMNS = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; -type Column = (typeof COLUMNS)[number]; +/** The note table's columns, in order (the editor keeps each row as these cells). */ +export const WORLD_TYPE_COLUMNS = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; +export type WorldTypeColumn = (typeof WORLD_TYPE_COLUMNS)[number]; +type Column = WorldTypeColumn; +const COLUMNS = WORLD_TYPE_COLUMNS; const HEADER_ALIASES: Record = { world: "World", worlds: "World", "world type": "World", type: "World", body: "World", terrain: "World", weight: "Weight", odds: "Weight", chance: "Weight", @@ -627,3 +630,32 @@ export function copyWorldTypeRows(rows: readonly WorldTypeRow[]): WorldTypeRow[] return c; }); } + +/** + * Cells in WORLD_TYPE_COLUMNS order → a row, or what's wrong (the + * editor's check; the same reading as the note's). + */ +export function readWorldTypeCells(cells: readonly string[]): { row?: WorldTypeRow; problem?: string } { + return readRow([...cells], [...COLUMNS]); +} + +/** Each fitting world's exact odds (0..1) for a context, most likely first. */ +export function worldTypeOdds(table: WorldTypeTable, ctx: Omit & { seed?: number }): { world: string; odds: number }[] { + const w = worldTypeWeights(table, ctx); + const total = Object.values(w).reduce((a, b) => a + b, 0); + if (total <= 0) return []; + const names = new Map(matchingWorldTypes(table, ctx).map((r) => [lc(r.world), r.world.trim()])); + return Object.entries(w) + .map(([k, v]) => ({ world: names.get(k) ?? k, odds: v / total })) + .sort((a, b) => b.odds - a.odds || a.world.localeCompare(b.world)); +} + +/** Roll `n` worlds (seeds `seed`, `seed + 1`, …) and count them, most rolled first. */ +export function rollWorldTypes(table: WorldTypeTable, ctx: Omit, n: number, seed = 1): { world: string; count: number }[] { + const counts = new Map(); + for (let i = 0; i < n; i++) { + const p = pickWorldType(table, { ...ctx, seed: seed + i }); + if (p) counts.set(p.terrain, (counts.get(p.terrain) ?? 0) + 1); + } + return [...counts].map(([world, count]) => ({ world, count })).sort((a, b) => b.count - a.count || a.world.localeCompare(b.world)); +} diff --git a/src/types.ts b/src/types.ts index 09aa0bde..d24fe6fd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -353,6 +353,10 @@ export interface HexmakerPluginSettings { biomePoolsFolder?: string; /** True once the shipped "All biomes" pool note was written (once, so a deleted one stays deleted). */ biomePoolSeeded?: boolean; + /** Vault folder for world types notes (which worlds space generators place); blank = `/world-types`. */ + worldTypesFolder?: string; + /** True once the shipped "Default space" world types note was written (once, so a deleted one stays deleted). */ + worldTypesSeeded?: boolean; /** True once settings-only palettes were written out as notes. */ palettesMigrated: boolean; /** diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index 6c88b9c1..afd2a318 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -21,6 +21,9 @@ import { addGeneratedPaths, pathColors } from "./generators"; import { renderPreviewLegend } from "../hex-map/terrainLegend"; import { IMAGE_EXTENSIONS, attachImageDropZone, getIconUrl, importBinaryFileToVault, mapBgImportFolder, selectAllOnFocus, slugify } from "../utils"; import { FileLinkSuggestModal } from "../hex-map/FileLinkSuggestModal"; +import { WorldTypesModal } from "../space/WorldTypesModal"; +import { STAR_SCATTER_ID } from "./procedural/starScatter"; +import { ORBITS_ID } from "./procedural/orbits"; import { SIZE_PRESETS, type SizePreset } from "./sizePresets"; import { LIVE_PREVIEW_DELAY_MS, sizeFromInput } from "../sizeInput"; import { @@ -625,6 +628,14 @@ export class NewMapSetupModal extends HexmakerModal { refresh(); }); } + // Space generators: the worlds they place come from a world types table. + if (kind && (kind.id === STAR_SCATTER_ID || kind.id === ORBITS_ID) && hasFeature(this.plugin.settings, "generators")) { + const r = this.row(optsBox, "World types"); + const btn = r.createEl("button", { text: "Edit world types…" }); + btn.addEventListener("click", () => { + new WorldTypesModal(this.app, this.plugin, this.origin?.map, undefined, kind.id === ORBITS_ID ? "system" : "sector").open(); + }); + } goBtn.setText(this.kindId === BLANK_ID ? (this.origin ? "Create & enter" : "Create") : (this.origin ? "Generate & enter" : "Generate")); }; diff --git a/styles.css b/styles.css index 457f3dc1..a4c6e3c7 100644 --- a/styles.css +++ b/styles.css @@ -8647,3 +8647,105 @@ textarea.duckmage-edit-region-notes-input { .duckmage-wfc-used-by { font-style: italic; } +/* World types table editor (space generators). */ +.duckmage-world-types-modal { + width: min(64em, 95vw); +} +.duckmage-world-types-head, +.duckmage-world-types-new, +.duckmage-world-types-preview-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} +.duckmage-world-types-problems, +.duckmage-world-types-status.is-error { + color: var(--text-error); +} +.duckmage-world-types-status { + flex: 1 1 auto; + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} +.duckmage-world-types-rows { + max-height: 40vh; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 4px; + margin: 6px 0; +} +.duckmage-world-types-row { + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + padding: 3px 6px; +} +.duckmage-world-types-row.is-invalid { + border-color: var(--text-error); +} +.duckmage-world-types-line { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 4px 6px; +} +.duckmage-world-types-line.is-setup { + opacity: 0.85; +} +.duckmage-world-types-cell { + display: flex; + flex-direction: column; + min-width: 0; +} +.duckmage-world-types-cell-label { + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} +.duckmage-world-types-cell input { + width: 8em; +} +.duckmage-world-types-cell.is-world input { + width: 11em; +} +.duckmage-world-types-cell.is-weight input { + width: 4em; +} +.duckmage-world-types-cell.is-generator input, +.duckmage-world-types-cell.is-options input { + width: 13em; +} +.duckmage-world-types-tools { + display: flex; + gap: 2px; + margin-left: auto; +} +.duckmage-world-types-dist { + display: grid; + grid-template-columns: minmax(8em, max-content) minmax(6em, 1fr) max-content max-content; + gap: 2px 8px; + align-items: center; + max-height: 14em; + overflow-y: auto; + margin-top: 4px; +} +.duckmage-world-types-dist-row { + display: contents; +} +.duckmage-world-types-dist-bar { + height: 0.7em; + background: var(--background-modifier-border); + border-radius: 2px; + overflow: hidden; +} +.duckmage-world-types-dist-fill { + display: block; + height: 100%; + width: var(--duckmage-dist, 0%); + background: var(--interactive-accent); +} +.duckmage-world-types-dist-num, +.duckmage-world-types-dist-odds { + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} diff --git a/tests/worldTypes.test.ts b/tests/worldTypes.test.ts new file mode 100644 index 00000000..f9e235a3 --- /dev/null +++ b/tests/worldTypes.test.ts @@ -0,0 +1,327 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { mulberry32 } from "../packages/hex-wfc/src/rng"; +import { MemVault } from "./helpers/memVault"; +import { + DEFAULT_WORLD_TYPES, + buildWorldTypes, + matchingWorldTypes, + orbitZone, + parseWorldTypes, + pickWorldType, + readSize, + readWorldTypeCells, + rollWorldTypes, + updateWorldTypes, + worldTypeCells, + worldTypeFor, + worldTypeOdds, + worldTypeSubmapDefault, + worldTypeWeights, + type OrbitZone, + type WorldTypeRow, + type WorldTypeTable, +} from "../src/space/worldTypes"; +import { DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { WorldTypeStore } from "../src/space/WorldTypeStore"; +import { PALETTE_PRESETS, SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; +import type { TerrainColor } from "../src/types"; + +const table = (rows: WorldTypeRow[], name = "T"): WorldTypeTable => ({ name, rows }); +const DEFAULT = table([...DEFAULT_WORLD_TYPE_ROWS], DEFAULT_WORLD_TYPES); + +// ── frozen copy of the old built-in tables (before world types) ────────── +// src/worldgen/procedural/orbits.ts and starScatter.ts at 316bb50. Do not +// update these to match new code: they are what Default space must equal. + +type Zone = "inner" | "habitable" | "outer"; +const OLD_ZONE_WEIGHTS: Record> = { + inner: { "molten planet": 4, "rocky planet": 4, "desert planet": 2, "asteroid belt": 0.5 }, + habitable: { "terrestrial planet": 4, "ocean planet": 3, "desert planet": 3, "rocky planet": 2, "asteroid belt": 1 }, + outer: { "gas giant": 4, "ice giant": 3, "ice planet": 3, "asteroid belt": 1.5, "rocky planet": 1 }, +}; +const OLD_BODY_NAMES = [ + "terrestrial planet", "ocean planet", "desert planet", "ice planet", "rocky planet", + "molten planet", "gas giant", "ice giant", "asteroid belt", +]; +const OLD_WORLD_WEIGHTS: Record = { + "garden world": 3, "desert world": 3, "barren world": 3.5, "ocean world": 2, + "ice world": 2, "asteroid belt": 1.5, "molten world": 1, "gas giant": 1, +}; +function oldWeightedPick(rand: () => number, names: string[], weights: Record, fallback = 1): string | undefined { + if (names.length === 0) return undefined; + const w = names.map((n) => Math.max(0, weights[n.toLowerCase()] ?? fallback)); + const total = w.reduce((a, b) => a + b, 0); + if (total <= 0) return names[Math.floor(rand() * names.length)]; + let r = rand() * total; + for (let i = 0; i < names.length; i++) { + r -= w[i]; + if (r < 0) return names[i]; + } + return names[names.length - 1]; +} +/** Old orbitRoles().zoneWeights for the shipped (named) bodies. */ +const oldZoneWeights = (bodies: string[], zone: Zone) => + Object.fromEntries(bodies.filter((b) => OLD_BODY_NAMES.includes(b)).map((b) => [b, OLD_ZONE_WEIGHTS[zone][b] ?? 0.5])); +const ofTypes = (terrains: TerrainColor[], types: string[]) => terrains.filter((t) => types.includes(t.type ?? "")).map((t) => t.name); +const OLD_SURFACE = { palette: "Expanded", cols: 20, rows: 14, generator: "procedural:planet-surface" }; +const OLD_SYSTEM_DEFAULTS: Record = { + "terrestrial planet": { ...OLD_SURFACE, options: { water: "65", climate: "temperate", relief: "normal" }, baseTerrain: "ocean" }, + "ocean planet": { ...OLD_SURFACE, options: { water: "85", climate: "lush", relief: "normal" }, baseTerrain: "ocean" }, + "desert planet": { ...OLD_SURFACE, options: { water: "10", climate: "arid", relief: "normal" }, baseTerrain: "desert" }, + "ice planet": { ...OLD_SURFACE, options: { water: "30", climate: "frozen", relief: "normal" }, baseTerrain: "ocean" }, + "rocky planet": { ...OLD_SURFACE, options: { water: "10", climate: "arid", relief: "rugged" }, baseTerrain: "desert" }, + "molten planet": { ...OLD_SURFACE, options: { water: "10", climate: "volcanic", relief: "rugged" }, baseTerrain: "desert" }, + moon: { ...OLD_SURFACE, options: { water: "10", climate: "frozen", relief: "rugged" }, baseTerrain: "desert" }, +}; +const OLD_SECTOR_DEFAULT = { palette: "Space - System", cols: 13, rows: 13, generator: "procedural:orbits", baseTerrain: "void" }; + +describe("Default space reproduces the old built-in odds", () => { + const bodies = ofTypes(SPACE_SYSTEM_TERRAINS, ["world", "gas-giant", "asteroids"]); + const worlds = ofTypes(SPACE_SECTOR_TERRAINS, ["world", "gas-giant", "asteroids"]); + + it("Orbits: every zone's weights are the old ones", () => { + for (const zone of ["inner", "habitable", "outer"] as Zone[]) { + expect(worldTypeWeights(DEFAULT, { map: "system", zone, palette: SPACE_SYSTEM_TERRAINS })).toEqual(oldZoneWeights(bodies, zone)); + } + }); + + it("Star scatter: the sector weights are the old ones", () => { + const old = Object.fromEntries(worlds.map((w) => [w, OLD_WORLD_WEIGHTS[w]])); + expect(worldTypeWeights(DEFAULT, { map: "sector", palette: SPACE_SECTOR_TERRAINS })).toEqual(old); + }); + + it("the same random stream gives the same choices, one draw each", () => { + for (let seed = 1; seed <= 300; seed++) { + for (const zone of ["inner", "habitable", "outer"] as Zone[]) { + const a = mulberry32(seed), b = mulberry32(seed); + const old = oldWeightedPick(a, bodies, oldZoneWeights(bodies, zone), 0.5); + const now = pickWorldType(DEFAULT, { map: "system", zone, seed, rand: b, palette: SPACE_SYSTEM_TERRAINS }); + expect(now?.terrain).toBe(old); + expect(b()).toBe(a()); // streams still in step + } + const a = mulberry32(seed), b = mulberry32(seed); + const old = oldWeightedPick(a, worlds, OLD_WORLD_WEIGHTS); + expect(pickWorldType(DEFAULT, { map: "sector", seed, rand: b, palette: SPACE_SECTOR_TERRAINS })?.terrain).toBe(old); + expect(b()).toBe(a()); + } + }); + + it("each world's map setup is the old palette submap default", () => { + for (const [world, want] of Object.entries(OLD_SYSTEM_DEFAULTS)) { + expect(worldTypeSubmapDefault(worldTypeFor(DEFAULT, world, { map: "system" })!)).toEqual(want); + } + for (const w of worlds) expect(worldTypeSubmapDefault(worldTypeFor(DEFAULT, w, { map: "sector" })!)).toEqual(OLD_SECTOR_DEFAULT); + // And they still match what the shipped palettes carry. + const sys = PALETTE_PRESETS.find((p) => p.name === "Space - System")!.submapDefaults!; + for (const [world, d] of Object.entries(sys)) expect(worldTypeSubmapDefault(worldTypeFor(DEFAULT, world, { map: "system" })!)).toEqual(d); + }); + + it("orbitZone is Orbits' split", () => { + expect([2, 3, 4, 5, 6, 7, 8].map((d) => orbitZone(d, 2, 8))).toEqual(["inner", "inner", "habitable", "habitable", "outer", "outer", "outer"]); + }); + + it("the note round-trips the shipped rows", () => { + const text = buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS); + const back = parseWorldTypes(text); + expect(back.problems).toEqual([]); + expect(back.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); + expect(text).toContain("hexmaker-world-types: 1"); + expect(text).toContain("| ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush, relief=normal | Expanded | ocean | |"); + }); +}); + +describe("world types note", () => { + const rows: WorldTypeRow[] = [ + { world: "Lava world", weight: 2, map: "system", zones: ["inner"], distance: { lo: 2, hi: 4 }, stars: ["red dwarf", "blue giant"], temperature: { lo: 0.8, hi: 1 }, size: { cols: { lo: 16, hi: 24 }, rows: { lo: 10, hi: 14 } }, generator: { path: "world/generators/Lava" }, options: { relief: "rugged" }, palette: "Expanded", baseTerrain: "desert", notes: "hot | dry" }, + { world: "Garden", generator: { builtin: "preset-volcanic" } }, + { world: "Ocean", weight: 0.5, generator: { id: "procedural:planet-surface" } }, + ]; + + it("round-trips every column and keeps prose", () => { + const text = buildWorldTypes("Mine", rows).replace("# Mine", "# Mine\n\nMy own words."); + expect(parseWorldTypes(text)).toEqual({ rows, problems: [], unreadable: [] }); + expect(updateWorldTypes(text, rows)).toBe(text); + const next = updateWorldTypes(text, rows.slice(1)); + expect(next).toContain("My own words."); + expect(parseWorldTypes(next).rows).toEqual(rows.slice(1)); + }); + + it("reads forgivingly: header names in any order, missing columns, × or x, % weights, links", () => { + const text = [ + "| Notes | Type | Odds | Size | Zone | Star |", + "|---|---|--:|---|---|---|", + "| a note | [[Ice world]] | 50% | 20x14 | Outer zone | Red dwarf; white dwarf |", + "| | Rock | | 10 - 12 by 8 | rings 3 to 5 | |", + "| | | | | | |", + ].join("\n"); + const p = parseWorldTypes(text); + expect(p.problems).toEqual([]); + expect(p.rows).toEqual([ + { world: "Ice world", weight: 0.5, zones: ["outer"], stars: ["Red dwarf", "white dwarf"], size: { cols: { lo: 20, hi: 20 }, rows: { lo: 14, hi: 14 } }, notes: "a note" }, + { world: "Rock", distance: { lo: 3, hi: 5 }, size: { cols: { lo: 10, hi: 12 }, rows: { lo: 8, hi: 8 } } }, + ]); + expect(readSize("16–24 × 10–14")).toEqual({ cols: { lo: 16, hi: 24 }, rows: { lo: 10, hi: 14 } }); + }); + + it("keeps rows it can't read, reports them, never uses them", () => { + const text = buildWorldTypes("T", [{ world: "A" }]).replace("| A |", "| B | lots | | | | | | | | | | |\n| A |"); + const p = parseWorldTypes(text); + expect(p.rows.map((r) => r.world)).toEqual(["A"]); + expect(p.problems.length).toBe(1); + expect(p.problems[0].text).toMatch(/weight "lots"/); + const next = updateWorldTypes(text, [{ world: "A", weight: 2 }, { world: "C" }]); + expect(next).toContain("| B | lots |"); + expect(parseWorldTypes(next).rows.map((r) => r.world)).toEqual(["A", "C"]); + for (const bad of [["X", "", "galaxy"], ["X", "", "", "nowhere"], ["X", "", "", "", "", "", "big"], ["X", "", "", "", "", "boiling"], ["X", "", "", "", "", "", "", "", "water"]]) { + const cells = [...bad, ...Array(12 - bad.length).fill("")]; + expect(readWorldTypeCells(cells).problem).toBeTruthy(); + } + expect(parseWorldTypes("no table").problems[0].text).toMatch(/no table/); + }); + + it("the editor's cells read back as the row", () => { + for (const r of [...rows, ...DEFAULT_WORLD_TYPE_ROWS]) expect(readWorldTypeCells(worldTypeCells(r)).row).toEqual(r); + }); +}); + +describe("pickWorldType", () => { + const t = table([ + { world: "Hot rock", weight: 3, map: "system", zones: ["inner"], size: { cols: { lo: 10, hi: 20 }, rows: { lo: 8, hi: 8 } }, generator: { id: "procedural:planet-surface" }, options: { climate: "volcanic" } }, + { world: "Garden", weight: 1, map: "system", zones: ["habitable"], stars: ["Yellow star"] }, + { world: "Snowball", weight: 1, map: "system", distance: { lo: 6, hi: 99 }, temperature: { lo: 0, hi: 0.2 } }, + { world: "Station", weight: 0, map: "system" }, + { world: "Mainworld", map: "sector" }, + ]); + + it("is deterministic for a seed", () => { + for (let seed = 0; seed < 50; seed++) expect(pickWorldType(t, { seed })).toEqual(pickWorldType(t, { seed })); + }); + + it("respects every filter (a filter the context doesn't know passes)", () => { + const worlds = (ctx: Parameters[1]) => matchingWorldTypes(t, ctx).map((r) => r.world); + expect(worlds({ map: "sector" })).toEqual(["Mainworld"]); + expect(worlds({ map: "system", zone: "inner" as OrbitZone, distance: 3 })).toEqual(["Hot rock"]); + expect(worlds({ map: "system", zone: "habitable", starType: "red dwarf", distance: 4 })).toEqual([]); + expect(worlds({ map: "system", zone: "habitable", starType: "yellow STAR", distance: 4 })).toEqual(["Garden"]); + expect(worlds({ map: "system", zone: "outer", distance: 7, temperature: 0.1 })).toEqual(["Snowball"]); + expect(worlds({ map: "system", zone: "outer", distance: 7, temperature: 0.5 })).toEqual([]); + expect(worlds({ map: "system" })).toEqual(["Hot rock", "Garden", "Snowball"]); + expect(pickWorldType(t, { map: "system", zone: "habitable", starType: "red dwarf", distance: 4, seed: 1 })).toBeNull(); + }); + + it("follows the weights, never picks weight 0, and only palette worlds (in palette order)", () => { + const counts = rollWorldTypes(t, { map: "system" }, 5000); + const n = Object.fromEntries(counts.map((c) => [c.world, c.count])); + expect(n.Station).toBeUndefined(); + expect(n["Hot rock"] / 5000).toBeGreaterThan(0.55); + expect(n["Hot rock"] / 5000).toBeLessThan(0.65); + expect(worldTypeOdds(t, { map: "system" })).toEqual([{ world: "Hot rock", odds: 0.6 }, { world: "Garden", odds: 0.2 }, { world: "Snowball", odds: 0.2 }]); + const pal = ["snowball", "Station", "hot rock"]; + expect(matchingWorldTypes(t, { map: "system", palette: pal }).map((r) => r.world)).toEqual(["Snowball", "Hot rock"]); + expect(pickWorldType(t, { map: "system", zone: "inner", seed: 3, palette: [{ name: "HOT ROCK" }] })?.terrain).toBe("HOT ROCK"); + }); + + it("rolls the size in range and passes the map setup on", () => { + const sizes = new Set(); + for (let seed = 0; seed < 200; seed++) { + const p = pickWorldType(t, { map: "system", zone: "inner", distance: 2, seed })!; + expect(p.size!.cols).toBeGreaterThanOrEqual(10); + expect(p.size!.cols).toBeLessThanOrEqual(20); + expect(p.size!.rows).toBe(8); + sizes.add(p.size!.cols); + expect(p.generator).toEqual({ id: "procedural:planet-surface" }); + expect(p.options).toEqual({ climate: "volcanic" }); + } + expect(sizes.size).toBeGreaterThan(5); + expect(pickWorldType(t, { map: "sector", seed: 1 })!.size).toBeUndefined(); + }); + + it("a world with several fitting rows adds them up, then picks one of its rows", () => { + const two = table([ + { world: "Rock", weight: 1, notes: "a" }, + { world: "Rock", weight: 3, notes: "b" }, + { world: "Ice", weight: 4 }, + ]); + expect(worldTypeWeights(two, {})).toEqual({ rock: 4, ice: 4 }); + const seen = new Set(); + for (let seed = 0; seed < 100; seed++) { + const p = pickWorldType(two, { seed })!; + if (p.terrain === "Rock") seen.add(p.row.notes!); + } + expect([...seen].sort()).toEqual(["a", "b"]); + }); +}); + +// ── the store ──────────────────────────────────────────────────────────── + +function storePlugin(vault: MemVault, settings: Record = {}) { + return { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { worldFolder: "world", ...settings } as Record, + saveSettings: async () => {}, + }; +} +const NOTE = `world/world-types/${DEFAULT_WORLD_TYPES}.md`; + +describe("WorldTypeStore", () => { + it("writes the shipped table once, and not again once deleted", async () => { + const v = new MemVault(); + const plugin = storePlugin(v); + const store = new WorldTypeStore(plugin as never); + await store.init(); + expect(v.files.get(NOTE)).toContain("hexmaker-world-types: 1"); + expect(store.get(DEFAULT_WORLD_TYPES)!.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); + expect(plugin.settings.worldTypesSeeded).toBe(true); + v.files.delete(NOTE); + const again = new WorldTypeStore(plugin as never); + await again.init(); + await again.ensureDefault(); + expect(v.files.has(NOTE)).toBe(false); + // Restore default writes it back. + expect(await again.restoreDefault()).toBe(true); + expect(again.get(DEFAULT_WORLD_TYPES)!.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); + }); + + it("doesn't seed when space maps are off (until asked)", async () => { + const v = new MemVault(); + const store = new WorldTypeStore(storePlugin(v, { mapKinds: ["world"] }) as never); + await store.init(); + expect(v.files.has(NOTE)).toBe(false); + await store.ensureDefault(); + expect(v.files.has(NOTE)).toBe(true); + }); + + it("reads hand edits live, keeps unreadable rows on update, restores with a backup", async () => { + const v = new MemVault(); + const store = new WorldTypeStore(storePlugin(v) as never); + await store.init(); + let changes = 0; + store.onChange(() => changes++); + const text = v.files.get(NOTE)!.replace("| garden world | 3 |", "| garden world | 9 |").replace("| moon |", "| ??? | huge | | | | | | | | | | |\n| moon |"); + v.files.set(NOTE, text); + store.onModify(v.app().vault.getAbstractFileByPath(NOTE)!); + await store.ensureDefault(); // waits for the read + expect(changes).toBeGreaterThan(0); + expect(worldTypeWeights(store.get(DEFAULT_WORLD_TYPES)!, { map: "sector" })["garden world"]).toBe(9); + expect(store.problemsOf(DEFAULT_WORLD_TYPES).length).toBe(1); + await store.update(DEFAULT_WORLD_TYPES, [{ world: "garden world" }]); + expect(v.files.get(NOTE)).toContain("| ??? | huge |"); + expect(store.get(DEFAULT_WORLD_TYPES)!.rows).toEqual([{ world: "garden world" }]); + await store.restoreDefault(); + expect(store.get(DEFAULT_WORLD_TYPES)!.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); + expect([...v.binaries.keys(), ...v.files.keys()].some((p) => p.includes("backups/world-types-"))).toBe(true); + }); + + it("creates tables and lists them by name", async () => { + const v = new MemVault(); + const store = new WorldTypeStore(storePlugin(v) as never); + await store.init(); + expect(await store.create("Hard SF", [{ world: "rocky planet", weight: 2 }])).toEqual({ name: "Hard SF" }); + expect("error" in (await store.create("hard sf"))).toBe(true); + expect("error" in (await store.create(" "))).toBe(true); + expect(store.list().map((t) => t.name)).toEqual([DEFAULT_WORLD_TYPES, "Hard SF"]); + expect(store.get("world/world-types/Hard SF.md")!.rows).toEqual([{ world: "rocky planet", weight: 2 }]); + }); +}); From 8bdf81ef9573560185301ca868c434b2d6ea4712 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 02:08:17 -0400 Subject: [PATCH 271/558] fix(world-types): editor fits a wider modal; inputs named by column Sandbox check: the modal was the default width (each row three lines); palette names were cut off; inputs were named by their placeholder. Co-Authored-By: Claude Opus 5.5 --- src/space/WorldTypesModal.ts | 6 +++--- styles.css | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts index 5a7fcaa0..88cf7cfc 100644 --- a/src/space/WorldTypesModal.ts +++ b/src/space/WorldTypesModal.ts @@ -310,7 +310,7 @@ export class WorldTypesModal extends HexmakerModal { const wrap = parent.createEl("label", { cls: `duckmage-world-types-cell is-${c.toLowerCase()}` }); wrap.createSpan({ cls: "duckmage-world-types-cell-label", text: c }); if (c === "Map") { - const sel = wrap.createEl("select"); + const sel = wrap.createEl("select", { attr: { "aria-label": c } }); for (const [v, text] of [["", "Any"], ["sector", "Sector"], ["system", "System"]]) sel.createEl("option", { value: v, text }); // A value the select doesn't list (typed in the note) stays as it was. if (cells[i] && !["sector", "system"].includes(cells[i])) sel.createEl("option", { value: cells[i], text: cells[i] }); @@ -319,7 +319,7 @@ export class WorldTypesModal extends HexmakerModal { sel.addEventListener("change", () => { cells[i] = sel.value; this.cellChanged(cells, row); }); return; } - const input = wrap.createEl("input", { type: "text", value: cells[i] ?? "", attr: { placeholder: PLACEHOLDERS[c] ?? "" } }); + const input = wrap.createEl("input", { type: "text", value: cells[i] ?? "", attr: { placeholder: PLACEHOLDERS[c] ?? "", "aria-label": c } }); if (list) input.setAttr("list", list); input.disabled = locked; input.addEventListener("input", () => { cells[i] = input.value; this.cellChanged(cells, row); }); @@ -341,7 +341,7 @@ export class WorldTypesModal extends HexmakerModal { const controls = el.createDiv({ cls: "duckmage-world-types-preview-controls" }); const select = (label: string, options: [string, string][], value: string, set: (v: string) => void) => { const l = controls.createEl("label", { text: `${label} ` }); - const s = l.createEl("select"); + const s = l.createEl("select", { attr: { "aria-label": `Preview ${label.toLowerCase()}` } }); for (const [v, t] of options) s.createEl("option", { value: v, text: t }); s.value = value; s.addEventListener("change", () => { set(s.value); this.renderPreview(); }); diff --git a/styles.css b/styles.css index a4c6e3c7..aa6f8b3f 100644 --- a/styles.css +++ b/styles.css @@ -8648,8 +8648,9 @@ textarea.duckmage-edit-region-notes-input { font-style: italic; } /* World types table editor (space generators). */ -.duckmage-world-types-modal { - width: min(64em, 95vw); +.modal.duckmage-world-types-modal { + width: min(72em, 95vw); + max-width: 95vw; } .duckmage-world-types-head, .duckmage-world-types-new, @@ -8711,6 +8712,7 @@ textarea.duckmage-edit-region-notes-input { .duckmage-world-types-cell.is-weight input { width: 4em; } +.duckmage-world-types-cell.is-palette input, .duckmage-world-types-cell.is-generator input, .duckmage-world-types-cell.is-options input { width: 13em; From 1d284af47026aff41e2f077a6118e64064d5b299 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 03:35:20 -0400 Subject: [PATCH 272/558] fix: undo restores a repainted hex; skip deferred map tabs; startup saves wait for map notes Found by the first run of the smoke vault matrix (dev/smoke): - Painting over a hex and undoing cleared its terrain instead of restoring the old one: the stroke read the "before" terrain from the hex note's frontmatter, which no longer holds map data. It now reads a still-queued write, else the map data (getTerrainFromFile, via the map store). - A map tab restored at startup but not shown yet is a deferred stand-in, not a HexMapView, so refreshHexMap() threw "renderGrid is not a function" (logged as "map note sync failed"). Refresh helpers, the hex-table reload, showMap and the openmap protocol handler now check instanceof. - The Advanced check-in and the one-time table-ranges survey saved settings before the map notes had loaded, which wrote every map's empty path list back into data.json. Both now wait for the stores. Co-Authored-By: Claude Opus 5.5 --- src/HexmakerPlugin.ts | 32 +++++++++++++++++++++----------- src/hex-map/HexMapView.ts | 10 ++++++---- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index dc58ed8b..b08df339 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -152,7 +152,8 @@ export default class HexmakerPlugin extends Plugin { // migrate per-hex data out of hex notes on the first run. void this.biomeStore.init(); void this.worldTypeStore.init(); - void this.paletteStore.init().then(() => this.mapStore.init()).then(() => this.ensureTablesForNewTerrains()); + const storesReady = this.paletteStore.init().then(() => this.mapStore.init()); + void storesReady.then(() => this.ensureTablesForNewTerrains()); // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. void this.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { if (!sandbox) return; @@ -170,11 +171,15 @@ export default class HexmakerPlugin extends Plugin { } else if (shouldNudge(this.settings, this.settings.maps.length)) { // A Simple user who's been at it a while: offer Advanced, once. this.settings.advancedNudgeAt = new Date().toISOString().slice(0, 10); - void this.saveSettings(); + // Saved once the map notes are loaded: a save before that writes + // every map's (empty) path list back into data.json, though the + // paths live in the map notes (smoke suite C5). + void storesReady.then(() => this.saveSettings()); new AdvancedNudgeModal(this.app, this).open(); } else { - // Once after updating: offer roll ranges for older tables (asks first). - void maybePromptTableRanges(this); + // Once after updating: offer roll ranges for older tables (asks + // first). After the stores load, for the same reason. + void storesReady.then(() => maybePromptTableRanges(this)); } }); @@ -558,8 +563,10 @@ export default class HexmakerPlugin extends Plugin { if (!mapName) return; const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP); if (leaves.length > 0) { - void this.app.workspace.revealLeaf(leaves[0]); - (leaves[0].view as HexMapView).navigateToMap(mapName); + // Revealing loads a deferred (restored, never shown) tab first. + void this.app.workspace.revealLeaf(leaves[0]).then(() => { + if (leaves[0].view instanceof HexMapView) leaves[0].view.navigateToMap(mapName); + }); } else { void this.app.workspace.getLeaf("tab") .setViewState({ type: VIEW_TYPE_HEX_MAP }) @@ -715,7 +722,8 @@ export default class HexmakerPlugin extends Plugin { await leaf.setViewState({ type: VIEW_TYPE_HEX_MAP, active: true }); } await this.app.workspace.revealLeaf(leaf); - (leaf.view as HexMapView).switchMapFromModal(name); + // Revealing loads a deferred tab, so this is the map view by now. + if (leaf.view instanceof HexMapView) leaf.view.switchMapFromModal(name); } openSetupWizard(): void { @@ -885,7 +893,7 @@ export default class HexmakerPlugin extends Plugin { this.loadAvailableIcons(); this.refreshHexMap(); this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_TABLE).forEach((leaf) => { - void (leaf.view as HexTableView).loadTable(); + if (leaf.view instanceof HexTableView) void leaf.view.loadTable(); }); } @@ -996,8 +1004,10 @@ export default class HexmakerPlugin extends Plugin { } refreshHexMap(): void { + // A tab restored at startup but not shown yet holds a deferred stand-in, + // not a HexMapView, until it's opened (and it renders then anyway). this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP).forEach((leaf) => { - (leaf.view as HexMapView).renderGrid(); + if (leaf.view instanceof HexMapView) leaf.view.renderGrid(); }); } @@ -1725,14 +1735,14 @@ export default class HexmakerPlugin extends Plugin { terrainOverrides: Map, ): void { this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP).forEach((leaf) => { - (leaf.view as HexMapView).renderGrid(terrainOverrides); + if (leaf.view instanceof HexMapView) leaf.view.renderGrid(terrainOverrides); }); } /** Update terrain filter sets in all open hex table views after a rename. */ refreshHexTableTerrainRename(oldName: string, newName: string): void { this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_TABLE).forEach((leaf) => { - (leaf.view as HexTableView).renameTerrainInFilters(oldName, newName); + if (leaf.view instanceof HexTableView) leaf.view.renameTerrainInFilters(oldName, newName); }); } diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index fa22b286..ac201a1c 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -12,7 +12,6 @@ import { setGmIconsInFile, setTerrainInFile, setIconOverrideInFile, - Frontmatter, } from "../frontmatter"; import { HexEditorModal } from "./HexEditorModal"; import { TerrainPickerModal } from "./TerrainPickerModal"; @@ -4941,9 +4940,12 @@ export class HexMapView extends ItemView { const path = this.plugin.hexPath(hx, hy, this.activeMapName); if (this.currentTerrainStroke) { if (!this.currentTerrainStroke.has(path)) { - const fmCache: Frontmatter | undefined = - this.app.metadataCache.getCache(path)?.frontmatter; - const oldTerrain = fmCache?.terrain ?? null; + // The terrain before this stroke: a write still queued for the + // hex, else the map data (the map note, via the store). Hex-note + // frontmatter no longer holds terrain, so reading it made undo + // clear a repainted hex instead of restoring it (smoke suite C6). + const pending = this.pendingTerrainWrites.get(path); + const oldTerrain = pending ? pending.terrain : getTerrainFromFile(this.app, path); this.currentTerrainStroke.set(path, { x: hx, y: hy, From 33a1d1b258146a85d366ab32088b0c188dc81e28 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 03:35:26 -0400 Subject: [PATCH 273/558] feat(smoke): parallel smoke-test vault matrix + npm run premerge (WM5) dev/smoke/run.mjs builds (or takes --build ) and snapshots the plugin, then per vault setup creates a sandboxed Obsidian (fresh-eyes sandbox.mjs, --plugin-data for fixture settings), up to 4 at once, and runs scripted checks through the plugin's own entry points: C1 no plugin console errors / error notices (CDP replay catches load-time errors), C2 settings resolved + saved, nothing lost from data.json, C3 every map opens and renders the right hex count, C4 untouched files byte-identical (migrations verified separately: hex data vs the old frontmatter, map notes, full-text backups, paths resolve, palette-note upgrades keep every terrain row), C5 a restart rewrites nothing, C6 paint a blank and a painted hex, undo, reload: same data, C7 registered commands, read-only ones run cleanly, C8 Play refuses a path edit that Build allows (plain-map paint in Play is recorded as a known gap: modes plan Phase 2). Setups: fresh, synthetic 1.5.5, owner real-data copy (seedF + copy of live data.json; skipped when absent), space only, overworld + regions (demo world), legacy neighbours world, custom palette without defaults, everything deleted, 80 maps nested 4 deep, Simple mid-ramp. Stops only its own sandboxes and checks other Obsidian processes are untouched; writes dev/smoke/last-run.json and last-pass.json (gitignored). npm run smoke (WSL hands over to node.exe) and npm run premerge (build, lint, test, integration, smoke; loud banner on failure). tests/smokeSuite.test.ts: the suite's pure helpers + guards for the three fixes it found. CLAUDE.md and README: run premerge before merging into feat/region-notes or deploying to the live vault. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 + CLAUDE.md | 9 + README.md | 5 + dev/smoke/cli.mjs | 32 +++ dev/smoke/lib/compare.mjs | 34 +++ dev/smoke/lib/disk.mjs | 246 +++++++++++++++++++ dev/smoke/lib/obsidian.mjs | 116 +++++++++ dev/smoke/lib/page.mjs | 441 ++++++++++++++++++++++++++++++++++ dev/smoke/premerge.mjs | 39 +++ dev/smoke/run.mjs | 464 ++++++++++++++++++++++++++++++++++++ dev/smoke/setups.mjs | 470 +++++++++++++++++++++++++++++++++++++ package.json | 6 +- tests/smokeSuite.test.ts | 94 ++++++++ 13 files changed, 1956 insertions(+), 2 deletions(-) create mode 100644 dev/smoke/cli.mjs create mode 100644 dev/smoke/lib/compare.mjs create mode 100644 dev/smoke/lib/disk.mjs create mode 100644 dev/smoke/lib/obsidian.mjs create mode 100644 dev/smoke/lib/page.mjs create mode 100644 dev/smoke/premerge.mjs create mode 100644 dev/smoke/run.mjs create mode 100644 dev/smoke/setups.mjs create mode 100644 tests/smokeSuite.test.ts diff --git a/.gitignore b/.gitignore index 67d4652d..9caad149 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,5 @@ data.json .claude/worktrees/* .integration-out/ dev/overworld-preview.js +dev/smoke/last-run.json +dev/smoke/last-pass.json diff --git a/CLAUDE.md b/CLAUDE.md index 20e631b1..e8de8526 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,6 +36,15 @@ Each coding session: **Before copying a build into this folder**, check which branch the current vault build came from — other sessions deploy from their own branches, and a deploy reverts theirs. 3. Use `/rebuild` for a final production build before committing (runs the TypeScript type-check and tests too) +## Before merging or deploying: `npm run premerge` + +**Before merging into `feat/region-notes` (or master) or deploying a build into the live vault, run `npm run premerge`** (from WSL, like every npm script here) and only go ahead when it ends with `PREMERGE PASSED`. It runs build → lint → unit tests → integration tests → the **smoke vault matrix**, stopping loudly at the first failure (owner decision WM5: the matrix runs locally, not in CI; CI keeps the Obsidian-free tests). + +- The matrix (`dev/smoke/run.mjs`, plan [[plan-work-modes]] §3) builds 10 vault setups (fresh install, a synthetic 1.5.5 vault, a copy of the owner's real data `C:/Users/markr/work/tmp/migtest/seedF` + a copy of the live `data.json`, space only, overworld + regions, neighbours world, a custom palette with no default names, everything deleted, 80 maps, Simple mid-ramp), each in its own sandboxed Obsidian (fresh-eyes `sandbox.mjs`, up to 4 at once), and checks: no plugin console errors; settings saved; every map opens and renders; untouched files unchanged on disk (migrations verified separately: map notes, backups, hex data vs the old frontmatter, paths resolve, palette upgrades keep every terrain); a restart rewrites nothing; paint → undo round trip; registered commands; Play refuses a path edit. ~5 minutes, mostly the real-data migration. +- Run parts of it: `npm run smoke -- --only fresh,v155 --jobs 2` (`--list` for the setup ids, `--keep` to keep run folders, `--build ` to test another build). A failed setup keeps its run folder (path in `dev/smoke/last-run.json`); a full pass writes `dev/smoke/last-pass.json` (commit, build hash, per-check results). +- It only stops the sandboxes it started and checks every other Obsidian process is still there (`otherObsidianBefore == otherObsidianAfter`). Never point it at the main vault. +- A new feature with a user-visible write path (paint, paths, a new note type, a migration) should get a smoke check in `dev/smoke/lib/page.mjs` / `setups.mjs` as well as unit tests. + ## Architecture The plugin source is split across `main.ts` (entry point re-export) and modules under `src/`. esbuild bundles everything into `main.js`, which Obsidian loads directly. diff --git a/README.md b/README.md index e80b061d..0702c585 100644 --- a/README.md +++ b/README.md @@ -398,8 +398,13 @@ npm run dev # watch mode — rebuilds main.js on every save npm run build # production build (type-check + bundle) npm run version # bump version (updates manifest.json and versions.json) npm test # run the test suite +npm run test:integration # integration tests +npm run smoke # smoke vault matrix in sandboxed Obsidian (Windows; see below) +npm run premerge # build + lint + tests + integration + smoke: run before merging or deploying ``` +**Before merging into the integration branch or deploying a build into a real vault, run `npm run premerge`** and wait for `PREMERGE PASSED`. The smoke matrix (`dev/smoke/run.mjs`) starts a throwaway, separately profiled Obsidian per vault setup (fresh install, an old 1.5.5 vault, space only, an overworld with regions, neighbour maps, a custom palette, a vault with its folders deleted, 80 maps, Simple level…), up to 4 at once, and checks the plugin loads without errors, every map opens, untouched notes stay byte-identical, a restart rewrites nothing, paint and undo round-trip, and Play mode refuses edits. It needs Windows Obsidian and the fresh-eyes tester's `sandbox.mjs` (set `UX_TOOLS_DIR` if it isn't in the default place); `npm run smoke -- --list` shows the setups and `--only ` runs some of them. Results go to `dev/smoke/last-run.json` (and `last-pass.json` on a full pass). + The built output is `main.js` in the repo root. Obsidian loads this file directly from the plugin folder. **Reload the plugin after a build:** diff --git a/dev/smoke/cli.mjs b/dev/smoke/cli.mjs new file mode 100644 index 00000000..9eeac79d --- /dev/null +++ b/dev/smoke/cli.mjs @@ -0,0 +1,32 @@ +#!/usr/bin/env node +/** + * `npm run smoke` entry: the smoke suite drives Windows Obsidian, so it + * must run under Windows node. On Windows this just runs run.mjs; under + * WSL (where npm runs, see CLAUDE.md) it hands over to node.exe with the + * same arguments and passes its exit code back. + */ +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync, execFileSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const RUN = path.join(HERE, "run.mjs"); +const args = process.argv.slice(2); + +const isWsl = process.platform === "linux" && /microsoft/i.test(fs.readFileSync("/proc/version", "utf8")); +if (process.platform === "win32") { + process.argv = [process.argv[0], RUN, ...args]; + await import(pathToFileURL(RUN).href); +} else if (isWsl) { + const winRun = execFileSync("wslpath", ["-w", RUN], { encoding: "utf8" }).trim(); + const r = spawnSync("node.exe", [winRun, ...args], { stdio: "inherit" }); + if (r.error) { + console.error(`Couldn't start Windows node (node.exe) from WSL: ${r.error.message}. Install Node on Windows, or run: node dev/smoke/run.mjs from a Windows shell.`); + process.exit(2); + } + process.exit(r.status ?? 1); +} else { + console.error("The smoke suite needs Windows Obsidian: run it on Windows or from WSL."); + process.exit(2); +} diff --git a/dev/smoke/lib/compare.mjs b/dev/smoke/lib/compare.mjs new file mode 100644 index 00000000..dd0bcadc --- /dev/null +++ b/dev/smoke/lib/compare.mjs @@ -0,0 +1,34 @@ +/** + * Pure comparison helpers for the smoke suite (unit-tested in + * tests/smokeSuite.test.ts). + */ + +/** Where two JSON values differ: "maps[2].savedViewport.zoom: 1 → 0.8" (first `max`). */ +export function jsonDiff(a, b, at = "", out = [], max = 8) { + if (out.length >= max) return out; + if (JSON.stringify(a) === JSON.stringify(b)) return out; + if (a && b && typeof a === "object" && typeof b === "object" && Array.isArray(a) === Array.isArray(b)) { + for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) jsonDiff(a[k], b[k], Array.isArray(a) ? `${at}[${k}]` : at ? `${at}.${k}` : k, out, max); + } else out.push(`${at || "(root)"}: ${JSON.stringify(a)?.slice(0, 80)} → ${JSON.stringify(b)?.slice(0, 80)}`); + return out; +} + +/** Stable JSON: object keys sorted at every level (store dumps come back in another order after a reload). */ +export function canon(v) { + const sort = (x) => (Array.isArray(x) ? x.map(sort) : x && typeof x === "object" ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, sort(x[k])])) : x); + return JSON.stringify(sort(v)); +} + +/** + * Settings the plugin sets once, on some later start (the "ready for + * more?" check-in, the one-time table-ranges survey): a restart may write + * these to data.json. Anything else it writes is a rewrite. + */ +export const ONE_TIME_KEYS = new Set(["tableRangesPrompt", "advancedNudgeAt"]); + + +/** data.json changed only in ONE_TIME_KEYS (top level). */ +export function oneTimeOnly(a, b) { + const keys = [...new Set(jsonDiff(a, b, "", [], 500).map((s) => s.split(/[.[:]/)[0]))]; + return keys.length > 0 && keys.every((k) => ONE_TIME_KEYS.has(k)); +} diff --git a/dev/smoke/lib/disk.mjs b/dev/smoke/lib/disk.mjs new file mode 100644 index 00000000..8a25a16e --- /dev/null +++ b/dev/smoke/lib/disk.mjs @@ -0,0 +1,246 @@ +/** + * Disk truth for the smoke suite (promoted from the migration runs' + * C:/Users/markr/work/tmp/migtest/disk.mjs). + * + * - snapshot(): content hash + mtime of every vault file that is the user's + * (everything outside .obsidian) plus the plugin's own folder (data.json, + * backups), so "nothing changed" can be checked file by file. + * - legacyTruth(): the map data that pre-map-note hex notes carry in their + * frontmatter, plus a hash of each note's body and non-data keys, to + * verify a migration moved exactly that and touched nothing else. + */ +import fs from "node:fs"; +import path from "node:path"; +import crypto from "node:crypto"; +import zlib from "node:zlib"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); +const YAML = createRequire(path.join(ROOT, "package.json"))("yaml"); + +const BUILD_FILES = new Set(["main.js", "manifest.json", "styles.css"]); +export const DATA_KEYS = ["terrain", "icon", "gm-icons", "gm-icon", "region", "duckmage-submap", "locked"]; +const FM = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/; +const sha = (buf) => crypto.createHash("sha1").update(buf).digest("hex").slice(0, 16); + +/** Vault-relative, forward slashes. */ +const rel = (vault, p) => path.relative(vault, p).split(path.sep).join("/"); + +/** + * { "": { h, m, size } } for the user's files and the plugin's + * folder (minus the three build files). Obsidian's own config (workspace + * layout etc.) is left out: it changes on every start. + */ +export function snapshot(vault, pluginId) { + const out = {}; + const pluginDir = path.join(vault, ".obsidian", "plugins", pluginId); + const walk = (dir) => { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) { + if (dir === vault && (e.name === ".obsidian" || e.name === ".trash")) continue; + walk(p); + } else if (e.isFile()) add(p); + } + }; + const add = (p) => { + const st = fs.statSync(p); + const buf = fs.readFileSync(p); + const entry = { h: sha(buf), m: Math.round(st.mtimeMs), size: st.size }; + // Palette notes keep their text, so a format upgrade can be checked row by row. + if (p.endsWith(".md") && st.size < 512 * 1024) { + const text = buf.toString("utf8"); + if (/^---\r?\n[\s\S]*?hexmaker-palette\s*:/.test(text)) entry.text = text; + } + out[rel(vault, p)] = entry; + }; + walk(vault); + if (fs.existsSync(pluginDir)) { + const walkPlugin = (dir) => { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) walkPlugin(p); + else if (e.isFile() && !(dir === pluginDir && BUILD_FILES.has(e.name))) add(p); + } + }; + walkPlugin(pluginDir); + } + return out; +} + +/** What changed between two snapshots. `touched` = rewritten with the same bytes. */ +export function diff(a, b) { + const added = [], removed = [], changed = [], touched = []; + for (const [p, x] of Object.entries(a)) { + const y = b[p]; + if (!y) removed.push(p); + else if (y.h !== x.h) changed.push(p); + else if (y.m !== x.m) touched.push(p); + } + for (const p of Object.keys(b)) if (!a[p]) added.push(p); + return { added, removed, changed, touched }; +} + +/** Hex data a legacy hex note's frontmatter carries (as MapStore.hexDataFromFrontmatter reads it). */ +export function hexDataFromFm(fm) { + const h = {}; + if (!fm) return h; + if (typeof fm.terrain === "string" && fm.terrain) h.terrain = fm.terrain; + if (typeof fm.icon === "string" && fm.icon) h.icon = fm.icon; + const gm = Array.isArray(fm["gm-icons"]) ? fm["gm-icons"].filter((v) => typeof v === "string") : typeof fm["gm-icon"] === "string" ? [fm["gm-icon"]] : []; + if (gm.length) h.gmIcons = gm; + if (typeof fm.region === "string" && fm.region) h.region = fm.region; + if (typeof fm["duckmage-submap"] === "string" && fm["duckmage-submap"]) h.locations = [fm["duckmage-submap"]]; + if (fm.locked === true || fm.locked === "true") h.locked = true; + return h; +} + +function parseNote(text) { + const mm = FM.exec(text); + let fm = null, err = null; + if (mm) { try { fm = YAML.parse(mm[1]) ?? {}; } catch (e) { err = String(e).slice(0, 80); } } + const body = mm ? text.slice(mm[0].length) : text; + const other = {}; + for (const [k, v] of Object.entries(fm ?? {})) if (!DATA_KEYS.includes(k) && k !== "hexmaker-map") other[k] = v; + return { fm, err, body, other }; +} + +/** + * Pre-migration truth: per map, the hex data in its hex notes; per note, + * hashes of body and non-data frontmatter. Maps are the unique names in + * data.json (first wins, like the plugin). + */ +export function legacyTruth(vault, data) { + const hexFolder = (data.hexFolder ?? "").replace(/^\/+|\/+$/g, ""); + const maps = [...new Set((data.maps ?? data.regions ?? []).map((m) => m.name))]; + const out = { maps: {}, notes: {} }; + for (const m of maps) { + const dir = path.join(vault, hexFolder, m); + out.maps[m] = {}; + if (!fs.existsSync(dir)) continue; + for (const f of fs.readdirSync(dir)) { + if (!/^-?\d+_-?\d+\.md$/.test(f)) continue; + const relPath = `${hexFolder ? hexFolder + "/" : ""}${m}/${f}`; + const text = fs.readFileSync(path.join(dir, f), "utf8"); + const n = parseNote(text); + const h = hexDataFromFm(n.fm); + if (Object.keys(h).length) out.maps[m][f.replace(/\.md$/, "")] = h; + out.notes[relPath] = { text: sha(text), body: sha(n.body), other: sha(JSON.stringify(n.other)), dataKeys: DATA_KEYS.filter((k) => n.fm && k in n.fm), yamlError: n.err }; + } + } + return out; +} + +/** A wikilink or plain name → the bare name ("[[_chult|Chult]]" → "chult"). */ +const bare = (s) => String(s ?? "").replace(/^\[\[|\]\]$/g, "").split("|")[0].split("/").pop().replace(/^_/, "").replace(/\.md$/, "").trim().toLowerCase(); + +/** Compare one hex: legacy truth vs what the store holds now. Returns a problem string or null. */ +function hexDiff(truth, store) { + const s = store ?? {}; + const probs = []; + for (const k of ["terrain", "icon"]) if ((truth[k] ?? null) !== (s[k] ?? null)) probs.push(`${k} ${truth[k]} → ${s[k]}`); + if (JSON.stringify(truth.gmIcons ?? []) !== JSON.stringify(s.gmIcons ?? [])) probs.push(`gmIcons ${truth.gmIcons} → ${s.gmIcons}`); + if (!!truth.locked !== !!s.locked) probs.push(`locked ${truth.locked} → ${s.locked}`); + if (truth.region && bare(truth.region) !== bare(s.region)) probs.push(`region ${truth.region} → ${s.region}`); + if (truth.locations) { + const have = new Set([...(s.locations ?? []), ...(s.regionMap ? [s.regionMap] : [])].map(bare)); + for (const l of truth.locations) if (!have.has(bare(l))) probs.push(`location ${l} missing`); + } + return probs.length ? probs.join("; ") : null; +} + +/** + * After migration: store data matches the truth, every note with data got + * cleaned (data keys gone, map link added), bodies and other keys + * untouched, no hex note created or lost. + */ +export function verifyMigration(vault, truth, store) { + const problems = []; + let hexes = 0, cleaned = 0, bodies = 0; + for (const [m, hs] of Object.entries(truth.maps)) { + for (const [k, h] of Object.entries(hs)) { + hexes++; + const p = hexDiff(h, store[m]?.[k]); + if (p) problems.push(`data ${m}/${k}: ${p}`); + } + for (const k of Object.keys(store[m] ?? {})) { + const s = store[m][k]; + // Only hexes the notes gave data to; a name-only or extra row is new data. + if (!hs[k] && (s.terrain || s.icon || s.gmIcons?.length)) problems.push(`extra hex in store ${m}/${k}: ${JSON.stringify(s)}`); + } + } + for (const [p, t] of Object.entries(truth.notes)) { + const file = path.join(vault, p); + if (!fs.existsSync(file)) { problems.push(`hex note missing: ${p}`); continue; } + const n = parseNote(fs.readFileSync(file, "utf8")); + if (sha(n.body) !== t.body) problems.push(`body changed: ${p}`); else bodies++; + if (sha(JSON.stringify(n.other)) !== t.other) problems.push(`user frontmatter changed: ${p}`); + const left = DATA_KEYS.filter((k) => n.fm && k in n.fm); + if (left.length) problems.push(`data keys left: ${p} ${left}`); + else if (t.dataKeys.length) { + cleaned++; + if (!n.fm?.["hexmaker-map"]) problems.push(`no map link: ${p}`); + } + } + return { hexesChecked: hexes, notesChecked: Object.keys(truth.notes).length, bodiesIdentical: bodies, cleaned, problems }; +} + +/** The migration's full-text backups (*.json.gz) hold each cleaned note exactly as it was. */ +export function verifyBackups(vault, pluginId, seedTexts) { + const bdir = path.join(vault, ".obsidian", "plugins", pluginId, "backups"); + const out = { backupDirs: 0, notes: 0, mismatches: 0, mapJson: 0 }; + if (!fs.existsSync(bdir)) return out; + for (const day of fs.readdirSync(bdir)) { + const d = path.join(bdir, day); + if (!fs.statSync(d).isDirectory()) continue; + out.backupDirs++; + for (const f of fs.readdirSync(d)) { + if (f.endsWith(".json") && !f.includes("hex-notes")) out.mapJson++; + if (!/hex-notes\.json(\.gz)?$/.test(f)) continue; + const buf = fs.readFileSync(path.join(d, f)); + const b = JSON.parse((f.endsWith(".gz") ? zlib.gunzipSync(buf) : buf).toString("utf8")); + for (const [p, text] of Object.entries(b.notes ?? {})) { + out.notes++; + if (seedTexts[p] !== undefined && seedTexts[p] !== sha(text)) out.mismatches++; + } + } + } + return out; +} + +/** note path → hash of its full text (for verifyBackups). */ +export const noteTextHashes = (truth) => Object.fromEntries(Object.entries(truth.notes).map(([p, t]) => [p, t.text])); + +/** A palette note's terrain rows: name → "color|icon|icon color|category|type" (backticks and derived "(…)" cells ignored). */ +export function paletteTerrains(text) { + const out = new Map(); + const lines = text.replace(/\r/g, "").split("\n"); + let cols = null; + for (const line of lines) { + if (!line.startsWith("|")) { if (cols) break; continue; } + const cells = line.slice(1, line.endsWith("|") ? -1 : undefined).split("|").map((c) => c.trim().replace(/^`|`$/g, "")); + if (!cols) { + if (cells[0].toLowerCase() !== "terrain") continue; + cols = cells.map((c) => c.toLowerCase()); + continue; + } + if (/^-+$/.test(cells[0])) continue; + const at = (name) => { const i = cols.indexOf(name); return i >= 0 ? (cells[i] ?? "").toLowerCase() : ""; }; + out.set(cells[0], [at("color"), at("icon"), at("icon color"), at("category"), at("type")].join("|")); + } + return out; +} + +/** Problems when a rewritten palette note lost or changed a terrain (a format upgrade may only add columns). */ +export function verifyPaletteUpgrade(before, after) { + const a = paletteTerrains(before), b = paletteTerrains(after); + const probs = []; + if (!a.size) probs.push("no terrain table before"); + for (const [name, v] of a) { + if (!b.has(name)) probs.push(`terrain "${name}" gone`); + else if (b.get(name) !== v) probs.push(`terrain "${name}": ${v} → ${b.get(name)}`); + } + for (const name of b.keys()) if (!a.has(name)) probs.push(`terrain "${name}" added`); + return probs; +} diff --git a/dev/smoke/lib/obsidian.mjs b/dev/smoke/lib/obsidian.mjs new file mode 100644 index 00000000..92949b54 --- /dev/null +++ b/dev/smoke/lib/obsidian.mjs @@ -0,0 +1,116 @@ +/** + * Sandboxed Obsidian for the smoke suite: wraps the fresh-eyes tester's + * sandbox.mjs (create / launch / stop) and its CDP helpers. + * + * SAFETY: every sandbox lives in its own run folder with its own Electron + * profile; `stop` kills only processes whose command line holds that + * profile path. Before anything runs in a page, the open vault is checked + * to be the run's own vault. + */ +import fs from "node:fs"; +import path from "node:path"; +import { execFile, execFileSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +export const TOOLS_DIR = process.env.UX_TOOLS_DIR + ?? process.env.UX_SANDBOX_DIR + ?? "C:/Users/markr/work/tools/skills-share/ux-testing/fresh-eyes-tester/scripts"; +export const SANDBOX = path.join(TOOLS_DIR, "sandbox.mjs"); + +let commonMod = null; +export async function common() { + if (!commonMod) commonMod = await import(pathToFileURL(path.join(TOOLS_DIR, "lib", "common.mjs")).href); + return commonMod; +} + +export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** Run sandbox.mjs; resolves its stdout (the last JSON object it printed) or rejects with its stderr. */ +function sandbox(args, { timeout = 180_000 } = {}) { + return new Promise((resolve, reject) => { + execFile(process.execPath, [SANDBOX, ...args], { encoding: "utf8", timeout, maxBuffer: 16 << 20 }, (err, stdout, stderr) => { + if (err) { reject(new Error(`sandbox ${args[0]} failed: ${(stderr || err.message).trim().slice(-2000)}`)); return; } + const i = stdout.lastIndexOf("\n{"); + const json = stdout.slice(i >= 0 ? i + 1 : stdout.indexOf("{")); + try { resolve(JSON.parse(json)); } catch { resolve({ raw: stdout }); } + }); + }); +} + +export async function createSandbox({ pluginDir, seed, pluginData, name }) { + const args = ["create", "--plugin-dir", pluginDir, "--name", name]; + if (seed) args.push("--seed", seed); + if (pluginData) args.push("--plugin-data", pluginData); + return sandbox(args); +} + +export const launchSandbox = (runDir) => sandbox(["launch", "--run", runDir, "--width", "1400", "--height", "900"], { timeout: 240_000 }); +export const stopSandbox = (runDir) => sandbox(["stop", "--run", runDir], { timeout: 60_000 }); + +/** + * Every Obsidian.exe process: { pid, main, cmd }. `main` = the browser + * (top) process; helpers carry `--type=`. Counting main processes is + * stable; helper processes come and go on their own. + */ +export function obsidianProcesses() { + const ps = "Get-CimInstance Win32_Process -Filter \"Name='Obsidian.exe'\" | ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; cmd = $_.CommandLine } } | ConvertTo-Json -Compress"; + const out = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ps], { encoding: "utf8" }).trim(); + if (!out) return []; + const list = [].concat(JSON.parse(out)); + return list.map((p) => ({ pid: p.pid, cmd: p.cmd ?? "", main: !/--type=/.test(p.cmd ?? "") })); +} + +/** + * A connected sandbox page with console capture. A fresh CDP session's + * Runtime.enable replays the messages logged before it attached, so errors + * thrown while the plugin loaded (before we connected) are caught too. + */ +export async function connectPage(runDir) { + const c = await common(); + const run = c.readRun(runDir); + const { browser, page } = await c.connect(run); + const base = await c.assertSandboxVault(page, run); + if (!base || !c.samePath(base, run.vault)) { + browser.disconnect(); + throw new Error(`SAFETY: open vault ${base} is not the sandbox vault ${run.vault}`); + } + const log = []; + const session = await page.createCDPSession(); + session.on("Runtime.consoleAPICalled", (e) => { + if (e.type !== "error" && e.type !== "warning" && e.type !== "assert") return; + const text = e.args.map((a) => a.value ?? a.description ?? a.unserializableValue ?? "").join(" "); + const frames = (e.stackTrace?.callFrames ?? []).map((f) => f.url).join(" "); + log.push({ level: e.type === "warning" ? "warning" : "error", text: text.slice(0, 2000), where: frames.slice(0, 500), ts: e.timestamp }); + }); + session.on("Runtime.exceptionThrown", (e) => { + const d = e.exceptionDetails; + const text = d.exception?.description ?? d.text ?? "exception"; + const frames = (d.stackTrace?.callFrames ?? []).map((f) => f.url).join(" ") + " " + (d.url ?? ""); + log.push({ level: "pageerror", text: String(text).slice(0, 2000), where: frames.slice(0, 500), ts: d.timestamp }); + }); + await session.send("Runtime.enable"); + page.setDefaultTimeout(600_000); + return { + run, browser, page, log, + async close() { + try { await session.detach(); } catch { /* gone */ } + browser.disconnect(); + }, + }; +} + +/** Errors that belong to this plugin (its code, its id or its name in the text or stack). */ +export function pluginErrors(log, pluginId) { + const mine = new RegExp(`plugin:${pluginId}|hexmaker|hexmap world creator|duckmage`, "i"); + return log.filter((e) => e.level !== "warning" && (mine.test(e.text) || mine.test(e.where))); +} + +/** Screenshot to the run's shots folder; never throws. */ +export async function shot(page, runDir, name) { + try { + const file = path.join(runDir, "shots", `${name}.png`); + fs.mkdirSync(path.dirname(file), { recursive: true }); + await page.screenshot({ path: file }); + return file; + } catch { return null; } +} diff --git a/dev/smoke/lib/page.mjs b/dev/smoke/lib/page.mjs new file mode 100644 index 00000000..7e918e40 --- /dev/null +++ b/dev/smoke/lib/page.mjs @@ -0,0 +1,441 @@ +/** + * Functions evaluated INSIDE the sandboxed Obsidian (page.evaluate). Each + * must be self-contained: no imports, no closure over module scope; only + * `window.app` and its arguments. They drive the plugin the way its own + * UI does (the map view's mouse handlers, its path tool, its undo), and + * reach into private fields only to pick a tool without clicking through a + * picker modal. + */ + +/** Wait until the plugin's stores are loaded; installs a vault-write tracker. */ +export async function waitReady(id, timeoutMs) { + const t0 = Date.now(); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const app = window.app; + if (!window.__smoke) { + window.__smoke = { lastWrite: Date.now(), writes: [] }; + const note = (kind) => (f, old) => { + window.__smoke.lastWrite = Date.now(); + if (window.__smoke.writes.length < 5000) window.__smoke.writes.push({ kind, path: f.path, old, t: Date.now() }); + }; + for (const k of ["modify", "create", "delete", "rename"]) app.vault.on(k, note(k)); + } + while (Date.now() - t0 < timeoutMs) { + const p = app.plugins.plugins[id]; + if (app.workspace.layoutReady && p?.mapStore?.isReady?.() && p.paletteStore?.isReady?.()) { + return { ready: true, ms: Date.now() - t0 }; + } + await sleep(250); + } + const p = app.plugins.plugins[id]; + return { ready: false, ms: Date.now() - t0, loaded: !!p, mapStore: !!p?.mapStore?.isReady?.(), palettes: !!p?.paletteStore?.isReady?.() }; +} + +/** Wait for `quietMs` with no vault writes (max `maxMs`), flushing the map store. */ +export async function settle(id, quietMs, maxMs) { + const t0 = Date.now(); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const p = window.app.plugins.plugins[id]; + for (;;) { + try { await p?.mapStore?.flush?.(); } catch { /* reported by C1 */ } + const quiet = Date.now() - (window.__smoke?.lastWrite ?? 0); + const busy = [...document.querySelectorAll(".notice")].some((n) => /moving map data|Indexing/i.test(n.textContent ?? "")); + if (quiet >= quietMs && !busy) return { ms: Date.now() - t0, quiet: true }; + if (Date.now() - t0 > maxMs) return { ms: Date.now() - t0, quiet: false }; + await sleep(250); + } +} + +/** Close modals (wizard nudges, prompts) so they don't swallow input. */ +export function closeModals() { + const n = document.querySelectorAll(".modal-container").length; + document.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); + return n; +} + +/** Notices on screen now. */ +export function notices() { + return [...document.querySelectorAll(".notice")].map((n) => (n.textContent ?? "").trim()).filter(Boolean); +} + +/** The plugin's settings as the checks need them. */ +export function state(id) { + const app = window.app; + const p = app.plugins.plugins[id]; + const s = p.settings; + const seen = new Set(); + const maps = s.maps.filter((m) => !seen.has(m.name) && !!seen.add(m.name)).map((m) => ({ + name: m.name, + cols: m.gridSize?.cols, rows: m.gridSize?.rows, + overworld: !!m.regions, + submapKind: m.submapKind ?? null, + parent: m.parent?.map ?? null, + world: m.world ? `${m.world.cx},${m.world.cy}` : null, + workMode: m.workMode ?? null, + paletteName: m.paletteName, + paths: p.mapStore.paths(m.name)?.length ?? 0, + hexes: p.mapStore.all(m.name).size, + broken: !!p.mapStore.broken?.has?.(m.name), + noteExists: !!app.vault.getAbstractFileByPath(p.mapStore.notePath(m.name)), + notePath: p.mapStore.notePath(m.name), + space: !!p.isSpaceMap?.(m.name), + })); + return { + version: p.manifest.version, + featureLevel: s.featureLevel, + advancedFeatures: s.advancedFeatures ?? [], + dismissedHints: s.dismissedHints ?? [], + mapKinds: s.mapKinds, + palettes: s.terrainPalettes.map((x) => x.name), + pathTypes: (s.pathTypes ?? []).length, + defaultMap: s.defaultMap, + setupComplete: !!s.setupComplete, + maps, + mapEntries: s.maps.length, + wizardOpen: app.workspace.getLeavesOfType("duckmage-setup-wizard").length, + commands: Object.keys(app.commands.commands).filter((c) => c.startsWith(id + ":")), + }; +} + +/** Every map's hex data from the store: { map: { "x_y": HexData } }. */ +export function dumpStore(id) { + const p = window.app.plugins.plugins[id]; + const out = {}; + const seen = new Set(); + for (const m of p.settings.maps) { + if (seen.has(m.name)) continue; + seen.add(m.name); + out[m.name] = {}; + for (const [k, h] of p.mapStore.all(m.name)) out[m.name][k] = h; + } + return out; +} + +/** Path counts per map and whether each map's paths resolve to hex chains. */ +export function pathState(id) { + const p = window.app.plugins.plugins[id]; + const out = {}; + const seen = new Set(); + for (const m of p.settings.maps) { + if (seen.has(m.name)) continue; + seen.add(m.name); + const paths = p.mapStore.paths(m.name) ?? []; + let resolved = null; + try { resolved = paths.length ? p.mapStore.resolved(m.name) : []; } catch (e) { resolved = "error: " + e; } + out[m.name] = { paths: paths.length, resolved: Array.isArray(resolved) ? resolved.length : resolved }; + } + return out; +} + +/** + * Open a map in the map view and wait for its hexes to render. + * Returns { ms, hexes, expected, canvas, active }. + */ +export async function openMap(id, name, timeoutMs) { + const app = window.app; + const p = app.plugins.plugins[id]; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const t0 = performance.now(); + await p.showMap(name); + const view = () => app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + let last = -1, stable = 0, hexes = 0; + while (performance.now() - t0 < timeoutMs) { + const v = view(); + const root = v?.containerEl; + hexes = root ? root.querySelectorAll(".duckmage-hex[data-x]").length : 0; + const canvas = root ? root.querySelectorAll("canvas").length : 0; + if (v?.activeMapName === name && (hexes > 0 || canvas > 0)) { + if (hexes === last) stable++; else stable = 0; + if (stable >= 3) break; + } + last = hexes; + await sleep(100); + } + const v = view(); + const m = p.getMap(name); + return { + ms: Math.round(performance.now() - t0), + active: v?.activeMapName ?? null, + hexes, + expected: m ? m.gridSize.cols * m.gridSize.rows : null, + canvas: v?.containerEl?.querySelectorAll("canvas").length ?? 0, + workModeBtn: !!v?.containerEl?.querySelector(".duckmage-work-mode-btn"), + }; +} + +/** Run a command by id; true if it ran (errors land in the console log). */ +export async function runCommand(cmdId) { + const ok = window.app.commands.executeCommandById(cmdId); + await new Promise((r) => setTimeout(r, 600)); + return ok; +} + +/** + * C6 round trip on `name`, through the map view's own mouse handler and + * undo: (a) paint a blank hex, check the map-note row, undo, row gone; + * (b) paint over a painted hex, undo, the old terrain is back; + * (c) reload the store from the note: same data as before. + */ +export async function paintRoundTrip(id, name) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await p.showMap(name); + await sleep(800); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== name) return { ok: false, error: "map view did not open " + name }; + const palette = p.getMapPalette(name).map((t) => t.name); + if (palette.length < 2) return { ok: true, skipped: "palette has fewer than 2 terrains" }; + const notePath = store.notePath(name); + const readNote = async () => ((await app.vault.adapter.exists(notePath)) ? app.vault.adapter.read(notePath) : null); + const rowFor = (text, key) => { + // The Hexes table writes "3_4"; people may write "3, 4". + const [x, y] = key.split("_"); + const re = new RegExp(`^\\|\\s*${x}(?:_|,\\s*)${y}\\s*\\|.*$`, "m"); + return text ? (re.exec(text)?.[0] ?? null) : null; + }; + const hexEls = [...view.containerEl.querySelectorAll(".duckmage-hex[data-x]")]; + const keyOf = (el) => `${el.dataset.x}_${el.dataset.y}`; + const blankEl = hexEls.find((el) => !store.get(name, keyOf(el))); + // Order-free: a reload may list hexes (and fields) in another order. + const canon = () => JSON.stringify([...store.all(name)].map(([k, h]) => [k, Object.fromEntries(Object.entries(h).sort())]).sort((a, b) => (a[0] < b[0] ? -1 : 1))); + const before = canon(); + const textBefore = await readNote(); + const paint = async (el, terrain) => { + view.leaveOtherToolFor?.("terrain"); + view.drawingMode = "terrain"; + view.isErasingMode = false; + view.terrainPickMode = false; + view.paintTerrainName = terrain; + view.paintBrushSize = 1; + el.scrollIntoView?.({ block: "center", inline: "center" }); + const r = el.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + el.dispatchEvent(new MouseEvent("mousedown", at)); + el.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + await view.terrainWritesSettled?.(); + await store.flush(); + }; + const undo = async () => { + await view.undo(); + await view.terrainWritesSettled?.(); + await store.flush(); + }; + const out = { ok: true, steps: [], problems: [] }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + // (a) blank hex + if (!blankEl) out.steps.push("no blank hex on this map"); + else { + const key = keyOf(blankEl); + const t1 = palette[0]; + await paint(blankEl, t1); + const got = store.get(name, key)?.terrain; + if (got !== t1) fail(`paint ${key}: store has ${got}, wanted ${t1}`); + const row = rowFor(await readNote(), key); + if (!row || !row.includes(t1)) fail(`paint ${key}: map note row missing or wrong: ${row}`); + await undo(); + if (store.get(name, key)?.terrain) fail(`undo ${key}: store still has ${store.get(name, key)?.terrain}`); + if (rowFor(await readNote(), key)) fail(`undo ${key}: map note row still there`); + out.steps.push(`blank ${key}: painted ${t1}, undone`); + } + // (b) painted hex: the one painted before, or paint one first (and undo that too) + let paintedEl = hexEls.find((el) => store.get(name, keyOf(el))?.terrain && palette.includes(store.get(name, keyOf(el)).terrain)); + let seeded = false; + if (!paintedEl && blankEl) { + await paint(blankEl, palette[0]); + paintedEl = blankEl; + seeded = true; + } + if (paintedEl) { + const key = keyOf(paintedEl); + const t0 = store.get(name, key).terrain; + const t2 = palette.find((t) => t !== t0); + await paint(paintedEl, t2); + if (store.get(name, key)?.terrain !== t2) fail(`overpaint ${key}: store has ${store.get(name, key)?.terrain}, wanted ${t2}`); + await undo(); + const back = store.get(name, key)?.terrain ?? null; + if (back !== t0) fail(`undo overpaint ${key}: terrain is ${back}, wanted the old ${t0}`); + const row = rowFor(await readNote(), key); + if (back === t0 && (!row || !row.includes(t0))) fail(`undo overpaint ${key}: map note row ${row}`); + out.steps.push(`painted ${key}: ${t0} → ${t2}, undone → ${back}`); + if (seeded) { await undo(); out.steps.push("seed undone"); } + } + view.exitTerrainMode?.(); + view.drawingMode = null; + await store.flush(); + // (c) the note reads back to the same data + await store.reloadFromNotes(); + await sleep(300); + const after = canon(); + if (after !== before) { + const was = new Map(JSON.parse(before)), now = new Map(JSON.parse(after)); + const keys = [...new Set([...was.keys(), ...now.keys()])].filter((k) => JSON.stringify(was.get(k)) !== JSON.stringify(now.get(k))); + fail(`store after undo + reload differs from before: ${keys.slice(0, 5).map((k) => `${k} ${JSON.stringify(was.get(k))} → ${JSON.stringify(now.get(k))}`).join(", ")}`); + } + const textAfter = await readNote(); + out.noteUnchanged = textAfter === textBefore; + return out; +} + +/** + * C8 mode locks on `name` (a plain map): in Play the path tool's edits are + * refused and nothing is written; in Build the same edit goes through and + * undoes. Also records whether terrain paint is locked in Play (it isn't + * yet: the modes plan's later phases). + */ +export async function modeLocks(id, name) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await p.showMap(name); + await sleep(600); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== name) return { ok: false, problems: ["map view did not open " + name] }; + const out = { ok: true, problems: [], steps: [], gaps: [] }; + const fail = (m) => { out.ok = false; out.problems.push(m); }; + const map = p.getMap(name); + const startMode = map.workMode; + const notePath = store.notePath(name); + const readNote = async () => ((await app.vault.adapter.exists(notePath)) ? app.vault.adapter.read(notePath) : null); + const types = p.getMapPathTypes(name); + const cols = map.gridSize.cols, rows = map.gridSize.rows; + // Candidate start/end hexes: a route may be refused (impassable ends, + // no way round), so Build tries a few pairs and Play reuses the one that drew. + const ox = map.gridOffset.x, oy = map.gridOffset.y; + const at = (fx, fy) => `${ox + Math.min(cols - 1, Math.max(0, Math.round(fx * (cols - 1))))}_${oy + Math.min(rows - 1, Math.max(0, Math.round(fy * (rows - 1))))}`; + const pairs = [[at(0.2, 0.2), at(0.5, 0.4)], [at(0.5, 0.5), at(0.7, 0.6)], [at(0.1, 0.8), at(0.3, 0.8)], [at(0.8, 0.2), at(0.8, 0.4)], [at(0.4, 0.1), at(0.6, 0.1)], [at(0, 0), at(0.2, 0)]] + .filter(([a, b]) => a !== b); + const draw = async ([a, b]) => { + const tool = view.pathTool; + tool.reset(); + tool.setType(types[0].name); + for (const k of [a, b]) { + const [x, y] = k.split("_").map(Number); + tool.click(x, y, undefined, false); + await sleep(50); + } + tool.done(); + await store.flush(); + await sleep(200); + }; + const pathsJson = () => JSON.stringify(store.paths(name)); + try { + if (!types.length) out.steps.push("no path types: path lock not tested"); + else { + // Build: a path draws and undoes (so the lock isn't simply everything). + view.setWorkMode("build"); + await store.flush(); + await sleep(300); + const b0 = pathsJson(); + let drawn = null; + for (const pair of pairs) { + await draw(pair); + if (pathsJson() !== b0) { drawn = pair; break; } + } + if (!drawn) fail(`Build: no path could be drawn (tried ${pairs.map((x) => x.join("→")).join(", ")})`); + else { + await view.undo(); + await store.flush(); + await sleep(200); + if (pathsJson() !== b0) fail("Build: undo didn't remove the drawn path"); + out.steps.push(`build: path ${drawn.join("→")} drawn and undone`); + // Play: the same edit is refused and nothing is written. + view.setWorkMode("play"); + await store.flush(); + await sleep(300); + const before = pathsJson(), text = await readNote(); + await draw(drawn); + if (pathsJson() !== before) fail("Play: a path was drawn"); + if ((await readNote()) !== text) fail("Play: the map note changed after a refused path edit"); + else out.steps.push("play: the same path edit refused, map note unchanged"); + } + } + // Play + terrain paint on a plain map: not locked yet (recorded, not failed). + view.setWorkMode("play"); + await sleep(200); + const hexEl = view.containerEl.querySelector(".duckmage-hex[data-x]"); + if (hexEl) { + const key = `${hexEl.dataset.x}_${hexEl.dataset.y}`; + const before = JSON.stringify(store.get(name, key) ?? null); + const terrain = p.getMapPalette(name).map((t) => t.name).find((t) => t !== store.get(name, key)?.terrain); + if (terrain) { + view.leaveOtherToolFor?.("terrain"); + view.drawingMode = "terrain"; + view.isErasingMode = false; + view.terrainPickMode = false; + view.paintTerrainName = terrain; + view.paintBrushSize = 1; + const r = hexEl.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + hexEl.dispatchEvent(new MouseEvent("mousedown", at)); + hexEl.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + await view.terrainWritesSettled?.(); + const changed = JSON.stringify(store.get(name, key) ?? null) !== before; + if (changed) { + out.gaps.push("Play doesn't lock terrain paint on a plain map yet (modes plan, Phase 2)"); + view.setWorkMode("build"); + await view.undo(); + await view.terrainWritesSettled?.(); + } else out.steps.push("play: terrain paint refused"); + view.exitTerrainMode?.(); + view.drawingMode = null; + } + } + } finally { + view.setWorkMode(startMode === "god" || startMode === "play" ? startMode : "build"); + + await store.flush(); + } + return out; +} + +/** + * Overworld paint lock: in Play, the terrain brush over the Regions view + * is refused (Notice) and no region's data changes. + */ +export async function overworldPaintLock(id, name) { + const app = window.app; + const p = app.plugins.plugins[id]; + const store = p.mapStore; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + await p.showMap(name); + await sleep(1500); + const view = app.workspace.getLeavesOfType("duckmage-hex-map")[0]?.view; + if (!view || view.activeMapName !== name) return { ok: false, problems: ["overworld did not open"] }; + const all = () => JSON.stringify(p.settings.maps.map((m) => [m.name, [...store.all(m.name)]])); + const startMode = p.getMap(name).workMode; + const out = { ok: true, problems: [], steps: [] }; + try { + view.setWorkMode("play"); + await store.flush(); + await sleep(300); + const before = all(); + view.showOverworldRegions?.(); + await sleep(800); + view.leaveOtherToolFor?.("terrain"); + view.drawingMode = "terrain"; + view.paintTerrainName = p.getMapPalette(name)[0]?.name ?? null; + const shown = view.overworldLayer?.showsRegions?.(view.getActiveMap?.()); + const box = view.containerEl.querySelector(".duckmage-hex-map-clip") ?? view.containerEl; + const r = box.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + const n0 = document.querySelectorAll(".notice").length; + box.dispatchEvent(new MouseEvent("mousedown", at)); + box.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + await sleep(400); + await store.flush(); + const said = [...document.querySelectorAll(".notice")].slice(n0).map((n) => n.textContent); + if (all() !== before) { out.ok = false; out.problems.push("Play: overworld paint changed region data"); } + out.steps.push(`regions view shown: ${shown}; notice: ${said.join(" | ") || "(none)"}`); + if (shown && !said.some((t) => /Switch to Build/i.test(t ?? ""))) { out.ok = false; out.problems.push("Play: no locked-paint notice"); } + view.exitTerrainMode?.(); + view.drawingMode = null; + } finally { + view.setWorkMode(startMode === "god" || startMode === "play" ? startMode : "build"); + + await store.flush(); + } + return out; +} diff --git a/dev/smoke/premerge.mjs b/dev/smoke/premerge.mjs new file mode 100644 index 00000000..44c7b0ff --- /dev/null +++ b/dev/smoke/premerge.mjs @@ -0,0 +1,39 @@ +#!/usr/bin/env node +/** + * `npm run premerge`: everything that must pass before merging into + * feat/region-notes or deploying a build into the live vault (owner + * decision WM5). Runs, in order, stopping at the first failure: + * build, lint, unit tests, integration tests, the smoke vault matrix + * (on the build just made: --no-build). + * Extra arguments go to the smoke suite (e.g. --only fresh,v155 --jobs 2). + * Run it where npm works for this repo (WSL; see CLAUDE.md). + */ +import { spawnSync } from "node:child_process"; + +const smokeArgs = process.argv.slice(2); +const npm = process.platform === "win32" ? "npm.cmd" : "npm"; +const steps = [ + ["build", npm, ["run", "build"]], + ["lint", npm, ["run", "lint"]], + ["unit tests", npm, ["test"]], + ["integration tests", npm, ["run", "test:integration"]], + ["smoke vault matrix", process.execPath, ["dev/smoke/cli.mjs", "--no-build", ...smokeArgs]], +]; + +const banner = (lines) => { + const w = Math.max(...lines.map((l) => l.length)) + 4; + console.log("\n" + "#".repeat(w)); + for (const l of lines) console.log(`# ${l.padEnd(w - 4)} #`); + console.log("#".repeat(w) + "\n"); +}; + +const t0 = Date.now(); +for (const [name, cmd, args] of steps) { + console.log(`\n=== premerge: ${name} ===`); + const r = spawnSync(cmd, args, { stdio: "inherit", shell: process.platform === "win32" }); + if (r.status !== 0) { + banner([`PREMERGE FAILED at: ${name} (exit ${r.status ?? r.signal ?? r.error?.message})`, "Do NOT merge into feat/region-notes or deploy to the live vault."]); + process.exit(1); + } +} +banner([`PREMERGE PASSED in ${Math.round((Date.now() - t0) / 1000)} s`, "Stamp: dev/smoke/last-pass.json"]); diff --git a/dev/smoke/run.mjs b/dev/smoke/run.mjs new file mode 100644 index 00000000..879a3c7d --- /dev/null +++ b/dev/smoke/run.mjs @@ -0,0 +1,464 @@ +#!/usr/bin/env node +/** + * Smoke-test vault matrix (plan-work-modes §3; owner decision WM5: run it + * LOCALLY before merging into feat/region-notes and before any live-vault + * deploy; CI keeps the Obsidian-free tests). + * + * node dev/smoke/run.mjs [--jobs 4] [--only fresh,v155] [--build ] [--no-build] [--keep] [--list] + * + * Windows node (Obsidian is a Windows app). From WSL use `npm run smoke`, + * which hands over to node.exe (dev/smoke/cli.mjs). + * + * 1. Builds the plugin through WSL (or takes --build , or the repo's + * current main.js with --no-build) and snapshots main.js / manifest.json / + * styles.css into a temp folder, so a running `npm run dev` can't change + * the plugin mid-suite. + * 2. Per vault setup (setups.mjs): builds the fixture, `sandbox.mjs create` + * (own vault + Electron profile), optionally a prep launch that builds + * maps through the plugin API, then a check launch running C1–C8, then a + * restart launch for C5. At most --jobs sandboxes at once (max 4). + * 3. Stops every sandbox it started and checks no other Obsidian was + * touched (main-process count and pids before == after). + * 4. Writes dev/smoke/last-run.json, and dev/smoke/last-pass.json when + * every setup passed: { commit, dirty, buildHash, setups, results }. + * + * Never touches the main vault: fixtures are generated or copied into the + * sandbox's own run folder; the open vault is checked before any script runs. + */ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import crypto from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { + common, createSandbox, launchSandbox, stopSandbox, connectPage, obsidianProcesses, pluginErrors, shot, sleep, +} from "./lib/obsidian.mjs"; +import { snapshot, diff, legacyTruth, verifyMigration, verifyBackups, noteTextHashes, verifyPaletteUpgrade } from "./lib/disk.mjs"; +import * as P from "./lib/page.mjs"; +import { canon, jsonDiff, oneTimeOnly } from "./lib/compare.mjs"; +import { SETUPS } from "./setups.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, "..", ".."); +const PLUGIN_FILES = ["main.js", "manifest.json", "styles.css"]; + +// ── args ────────────────────────────────────────────────────────────────── +const argv = process.argv.slice(2); +const flag = (k) => argv.includes(`--${k}`); +const val = (k, d) => { const i = argv.indexOf(`--${k}`); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : d; }; +if (flag("help") || flag("h")) { + console.log("usage: node dev/smoke/run.mjs [--jobs 4] [--only a,b] [--build ] [--no-build] [--keep] [--list]"); + process.exit(0); +} +if (flag("list")) { + for (const s of SETUPS) console.log(`${s.id.padEnd(16)} ${s.title}`); + process.exit(0); +} +if (process.platform !== "win32") { + console.error("dev/smoke/run.mjs drives Windows Obsidian: run it with Windows node, or `npm run smoke` from WSL."); + process.exit(2); +} +const jobs = Math.max(1, Math.min(4, Number(val("jobs", "4")) || 4)); +const only = val("only", null)?.split(",").map((s) => s.trim()).filter(Boolean) ?? null; +if (only) { + const unknown = only.filter((o) => !SETUPS.some((s) => s.id === o)); + if (unknown.length) { console.error(`unknown setup(s): ${unknown.join(", ")} (see --list)`); process.exit(2); } +} +const keep = flag("keep"); + +const log = (...a) => console.log(`[smoke ${new Date().toISOString().slice(11, 19)}]`, ...a); +const git = (...a) => { try { return execFileSync("git", ["-C", ROOT, ...a], { encoding: "utf8" }).trim(); } catch { return null; } }; +const toWsl = (p) => path.resolve(p).replace(/^([A-Za-z]):/, (_, d) => `/mnt/${d.toLowerCase()}`).replace(/\\/g, "/"); + +// ── 1. build + snapshot ─────────────────────────────────────────────────── +const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..*/, "").replace("T", "-"); +const work = path.join(os.tmpdir(), "hexmaker-smoke", stamp); +fs.mkdirSync(work, { recursive: true }); +let source = val("build", null); +if (!source) { + source = ROOT; + if (!flag("no-build")) { + log("building (npm run build through WSL)…"); + execFileSync("wsl.exe", ["-e", "bash", "-lc", `cd '${toWsl(ROOT)}' && npm run build`], { stdio: "inherit", env: { ...process.env, MSYS_NO_PATHCONV: "1" } }); + } +} +const buildDir = path.join(work, "build"); +fs.mkdirSync(buildDir); +const hash = crypto.createHash("sha256"); +for (const f of PLUGIN_FILES) { + const s = path.join(source, f); + if (!fs.existsSync(s)) { if (f === "styles.css") continue; console.error(`${f} missing in ${source}`); process.exit(2); } + const buf = fs.readFileSync(s); + hash.update(f).update(buf); + fs.writeFileSync(path.join(buildDir, f), buf); +} +const buildHash = hash.digest("hex").slice(0, 16); +const manifest = JSON.parse(fs.readFileSync(path.join(buildDir, "manifest.json"), "utf8")); +const pluginId = manifest.id; +const mainJs = fs.readFileSync(path.join(buildDir, "main.js"), "utf8"); +const expectedCommands = [...new Set([...mainJs.matchAll(/addCommand\(\{\s*id:\s*"([^"]+)"/g)].map((m) => `${pluginId}:${m[1]}`))]; +log(`build ${buildHash} (${manifest.version}) from ${source}; ${expectedCommands.length} commands`); + +// ── 2. the matrix ───────────────────────────────────────────────────────── +const selected = SETUPS.filter((s) => !only || only.includes(s.id)).sort((a, b) => Number(!!b.slow) - Number(!!a.slow)); +const started = []; // { runDir, profile } +const procsBefore = obsidianProcesses(); +// sandbox.mjs points runs/LATEST at each run it makes; put the owner's back afterwards. +const latestFile = (await common()).LATEST_FILE; +const latestBefore = fs.existsSync(latestFile) ? fs.readFileSync(latestFile, "utf8") : null; + +/** Read-only commands run in C7 (open views; change nothing on disk). */ +const READ_ONLY = ["open-hex-map", "open-hex-table", "open-random-tables"]; +const ERROR_NOTICE = /couldn't|could not|error|failed|unreadable|can't read/i; + +/** data.json, read again if it is caught mid-write (empty or half written). */ +async function readJson(file) { + for (let i = 0; ; i++) { + if (!fs.existsSync(file)) return null; + try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { if (i >= 20) throw e; await sleep(250); } + } +} + +async function runSetup(setup) { + const why = setup.unavailable?.(); + if (why) { + log(`${setup.id}: SKIPPED (${why})`); + return { id: setup.id, title: setup.title, ok: true, skipped: why, seconds: 0, runDir: null, checks: [] }; + } + const t0 = Date.now(); + const checks = []; + const rec = (check, ok, detail = "", extra = {}) => { + checks.push({ check, ok: !!ok, detail: String(detail).slice(0, 4000), ...extra }); + if (!ok) log(`${setup.id}: FAIL ${check}: ${String(detail).slice(0, 300)}`); + }; + const dir = path.join(work, setup.id); + fs.mkdirSync(dir, { recursive: true }); + let runDir = null, vault = null, sess = null; + const ev = (fn, ...args) => sess.page.evaluate(fn, ...args); + const stop = async () => { + if (sess) { await sess.close().catch(() => {}); sess = null; } + if (runDir) { + const r = await stopSandbox(runDir); + if (!r.ok) rec("stop", false, JSON.stringify(r)); + return r; + } + }; + const launch = async () => { + await launchSandbox(runDir); + sess = await connectPage(runDir); + // Expose the page helpers to setup extras (one object, re-sent per launch). + await sess.page.evaluate(`window.__smokePage = { ${Object.entries(P).map(([k, f]) => `${k}: ${f.toString()}`).join(",\n")} };`); + }; + try { + log(`${setup.id}: building fixture`); + const fx = await setup.build(dir); + const created = await createSandbox({ pluginDir: buildDir, seed: fx.seed, pluginData: fx.pluginData, name: `smoke-${setup.id}` }); + runDir = created.runDir; + vault = created.vault; + started.push({ runDir, profile: path.join(runDir, "profile") }); + log(`${setup.id}: sandbox ${runDir}`); + + // ── prep launch (recipe) ── + if (setup.recipe) { + await launch(); + const r = await ev(P.waitReady, pluginId, 120_000); + if (!r.ready) throw new Error(`prep: plugin not ready ${JSON.stringify(r)}`); + const info = await ev(setup.recipe, pluginId); + await ev(P.settle, pluginId, 2500, 120_000); + const errs = pluginErrors(sess.log, pluginId); + rec("prep", errs.length === 0, errs.length ? errs.map((e) => e.text).join(" || ") : JSON.stringify(info).slice(0, 600)); + await stop(); + if (setup.postPrep) setup.postPrep(vault, info, pluginId); + } + + // ── inputs, before the check launch ── + const dataFile = path.join(vault, ".obsidian", "plugins", pluginId, "data.json"); + const dataIn = await readJson(dataFile); + const truth = setup.migration ? legacyTruth(vault, dataIn) : null; + const snap0 = snapshot(vault, pluginId); + + // ── check launch ── + await launch(); + const ready = await ev(P.waitReady, pluginId, setup.expect.readyMs ?? 120_000); + rec("C1-ready", ready.ready, `stores ready in ${ready.ms} ms`, { ms: ready.ms }); + if (!ready.ready) throw new Error("plugin never became ready"); + await ev(P.settle, pluginId, 3000, setup.expect.readyMs ?? 120_000); + let state = await ev(P.state, pluginId); + const wizardAtLoad = state.wizardOpen; + + // C2: settings resolved and saved; nothing in data.json lost. + { + const disk = await readJson(dataFile); + const probs = []; + if (!disk) probs.push("no data.json written"); + else { + if (disk.featureLevel === undefined) probs.push("featureLevel not saved"); + if (setup.expect.level && state.featureLevel !== setup.expect.level) probs.push(`level ${state.featureLevel}, expected ${setup.expect.level}`); + if (setup.expect.level && disk.featureLevel !== setup.expect.level) probs.push(`saved level ${disk.featureLevel}, expected ${setup.expect.level}`); + const renamed = { regions: "maps", defaultRegion: "defaultMap" }; + const lost = Object.keys(dataIn ?? {}).filter((k) => !(k in disk) && !(renamed[k] && renamed[k] in disk)); + if (lost.length) probs.push(`keys lost from data.json: ${lost.join(", ")}`); + const inMaps = new Set((dataIn?.maps ?? dataIn?.regions ?? []).map((m) => m.name)); + const outMaps = new Set((disk.maps ?? []).map((m) => m.name)); + const goneMaps = [...inMaps].filter((m) => !outMaps.has(m)); + if (goneMaps.length) probs.push(`maps lost from data.json: ${goneMaps.join(", ")}`); + } + rec("C2-settings", probs.length === 0, probs.join("; ") || `level ${state.featureLevel}, ${state.maps.length} maps, palettes ${state.palettes.length}, kinds ${state.mapKinds}`); + } + + // C3: every map opens and renders. + const opens = []; + let firstOpen = null; + { + const budget = setup.expect.openMs ?? 20_000; + const probs = []; + for (const m of state.maps) { + const r = await ev(P.openMap, pluginId, m.name, budget + 5000); + firstOpen ??= r; + opens.push({ map: m.name, ...r }); + if (r.active !== m.name) probs.push(`${m.name}: view shows ${r.active}`); + else if (m.broken) probs.push(`${m.name}: map note unreadable`); + else if (r.hexes === 0 && r.canvas === 0) probs.push(`${m.name}: nothing rendered`); + else if (!m.overworld && r.hexes !== r.expected) probs.push(`${m.name}: ${r.hexes} hexes, expected ${r.expected}`); + if (r.ms > budget) probs.push(`${m.name}: ${r.ms} ms > ${budget} ms`); + } + const slow = opens.slice().sort((a, b) => b.ms - a.ms)[0]; + rec("C3-maps-open", probs.length === 0 && opens.length > 0, probs.join("; ") || `${opens.length} maps opened; slowest ${slow?.map} ${slow?.ms} ms`, { opens: opens.map((o) => [o.map, o.ms, o.hexes]) }); + } + await ev(P.settle, pluginId, 2500, 60_000); + + // C4: untouched data unchanged on disk (migration rewrites checked separately). + const snap1 = snapshot(vault, pluginId); + { + const d = diff(snap0, snap1); + const pluginRel = `.obsidian/plugins/${pluginId}/`; + const migrated = new Set(truth ? Object.entries(truth.notes).filter(([, t]) => t.dataKeys.length).map(([p]) => p) : []); + // Palette notes in an older format are upgraded on load (new columns, + // the Path types table): allowed when every terrain row is unchanged. + const upgraded = [], paletteProbs = []; + for (const p of d.changed) { + if (snap0[p]?.text === undefined) continue; + const probs = verifyPaletteUpgrade(snap0[p].text, fs.readFileSync(path.join(vault, p), "utf8")); + if (probs.length) paletteProbs.push(`${p}: ${probs.slice(0, 4).join(", ")}`); else upgraded.push(p); + } + if (upgraded.length || paletteProbs.length) rec("M-palettes", paletteProbs.length === 0, paletteProbs.join("; ") || `${upgraded.length} palette notes upgraded, every terrain row kept: ${upgraded.join(", ")}`); + const allowed = (p) => p === `${pluginRel}data.json` || migrated.has(p) || upgraded.includes(p); + const changed = d.changed.filter((p) => !allowed(p)); + // A backup rewritten with the same bytes loses nothing; other bytes would ("changed"). + const touched = d.touched.filter((p) => !allowed(p) && !p.startsWith(`${pluginRel}backups/`)); + const removed = d.removed.filter((p) => !allowed(p)); + const ok = changed.length === 0 && removed.length === 0 && touched.length === 0; + rec("C4-untouched", ok, + ok ? `${Object.keys(snap0).length} files unchanged; ${d.added.length} new (${d.added.slice(0, 6).join(", ")}${d.added.length > 6 ? ", …" : ""}); ${migrated.size} migrated notes checked below` + : `changed: ${changed.slice(0, 15).join(", ")}${changed.length > 15 ? ` (+${changed.length - 15})` : ""}; rewritten same bytes: ${touched.slice(0, 15).join(", ")}${touched.length > 15 ? ` (+${touched.length - 15})` : ""}; removed: ${removed.slice(0, 15).join(", ")}`, + { added: d.added.length, changed: changed.length, touched: touched.length, removed: removed.length }); + } + + // Migration: map notes written, data moved exactly, backups, paths. + if (truth) { + const store = await ev(P.dumpStore, pluginId); + const vm = verifyMigration(vault, truth, store); + rec("M-data", vm.problems.length === 0, vm.problems.length ? vm.problems.slice(0, 12).join("; ") : `${vm.hexesChecked} hexes match, ${vm.cleaned} notes cleaned, ${vm.bodiesIdentical}/${vm.notesChecked} bodies identical`); + const hexFolder = (dataIn.hexFolder ?? "").replace(/^\/+|\/+$/g, ""); + const noteProbs = []; + for (const m of Object.keys(truth.maps)) { + const np = path.join(vault, hexFolder, m, `_${m}.md`); + if (!fs.existsSync(np)) { noteProbs.push(`${m}: no map note`); continue; } + const head = fs.readFileSync(np, "utf8").slice(0, 400); + if (!/hexmaker-map:\s*\d+/.test(head)) noteProbs.push(`${m}: map note has no hexmaker-map format`); + } + rec("M-map-notes", noteProbs.length === 0, noteProbs.join("; ") || `${Object.keys(truth.maps).length} map notes written`); + const cleanedCount = Object.values(truth.notes).filter((t) => t.dataKeys.length).length; + const b = verifyBackups(vault, pluginId, noteTextHashes(truth)); + rec("M-backups", b.mismatches === 0 && b.notes >= cleanedCount && b.backupDirs > 0, `${b.notes} notes backed up (needed ${cleanedCount}), ${b.mismatches} mismatches, ${b.mapJson} map backups`); + const ps = await ev(P.pathState, pluginId); + const pathProbs = []; + let chains = 0, paths = 0; + for (const m of dataIn.maps ?? []) { + if (!(m.pathChains ?? []).some((c) => (c.hexes ?? []).length > 1)) continue; + chains += m.pathChains.length; + const s = ps[m.name]; + if (!s || s.paths === 0) pathProbs.push(`${m.name}: no paths after migration`); + else if (typeof s.resolved !== "number" || s.resolved === 0) pathProbs.push(`${m.name}: paths don't resolve (${s.resolved})`); + paths += s?.paths ?? 0; + } + rec("M-paths", pathProbs.length === 0, pathProbs.join("; ") || `${chains} legacy chains → ${paths} paths, all resolve`); + } + + // C7: registered commands; read-only ones run cleanly. + { + state = await ev(P.state, pluginId); + const missing = expectedCommands.filter((c) => !state.commands.includes(c)); + const errBefore = pluginErrors(sess.log, pluginId).length; + const ran = []; + for (const c of READ_ONLY) { + const id = `${pluginId}:${c}`; + if (!state.commands.includes(id)) continue; + ran.push(`${c}: ${await ev(P.runCommand, id)}`); + await ev(P.closeModals); + } + await sleep(500); + const errs = pluginErrors(sess.log, pluginId).slice(errBefore); + rec("C7-commands", missing.length === 0 && errs.length === 0, `${state.commands.length}/${expectedCommands.length} registered${missing.length ? `; missing ${missing.join(", ")}` : ""}; ran ${ran.join(", ")}${errs.length ? `; errors: ${errs.map((e) => e.text).join(" || ")}` : ""}`); + } + + // Setup-specific checks. + if (setup.extra) { + const ctx = { pluginId, state, ev, log: sess.log, readyMs: ready.ms, firstOpen, wizardAtLoad, runDir, vault, snap0 }; + for (const c of await setup.extra(ctx)) rec(c.check, c.ok, c.detail); + state = await ev(P.state, pluginId); + } + + // C6 + C8 on the smallest plain map. + const plain = state.maps.filter((m) => !m.overworld && m.cols * m.rows > 0).sort((a, b) => a.cols * a.rows - b.cols * b.rows); + const target = plain.find((m) => m.hexes > 0) ?? plain[0]; + if (!target) rec("C6-paint", false, "no plain map to paint on"); + else { + const r = await ev(P.paintRoundTrip, pluginId, target.name); + rec("C6-paint", r.ok, `${target.name}: ${[...(r.steps ?? []), ...(r.problems ?? []), r.skipped ?? "", r.error ?? ""].filter(Boolean).join("; ")}${r.noteUnchanged === false ? "; map note text differs after undo (data same)" : ""}`); + if (!setup.skipModeLocks) { + const l = await ev(P.modeLocks, pluginId, target.name); + rec("C8-mode-locks", l.ok, `${target.name}: ${[...l.steps, ...l.problems].join("; ")}`, { gaps: l.gaps }); + for (const g of l.gaps ?? []) checks.push({ check: "C8-gap", ok: true, gap: true, detail: g }); + } + } + + // C1: no plugin errors, no error notices, over the whole check launch. + { + const errs = pluginErrors(sess.log, pluginId); + const others = sess.log.filter((e) => e.level !== "warning" && !errs.includes(e)); + const ns = (await ev(P.notices)).filter((n) => ERROR_NOTICE.test(n)); + rec("C1-no-errors", errs.length === 0 && ns.length === 0, + `${errs.length} plugin errors${errs.length ? ": " + errs.slice(0, 5).map((e) => e.text.split("\n")[0]).join(" || ") : ""}; error notices: ${ns.join(" | ") || "none"}; other console errors (not the plugin's): ${others.length}`, + { pluginErrors: errs.slice(0, 20), otherErrors: others.slice(0, 10).map((e) => e.text.slice(0, 300)) }); + } + + // ── C5: restart rewrites nothing ── + const storeBefore = canon(await ev(P.dumpStore, pluginId)); + const levelBefore = state.featureLevel; + await ev(P.settle, pluginId, 3000, 60_000); + await stop(); + const snapA = snapshot(vault, pluginId); + const dataA = await readJson(dataFile); + await launch(); + const r2 = await ev(P.waitReady, pluginId, setup.expect.readyMs ?? 120_000); + await ev(P.settle, pluginId, 4000, 90_000); + const storeAfter = canon(await ev(P.dumpStore, pluginId)); + const state2 = await ev(P.state, pluginId); + const errs2 = pluginErrors(sess.log, pluginId); + await stop(); + const snapB = snapshot(vault, pluginId); + const dataB = await readJson(dataFile); + { + const d = diff(snapA, snapB); + const probs = []; + if (!r2.ready) probs.push("not ready after restart"); + const dataRel = `.obsidian/plugins/${pluginId}/data.json`; + const dataOneTime = d.changed.includes(dataRel) && oneTimeOnly(dataA, dataB); + const changed = dataOneTime ? d.changed.filter((p) => p !== dataRel) : d.changed; + if (changed.length) probs.push(`changed: ${changed.slice(0, 12).join(", ")}`); + if (changed.includes(dataRel)) probs.push(`data.json: ${jsonDiff(dataA, dataB).join("; ")}`); + if (dataOneTime) checks.push({ check: "C5-one-time", ok: true, detail: `data.json one-time settings written on restart: ${jsonDiff(dataA, dataB).join("; ")}` }); + if (d.touched.length) probs.push(`rewritten same bytes: ${d.touched.slice(0, 12).join(", ")}`); + if (d.added.length) probs.push(`new: ${d.added.slice(0, 12).join(", ")}`); + if (d.removed.length) probs.push(`removed: ${d.removed.slice(0, 12).join(", ")}`); + if (storeAfter !== storeBefore) probs.push(`map data differs after restart: ${jsonDiff(JSON.parse(storeBefore), JSON.parse(storeAfter)).join("; ")}`); + if (state2.featureLevel !== levelBefore) probs.push(`level ${levelBefore} → ${state2.featureLevel}`); + if (errs2.length) probs.push(`plugin errors: ${errs2.slice(0, 3).map((e) => e.text.split("\n")[0]).join(" || ")}`); + rec("C5-restart", probs.length === 0, probs.join("; ") || `0 files rewritten, map data and level the same (ready ${r2.ms} ms)`); + } + } catch (e) { + rec("crash", false, e.stack ?? String(e)); + if (sess) await shot(sess.page, runDir, `${setup.id}-crash`); + } finally { + try { await stop(); } catch (e) { rec("stop", false, String(e)); } + } + const ok = checks.every((c) => c.ok); + log(`${setup.id}: ${ok ? "PASS" : "FAIL"} in ${Math.round((Date.now() - t0) / 1000)} s`); + return { id: setup.id, title: setup.title, ok, seconds: Math.round((Date.now() - t0) / 1000), runDir, checks }; +} + +async function pool(items, n, fn) { + const out = new Array(items.length); + let next = 0; + const worker = async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]); } }; + await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker)); + return out; +} + +const t0 = Date.now(); +log(`${selected.length} setups, ${jobs} at a time: ${selected.map((s) => s.id).join(", ")}`); +let results; +const onSignal = async () => { + log("interrupted: stopping sandboxes"); + for (const s of started) await stopSandbox(s.runDir).catch(() => {}); + process.exit(130); +}; +process.on("SIGINT", onSignal); +try { + results = await pool(selected, jobs, runSetup); +} finally { + // Belt and braces: every run stopped (stop is idempotent). + for (const s of started) await stopSandbox(s.runDir).catch(() => {}); +} + +if (latestBefore !== null) fs.writeFileSync(latestFile, latestBefore); + +// ── 3. other Obsidian processes untouched ──────────────────────────────── +await sleep(1000); +const procsAfter = obsidianProcesses(); +const mineProfiles = started.map((s) => s.profile.toLowerCase()); +const isMine = (p) => mineProfiles.some((m) => p.cmd.toLowerCase().includes(m)); +const otherBefore = procsBefore.filter((p) => p.main && !isMine(p)); +const otherAfter = procsAfter.filter((p) => p.main && !isMine(p)); +const leftMine = procsAfter.filter(isMine); +const vanished = otherBefore.filter((p) => !procsAfter.some((q) => q.pid === p.pid)); +const safety = { + otherObsidianBefore: otherBefore.length, + otherObsidianAfter: otherAfter.length, + otherPidsBefore: otherBefore.map((p) => p.pid), + otherPidsAfter: otherAfter.map((p) => p.pid), + vanished: vanished.map((p) => p.pid), + sandboxProcessesLeft: leftMine.length, + ok: otherBefore.length === otherAfter.length && vanished.length === 0 && leftMine.length === 0, +}; + +// ── 4. record ──────────────────────────────────────────────────────────── +const allOk = results.every((r) => r.ok) && safety.ok; +const record = { + ok: allOk, + ts: new Date().toISOString(), + commit: git("rev-parse", "HEAD"), + branch: git("rev-parse", "--abbrev-ref", "HEAD"), + dirty: (git("status", "--porcelain", "--untracked-files=no") ?? "") !== "", + buildHash, + buildSource: path.resolve(source), + version: manifest.version, + seconds: Math.round((Date.now() - t0) / 1000), + jobs, + setups: results.map((r) => r.id), + safety, + results: Object.fromEntries(results.map((r) => [r.id, { ok: r.ok, ...(r.skipped ? { skipped: r.skipped } : {}), title: r.title, seconds: r.seconds, runDir: r.ok && !keep ? null : r.runDir, checks: r.checks }])), +}; +fs.writeFileSync(path.join(HERE, "last-run.json"), JSON.stringify(record, null, 2)); +if (allOk) fs.writeFileSync(path.join(HERE, "last-pass.json"), JSON.stringify(record, null, 2)); + +// Passed runs are deleted (the real-data copy is ~150 MB); failed ones stay for a look. +if (!keep) { + for (const r of results) if (r.ok && r.runDir) fs.rmSync(r.runDir, { recursive: true, force: true }); + fs.rmSync(work, { recursive: true, force: true }); +} + +console.log("\n── smoke matrix ─────────────────────────────────────────────"); +for (const r of results) { + const fails = r.checks.filter((c) => !c.ok); + const gaps = r.checks.filter((c) => c.gap); + if (r.skipped) { console.log(`SKIP ${r.id.padEnd(15)} ${r.skipped}`); continue; } + console.log(`${r.ok ? "PASS" : "FAIL"} ${r.id.padEnd(15)} ${String(r.seconds).padStart(4)} s ${r.checks.length} checks${gaps.length ? `, ${gaps.length} known gap(s)` : ""}`); + for (const f of fails) console.log(` ✗ ${f.check}: ${f.detail.split("\n")[0].slice(0, 400)}`); +} +console.log(`other Obsidian: ${safety.otherObsidianBefore} before, ${safety.otherObsidianAfter} after${safety.vanished.length ? `; VANISHED ${safety.vanished}` : ""}; sandbox processes left: ${safety.sandboxProcessesLeft}`); +const skipped = results.filter((r) => r.skipped).length; +console.log(`${allOk ? "SMOKE PASSED" : "SMOKE FAILED"}${skipped ? ` (${skipped} setup(s) SKIPPED)` : ""} (${record.seconds} s, build ${buildHash}, commit ${record.commit?.slice(0, 7)}${record.dirty ? " +dirty" : ""}) → ${path.join(HERE, allOk ? "last-pass.json" : "last-run.json")}`); +process.exit(allOk ? 0 : 1); diff --git a/dev/smoke/setups.mjs b/dev/smoke/setups.mjs new file mode 100644 index 00000000..6e56f24f --- /dev/null +++ b/dev/smoke/setups.mjs @@ -0,0 +1,470 @@ +/** + * The vault setups of the smoke matrix (plan-work-modes §3.1, F1–F10). + * Every fixture is built from code into a temp folder, or copied; never the + * main vault. A setup can: + * build(dir) write seed notes / a data.json into `dir` → { seed?, pluginData? } + * recipe an in-page function run in a first "prep" launch (makes + * maps through the plugin's own API), then Obsidian stops + * postPrep(vault, prepInfo) change the vault on disk after prep + * migration the check launch migrates legacy hex notes (verified) + * expect what the checks assert for this setup + * extra setup-specific checks in the check launch + */ +import fs from "node:fs"; +import path from "node:path"; + +export const REAL_SEED = process.env.SMOKE_REAL_SEED ?? "C:/Users/markr/work/tmp/migtest/seedF"; +export const REAL_DATA = process.env.SMOKE_REAL_DATA ?? "C:/Users/markr/Documents/KB/journal/.obsidian/plugins/duckmage-plugin/data.json"; +export const MARKER = ".hexmaker-sandbox"; + +const write = (file, text) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); }; +const writeJson = (file, obj) => write(file, JSON.stringify(obj, null, 2)); +const seedDir = (dir) => { const s = path.join(dir, "seed"); fs.mkdirSync(s, { recursive: true }); write(path.join(s, MARKER), "smoke suite sandbox\n"); return s; }; + +// ── F2: a small vault as plugin 1.5.5 left it ───────────────────────────── + +const V155_TERRAINS = [ + { name: "ocean", color: "#29507f", category: "sea" }, + { name: "grass", color: "#69a168", icon: "bw-grassland.png", category: "lowlands" }, + { name: "hills", color: "#e0e8a1", icon: "bw-hills.png", category: "lowlands" }, + { name: "forest", color: "#2f6b3a", category: "forest" }, + { name: "mountains", color: "#8b7d6b", category: "mountains" }, + { name: "snow", color: "#e0f2fe", category: "snow" }, +]; + +/** Hex note text in the 1.5.5 shape: map data in frontmatter, old template body. */ +function v155Note(x, y, fm, body = "") { + const lines = ["---"]; + for (const [k, v] of Object.entries(fm)) { + if (Array.isArray(v)) { lines.push(`${k}:`); for (const i of v) lines.push(` - ${i}`); } + else lines.push(`${k}: ${v}`); + } + lines.push("---", "", `# Hex ${x}, ${y}`, "", "**Region:**", "**Terrain:**", "", "### description", "", body, "", "### Towns", "", "### Dungeons", "", "### Features", "", "### Quests", "", "### Factions", "", "### Encounters Table", ""); + return lines.join("\n"); +} + +function buildV155(dir) { + const seed = seedDir(dir); + const hexRoot = path.join(seed, "world", "hexes"); + const maps = [ + { name: "coast", cols: 8, rows: 6 }, + { name: "north", cols: 6, rows: 5 }, + { name: "harbour", cols: 4, rows: 4 }, + ]; + const terr = V155_TERRAINS.map((t) => t.name); + for (const m of maps) { + for (let y = 0; y < m.rows; y++) for (let x = 0; x < m.cols; x++) { + const i = x * 7 + y * 3 + m.name.length; + if (i % 5 === 4) continue; // some hexes have no note at all + const fm = { terrain: terr[i % terr.length] }; + if (i % 7 === 0) fm.icon = "bw-hills.png"; + if (i % 11 === 0) fm["gm-icons"] = ["I_Ruins.png", "I_Monolith.png"]; + if (m.name === "coast" && x < 3) fm.region = "Saltmarsh"; + if (i % 13 === 0) fm.locked = true; + if (i % 9 === 0) { fm.tags = "[hex, smoke]"; fm.aliases = `[Spot ${x}-${y}]`; } + const body = i % 4 === 0 ? `Old notes for ${m.name} ${x},${y}. Keep me exactly.` : ""; + write(path.join(hexRoot, m.name, `${x}_${y}.md`), v155Note(x, y, fm, body)); + } + } + // The harbour is a submap of coast 2_2 (1.5.5: duckmage-submap on the hex note). + write(path.join(hexRoot, "coast", "2_2.md"), v155Note(2, 2, { terrain: "grass", "duckmage-submap": "harbour" }, "The harbour town.")); + // A hex note with no frontmatter at all, and one with a typed body. + write(path.join(hexRoot, "north", "5_4.md"), "# Hex 5, 4\n\nJust prose, no frontmatter.\n"); + write(path.join(seed, "world", "Lore.md"), "# Lore\n\nA note that isn't a hex. [[coast]]\n"); + const data = { + mySetting: "default", + worldFolder: "world", + hexFolder: "world/hexes", + townsFolder: "", dungeonsFolder: "", questsFolder: "", featuresFolder: "", iconsFolder: "", + templatePath: "", + hexGap: "0.2", + terrainPalettes: [{ name: "Default", terrains: V155_TERRAINS }], + maps: [ + { + name: "coast", paletteName: "Default", gridSize: { cols: 8, rows: 6 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", + pathChains: [ + { typeName: "Road", hexes: ["0_1", "1_1", "2_2", "3_2", "4_3"] }, + { typeName: "River", hexes: ["6_0", "6_1", "5_2", "5_3"] }, + { typeName: "Road", hexes: ["2_2"] }, + ], + }, + { name: "north", paletteName: "Default", gridSize: { cols: 6, rows: 5 }, gridOffset: { x: 0, y: 0 }, pathChains: [{ typeName: "River", hexes: ["0_0", "1_0", "2_1"] }] }, + { name: "harbour", paletteName: "Default", gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 0, y: 0 }, pathChains: [] }, + ], + zoomLevel: 1, + pathTypes: [ + { name: "Road", color: "#a16207", width: 5, lineStyle: "solid", routing: "through" }, + { name: "River", color: "#3b82f6", width: 6, lineStyle: "solid", routing: "through" }, + ], + hexOrientation: "flat", + staggerOffset: "odd", + tablesFolder: "world/tables", + factionsFolder: "", regionsFolder: "", + defaultTableDice: 100, + rollTableExcludedFolders: ["terrain"], + encounterTableExcludedFolders: ["terrain"], + defaultMap: "coast", + workflowsFolder: "", + setupComplete: true, + setupDismissed: false, + roadColor: "#a16207", + riverColor: "#3b82f6", + savedWith: "1.5.5", + }; + const pluginData = path.join(dir, "data.json"); + writeJson(pluginData, data); + return { seed, pluginData }; +} + +// ── in-page recipes (self-contained; run with (pluginId, args)) ─────────── + +function recipeSpace(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + p.settings.mapKinds = ["space"]; + p.onMapKindsChanged?.(); + const sector = await p.installPalettePreset("Space - Sector"); + const system = await p.installPalettePreset("Space - System"); + const made = []; + const mk = async (name, cols, rows, pal, parent) => { + const r = await p.createNewMap(name, cols, rows, pal, 0, 0, undefined, undefined, undefined, { quiet: true, ...(parent ? { parent } : {}) }); + if ("error" in r) throw new Error(r.error); + made.push(r.name); + return r.name; + }; + const s = await mk("Rim Sector", 10, 8, sector); + const pal = p.getMapPalette(s).map((t) => t.name); + p.mapStore.setMany(s, [["2_2", { terrain: pal[1] ?? pal[0] }], ["3_3", { terrain: pal[2] ?? pal[0] }], ["5_4", { terrain: pal[0] }]]); + const sys = await mk("Vega System", 9, 9, system, { map: s, hex: "2_2" }); + await p.linkSubmap(s, 2, 2, sys); + const planetPal = p.childPaletteFor(sys); + const planet = await mk("Vega IV", 8, 6, planetPal, { map: sys, hex: "4_4" }); + await p.linkSubmap(sys, 4, 4, planet); + await p.saveSettings(); + await p.mapStore.flush(); + return { made, palettes: p.settings.terrainPalettes.map((x) => x.name), planetPal }; + })(); +} + +function recipeOverworld(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + await p.setFeatureLevel("advanced"); + const t0 = Date.now(); + while (!p.devTools && Date.now() - t0 < 30000) await new Promise((r) => setTimeout(r, 300)); + if (!p.devTools) throw new Error("devTools missing (sandbox marker?)"); + const demo = await p.devTools.buildDemoWorld({ seed: 7 }); + await p.saveSettings(); + await p.mapStore.flush(); + return { overworld: demo.overworld, regions: demo.regions, hexes: demo.overworldHexes }; + })(); +} + +function recipeNeighbours(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + await p.setFeatureLevel("advanced"); + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const wid = "wsmoke1"; + const names = []; + const slots = [[0, 0], [1, 0], [0, 1], [1, 1]]; + for (const [i, [cx, cy]] of slots.entries()) { + // Legacy worlds: every map numbers its own hexes from 0 (no shared coordinates). + const r = await p.createNewMap(`Shire ${String.fromCharCode(65 + i)}`, 10, 8, pal, 0, 0, "odd", undefined, undefined, { quiet: true }); + if ("error" in r) throw new Error(r.error); + p.getMap(r.name).world = { id: wid, cx, cy }; + const terr = p.getMapPalette(r.name).map((t) => t.name); + const cells = []; + for (let x = 0; x < 10; x++) for (let y = 0; y < 8; y++) if ((x + y + i) % 3 === 0) cells.push([`${x}_${y}`, { terrain: terr[(x * 3 + y + i) % terr.length] }]); + p.mapStore.setMany(r.name, cells); + names.push(r.name); + } + await p.saveSettings(); + await p.mapStore.flush(); + return { maps: names }; + })(); +} + +function recipeCustomPalette(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + const app = window.app; + p.settings.setupComplete = true; + app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + p.settings.terrainPalettes.push({ + name: "Moorland", + terrains: [ + { name: "bog", color: "#556b2f" }, + { name: "crag", color: "#7a7a7a" }, + { name: "heath", color: "#9a7b9a", type: "grassland" }, + { name: "tarn", color: "#24466b", type: "water" }, + { name: "barrow", color: "#3b2f2f" }, + ], + }); + p.settings.defaultPalette = "Moorland"; + await p.saveSettings(); + await sleep(1500); + // Delete every other palette's note: the store drops them from settings. + for (const pal of p.settings.terrainPalettes.map((x) => x.name)) { + if (pal === "Moorland") continue; + const f = p.paletteStore.noteFor(pal); + if (f) await app.vault.delete(f); + await sleep(300); + } + await sleep(1500); + // The default map from a fresh install (on a default palette) goes too. + for (const m of [...p.settings.maps]) if (m.paletteName !== "Moorland") p.settings.maps.splice(p.settings.maps.indexOf(m), 1); + const r = await p.createNewMap("The Moor", 9, 7, "Moorland", 0, 0, undefined, undefined, undefined, { quiet: true }); + if ("error" in r) throw new Error(r.error); + p.settings.defaultMap = r.name; + const terr = ["bog", "crag", "heath", "tarn", "barrow"]; + const cells = []; + for (let x = 0; x < 9; x++) for (let y = 0; y < 7; y++) if ((x * y) % 2 === 0) cells.push([`${x}_${y}`, { terrain: terr[(x + y) % 5] }]); + p.mapStore.setMany(r.name, cells); + await p.saveSettings(); + await p.mapStore.flush(); + return { palettes: p.settings.terrainPalettes.map((x) => x.name), map: r.name }; + })(); +} + +function recipeDeleted(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + await p.setFeatureLevel("advanced"); + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const made = []; + for (const n of ["Gone One", "Gone Two"]) { + const r = await p.createNewMap(n, 8, 6, pal, 0, 0, undefined, undefined, undefined, { quiet: true }); + if ("error" in r) throw new Error(r.error); + const terr = p.getMapPalette(r.name).map((t) => t.name); + p.mapStore.setMany(r.name, [["1_1", { terrain: terr[0] }], ["2_2", { terrain: terr[1] }], ["3_3", { terrain: terr[2] }]]); + made.push(r.name); + } + const types = p.getMapPathTypes(made[0]); + if (types.length) p.mapStore.setPaths(made[0], [{ name: "Old road", typeName: types[0].name, branches: [{ anchors: ["0_1", "4_3"] }] }]); + await p.saveSettings(); + await p.mapStore.flush(); + return { + made, + folders: [p.settings.hexFolder, p.paletteStore.folder(), p.settings.tablesFolder, p.settings.workflowsFolder, p.templatesFolder?.()].filter(Boolean), + }; + })(); +} + +function recipeManyMaps(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + await p.setFeatureLevel("advanced"); + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const made = []; + const errors = []; + const mk = async (raw, parent) => { + const r = await p.createNewMap(raw, 6, 5, pal, 0, 0, undefined, undefined, undefined, { quiet: true, ...(parent ? { parent: { map: parent, hex: "2_2" } } : {}) }); + if ("error" in r) { errors.push(`${raw}: ${r.error}`); return null; } + const terr = p.getMapPalette(r.name).map((t) => t.name); + p.mapStore.setMany(r.name, [["0_0", { terrain: terr[made.length % terr.length] }], ["2_2", { terrain: terr[(made.length + 1) % terr.length] }]]); + if (parent) await p.linkSubmap(parent, 2, 2, r.name); + made.push(r.name); + return r.name; + }; + // Duplicate-ish names: same words, different case/spacing/punctuation. + const tops = ["Ash Vale", "Ash Vale!", "ash vale 2", "Ashvale", "Ash-Vale (old)", "Brine", "BRINE", "Brine 1", "Cinder", "Cinder Isle", + "Dune", "Dunes", "Elder", "Elder Wood", "Fen", "Fenn", "Gale", "Gale's End", "Hollow", "Hollows"]; + const topNames = []; + for (const t of tops) { const n = await mk(t); if (n) topNames.push(n); } + // Names that slug to a folder already taken are refused (as they should be): top up to 20. + for (let i = 1; topNames.length < 20; i++) { const n = await mk(`Isle ${i}`); if (n) topNames.push(n); } + // Nested locations four deep under the first 15 tops (15 × 4 = 60). + for (const top of topNames.slice(0, 15)) { + let parent = top; + for (let d = 1; d <= 4; d++) parent = (await mk(`${top} L${d}`, parent)) ?? parent; + } + await p.saveSettings(); + await p.mapStore.flush(); + return { made: made.length, errors }; + })(); +} + +function recipeSimpleMid(id) { + return (async () => { + const p = window.app.plugins.plugins[id]; + p.settings.setupComplete = true; + window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); + await p.setFeatureLevel("simple"); + await p.enableAdvancedFeature("workflows"); + p.settings.dismissedHints = [...new Set([...(p.settings.dismissedHints ?? []), "generators-toolbar", "regions-map-menu"])]; + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const r = await p.createNewMap("Starter Isle", 10, 8, pal, 0, 0, undefined, undefined, undefined, { quiet: true }); + if ("error" in r) throw new Error(r.error); + const terr = p.getMapPalette(r.name).map((t) => t.name); + const cells = []; + for (let x = 0; x < 10; x++) for (let y = 0; y < 8; y++) if ((x + 2 * y) % 4 === 0) cells.push([`${x}_${y}`, { terrain: terr[(x + y) % terr.length] }]); + p.mapStore.setMany(r.name, cells); + p.settings.defaultMap = r.name; + await p.saveSettings(); + await p.mapStore.flush(); + return { map: r.name, level: p.settings.featureLevel, advancedFeatures: p.settings.advancedFeatures }; + })(); +} + +// ── setup-specific checks (Node side; ctx.ev(fn, ...args) evaluates in page) ── + +async function freshExtra(ctx) { + const out = []; + const st = ctx.state; + out.push({ check: "F1-wizard", ok: st.wizardOpen > 0, detail: `setup wizard leaves: ${st.wizardOpen}` }); + // Create a map + paint through the API: only the map note may be written. + const r = await ctx.ev((id) => (async () => { + const app = window.app, p = app.plugins.plugins[id]; + const t = Date.now(); + const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; + const res = await p.createNewMap("Smoke Fresh", 8, 6, pal, 0, 0, undefined, undefined, undefined, { quiet: true }); + if ("error" in res) return { error: res.error }; + const terr = p.getMapPalette(res.name).map((x) => x.name); + p.mapStore.set(res.name, "1_1", { terrain: terr[0] }); + p.mapStore.set(res.name, "2_3", { terrain: terr[1] }); + await p.mapStore.flush(); + await new Promise((r2) => setTimeout(r2, 1500)); + const files = [...new Set(window.__smoke.writes.filter((w) => w.t >= t && /\.md$/.test(w.path)).map((w) => w.path))]; + const note = p.mapStore.notePath(res.name); + // First hex note: links its map note, carries no map data. + await p.createHexNote(1, 1, res.name); + const hexPath = p.hexPath(1, 1, res.name); + const text = (await app.vault.adapter.exists(hexPath)) ? await app.vault.adapter.read(hexPath) : null; + return { map: res.name, files, note, hexPath, hasLink: !!text && /hexmaker-map:/.test(text), hasTerrain: !!text && /^terrain\s*:/m.test(text) }; + })(), ctx.pluginId); + if (r.error) out.push({ check: "F1-create-paint", ok: false, detail: r.error }); + else { + const others = r.files.filter((f) => f !== r.note); + out.push({ check: "F1-create-paint", ok: r.files.includes(r.note) && others.length === 0, detail: `wrote ${r.files.join(", ") || "(nothing)"}` }); + out.push({ check: "F1-first-hex-note", ok: r.hasLink && !r.hasTerrain, detail: `${r.hexPath}: map link ${r.hasLink}, terrain key ${r.hasTerrain}` }); + } + return out; +} + +async function spaceExtra(ctx) { + const st = ctx.state; + const out = []; + out.push({ check: "F4-kinds", ok: JSON.stringify(st.mapKinds) === JSON.stringify(["space"]), detail: `mapKinds ${JSON.stringify(st.mapKinds)}` }); + const spaceMaps = st.maps.filter((m) => m.space).map((m) => m.name); + out.push({ check: "F4-space-maps", ok: spaceMaps.length >= 2, detail: `space maps: ${spaceMaps.join(", ")}` }); + const chain = st.maps.filter((m) => m.parent).map((m) => `${m.parent} → ${m.name}`); + out.push({ check: "F4-chain", ok: chain.length >= 2, detail: chain.join("; ") }); + return out; +} + +async function overworldExtra(ctx) { + const ow = ctx.state.maps.find((m) => m.overworld); + if (!ow) return [{ check: "F5-overworld", ok: false, detail: "no overworld map" }]; + const regions = ctx.state.maps.filter((m) => m.submapKind === "region" && m.parent === ow.name); + const out = [{ check: "F5-regions", ok: regions.length > 0, detail: `${ow.name}: ${regions.length} region maps` }]; + const lock = await ctx.ev((id, n) => window.__smokePage.overworldPaintLock(id, n), ctx.pluginId, ow.name); + out.push({ check: "C8-overworld-paint", ok: lock.ok, detail: [...lock.steps, ...lock.problems].join("; ") }); + return out; +} + +async function neighboursExtra(ctx) { + const inWorld = ctx.state.maps.filter((m) => m.world); + return [{ check: "F6-world", ok: inWorld.length === 4, detail: inWorld.map((m) => `${m.name}@${m.world}`).join(", ") }]; +} + +async function customPaletteExtra(ctx) { + const st = ctx.state; + return [ + { check: "F7-palettes", ok: st.palettes.length === 1 && st.palettes[0] === "Moorland", detail: `palettes: ${st.palettes.join(", ")}` }, + ]; +} + +async function deletedExtra(ctx) { + const st = ctx.state; + const notices = await ctx.ev(() => window.__smokePage.notices()); + const errLoop = ctx.log.length; + await new Promise((r) => setTimeout(r, 8000)); + const grew = ctx.log.length - errLoop; + return [ + // Recorded, not judged (owner call, see open-work): what the plugin does with maps whose folder and note are gone. + { check: "F8-loads", ok: true, detail: `maps: ${st.maps.map((m) => `${m.name} (${!m.noteExists ? "no note" : ctx.snap0[m.notePath] ? "note kept" : "note re-created, " + m.hexes + " hexes"})`).join(", ")}; palettes: ${st.palettes.join(", ") || "(none)"}; path types: ${st.pathTypes}` }, + { check: "F8-no-loop", ok: grew === 0, detail: `console errors/warnings added in 8 s idle: ${grew}; notices: ${notices.join(" | ") || "(none)"}` }, + ]; +} + +async function manyMapsExtra(ctx) { + const n = ctx.state.maps.length; + const deep = ctx.state.maps.filter((m) => / L4$/i.test(m.name) || /-l4$/.test(m.name)).length; + return [{ check: "F9-count", ok: n >= 80, detail: `${n} maps, ${deep} at depth 4, store ready in ${ctx.readyMs} ms` }]; +} + +async function simpleMidExtra(ctx) { + const st = ctx.state; + const out = []; + out.push({ check: "F10-level", ok: st.featureLevel === "simple" && st.advancedFeatures.includes("workflows"), detail: `level ${st.featureLevel}, advanced ${JSON.stringify(st.advancedFeatures)}` }); + out.push({ check: "F10-hints", ok: st.dismissedHints.includes("generators-toolbar"), detail: `dismissed ${JSON.stringify(st.dismissedHints)}` }); + // The generator page is Advanced: in Simple the command offers to turn it on instead. + const r = await ctx.ev((id) => (async () => { + const app = window.app; + app.commands.executeCommandById(`${id}:open-terrain-generator`); + await new Promise((res) => setTimeout(res, 800)); + const modal = document.querySelectorAll(".modal-container").length; + const gen = app.workspace.getLeavesOfType("duckmage-terrain-generator").length; + document.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); + return { modal, gen }; + })(), ctx.pluginId); + out.push({ check: "F10-gate", ok: r.modal > 0 && r.gen === 0, detail: `generator command: modal ${r.modal}, generator view ${r.gen}` }); + out.push({ check: "F10-mode-switch", ok: !!ctx.firstOpen?.workModeBtn, detail: `work mode button on the map: ${!!ctx.firstOpen?.workModeBtn}` }); + return out; +} + +// ── the matrix ──────────────────────────────────────────────────────────── + +export const SETUPS = [ + { + id: "real-data", title: "Owner real-data copy (seedF + live data.json), migrates", slow: true, + // Private data on the owner's machine (SMOKE_REAL_SEED / SMOKE_REAL_DATA elsewhere): skipped, loudly, without it. + unavailable: () => (!fs.existsSync(REAL_SEED) ? `real seed missing: ${REAL_SEED}` : !fs.existsSync(REAL_DATA) ? `live data.json missing: ${REAL_DATA}` : null), + build(dir) { + if (!fs.existsSync(REAL_SEED)) throw new Error(`real seed missing: ${REAL_SEED}`); + if (!fs.existsSync(REAL_DATA)) throw new Error(`live data.json missing: ${REAL_DATA}`); + const pluginData = path.join(dir, "data.json"); + fs.copyFileSync(REAL_DATA, pluginData); // a COPY: the sandbox never sees the live file + return { seed: REAL_SEED, pluginData }; + }, + migration: true, + expect: { level: "advanced", readyMs: 600_000, openMs: 60_000 }, + }, + { id: "fresh", title: "Fresh install", build: (dir) => ({ seed: seedDir(dir) }), expect: { level: "simple", wizard: true }, extra: freshExtra, skipPaint: true }, + { id: "v155", title: "Synthetic 1.5.5 vault (hex-note frontmatter + data.json maps), migrates", build: buildV155, migration: true, expect: { level: "advanced" } }, + { id: "space", title: "Space only (sector → system → planet)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeSpace, expect: {}, extra: spaceExtra }, + { id: "overworld", title: "Overworld + regions (demo world, seed 7)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeOverworld, expect: { level: "advanced", openMs: 60_000 }, extra: overworldExtra }, + { id: "neighbours", title: "Neighbours world (legacy 2×2, own coordinates)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeNeighbours, expect: { level: "advanced" }, extra: neighboursExtra }, + { id: "custom-palette", title: "One custom palette, no default names", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeCustomPalette, expect: {}, extra: customPaletteExtra }, + { + id: "deleted", title: "Everything deleted (no palettes, path types or map folders)", + build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeDeleted, + postPrep(vault, info, pluginId) { + for (const f of info.folders ?? []) { + const p = path.join(vault, f); + if (fs.existsSync(p) && path.resolve(p).startsWith(path.resolve(vault) + path.sep)) fs.rmSync(p, { recursive: true, force: true }); + } + const dataFile = path.join(vault, ".obsidian", "plugins", pluginId, "data.json"); + const data = JSON.parse(fs.readFileSync(dataFile, "utf8")); + data.terrainPalettes = []; + data.pathTypes = []; + fs.writeFileSync(dataFile, JSON.stringify(data, null, 2)); + }, + expect: { level: "advanced" }, extra: deletedExtra, skipModeLocks: true, + }, + { id: "many-maps", title: "Many maps (80, nested 4 deep, look-alike names)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeManyMaps, expect: { level: "advanced" }, extra: manyMapsExtra }, + { id: "simple-mid", title: "Simple level, mid-ramp (workflows on, hints dismissed)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeSimpleMid, expect: { level: "simple" }, extra: simpleMidExtra }, +]; + diff --git a/package.json b/package.json index f9a1f2f5..1f8fb127 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,11 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", + "smoke": "node dev/smoke/cli.mjs", + "premerge": "node dev/smoke/premerge.mjs", "test:e2e": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/e2e-*.integration.ts", "lint": "eslint . --ext .js,.ts", "obsidian:login": "node dev/obsidian-login.mjs", diff --git a/tests/smokeSuite.test.ts b/tests/smokeSuite.test.ts new file mode 100644 index 00000000..11e25b38 --- /dev/null +++ b/tests/smokeSuite.test.ts @@ -0,0 +1,94 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +// The smoke suite's pure helpers (dev/smoke; the suite itself needs Windows Obsidian). +import { canon, jsonDiff, oneTimeOnly } from "../dev/smoke/lib/compare.mjs"; +import { diff, hexDataFromFm, paletteTerrains, verifyPaletteUpgrade } from "../dev/smoke/lib/disk.mjs"; + +const read = (...p: string[]) => readFileSync(path.join(process.cwd(), ...p), "utf8").replace(/\r\n/g, "\n"); + +describe("smoke suite: comparison helpers", () => { + it("canon ignores key order at every level", () => { + expect(canon({ b: 1, a: { d: [1, { y: 2, x: 1 }], c: 3 } })).toBe(canon({ a: { c: 3, d: [1, { x: 1, y: 2 }] }, b: 1 })); + expect(canon([2, 1])).not.toBe(canon([1, 2])); + }); + + it("jsonDiff names the paths that differ", () => { + const d = jsonDiff({ maps: [{ name: "a", zoom: 1 }], x: 1 }, { maps: [{ name: "a", zoom: 2 }], x: 1 }); + expect(d).toEqual(["maps[0].zoom: 1 → 2"]); + expect(jsonDiff({ a: 1 }, { a: 1 })).toEqual([]); + }); + + it("a restart may only write the one-time settings", () => { + expect(oneTimeOnly({ a: 1 }, { a: 1, tableRangesPrompt: "done" })).toBe(true); + expect(oneTimeOnly({ a: 1 }, { a: 1, advancedNudgeAt: "2026-10-11", tableRangesPrompt: "done" })).toBe(true); + // The churn the suite found: maps' path lists written back on a later start. + expect(oneTimeOnly({ maps: [{ name: "a" }] }, { maps: [{ name: "a", pathChains: [] }], tableRangesPrompt: "done" })).toBe(false); + expect(oneTimeOnly({ a: 1 }, { a: 1 })).toBe(false); + }); + + it("snapshot diff tells changed, rewritten, added and removed apart", () => { + const a = { x: { h: "1", m: 1 }, y: { h: "2", m: 1 }, z: { h: "3", m: 1 } }; + const b = { x: { h: "1", m: 1 }, y: { h: "9", m: 2 }, z: { h: "3", m: 5 }, w: { h: "4", m: 1 } }; + expect(diff(a, b)).toEqual({ added: ["w"], removed: [], changed: ["y"], touched: ["z"] }); + expect(diff(b, a).removed).toEqual(["w"]); + }); +}); + +describe("smoke suite: legacy hex data and palette upgrades", () => { + it("reads 1.5.5 hex-note frontmatter like MapStore.hexDataFromFrontmatter", () => { + expect(hexDataFromFm({ terrain: "grass", "gm-icon": "I_Ruins.png", "duckmage-submap": "harbour", locked: "true", tags: ["x"] })) + .toEqual({ terrain: "grass", gmIcons: ["I_Ruins.png"], locations: ["harbour"], locked: true }); + expect(hexDataFromFm({ terrain: "" })).toEqual({}); + expect(hexDataFromFm(null)).toEqual({}); + }); + + const OLD = [ + "---", "hexmaker-palette: 1", "---", "", "| Terrain | Color | Icon | Icon color | Category | Type |", "| --- | --- | --- | --- | --- | --- |", + "| water | #60a5fa | | | | water |", "| grass | #69a168 | bw-grassland.png | | lowlands | grassland |", "", + ].join("\n"); + const NEW = [ + "---", "hexmaker-palette: 1", "---", "", "| Terrain | Color | Icon | Icon color | Category | Type | Impassable |", "| --- | --- | --- | --- | --- | --- | --- |", + "| water | `#60a5fa` | | | | water | (yes) |", "| grass | `#69a168` | bw-grassland.png | | lowlands | grassland | (no) |", "", + "## Path types", "", "| Path | Color |", "| --- | --- |", "| Road | `#a16207` |", "", + ].join("\n"); + + it("a palette note upgrade that only adds columns and tables passes", () => { + expect(paletteTerrains(NEW).get("grass")).toBe("#69a168|bw-grassland.png||lowlands|grassland"); + expect(paletteTerrains(NEW).has("Road")).toBe(false); + expect(verifyPaletteUpgrade(OLD, NEW)).toEqual([]); + }); + + it("a rewrite that loses or changes a terrain is caught", () => { + expect(verifyPaletteUpgrade(OLD, NEW.replace("| water |", "| sea |"))).toEqual(['terrain "water" gone', 'terrain "sea" added']); + expect(verifyPaletteUpgrade(OLD, NEW.replace("`#69a168`", "`#000000`"))).toHaveLength(1); + }); +}); + +/** + * Regression guards for the bugs the smoke suite's first run found + * (2026-10-11). Each has a scripted check in dev/smoke too; these keep the + * fixes from quietly reverting between smoke runs. + */ +describe("smoke suite findings stay fixed", () => { + it("C6: a terrain stroke remembers the old terrain from the map data, not the hex note's frontmatter", () => { + const src = read("src", "hex-map", "HexMapView.ts"); + const start = src.indexOf(" private onHexPaintClick("); + const body = src.slice(start, src.indexOf("\n }\n", start)); + expect(body).toMatch(/oldTerrain = pending \? pending\.terrain : getTerrainFromFile\(this\.app, path\)/); + expect(body).not.toMatch(/getCache\(path\)\?\.frontmatter/); + }); + + it("C5: views restored as deferred tabs are skipped, never cast and called", () => { + const src = read("src", "HexmakerPlugin.ts"); + expect(src).not.toMatch(/\(leaf\.view as Hex(Map|Table)View\)\./); + expect(src).toMatch(/if \(leaf\.view instanceof HexMapView\) leaf\.view\.renderGrid\(\);/); + }); + + it("C5: startup saves wait for the map notes to load", () => { + const src = read("src", "HexmakerPlugin.ts"); + expect(src).toMatch(/void storesReady\.then\(\(\) => maybePromptTableRanges\(this\)\);/); + expect(src).toMatch(/void storesReady\.then\(\(\) => this\.saveSettings\(\)\);/); + }); +}); From 5133006968cb1895a1609a0b19080ed51c26a98c Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 04:38:31 -0400 Subject: [PATCH 274/558] feat(modes): classify every action per work mode, enforce at the writers, parallel undo per mode (WM1-WM6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/workMode.ts: ACTION_POLICY (one table: which modes allow each user action), TOOL_ACTIONS / COMMAND_ACTIONS / MENU_ACTIONS mapping every drawing tool, command and map-view menu item onto it, lockedHint / lockedSummary one-line hints. Play = what a GM does in a game (tokens, note text, rolls, layers, links in notes); Build adds and edits map data; God also reshapes, swaps, shrinks and deletes. Note text, settings and palettes are never locked. - src/modeGate.ts: the write gate. MapStore.set(…, action) refuses a locked write (nothing written, console warning); the frontmatter hex setters pass their action; token writes, swaps, map delete, location links and the path gate use it too. - UI: the drawing panel hides locked tools behind one line; Play hides the grid's +/-, Build disables - (God); hex/overworld/token menus go through ModeMenu (locked items left out, one hint line); hex editor shows one line where locked terrain/icon pickers were; map Properties and Delete, Locations list and hex table terrain picker follow the mode. - src/undoBook.ts: one undo/redo queue per map per mode for the session (plugin.undoBook). Undo in a mode undoes only that mode's actions; an entry whose target changed since (compared with its "after" snapshot) is skipped part by part. Covers terrain/icon/region/faction strokes, sub-hex paint, paths, swaps, calibration, tokens (move/place/remove), hex editor edits and biome reroll/swap (MapStore.record → cell edits). Buttons' tooltips name the mode; queues follow map renames. - Smoke C8: terrain paint in Play is now a real check (Play refuses, Build paints and undoes). - Tests: workModeCoverage (commands, tools, menus classified; policy), workModeUndo (per-mode queues, cross-mode skip, cell edits, gate, MapStore refusal and record). README/help: Modes and undo per mode. Co-Authored-By: Claude Opus 5.5 --- README.md | 12 +- dev/smoke/lib/page.mjs | 66 ++- package.json | 4 +- src/HexmakerPlugin.ts | 32 +- src/frontmatter.ts | 34 +- src/hex-map/BiomeModals.ts | 19 +- src/hex-map/EditRegionModal.ts | 6 +- src/hex-map/HexEditorModal.ts | 53 +- src/hex-map/HexMapView.ts | 745 +++++++++++++------------ src/hex-map/LocationsModal.ts | 12 +- src/hex-map/MapModal.ts | 17 +- src/hex-map/help.md | 10 +- src/hex-map/modeMenu.ts | 67 +++ src/hex-map/undoItems.ts | 88 +++ src/hex-table/HexTerrainPickerModal.ts | 8 +- src/maps/MapStore.ts | 47 +- src/modeGate.ts | 34 ++ src/paths/editGate.ts | 4 +- src/undoBook.ts | 214 +++++++ src/workMode.ts | 232 +++++++- styles.css | 19 + tests/hitTest.test.ts | 2 +- tests/openNote.test.ts | 3 +- tests/workModeCoverage.test.ts | 138 +++++ tests/workModeUndo.test.ts | 260 +++++++++ 25 files changed, 1687 insertions(+), 439 deletions(-) create mode 100644 src/hex-map/modeMenu.ts create mode 100644 src/hex-map/undoItems.ts create mode 100644 src/modeGate.ts create mode 100644 src/undoBook.ts create mode 100644 tests/workModeCoverage.test.ts create mode 100644 tests/workModeUndo.test.ts diff --git a/README.md b/README.md index 0702c585..50c66362 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ An interactive hex grid rendered as an Obsidian panel. - **Zoom** with the scroll wheel. - **Expand** the grid with the `+`/`−` buttons at the map edges. - **Go to hex** (`⌖` button in the toolbar) — enter coordinates to centre the view on a specific hex. -- **Undo / Redo** (`↩` / `↪` buttons) — step back or forward through terrain and icon paint operations. +- **Undo / Redo** (`↩` / `↪` buttons, Ctrl/Cmd+Z) — step back or forward through this map's changes made in its current work mode (one queue per map per mode; see **Work modes** below). ### Maps Organise your world into multiple named hex maps, each stored as a subfolder under your hex folder. The active map name is shown in the top-left of the toolbar as a dropdown button. @@ -126,7 +126,15 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Each hex is written to its region as you draw, so the overworld and any open view of those regions update during the stroke. Picking a terrain on an overworld switches to this view; where there's no region yet the brush does nothing ("No region here yet; place a biome first"), and in Play it's locked ("Switch to Build to paint the regions."). In both views, clicking a hex or brick with a region goes into it in every mode; clicking an empty one sets its biome (Build and God). Right-click a region for **Enter region** and **Edit region…**: one window with the region's name (editable), the overworld hex it's on, **Enter region** and **Open map note**, its biome, a few facts (size and shape, palette, terrain counts, neighbouring regions you can click to go to, locations) and its notes. The notes are kept in the region's map note under a plain `## Notes` heading, so you can also edit them there; they're editable in every mode. In God mode the biome is a picker (choosing another remakes the region), with **Reroll** and **Settings…** (biome, blend, seed, live preview); in Build and Play it's shown with "Switch to God to change it." On an empty hex the menu offers **Set biome…** (Build and God). The overworld is the big-picture view, so it has no hex editor: right-click shows only these region-level items, **Center on this hex** and the hex's **Locations**. Painted hexes are locked, so remaking a region keeps them. - **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one; hover a hex for its region's name). Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. -**Work modes: Play, Build, God.** Each map has a work mode, always shown on the toolbar next to the map button; click it to switch. It's saved in the map note as a plain `mode:` property (`play`, `build` or `god`), so each map opens in its own mode; new maps are in Build. For now two rules are enforced on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs God; in Build and Play those buttons are greyed out with "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region), or making regions at all (**Make the missing regions…**), needs Build or God; in Play the biome picker is greyed out with "Switch to Build to place a biome.", and **New map from this hex… → Region** is greyed out with "Switch to Build to make a region." There are no confirm boxes for these any more: the mode is the safety catch. Note text is never locked in any mode, and settings and palettes aren't either. +**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (the `mode:` line in its map note) and opens in it next time; new maps are in **Build**. + +- **Play** is for running a game: move, place and remove tokens, open and edit notes, roll tables, link tables and factions to hexes, turn layers on and off. The map itself stays as it is. The drawing panel shows only the tools Play allows, with one line naming the mode for the rest ("Switch to Build to edit the map."); the grid's **+** / **−** buttons are hidden, the hex editor shows "Switch to Build to paint terrain." where the terrain and icon pickers were, the map's properties say "Switch to Build to change the map's properties.", and the right-click menu leaves out what's locked and ends with one such line. +- **Build** adds and edits: paint terrain, icons and region areas, draw paths, link maps to hexes, grow the map, make maps and regions from a hex, change the map's properties, place a biome on an empty overworld hex. +- **God** can do everything, including changing a placed biome (**Reroll**, **Settings…**), swapping hexes, shrinking the grid and deleting the map. + +Notes, settings and palettes are never locked. There are no confirm boxes for these: the mode is the safety catch. + +**Undo per mode.** Each map has its own undo queue in each mode, kept until you close the vault. Undo (**↩** or Ctrl+Z) and redo take back the last thing done on this map in the mode it's in now: undoing a token move in Play never undoes Build's terrain, and switching back to Build picks its queue up where you left it. If something was changed again in another mode since (a token moved in Build, then again in Play), Build's undo skips it rather than moving it back. Terrain, icons, region areas, paths, tokens, swaps, hex editor edits and biome changes (reroll, swap) are all undoable. The buttons' tooltips name the mode. Which biome a hex is comes from its terrain's **Type**, never its name: forest-type terrains are temperate forest, wetland swamp, and so on. Where a type has variants, the **last** terrains of that type in the palette stand for them, in this order: forest → taiga, deep forest; grassland → savanna; hills → karst; wetland → river delta. Reorder the palette to choose (on Expanded: evergreen, evergreen heavy, savanna, jungle hills, river delta). A terrain with no type has no biome. diff --git a/dev/smoke/lib/page.mjs b/dev/smoke/lib/page.mjs index 7e918e40..b491dfad 100644 --- a/dev/smoke/lib/page.mjs +++ b/dev/smoke/lib/page.mjs @@ -281,8 +281,7 @@ export async function paintRoundTrip(id, name) { /** * C8 mode locks on `name` (a plain map): in Play the path tool's edits are * refused and nothing is written; in Build the same edit goes through and - * undoes. Also records whether terrain paint is locked in Play (it isn't - * yet: the modes plan's later phases). + * undoes. Terrain paint likewise: Play refuses it, Build paints and undoes. */ export async function modeLocks(id, name) { const app = window.app; @@ -352,35 +351,56 @@ export async function modeLocks(id, name) { else out.steps.push("play: the same path edit refused, map note unchanged"); } } - // Play + terrain paint on a plain map: not locked yet (recorded, not failed). - view.setWorkMode("play"); - await sleep(200); + // Terrain paint on a plain map, through the real mouse handlers: Play + // refuses it (nothing written), Build paints it, and Build's undo takes + // it back (WM6: Play's queue is untouched). const hexEl = view.containerEl.querySelector(".duckmage-hex[data-x]"); if (hexEl) { const key = `${hexEl.dataset.x}_${hexEl.dataset.y}`; - const before = JSON.stringify(store.get(name, key) ?? null); const terrain = p.getMapPalette(name).map((t) => t.name).find((t) => t !== store.get(name, key)?.terrain); if (terrain) { - view.leaveOtherToolFor?.("terrain"); - view.drawingMode = "terrain"; - view.isErasingMode = false; - view.terrainPickMode = false; - view.paintTerrainName = terrain; - view.paintBrushSize = 1; - const r = hexEl.getBoundingClientRect(); - const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; - hexEl.dispatchEvent(new MouseEvent("mousedown", at)); - hexEl.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); - await view.terrainWritesSettled?.(); - const changed = JSON.stringify(store.get(name, key) ?? null) !== before; - if (changed) { - out.gaps.push("Play doesn't lock terrain paint on a plain map yet (modes plan, Phase 2)"); + const paint = async () => { + view.leaveOtherToolFor?.("terrain"); + view.drawingMode = "terrain"; + view.isErasingMode = false; + view.terrainPickMode = false; + view.paintTerrainName = terrain; + view.paintBrushSize = 1; + const el = view.containerEl.querySelector(`.duckmage-hex[data-x="${hexEl.dataset.x}"][data-y="${hexEl.dataset.y}"]`) ?? hexEl; + const r = el.getBoundingClientRect(); + const at = { bubbles: true, cancelable: true, button: 0, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }; + el.dispatchEvent(new MouseEvent("mousedown", at)); + el.ownerDocument.dispatchEvent(new MouseEvent("mouseup", at)); + await view.terrainWritesSettled?.(); + await sleep(100); + view.exitTerrainMode?.(); + view.drawingMode = null; + }; + const now = () => JSON.stringify(store.get(name, key) ?? null); + view.setWorkMode("play"); + await sleep(200); + const before = now(), text = await readNote(); + await paint(); + await store.flush(); + if (now() !== before) { + fail("Play: terrain paint was written"); view.setWorkMode("build"); await view.undo(); await view.terrainWritesSettled?.(); - } else out.steps.push("play: terrain paint refused"); - view.exitTerrainMode?.(); - view.drawingMode = null; + } else if ((await readNote()) !== text) fail("Play: the map note changed after a refused terrain paint"); + else out.steps.push("play: terrain paint refused, map note unchanged"); + view.setWorkMode("build"); + await sleep(200); + await paint(); + if (store.get(name, key)?.terrain !== terrain) fail("Build: terrain paint was not written"); + else { + out.steps.push("build: terrain paint written"); + await view.undo(); + await view.terrainWritesSettled?.(); + await sleep(100); + if (now() !== before) fail("Build: undo didn't take the paint back"); + else out.steps.push("build: undo took it back"); + } } } } finally { diff --git a/package.json b/package.json index 1f8fb127..c1768281 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index b08df339..a03f4c08 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -68,6 +68,10 @@ import DEFAULT_HEX_TEMPLATE from "./defaultHexTemplate.md"; import { migrateMapData, pluginVersion } from "./compat"; import { getTerrainFromFile, getHexRegionFromFile, clearPendingTerrain, setHexDataSource } from "./frontmatter"; import { MapStore, withoutNotePaths } from "./maps/MapStore"; +import { setModeMapLookup } from "./modeGate"; +import { cellEdits, UndoBook } from "./undoBook"; +import type { UndoItem } from "./hex-map/undoItems"; +import { workModeOf } from "./workMode"; import { withMapLink } from "./maps/mapNote"; import { addLocationPatch, @@ -130,6 +134,8 @@ export default class HexmakerPlugin extends Plugin { }); /** Keeps routes in place when terrain, the palette, the size or a type's routing changes (Decision 3). */ pathPins = new RoutePins(this); + /** Undo/redo, one queue per map per work mode, for as long as the vault is open (WM6). */ + undoBook = new UndoBook(); async onload() { await this.loadSettings(); @@ -142,6 +148,7 @@ export default class HexmakerPlugin extends Plugin { setIconPackDefault(() => defaultIconPack(this.settings)); setHexDataSource(this.mapStore); setPathEditMapLookup((name) => this.getMap(name)); + setModeMapLookup((name) => this.getMap(name)); // Notes written by this plugin are read from memory until indexed (see frontmatter.ts). this.registerEvent(this.app.metadataCache.on("changed", (file) => clearPendingTerrain(file.path))); // Defer until vault metadata cache is ready; calling before layout-ready @@ -1751,12 +1758,29 @@ export default class HexmakerPlugin extends Plugin { * note; a hex that has a note also gets it as an alias, replacing the * previous name's alias and keeping any the user added. */ + /** Record an action done on `mapName` in its current work mode (WM6). */ + pushUndo(mapName: string, item: UndoItem): void { + this.undoBook.push(mapName, workModeOf(this.getMap(mapName)), item); + } + + /** + * Run a map data edit (hex editor, biome and region actions) and record + * the hexes it changed, field by field, in `mapName`'s queue for its + * current mode. Edits that change nothing record nothing. + */ + async undoableEdit(mapName: string, fn: () => T | Promise): Promise { + const { result, cells } = await this.mapStore.record(fn); + const edits = cellEdits(cells); + if (edits.length) this.pushUndo(mapName, { kind: "cells", edits }); + return result; + } + async setHexName(mapName: string, x: number, y: number, raw: string): Promise { const key = `${x}_${y}`; const name = cleanHexName(raw); const old = this.mapStore.get(mapName, key)?.name; if ((old ?? "") === name) return; - this.mapStore.set(mapName, key, { name: name || null }); + this.mapStore.set(mapName, key, { name: name || null }, "edit-note"); // The " x, y" alias rides along (added if the note lacks it). const coord = this.hexCoordAlias(mapName, x, y); await syncHexAliases(this.app, this.hexPath(x, y, mapName), [ @@ -2426,7 +2450,7 @@ export default class HexmakerPlugin extends Plugin { if (childMap === parentMap) return; const key = `${x}_${y}`; const patch = addLocationPatch(this.mapStore.get(parentMap, key), childMap); - if (patch.locations) this.mapStore.set(parentMap, key, patch); + if (patch.locations && !this.mapStore.set(parentMap, key, patch, "link-map")) return; this.noParentMaps.clear(); const child = this.getMap(childMap); if (child && !child.parent) { @@ -2466,7 +2490,7 @@ export default class HexmakerPlugin extends Plugin { let changed = false; for (const n of names) { const patch = removeMapPatch(this.mapStore.get(parentMap, key), n); - if (Object.keys(patch).length) this.mapStore.set(parentMap, key, patch); + if (Object.keys(patch).length && !this.mapStore.set(parentMap, key, patch, "link-map")) continue; const child = this.getMap(n); if (child?.parent?.map === parentMap && child.parent.hex === key) { delete child.parent; @@ -2481,7 +2505,7 @@ export default class HexmakerPlugin extends Plugin { /** Reorder the Locations of hex (x, y). */ setHexLocations(parentMap: string, x: number, y: number, locations: string[]): void { - this.mapStore.set(parentMap, `${x}_${y}`, { locations: locations.length ? locations : null }); + this.mapStore.set(parentMap, `${x}_${y}`, { locations: locations.length ? locations : null }, "link-map"); } /** Save region settings on `mapName` (fixed fields stay put while it has regions). */ diff --git a/src/frontmatter.ts b/src/frontmatter.ts index 47b2c8f3..e8bab595 100644 --- a/src/frontmatter.ts +++ b/src/frontmatter.ts @@ -1,5 +1,6 @@ -import { App, TFile } from "obsidian"; +import { App, TFile, parseYaml } from "obsidian"; import type { TokenEntry, TokenShape, TokenSize } from "./types"; +import type { ModeAction } from "./workMode"; import { type OverlayPatternKey, DEFAULT_OVERLAY_PATTERN_KEY, @@ -77,7 +78,8 @@ export interface HexDataSource { isReady(): boolean; resolve(path: string): { map: string; key: string } | null; get(map: string, key: string): import("./maps/mapNote").HexData | undefined; - set(map: string, key: string, patch: Record): void; + /** `action`: the user action (work-mode gate); false when refused. */ + set(map: string, key: string, patch: Record, action?: ModeAction): boolean; } let hexSource: HexDataSource | null = null; export function setHexDataSource(src: HexDataSource | null): void { @@ -158,7 +160,7 @@ export async function setTerrainInFile( terrainKey: string | null, ): Promise { const loc = hexLoc(path); - if (loc) { hexSource!.set(loc.map, loc.key, { terrain: terrainKey }); return true; } + if (loc) return hexSource!.set(loc.map, loc.key, { terrain: terrainKey }, "paint-terrain"); const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { @@ -254,7 +256,7 @@ export async function setHexRegionInFile( regionName: string | null, ): Promise { const loc = hexLoc(path); - if (loc) { hexSource!.set(loc.map, loc.key, { region: regionName }); return true; } + if (loc) return hexSource!.set(loc.map, loc.key, { region: regionName }, "paint-region-area"); const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { @@ -339,7 +341,7 @@ export async function setIconOverrideInFile( icon: string | null, ): Promise { const loc = hexLoc(path); - if (loc) { hexSource!.set(loc.map, loc.key, { icon }); return true; } + if (loc) return hexSource!.set(loc.map, loc.key, { icon }, "paint-icon"); const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { @@ -401,7 +403,7 @@ export async function setGmIconsInFile( icons: string[], ): Promise { const loc = hexLoc(path); - if (loc) { hexSource!.set(loc.map, loc.key, { gmIcons: [...icons] }); return true; } + if (loc) return hexSource!.set(loc.map, loc.key, { gmIcons: [...icons] }, "paint-icon"); const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { @@ -456,6 +458,24 @@ export function getTokenDataFromCache(app: App, file: TFile): TokenEntry | null }; } +/** + * Where a token note's token is now ({hex, map}), read from the file + * itself (the metadata cache can lag a write by a tick), or null when the + * note isn't a token. For undo's "has it moved since?" check. + */ +export async function readTokenPlace(app: App, path: string): Promise<{ hex: string; map: string } | null> { + const file = app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) return null; + const text = await app.vault.read(file); + const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text); + if (!m) return null; + let fm: Record | null = null; + try { fm = parseYaml(m[1]) as Record | null; } catch { return null; } + if (!fm?.["token"]) return null; + const s = (v: unknown) => (typeof v === "string" ? v : ""); + return { hex: s(fm["token-hex"]), map: s(fm["token-map"]) }; +} + export async function setTokenHex( app: App, path: string, @@ -574,7 +594,7 @@ export async function setSubmapInFile( mapName: string | null, ): Promise { const loc = hexLoc(path); - if (loc) { hexSource!.set(loc.map, loc.key, { locations: mapName ? [mapName] : null }); return true; } + if (loc) return hexSource!.set(loc.map, loc.key, { locations: mapName ? [mapName] : null }, "link-map"); const file = app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return false; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { diff --git a/src/hex-map/BiomeModals.ts b/src/hex-map/BiomeModals.ts index 9b29d10f..0a959d99 100644 --- a/src/hex-map/BiomeModals.ts +++ b/src/hex-map/BiomeModals.ts @@ -56,6 +56,17 @@ export function mayReshape(host: BiomeHost, parentName: string, px: number, py: return biomeLock(host, parentName, px, py) === undefined; } +/** + * Run a biome change on hex (px, py) of an overworld. Changing a placed + * region (swap, reroll, regenerate) is recorded for undo in the overworld + * queue of its mode (WM6), as the map data it changes; making a region + * for the first time is not (it makes a map). + */ +export async function reshapeUndoable(plugin: HexmakerPlugin, parentName: string, px: number, py: number, fn: () => Promise): Promise { + if (!regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`)) return fn(); + return plugin.undoableEdit(parentName, fn); +} + /** Mark a button as locked by the work mode: disabled, with the hint as its tooltip. */ export function lockButton(btn: HTMLButtonElement, hint: string): void { btn.disabled = true; @@ -122,7 +133,7 @@ export class BiomePickerModal extends HexmakerModal { reroll.addEventListener("click", () => { if (!mayReshape(this.host, this.parentName, this.px, this.py)) return; this.close(); - void regenerateRegion(plugin, region.name, { seed: newSeed() }).then(() => this.host.changed()); + void reshapeUndoable(plugin, this.parentName, this.px, this.py, () => regenerateRegion(plugin, region.name, { seed: newSeed() })).then(() => this.host.changed()); }); } row.createEl("button", { text: "Settings…" }).addEventListener("click", () => { @@ -137,7 +148,7 @@ export class BiomePickerModal extends HexmakerModal { private async apply(biome: BiomeId): Promise { const notice = new Notice("Making the region…", 0); - const res = await setBiomeAt(this.host.plugin, this.parentName, this.px, this.py, biome); + const res = await reshapeUndoable(this.host.plugin, this.parentName, this.px, this.py, () => setBiomeAt(this.host.plugin, this.parentName, this.px, this.py, biome)); notice.hide(); if ("error" in res) new Notice(res.error); this.host.changed(); @@ -264,8 +275,8 @@ export class RegionGenModal extends HexmakerModal { const region = regionMapAt(plugin.settings.maps, this.parentName, hex); const notice = new Notice(region ? "Remaking the region…" : "Making the region…", 0); let res: { name: string } | { error: string }; - if (this.opts.biome) res = await setBiomeAt(plugin, this.parentName, this.px, this.py, this.opts.biome, this.opts); - else if (region) { await regenerateRegion(plugin, region.name, this.opts); res = { name: region.name }; } + if (this.opts.biome) { const biome = this.opts.biome; res = await reshapeUndoable(plugin, this.parentName, this.px, this.py, () => setBiomeAt(plugin, this.parentName, this.px, this.py, biome, this.opts)); } + else if (region) { await reshapeUndoable(plugin, this.parentName, this.px, this.py, () => regenerateRegion(plugin, region.name, this.opts)); res = { name: region.name }; } else res = await createRegion(plugin, this.parentName, this.px, this.py, { ...this.opts, fill: "match" }); notice.hide(); if ("error" in res) new Notice(res.error); diff --git a/src/hex-map/EditRegionModal.ts b/src/hex-map/EditRegionModal.ts index 30ea3db0..a0cc6a81 100644 --- a/src/hex-map/EditRegionModal.ts +++ b/src/hex-map/EditRegionModal.ts @@ -26,7 +26,7 @@ import { biomeInfo, type BiomeId } from "../overworld/biomes"; import { hexBiomeAt, overworldOf, regenerateRegion, regionBiomeStatus, setBiomeAt } from "../overworld/regionsVault"; import { openBiomeGenerator } from "./BiomeLibraryModal"; import { editRegionPlan, terrainCountsText } from "../overworld/overworldInput"; -import { mayReshape, paintableBiomes, RegionGenModal, type BiomeHost } from "./BiomeModals"; +import { mayReshape, paintableBiomes, RegionGenModal, reshapeUndoable, type BiomeHost } from "./BiomeModals"; import { openNoteFocused } from "../openNote"; import { createIconEl, getIconUrl } from "../utils"; @@ -270,7 +270,7 @@ export class EditRegionModal extends HexmakerModal { private async setBiome(biome: BiomeId): Promise { if (!mayReshape(this.host, this.overworld, this.px, this.py)) return; const notice = new Notice("Remaking the region…", 0); - const res = await setBiomeAt(this.host.plugin, this.overworld, this.px, this.py, biome); + const res = await reshapeUndoable(this.host.plugin, this.overworld, this.px, this.py, () => setBiomeAt(this.host.plugin, this.overworld, this.px, this.py, biome)); notice.hide(); if ("error" in res) new Notice(res.error); this.host.changed(); @@ -280,7 +280,7 @@ export class EditRegionModal extends HexmakerModal { private async reroll(name: string): Promise { if (!mayReshape(this.host, this.overworld, this.px, this.py)) return; - await regenerateRegion(this.host.plugin, name, { seed: Math.floor(Math.random() * 1e9) }); + await reshapeUndoable(this.host.plugin, this.overworld, this.px, this.py, () => regenerateRegion(this.host.plugin, name, { seed: Math.floor(Math.random() * 1e9) })); this.host.changed(); await this.saveNotes(); this.render(); diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 43bfd680..5f660091 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -1,4 +1,7 @@ -import { App, Menu, Notice, TFile } from "obsidian"; +import { App, Notice, TFile } from "obsidian"; +import { canDo } from "../modeGate"; +import { lockedHint, workModeOf, type ModeAction } from "../workMode"; +import { ModeMenu } from "./modeMenu"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { @@ -281,11 +284,14 @@ export class HexEditorModal extends HexmakerModal { }); this.renderTerrainHeader(headerPreview, directTerrain, directIcon); const changeHint = terrainHeader.createSpan({ cls: "duckmage-terrain-change-hint", text: "▸ change" }); - const syncChangeHint = () => changeHint.toggle(!terrainBody.isShown()); + const syncChangeHint = () => changeHint.toggle(!terrainBody.isShown() && canDo(this.mapName, "paint-terrain")); syncChangeHint(); terrainHeader.addEventListener("click", syncChangeHint); const refreshHeader = () => this.renderTerrainHeader(headerPreview, this.directTerrain, this.directIcon); - this.renderTerrainSection(terrainBody, path, directTerrain, refreshHeader); + // Terrain and icons are map data: the map's work mode may lock them + // (one line instead of the pickers). Notes are never locked (WM2). + if (canDo(this.mapName, "paint-terrain")) this.renderTerrainSection(terrainBody, path, directTerrain, refreshHeader); + else this.renderModeLocked(terrainBody, "paint-terrain"); bodyEl.createEl("hr", { cls: "duckmage-editor-divider" }); @@ -410,7 +416,13 @@ export class HexEditorModal extends HexmakerModal { "Icons", "hexEditorIconsCollapsed", ); - this.renderIconSections(iconsBody, path, directIcon, this.directGmIcons, refreshHeader); + if (canDo(this.mapName, "paint-icon")) this.renderIconSections(iconsBody, path, directIcon, this.directGmIcons, refreshHeader); + else this.renderModeLocked(iconsBody, "paint-icon"); + } + + /** One line where a section the work mode locks would be. */ + private renderModeLocked(container: HTMLElement, action: ModeAction): void { + container.createDiv({ cls: "duckmage-editor-mode-locked", text: lockedHint(action) }); } onClose() { @@ -470,7 +482,7 @@ export class HexEditorModal extends HexmakerModal { return; } saved = name; - void this.saves.track(this.plugin.setHexName(mapName, x, y, name).then(() => this.onChanged())); + void this.saves.track(this.plugin.undoableEdit(mapName, () => this.plugin.setHexName(mapName, x, y, name)).then(() => this.onChanged())); }; input.addEventListener("input", () => { debounce.schedule(); @@ -697,13 +709,13 @@ export class HexEditorModal extends HexmakerModal { const add = strip.createEl("button", { cls: "duckmage-maps-chip-add", text: "+", attr: { "aria-label": "Add a map to this hex", title: "New map from this hex, link one, or manage locations" } }); add.addEventListener("click", (e) => { const { x, y } = this; - const menu = new Menu(); - menu.addItem((i) => i.setTitle("New map from this hex…").setIcon("plus").onClick(() => { this.close(); this.options.onNewChildMap?.(x, y); })); + const menu = new ModeMenu(workModeOf(this.plugin.getMap(this.mapName))); + menu.add("editor.new-map", "New map from this hex…", "plus", () => { this.close(); this.options.onNewChildMap?.(x, y); }); if (this.options.onLinkExistingMap) { - menu.addItem((i) => i.setTitle("Link existing map…").setIcon("link").onClick(() => { this.close(); this.options.onLinkExistingMap?.(x, y); })); + menu.add("editor.link-map", "Link existing map…", "link", () => { this.close(); this.options.onLinkExistingMap?.(x, y); }); } if (locs.length && this.options.onManageLocations) { - menu.addItem((i) => i.setTitle(`Manage locations (${locs.length})…`).setIcon("list").onClick(() => { this.close(); this.options.onManageLocations?.(x, y); })); + menu.add("editor.manage-locations", `Manage locations (${locs.length})…`, "list", () => { this.close(); this.options.onManageLocations?.(x, y); }); } menu.showAtMouseEvent(e); }); @@ -815,7 +827,7 @@ export class HexEditorModal extends HexmakerModal { let selectedTerrain = currentTerrain; const applyTerrain = async (terrain: string | null): Promise => { if (terrain !== null) await this.ensureHexNote(); - await setTerrainInFile(this.app, path, terrain); + if (!(await this.plugin.undoableEdit(this.mapName, () => setTerrainInFile(this.app, path, terrain)))) return; // The terrain's encounters table follows the terrain: show the swap. void this.plugin .syncHexEncounterTableLink(path, terrain) @@ -914,7 +926,7 @@ export class HexEditorModal extends HexmakerModal { "— terrain default —", async (picked) => { await this.ensureHexNote(); - await setIconOverrideInFile(this.app, path, picked); + if (!(await this.plugin.undoableEdit(this.mapName, () => setIconOverrideInFile(this.app, path, picked)))) return; this.directIcon = picked; onIconChange(); // header shows the icon override this.onChanged(terrainOverrides(), new Map([[path, picked]])); @@ -953,7 +965,7 @@ export class HexEditorModal extends HexmakerModal { const persist = async (): Promise => { await this.ensureHexNote(); - await setGmIconsInFile(this.app, path, list); + if (!(await this.plugin.undoableEdit(this.mapName, () => setGmIconsInFile(this.app, path, list)))) return; // Pass the new list directly via the overrides arg so the view // can update the hex's data-gm-icons attribute immediately // without round-tripping through the metadata cache (which lags @@ -1477,16 +1489,16 @@ export class HexEditorModal extends HexmakerModal { const terrain = field === "Terrain" ? this.plugin.getMapPalette(this.mapName).find((t) => sameName(t.name, written))?.name : undefined; - if (field === "Region" || terrain) { + if ((field === "Region" || terrain) && canDo(this.mapName, field === "Region" ? "paint-region-area" : "paint-terrain")) { actions.createEl("button", { text: `Use "${terrain ?? written}" on the map` }).addEventListener("click", () => { void this.saves.track((async () => { if (field === "Terrain") { await this.ensureHexNote(); - await setTerrainInFile(this.app, path, terrain!); + await this.plugin.undoableEdit(this.mapName, () => setTerrainInFile(this.app, path, terrain!)); await this.plugin.syncHexEncounterTableLink(path, terrain!); this.onChanged(new Map([[path, terrain!]])); } else { - await setHexRegionInFile(this.app, path, written); + await this.plugin.undoableEdit(this.mapName, () => setHexRegionInFile(this.app, path, written)); this.onChanged(); } await this.loadData(); @@ -1738,16 +1750,17 @@ export class HexEditorModal extends HexmakerModal { rollBtn.addEventListener("click", () => { const picked = pick(); - if (!picked) { setMapTable(); return; } + // No table yet: the map's (Build), else this hex's own (note text, any mode). + if (!picked) { if (canDo(this.mapName, "map-properties")) setMapTable(); else chooseTable((f) => setHexTable(f)); return; } new RandomTableModal(this.app, this.plugin, undefined, picked.path, this.rollTarget(section)).open(); }); srcBtn.addEventListener("click", (e) => { - const menu = new Menu(); + const menu = new ModeMenu(workModeOf(this.plugin.getMap(this.mapName))); const mapTable = mapSectionTable(this.plugin.getMap(this.mapName), section); - menu.addItem((i) => i.setTitle(mapTable ? `Change the map's ${spec.noun} table…` : `Set the map's ${spec.noun} table…`).onClick(setMapTable)); - menu.addItem((i) => i.setTitle(`Use a different table for this hex…`).onClick(() => chooseTable((f) => setHexTable(f)))); + menu.add("editor.map-table", mapTable ? `Change the map's ${spec.noun} table…` : `Set the map's ${spec.noun} table…`, null, setMapTable); + menu.add("editor.hex-table", `Use a different table for this hex…`, null, () => chooseTable((f) => setHexTable(f))); if (this.hexSectionTable(path, section)) { - menu.addItem((i) => i.setTitle("Use the map's table on this hex").onClick(() => setHexTable(null))); + menu.add("editor.hex-table", "Use the map's table on this hex", null, () => setHexTable(null)); } menu.showAtMouseEvent(e); }); diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index ac201a1c..90039b45 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -1,4 +1,4 @@ -import { ItemView, Menu, Notice, Scope, TFile, TFolder, WorkspaceLeaf } from "obsidian"; +import { ItemView, Notice, Scope, TFile, TFolder, WorkspaceLeaf } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import { normalizeFolder, getIconUrl, createIconEl } from "../utils"; import { @@ -12,7 +12,10 @@ import { setGmIconsInFile, setTerrainInFile, setIconOverrideInFile, + getGmIconsFromFile, + readTokenPlace, } from "../frontmatter"; +import { cellPatch, currentCellEdits, sameValue, stillCurrent, UNDO_DEPTH, type UndoDirection } from "../undoBook"; import { HexEditorModal } from "./HexEditorModal"; import { TerrainPickerModal } from "./TerrainPickerModal"; import { IconPickerModal } from "./IconPickerModal"; @@ -33,7 +36,9 @@ import { PathTool } from "./pathTool"; import type { PinRecord } from "../paths/routePins"; import { pathListSummary } from "./pathTool"; import { flowerPetals, MapHistory, navArrows, neighbourButton, PAD_SIDES } from "../maps/mapNav"; -import { ADD_REGION_LOCKED_HINT, canAdd, WORK_MODES, WORK_MODE_TEXT, workModeOf, type WorkMode } from "../workMode"; +import { ADD_REGION_LOCKED_HINT, allows, canAdd, lockedHint, lockedSummary, TOOL_ACTIONS, WORK_MODES, WORK_MODE_TEXT, workModeOf, type ModeAction, type WorkMode } from "../workMode"; +import { canDo, guardWrite } from "../modeGate"; +import { ModeMenu } from "./modeMenu"; import { REGION_AREAS_TOOL } from "./toolMode"; import { openNoteFocused } from "../openNote"; import { coordHaloColor } from "../coordStyle"; @@ -96,72 +101,7 @@ import { } from "../frontmatter"; import { PainterContextMenu } from "./PainterContextMenu"; -type TerrainUndoEntry = { - x: number; - y: number; - path: string; - oldTerrain: string | null; - newTerrain: string | null; -}; -type IconUndoEntry = { - x: number; - y: number; - path: string; - oldIcon: string | null; - newIcon: string | null; - isGm: boolean; - /** Full GM-icon list before/after the stroke. Only populated when - * isGm=true and the new painter (multi-add) path mutated this hex. - * Undo restores the full list; legacy oldIcon/newIcon kept for - * back-compat with strokes recorded before the multi-add change. */ - oldGmList?: string[]; - newGmList?: string[]; -}; -type FactionUndoEntry = { - hexPath: string; - factionBasename: string; - factionFilePath: string; - /** Whether the faction link was present before this stroke began. */ - wasPresent: boolean; -}; -type RegionUndoEntry = { - hexPath: string; - oldRegion: string | null; - newRegion: string | null; -}; -/** A sub-hex painted in an overworld's full view: a hex of a region map. */ -type SubHexUndoEntry = { - map: string; - key: string; - oldTerrain: string | null; - oldLocked: boolean; - newTerrain: string | null; -}; -interface CalibrateSnapshot { - bg?: { offsetX: number; offsetY: number; scale: number; rotation: number; opacity: number }; - grid: { scaleX: number; scaleY: number; offsetX: number; offsetY: number; legacyScale: number }; -} - -type UndoItem = - /** `pins`: anchors the stroke made paths gain to keep their routes (undone with it). */ - | { kind: "terrain"; entries: TerrainUndoEntry[]; pins?: PinRecord[] } - | { kind: "icon"; entries: IconUndoEntry[] } - | { kind: "faction"; entries: FactionUndoEntry[] } - | { kind: "region"; entries: RegionUndoEntry[] } - | { kind: "subhex"; entries: SubHexUndoEntry[] } - | { kind: "swap"; x1: number; y1: number; x2: number; y2: number } - | { - kind: "path"; - mapName: string; - before: MapPath[]; - after: MapPath[]; - } - | { - kind: "calibrate"; - mapName: string; - before: CalibrateSnapshot; - after: CalibrateSnapshot; - }; +import type { CalibrateSnapshot, FactionUndoEntry, IconUndoEntry, RegionUndoEntry, SubHexUndoEntry, TerrainUndoEntry, TokenSnap, UndoItem } from "./undoItems"; function nullOverrides(paths: string[]): Map { return new Map(paths.map((p) => [p, null])); @@ -366,9 +306,8 @@ export class HexMapView extends ItemView { private erasedRegions = new Set(); // hexPaths with cleared region private savingIndicatorEl: HTMLElement | null = null; // Undo / redo - private readonly UNDO_DEPTH = 20; - private undoStack: UndoItem[] = []; - private redoStack: UndoItem[] = []; + // (the queues live in plugin.undoBook: one per map per work mode, WM6) + private stopUndoListen: (() => void) | null = null; private currentTerrainStroke: Map | null = null; private currentIconStroke: Map | null = null; private currentFactionStroke: Map | null = null; @@ -414,6 +353,8 @@ export class HexMapView extends ItemView { private pendingTokenNotePath: string | null = null; private pendingTokenPlaceData: { icon?: string; shape: import("../types").TokenShape; size: import("../types").TokenSize; color?: string; border?: string; description?: string } | null = null; private tokenBtn: HTMLButtonElement | null = null; + /** The drawing panel's one line naming the mode that unlocks the hidden tools. */ + private toolsLockedEl: HTMLElement | null = null; constructor(leaf: WorkspaceLeaf, plugin: HexmakerPlugin) { super(leaf); @@ -563,11 +504,10 @@ export class HexMapView extends ItemView { } this.exitCurrentMode(); this.exitPathMode(); - this.undoStack = []; - this.redoStack = []; - this.updateUndoButton(); if (opts.recordHistory !== false) this.history.visit(this.activeMapName); this.switchToMap(name); + // Each map keeps its own undo queues (WM6): show the new map's. + this.updateUndoButton(); } /** Back to the previously viewed map (skips maps deleted since). */ @@ -767,6 +707,7 @@ export class HexMapView extends ItemView { /** The work-mode switch: names the map's mode; click to pick another. */ private refreshWorkModeBtn(): void { + this.applyWorkModeUi(); const btn = this.workModeBtn; if (!btn) return; const mode = workModeOf(this.plugin.getMap(this.activeMapName)); @@ -783,14 +724,9 @@ export class HexMapView extends ItemView { const map = this.plugin.getMap(this.activeMapName); if (!map) return; const cur = workModeOf(map); - const menu = new Menu(); + const menu = new ModeMenu(cur); for (const m of WORK_MODES) { - menu.addItem((item) => - item - .setTitle(`${WORK_MODE_TEXT[m].label}: ${WORK_MODE_TEXT[m].desc}`) - .setChecked(m === cur) - .onClick(() => this.setWorkMode(m)), - ); + menu.add("mode.switch", `${WORK_MODE_TEXT[m].label}: ${WORK_MODE_TEXT[m].desc}`, null, () => this.setWorkMode(m), { checked: m === cur }); } menu.showAtMouseEvent(e); } @@ -799,11 +735,65 @@ export class HexMapView extends ItemView { setWorkMode(mode: WorkMode): void { const map = this.plugin.getMap(this.activeMapName); if (!map || workModeOf(map) === mode) return; + // The current stroke belongs to the mode it was made in. + this.commitTerrainStroke(); + this.commitIconStroke(); map.workMode = mode; void this.plugin.saveSettings(); + // A tool the new mode locks is put down. + if (this.drawingMode && !allows(mode, TOOL_ACTIONS[this.drawingMode])) this.exitCurrentMode(); this.refreshWorkModeBtn(); // The neighbour "+" buttons lock and unlock with the mode. this.refreshSideCrumbs(); + this.applyWorkModeUi(); + // Each mode has its own undo queue (WM6). + this.updateUndoButton(); + } + + /** + * Show the open map's mode on the UI: the drawing panel shows only the + * tools the mode allows, with one line naming the mode that unlocks the + * rest; the grid's +/− buttons follow (CSS on the mode class). + */ + private applyWorkModeUi(): void { + const mode = this.currentWorkMode(); + this.contentEl.removeClass("duckmage-mode-play", "duckmage-mode-build", "duckmage-mode-god"); + this.contentEl.addClass(`duckmage-mode-${mode}`); + const tools: [HTMLElement | null, ModeAction][] = [ + [this.terrainToolbarBtn, TOOL_ACTIONS.terrain], + [this.iconToolbarBtn, TOOL_ACTIONS.icon], + [this.pathToolbarBtn, TOOL_ACTIONS.path], + [this.tableLinkBtn, TOOL_ACTIONS.tableLink], + [this.submapLinkBtn, TOOL_ACTIONS.submapLink], + [this.factionLinkBtn, TOOL_ACTIONS.factionLink], + [this.regionLinkBtn, TOOL_ACTIONS.regionLink], + [this.tokenBtn, TOOL_ACTIONS.placeToken], + ]; + const locked: ModeAction[] = []; + for (const [btn, action] of tools) { + const ok = allows(mode, action); + btn?.toggle(ok); + if (!ok) locked.push(action); + } + const hint = lockedSummary(locked); + if (this.toolsLockedEl) { + this.toolsLockedEl.setText(hint ?? ""); + this.toolsLockedEl.toggle(!!hint); + } + for (const b of this.contentEl.querySelectorAll(".duckmage-shrink-btn")) { + b.disabled = !allows(mode, "shrink-map"); + b.setAttr("title", allows(mode, "shrink-map") ? "Remove this edge" : lockedHint("shrink-map")); + } + } + + /** + * May the open map do `action` in its mode? When not, says which mode + * would (one Notice) and returns false. + */ + private modeAllows(action: ModeAction): boolean { + if (canDo(this.activeMapName, action)) return true; + new Notice(lockedHint(action)); + return false; } /** @@ -932,6 +922,9 @@ export class HexMapView extends ItemView { const { contentEl } = this; contentEl.addClass("duckmage-hex-map-container"); + // Undo entries can come from outside the view (hex editor, region editor). + this.stopUndoListen?.(); + this.stopUndoListen = this.plugin.undoBook.onChange(() => this.updateUndoButton()); // A prior build (or a crashed view) may have left a calibration banner // attached to the document body. Sweep before we render so the user @@ -1143,6 +1136,12 @@ export class HexMapView extends ItemView { return; } if (e.button !== 0) return; + // The map's work mode may lock the active tool: say so once, put it down. + if (this.drawingMode && !this.modeAllows(TOOL_ACTIONS[this.drawingMode])) { + this.exitCurrentMode(); + hasDragged = true; + return; + } // Overworld full view: the terrain tool paints the regions' own hexes. if (this.drawingMode === "terrain" && OverworldLayer.viewOf(this.plugin, this.getActiveMap()) === "biomes") { // The brush paints the regions, so it works in the Regions view. @@ -1478,8 +1477,6 @@ export class HexMapView extends ItemView { new MapModal(this.app, this.plugin, this, () => { this.exitTerrainMode(); this.exitPathMode(); - this.undoStack = []; - this.redoStack = []; this.updateUndoButton(); this.updateMapBtnLabel(); this.refreshMapNav(); @@ -1900,7 +1897,7 @@ export class HexMapView extends ItemView { group.createEl("button", { cls: "duckmage-expand-btn", text: "+" }) .addEventListener("click", () => { - if (!sizeLocked()) void expandAction(); + if (this.modeAllows("grow-map") && !sizeLocked()) void expandAction(); }); const shrinkBtn = group.createEl("button", { @@ -1920,7 +1917,7 @@ export class HexMapView extends ItemView { let pendingPaths: string[] = []; let confirmTimer: number | null = null; shrinkBtn.addEventListener("click", () => { - if (!canShrink() || sizeLocked()) return; + if (!this.modeAllows("shrink-map") || !canShrink() || sizeLocked()) return; const paths = edgePaths(); const dirty = paths.some((p) => this.hexHasContent(p)); if (dirty && !shrinkBtn.hasClass("is-confirming")) { @@ -2046,6 +2043,11 @@ export class HexMapView extends ItemView { text: "Token", }); this.tokenBtn.addEventListener("click", () => this.handleTokenButton()); + + // Tools the map's mode locks are hidden; this line says how to get them. + this.toolsLockedEl = toolbar.createDiv({ cls: "duckmage-tools-locked" }); + this.toolsLockedEl.hide(); + this.applyWorkModeUi(); } private showPainterContextMenu( @@ -2144,6 +2146,7 @@ export class HexMapView extends ItemView { } private handleTerrainButton(): void { + if (this.drawingMode !== "terrain" && !this.modeAllows(TOOL_ACTIONS.terrain)) return; // Keep the current tool while the picker is open: closing it without a // pick (Escape, clicking away, or after only changing the brush size) // must leave painting exactly as it was. It used to exit terrain mode @@ -2206,6 +2209,7 @@ export class HexMapView extends ItemView { } private handleIconButton(): void { + if (this.drawingMode !== "icon" && !this.modeAllows(TOOL_ACTIONS.icon)) return; if (this.drawingMode === "icon") { this.exitIconMode(); return; } this.openIconPicker(); } @@ -2262,6 +2266,7 @@ export class HexMapView extends ItemView { /** `keep`: opened from the tool's own right-click menu; stay in the tool unless something is picked. */ private handleTableLinkButton(keep = false): void { + if (this.drawingMode !== "tableLink" && !this.modeAllows(TOOL_ACTIONS.tableLink)) return; if (!keep && this.drawingMode === "tableLink") { this.exitTableLinkMode(); return; } new FolderTreePickerModal( this.app, @@ -2294,6 +2299,7 @@ export class HexMapView extends ItemView { } private handleSubmapLinkButton(keep = false): void { + if (this.drawingMode !== "submapLink" && !this.modeAllows(TOOL_ACTIONS.submapLink)) return; if (!keep && this.drawingMode === "submapLink") { this.exitSubmapLinkMode(); return; } new SubmapPickerModal( this.app, @@ -2319,6 +2325,7 @@ export class HexMapView extends ItemView { } private handleFactionLinkButton(): void { + if (this.drawingMode !== "factionLink" && !this.modeAllows(TOOL_ACTIONS.factionLink)) return; new FactionPickerModal(this.app, this.plugin, (filePath) => { this.leaveOtherToolFor("factionLink"); this.drawingMode = "factionLink"; @@ -2341,6 +2348,7 @@ export class HexMapView extends ItemView { } private handleRegionLinkButton(): void { + if (this.drawingMode !== "regionLink" && !this.modeAllows(TOOL_ACTIONS.regionLink)) return; new GeoRegionPickerModal(this.app, this.plugin, (filePath) => { this.leaveOtherToolFor("regionLink"); this.drawingMode = "regionLink"; @@ -2369,6 +2377,7 @@ export class HexMapView extends ItemView { } private handleTokenButton(keep = false): void { + if (this.drawingMode !== "placeToken" && !this.modeAllows(TOOL_ACTIONS.placeToken)) return; if (!keep && this.drawingMode === "placeToken") { this.exitTokenMode(); return; @@ -2399,6 +2408,7 @@ export class HexMapView extends ItemView { } private handleSwapButton(): void { + if (this.drawingMode !== "swap" && !this.modeAllows(TOOL_ACTIONS.swap)) return; if (this.drawingMode === "swap") { this.exitSwapMode(); } else { @@ -2486,34 +2496,34 @@ export class HexMapView extends ItemView { "", { color: this.nextTokenFill() }, (notePath, data) => { - void applyTokenFrontmatter(this.app, notePath, { + void this.placeToken(notePath, { icon: data.icon, shape: data.shape, size: data.size, color: data.color, border: data.border, description: data.description, - hex: `${x}_${y}`, - map: this.activeMapName, - visible: true, - }).then(() => this.updateTokenLayer()); + }, `${x}_${y}`); }, undefined, "Create token", ).open(); } + /** Put a token (new or moved) on hex `hex` of the open map; undoable. */ + private async placeToken(notePath: string, look: NonNullable, hex: string): Promise { + const map = this.activeMapName; + if (!guardWrite(map, "token")) return; + const was = await readTokenPlace(this.app, notePath); + this.pushTokenUndo(notePath, map, was, { hex, map, visible: true, look }); + await applyTokenFrontmatter(this.app, notePath, { ...look, hex, map, visible: true }); + this.updateTokenLayer(); + } + private async onHexTokenPlaceClick(x: number, y: number): Promise { if (!this.pendingTokenNotePath || !this.pendingTokenPlaceData) return; - const hexKey = `${x}_${y}`; - await applyTokenFrontmatter(this.app, this.pendingTokenNotePath, { - ...this.pendingTokenPlaceData, - hex: hexKey, - map: this.activeMapName, - visible: true, - }); + await this.placeToken(this.pendingTokenNotePath, this.pendingTokenPlaceData, `${x}_${y}`); this.exitTokenMode(); - this.updateTokenLayer(); } private async performSwap(pathA: string, pathB: string): Promise { @@ -2561,6 +2571,8 @@ export class HexMapView extends ItemView { y2: number, isUndoRedo = false, ): Promise { + // Swapping moves notes and map data: God only (src/workMode.ts). + if (!guardWrite(this.activeMapName, "swap-hexes")) return; const pathA = this.plugin.hexPath(x1, y1, this.activeMapName); const pathB = this.plugin.hexPath(x2, y2, this.activeMapName); @@ -2626,9 +2638,8 @@ export class HexMapView extends ItemView { } if (!isUndoRedo) { - this.undoStack.push({ kind: "swap", x1, y1, x2, y2 }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + const at = (x: number, y: number) => this.plugin.mapStore.get(this.activeMapName, `${x}_${y}`) ?? null; + this.pushUndo({ kind: "swap", x1, y1, x2, y2, after: [at(x1, y1), at(x2, y2)] }); this.updateUndoButton(); } } @@ -3014,9 +3025,7 @@ export class HexMapView extends ItemView { ): void { // Skip no-op snapshots (drag that didn't actually move anything) if (JSON.stringify(before) === JSON.stringify(after)) return; - this.undoStack.push({ kind: "calibrate", mapName, before, after }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + this.pushUndo({ kind: "calibrate", mapName, before, after }, mapName); this.updateUndoButton(); } @@ -3538,6 +3547,8 @@ export class HexMapView extends ItemView { * view open doesn't inherit a half-dead calibration state. */ async onClose(): Promise { + this.stopUndoListen?.(); + this.stopUndoListen = null; if (this.settleTimer !== null) window.clearTimeout(this.settleTimer); if (this.badgeTimer !== null) window.clearTimeout(this.badgeTimer); this.cancelMeasuredLayers?.(); @@ -4591,143 +4602,83 @@ export class HexMapView extends ItemView { const childPlan = submapMenuPlan(this.plugin.mapStore.get(this.activeMapName, `${x}_${y}`) ?? { locations: getHexMapsFromFile(this.app, hexPath).locations }); - const menu = new Menu(); + // Items the map's work mode locks are left out, with one hint line. + const menu = new ModeMenu(this.currentWorkMode()); - menu.addItem((item) => - item - .setTitle("Center on this hex") - .setIcon("crosshair") - .onClick(() => this.centerOnHex(x, y)), - ); + menu.add("hex.center", "Center on this hex", "crosshair", () => this.centerOnHex(x, y)); menu.addSeparator(); - menu.addItem((item) => - item - .setTitle("Open note") - .setIcon("file-text") - .onClick(async () => { - const existing = this.app.vault.getAbstractFileByPath(hexPath); - const file = - existing instanceof TFile - ? existing - : await this.plugin.createHexNote(x, y, this.activeMapName); - if (file) await openNoteFocused(this.app, file); - }), - ); + menu.add("hex.open-note", "Open note", "file-text", () => { + void (async () => { + const existing = this.app.vault.getAbstractFileByPath(hexPath); + const file = + existing instanceof TFile + ? existing + : await this.plugin.createHexNote(x, y, this.activeMapName); + if (file) await openNoteFocused(this.app, file); + })(); + }); // Maps from this hex (K7): its region, then up to two locations by // name, or one "Locations (n)…" item that opens the list. const region = childPlan.region; if (region && this.plugin.getMap(region)) { - menu.addItem((item) => - item - .setTitle(`Enter region: ${this.plugin.mapLabel(region)}`) - .setIcon("log-in") - .onClick(() => this.navigateToMap(region)), - ); + menu.add("hex.enter-region", `Enter region: ${this.plugin.mapLabel(region)}`, "log-in", () => this.navigateToMap(region)); } for (const loc of childPlan.open) { - menu.addItem((item) => - item - .setTitle(`Open: ${this.plugin.mapLabel(loc)}`) - .setIcon("map-pin") - .onClick(() => { - if (this.plugin.getMap(loc)) this.navigateToMap(loc); - else this.openLocationsList(x, y); - }), - ); + menu.add("hex.open-location", `Open: ${this.plugin.mapLabel(loc)}`, "map-pin", () => { + if (this.plugin.getMap(loc)) this.navigateToMap(loc); + else this.openLocationsList(x, y); + }); } if (childPlan.listCount) { - menu.addItem((item) => - item - .setTitle(`Locations (${childPlan.listCount})…`) - .setIcon("list") - .onClick(() => this.openLocationsList(x, y)), - ); + menu.add("hex.locations", `Locations (${childPlan.listCount})…`, "list", () => this.openLocationsList(x, y)); } - menu.addItem((item) => - item - .setTitle("New map from this hex…") - .setIcon("plus") - .onClick(() => this.openNewSubmapSetup(x, y)), - ); - menu.addItem((item) => - item - .setTitle("Link existing map…") - .setIcon("link") - .onClick(() => this.openLinkExistingMap(x, y)), - ); + menu.add("hex.new-map", "New map from this hex…", "plus", () => this.openNewSubmapSetup(x, y)); + menu.add("hex.link-map", "Link existing map…", "link", () => this.openLinkExistingMap(x, y)); if (childPlan.open.length) { // Unlinking and reordering live in the list. - menu.addItem((item) => - item - .setTitle("Manage locations…") - .setIcon("list") - .onClick(() => this.openLocationsList(x, y)), - ); + menu.add("hex.manage-locations", "Manage locations…", "list", () => this.openLocationsList(x, y)); } - menu.addItem((item) => - item - .setTitle("Link table") - .setIcon("table") - .onClick(() => { - new FolderTreePickerModal( - this.app, - this.plugin, - this.plugin.settings.tablesFolder, - "Link table", - "Filter tables…", - "No tables found.", - (file) => void this.linkTableToHex(x, y, file), - () => { - void this.app.workspace - .getLeaf("tab") - .setViewState({ type: VIEW_TYPE_RANDOM_TABLES }); - }, - (file) => void this.openRandomTableAtFile(file), - ).open(); - }), - ); + menu.add("hex.link-table", "Link table", "table", () => { + new FolderTreePickerModal( + this.app, + this.plugin, + this.plugin.settings.tablesFolder, + "Link table", + "Filter tables…", + "No tables found.", + (file) => void this.linkTableToHex(x, y, file), + () => { + void this.app.workspace + .getLeaf("tab") + .setViewState({ type: VIEW_TYPE_RANDOM_TABLES }); + }, + (file) => void this.openRandomTableAtFile(file), + ).open(); + }); - menu.addItem((item) => - item - .setTitle("Swap hex") - .setIcon("arrow-left-right") - .onClick(() => { - if (this.drawingMode !== "swap") this.handleSwapButton(); - void this.onHexSwapClick(x, y); - }), - ); + menu.add("hex.swap", "Swap hex", "arrow-left-right", () => { + if (this.drawingMode !== "swap") this.handleSwapButton(); + void this.onHexSwapClick(x, y); + }); - menu.addItem((item) => - item - .setTitle("Create token here") - .setIcon("circle-user") - .onClick(() => this.createTokenAtHex(x, y)), - ); + menu.add("hex.create-token", "Create token here", "circle-user", () => this.createTokenAtHex(x, y)); // ── Contextual delete options ────────────────────────────────────────── if (terrain || iconOverride) { menu.addSeparator(); if (terrain) { - menu.addItem((item) => - item.setTitle("Clear terrain").setIcon("eraser") - .onClick(() => { - this.scheduleTerrainWrite(x, y, hexPath, null); - this.renderGrid(); - }), - ); + menu.add("hex.clear-terrain", "Clear terrain", "eraser", () => { + this.paintOne(x, y, null); + }); } if (iconOverride) { - menu.addItem((item) => - item.setTitle("Remove icon override").setIcon("image-off") - .onClick(() => { - this.scheduleIconWrite(x, y, hexPath, null); - this.renderGrid(undefined, new Map([[hexPath, null]])); - }), - ); + menu.add("hex.remove-icon", "Remove icon override", "image-off", () => { + this.removeIconOverride(x, y); + }); } } @@ -4747,30 +4698,23 @@ export class HexMapView extends ItemView { const key = `${px}_${py}`; const region = regionMapAt(this.plugin.settings.maps, this.activeMapName, key)?.name; const locations = this.plugin.mapStore.get(this.activeMapName, key)?.locations?.length ?? 0; - const menu = new Menu(); + const menu = new ModeMenu(this.currentWorkMode()); const icons: Record = { "enter-region": "log-in", "edit-region": "settings-2", "set-biome": "trees", center: "crosshair", locations: "list" }; for (const it of overworldMenu(this.getActiveMap(), !!region, locations)) { - menu.addItem((item) => { - item - .setTitle(it.id === "enter-region" && region ? `Enter region: ${this.plugin.mapLabel(region)}` : it.enabled ? it.title : `${it.title} (${it.hint})`) - .setIcon(icons[it.id] ?? "dot") - .setDisabled(!it.enabled); - if (!it.enabled) return; - item.onClick(() => { - if (it.id === "enter-region" && region) { - if (cell) this.enterRegionAt(region, cell.x, cell.y); - else this.navigateToMap(region); - } else if (it.id === "edit-region") this.openEditRegion(px, py); - else if (it.id === "set-biome") new BiomePickerModal(this.biomeHost(), this.activeMapName, px, py).open(); - else if (it.id === "center") this.centerOnHex(px, py); - else if (it.id === "locations") this.openLocationsList(px, py); - }); - }); + const id = `ow.${it.id}` as const; + const title = it.id === "enter-region" && region ? `Enter region: ${this.plugin.mapLabel(region)}` : it.enabled ? it.title : `${it.title} (${it.hint})`; + menu.add(id, title, icons[it.id] ?? "dot", () => { + if (it.id === "enter-region" && region) { + if (cell) this.enterRegionAt(region, cell.x, cell.y); + else this.navigateToMap(region); + } else if (it.id === "edit-region") this.openEditRegion(px, py); + else if (it.id === "set-biome") new BiomePickerModal(this.biomeHost(), this.activeMapName, px, py).open(); + else if (it.id === "center") this.centerOnHex(px, py); + else if (it.id === "locations") this.openLocationsList(px, py); + }, { disabled: !it.enabled }); } // Mark the party (or anything) on the overworld: tokens sit on its hexes. - menu.addItem((item) => - item.setTitle("Create token here").setIcon("circle-user").onClick(() => this.createTokenAtHex(px, py)), - ); + menu.add("ow.create-token", "Create token here", "circle-user", () => this.createTokenAtHex(px, py)); menu.showAtMouseEvent(evt); } @@ -4786,6 +4730,10 @@ export class HexMapView extends ItemView { } private async onHexClick(x: number, y: number, e?: MouseEvent): Promise { + if (this.drawingMode && !this.modeAllows(TOOL_ACTIONS[this.drawingMode])) { + this.exitCurrentMode(); + return; + } if (this.drawingMode === "path") { this.pathTool.click(x, y, e, this.isErasingMode); return; @@ -4989,9 +4937,7 @@ export class HexMapView extends ItemView { oldGmList: priorList, newGmList: newList, }; - this.undoStack.push({ kind: "icon", entries: [undoEntry] }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + this.pushUndo({ kind: "icon", entries: [undoEntry] }); this.updateUndoButton(); if (newList.length > 0) { @@ -5330,9 +5276,7 @@ export class HexMapView extends ItemView { const stroke = this.currentSubStroke; this.currentSubStroke = null; if (!stroke || stroke.size === 0) return; - this.undoStack.push({ kind: "subhex", entries: [...stroke.values()] }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + this.pushUndo({ kind: "subhex", entries: [...stroke.values()] }); this.updateUndoButton(); } @@ -5471,6 +5415,28 @@ export class HexMapView extends ItemView { }; } + /** Set (or clear) one hex's terrain from a menu: mode-gated and undoable. */ + private paintOne(x: number, y: number, terrain: string | null): void { + if (!this.modeAllows("paint-terrain")) return; + const path = this.plugin.hexPath(x, y, this.activeMapName); + const old = getTerrainFromFile(this.app, path); + if (old === terrain) return; + this.pushUndo({ kind: "terrain", entries: [{ x, y, path, oldTerrain: old, newTerrain: terrain }] }); + this.scheduleTerrainWrite(x, y, path, terrain); + this.renderGrid(); + } + + /** "Remove icon override" from the hex menu: mode-gated and undoable. */ + private removeIconOverride(x: number, y: number): void { + if (!this.modeAllows("paint-icon")) return; + const path = this.plugin.hexPath(x, y, this.activeMapName); + const old = getIconOverrideFromFile(this.app, path); + if (!old) return; + this.pushUndo({ kind: "icon", entries: [{ x, y, path, oldIcon: old, newIcon: null, isGm: false }] }); + this.scheduleIconWrite(x, y, path, null); + this.renderGrid(undefined, new Map([[path, null]])); + } + private commitTerrainStroke(): void { this.commitSubStroke(); if (!this.currentTerrainStroke || this.currentTerrainStroke.size === 0) { @@ -5481,9 +5447,7 @@ export class HexMapView extends ItemView { // Pins made by this stroke's writes (some land after the mouse is up). const pins = this.strokePins ?? []; this.strokePins = pins; - this.undoStack.push({ kind: "terrain", entries, pins }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + this.pushUndo({ kind: "terrain", entries, pins }); this.currentTerrainStroke = null; this.updateUndoButton(); void this.releaseStrokePins(pins); @@ -5495,9 +5459,7 @@ export class HexMapView extends ItemView { return; } const entries = [...this.currentIconStroke.values()]; - this.undoStack.push({ kind: "icon", entries }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + this.pushUndo({ kind: "icon", entries }); this.currentIconStroke = null; this.updateUndoButton(); } @@ -5508,9 +5470,7 @@ export class HexMapView extends ItemView { return; } const entries = [...this.currentFactionStroke.values()]; - this.undoStack.push({ kind: "faction", entries }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + this.pushUndo({ kind: "faction", entries }); this.currentFactionStroke = null; this.updateUndoButton(); } @@ -5521,70 +5481,168 @@ export class HexMapView extends ItemView { return; } const entries = [...this.currentRegionStroke.values()]; - this.undoStack.push({ kind: "region", entries }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + this.pushUndo({ kind: "region", entries }); this.currentRegionStroke = null; this.updateUndoButton(); } + /** Record an action in this map's queue for its current mode (WM6). */ + private pushUndo(item: UndoItem, mapName = this.activeMapName): void { + this.plugin.pushUndo(mapName, item); + } + + /** The open map's work mode: its undo queue is the one the buttons use. */ + private currentWorkMode(): WorkMode { + return workModeOf(this.plugin.getMap(this.activeMapName)); + } + + private undoBusy = false; + + /** Undo the last action done on this map in its current mode (WM6). */ private async undo(): Promise { - const item = this.undoStack.pop(); - if (!item) return; - this.redoStack.push(item); - if (item.kind === "terrain") { - this.strokePins = null; - this.applyStroke(item.entries, "old"); - // Once the old terrain is back, the anchors the stroke pinned go too. - if (item.pins?.length) { - const pins = item.pins; - await this.terrainWritesSettled(); - this.plugin.pathPins.rerouteInstead(pins); + await this.undoStep("undo"); + } + + private async redo(): Promise { + await this.undoStep("redo"); + } + + /** + * One undo or redo step from this map's queue for its mode. An entry whose + * target changed since (in another mode, or by hand) is skipped part by + * part, so it never reverts the newer change (prepareUndo). + */ + private async undoStep(dir: UndoDirection): Promise { + if (this.undoBusy) return; + this.undoBusy = true; + try { + // Reads below compare against what's stored: let queued writes land. + await this.terrainWritesSettled(); + const item = await this.plugin.undoBook.step(this.activeMapName, this.currentWorkMode(), dir, (it, d) => this.prepareUndo(it, d)); + if (item) await this.applyUndo(item, dir); + } finally { + this.undoBusy = false; + this.updateUndoButton(); + } + } + + /** + * The part of `item` whose target still shows what the entry left there + * (undo: its "after"; redo: its "before"), or null when none does. + */ + private async prepareUndo(item: UndoItem, dir: UndoDirection): Promise { + const store = this.plugin.mapStore; + const keep = (parts: E[], current: (p: E) => unknown, before: (p: E) => unknown, after: (p: E) => unknown) => + stillCurrent(parts, dir, current, before, after); + switch (item.kind) { + case "terrain": { + const entries = keep(item.entries, (e) => getTerrainFromFile(this.app, e.path), (e) => e.oldTerrain, (e) => e.newTerrain); + return entries ? { ...item, entries } : null; + } + case "icon": { + const list = (l: string[] | undefined, one: string | null) => l ?? (one !== null ? [one] : []); + const entries = keep( + item.entries, + (e) => (e.isGm ? getGmIconsFromFile(this.app, e.path) : getIconOverrideFromFile(this.app, e.path)), + (e) => (e.isGm ? list(e.oldGmList, e.oldIcon) : e.oldIcon), + (e) => (e.isGm ? list(e.newGmList, e.newIcon) : e.newIcon), + ); + return entries ? { ...item, entries } : null; + } + case "faction": { + const entries = keep(item.entries, (e) => this.getFactionLinksFromCache(e.hexPath).includes(e.factionBasename), (e) => e.wasPresent, (e) => !e.wasPresent); + return entries ? { ...item, entries } : null; + } + case "region": { + const entries = keep(item.entries, (e) => getHexRegionFromFile(this.app, e.hexPath), (e) => e.oldRegion, (e) => e.newRegion); + return entries ? { ...item, entries } : null; + } + case "subhex": { + const entries = keep(item.entries, (e) => store.get(e.map, e.key)?.terrain ?? null, (e) => e.oldTerrain, (e) => e.newTerrain); + return entries ? { ...item, entries } : null; + } + case "swap": { + if (!item.after) return item; + const now = [store.get(this.activeMapName, `${item.x1}_${item.y1}`) ?? null, store.get(this.activeMapName, `${item.x2}_${item.y2}`) ?? null]; + // A swap is its own inverse: before it, the two hexes held each other's data. + const want = dir === "undo" ? item.after : [item.after[1], item.after[0]]; + return sameValue(now, want) ? item : null; + } + case "path": { + const want = dir === "undo" ? item.after : item.before; + return sameValue(store.paths(item.mapName), want) ? item : null; + } + case "calibrate": { + const map = this.plugin.getMap(item.mapName); + if (!map) return null; + return sameValue(this.captureCalibration(map), dir === "undo" ? item.after : item.before) ? item : null; + } + case "cells": { + const edits = currentCellEdits(item.edits, dir, (m, k) => store.get(m, k) as Record | undefined); + return edits ? { ...item, edits } : null; + } + case "token": { + const now = await readTokenPlace(this.app, item.path); + const want = dir === "undo" ? item.after : item.before; + const place = (t: TokenSnap | null) => (t ? { hex: t.hex, map: t.map } : null); + return sameValue(now, place(want)) ? item : null; } - } else if (item.kind === "icon") { - await this.applyIconStroke(item.entries, "old"); - } else if (item.kind === "faction") { - await this.applyFactionStroke(item.entries, "old"); - } else if (item.kind === "region") { - await this.applyRegionStroke(item.entries, "old"); - } else if (item.kind === "subhex") { - this.applySubStroke(item.entries, "old"); - } else if (item.kind === "swap") { - await this.executeHexSwap(item.x1, item.y1, item.x2, item.y2, true); - } else if (item.kind === "calibrate") { - await this.applyCalibrationSnapshot(item.mapName, item.before); - } else { - await this.applyPathSnapshot(item.mapName, item.before); } - this.updateUndoButton(); } - private async redo(): Promise { - const item = this.redoStack.pop(); - if (!item) return; - this.undoStack.push(item); + /** Apply a prepared entry (undo: back to "before"; redo: to "after"). */ + private async applyUndo(item: UndoItem, dir: UndoDirection): Promise { + const which = dir === "undo" ? "old" : "new"; if (item.kind === "terrain") { - // Repainting pins the routes again (and they're recorded afresh). - item.pins = []; - this.strokePins = item.pins; - this.applyStroke(item.entries, "new"); - void this.releaseStrokePins(item.pins); + if (dir === "undo") { + this.strokePins = null; + this.applyStroke(item.entries, "old"); + // Once the old terrain is back, the anchors the stroke pinned go too. + if (item.pins?.length) { + const pins = item.pins; + await this.terrainWritesSettled(); + this.plugin.pathPins.rerouteInstead(pins); + } + } else { + // Repainting pins the routes again (and they're recorded afresh). + item.pins = []; + this.strokePins = item.pins; + this.applyStroke(item.entries, "new"); + void this.releaseStrokePins(item.pins); + } } else if (item.kind === "icon") { - await this.applyIconStroke(item.entries, "new"); + await this.applyIconStroke(item.entries, which); } else if (item.kind === "faction") { - await this.applyFactionStroke(item.entries, "new"); + await this.applyFactionStroke(item.entries, which); } else if (item.kind === "region") { - await this.applyRegionStroke(item.entries, "new"); + await this.applyRegionStroke(item.entries, which); } else if (item.kind === "subhex") { - this.applySubStroke(item.entries, "new"); + this.applySubStroke(item.entries, which); } else if (item.kind === "swap") { await this.executeHexSwap(item.x1, item.y1, item.x2, item.y2, true); } else if (item.kind === "calibrate") { - await this.applyCalibrationSnapshot(item.mapName, item.after); + await this.applyCalibrationSnapshot(item.mapName, dir === "undo" ? item.before : item.after); + } else if (item.kind === "path") { + await this.applyPathSnapshot(item.mapName, dir === "undo" ? item.before : item.after); + } else if (item.kind === "cells") { + for (const e of item.edits) this.plugin.mapStore.set(e.map, e.key, cellPatch(e, dir)); + this.renderGrid(); } else { - await this.applyPathSnapshot(item.mapName, item.after); + await this.applyTokenSnap(item.path, dir === "undo" ? item.before : item.after); } - this.updateUndoButton(); + } + + /** Put a token where a snapshot says (null: it stops being a token). */ + private async applyTokenSnap(path: string, snap: TokenSnap | null): Promise { + if (!snap) await removeTokenFrontmatter(this.app, path); + else await applyTokenFrontmatter(this.app, path, { ...(snap.look ?? {}), hex: snap.hex, map: snap.map, visible: snap.visible ?? true }); + this.updateTokenLayer(); + } + + /** Record a token change for undo (from a token's data before and after). */ + private pushTokenUndo(path: string, mapName: string, before: TokenSnap | null, after: TokenSnap | null): void { + if (sameValue(before, after)) return; + this.pushUndo({ kind: "token", path, before, after }, mapName); } private applyPathSnapshot(mapName: string, paths: MapPath[]): Promise { @@ -5711,8 +5769,18 @@ export class HexMapView extends ItemView { } private updateUndoButton(): void { - if (this.undoBtn) this.undoBtn.disabled = this.undoStack.length === 0; - if (this.redoBtn) this.redoBtn.disabled = this.redoStack.length === 0; + // The buttons act on this map's queue for its current mode, and say so. + const mode = this.currentWorkMode(); + const label = WORK_MODE_TEXT[mode].label; + const book = this.plugin.undoBook; + if (this.undoBtn) { + this.undoBtn.disabled = !book.canUndo(this.activeMapName, mode); + this.undoBtn.setAttr("title", `Undo (${label} mode, up to ${UNDO_DEPTH})`); + } + if (this.redoBtn) { + this.redoBtn.disabled = !book.canRedo(this.activeMapName, mode); + this.redoBtn.setAttr("title", `Redo (${label} mode)`); + } } private updateSavingIndicator(): void { @@ -5942,6 +6010,7 @@ export class HexMapView extends ItemView { * T7); leave the tool with right-click → Exit tool, Esc, or the mode bar. */ private handlePathButton(): void { + if (this.drawingMode !== "path" && !this.modeAllows(TOOL_ACTIONS.path)) return; new PathPickerModal( this.app, this.plugin, @@ -6006,9 +6075,7 @@ export class HexMapView extends ItemView { } private pushPathUndo(mapName: string, before: MapPath[], after: MapPath[]): void { - this.undoStack.push({ kind: "path", mapName, before, after }); - if (this.undoStack.length > this.UNDO_DEPTH) this.undoStack.shift(); - this.redoStack = []; + this.pushUndo({ kind: "path", mapName, before, after }, mapName); this.updateUndoButton(); } @@ -7626,7 +7693,10 @@ export class HexMapView extends ItemView { tokenEl.style.left = `${newCenter.cx}px`; tokenEl.style.top = `${newCenter.cy}px`; } - void setTokenHex(this.app, token.filePath, closestHex, token.map); + if (guardWrite(token.map, "token")) { + this.pushTokenUndo(token.filePath, token.map, { hex: token.hex, map: token.map }, { hex: closestHex, map: token.map }); + void setTokenHex(this.app, token.filePath, closestHex, token.map); + } } else { const orig = centerMap.get(token.hex); if (orig) { @@ -7651,67 +7721,48 @@ export class HexMapView extends ItemView { void applyTokenFrontmatter(this.app, token.filePath, data) .then(() => this.updateTokenLayer()); }, - () => { - void removeTokenFrontmatter(this.app, token.filePath) - .then(() => this.updateTokenLayer()); - }, + () => this.removeToken(token), ).open(); } + /** A token's place and look, for undo of making or removing it. */ + private tokenSnap(token: TokenEntry): TokenSnap { + return { + hex: token.hex, + map: token.map, + visible: token.visible, + look: { icon: token.icon, shape: token.shape, size: token.size, color: token.color, border: token.border, tokenLink: token.tokenLink, description: token.description }, + }; + } + + /** Remove a token from the map (the note stays); undoable. */ + private removeToken(token: TokenEntry): void { + if (!guardWrite(token.map, "token")) return; + this.pushTokenUndo(token.filePath, token.map, this.tokenSnap(token), null); + void removeTokenFrontmatter(this.app, token.filePath) + .then(() => this.updateTokenLayer()); + } + private openTokenInfo(token: TokenEntry): void { new TokenInfoModal( this.app, token, (x, y) => this.centerOnHex(x, y), - () => { - void removeTokenFrontmatter(this.app, token.filePath) - .then(() => this.updateTokenLayer()); - }, + () => this.removeToken(token), () => this.openTokenEditor(token), ).open(); } private showTokenContextMenu(evt: MouseEvent, token: TokenEntry): void { - const menu = new Menu(); - - menu.addItem((item) => - item - .setTitle("Token info") - .setIcon("info") - .onClick(() => this.openTokenInfo(token)), - ); - - menu.addItem((item) => - item - .setTitle("Edit token") - .setIcon("pencil") - .onClick(() => this.openTokenEditor(token)), - ); - - menu.addItem((item) => - item - .setTitle("Open note") - .setIcon("file-text") - .onClick(() => { - const file = this.app.vault.getAbstractFileByPath(token.filePath); - if (file instanceof TFile) { - void openNoteFocused(this.app, file); - } - }), - ); - + const menu = new ModeMenu(this.currentWorkMode()); + menu.add("token.info", "Token info", "info", () => this.openTokenInfo(token)); + menu.add("token.edit", "Edit token", "pencil", () => this.openTokenEditor(token)); + menu.add("token.open-note", "Open note", "file-text", () => { + const file = this.app.vault.getAbstractFileByPath(token.filePath); + if (file instanceof TFile) void openNoteFocused(this.app, file); + }); menu.addSeparator(); - - menu.addItem((item) => - item - .setTitle("Remove token") - .setIcon("trash") - .onClick(() => { - void removeTokenFrontmatter(this.app, token.filePath) - .then(() => this.updateTokenLayer()); - }), - ); - + menu.add("token.remove", "Remove token", "trash", () => this.removeToken(token)); menu.showAtMouseEvent(evt); } } diff --git a/src/hex-map/LocationsModal.ts b/src/hex-map/LocationsModal.ts index 2bb29c27..77284fff 100644 --- a/src/hex-map/LocationsModal.ts +++ b/src/hex-map/LocationsModal.ts @@ -2,6 +2,8 @@ import { App } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { filterByQuery, moveItem } from "../maps/submaps"; +import { canDo } from "../modeGate"; +import { lockedHint } from "../workMode"; export interface LocationsModalActions { open: (map: string) => void; @@ -51,6 +53,12 @@ export class LocationsModal extends HexmakerModal { }); this.contentEl.createDiv({ cls: "duckmage-locations-list" }); const foot = this.contentEl.createDiv({ cls: "duckmage-locations-foot" }); + // Adding, unlinking and reordering change the map (Build); Play only opens. + if (!canDo(this.mapName, "link-map")) { + foot.createSpan({ cls: "duckmage-editor-mode-locked", text: lockedHint("link-map") }); + this.drawList(); + return; + } foot.createEl("button", { text: "New location…" }).addEventListener("click", () => { this.close(); this.actions.newLocation(); @@ -73,7 +81,8 @@ export class LocationsModal extends HexmakerModal { if (!all.length) list.createDiv({ cls: "duckmage-picker-list-empty", text: "No locations yet." }); else if (!shown.length) list.createDiv({ cls: "duckmage-picker-list-empty", text: "No location matches." }); // Reordering only makes sense on the whole list. - const canDrag = !this.query.trim() && all.length > 1; + const editable = canDo(this.mapName, "link-map"); + const canDrag = editable && !this.query.trim() && all.length > 1; for (const it of shown) { const map = this.plugin.getMap(it.name); const row = list.createDiv({ cls: "duckmage-locations-row" }); @@ -109,6 +118,7 @@ export class LocationsModal extends HexmakerModal { const open = row.createEl("button", { text: "Open", attr: { "aria-label": `Open ${it.label}` } }); open.disabled = !map; open.addEventListener("click", () => this.openMap(it.name)); + if (!editable) continue; const unlink = row.createEl("button", { text: "✕", cls: "duckmage-locations-unlink", attr: { "aria-label": `Unlink ${it.label}`, title: "Unlink from this hex (the map itself stays)" } }); unlink.addEventListener("click", () => { void this.plugin.unlinkSubmap(this.mapName, this.x, this.y, it.name).then(() => { diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 6565ea60..12900170 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -25,7 +25,8 @@ import { regionsOf, removeMapPatch } from "../maps/submaps"; import { RegionSettingsModal } from "./newChildMap"; import { GenerateRegionsModal, NewOverworldModal } from "./OverworldModals"; import { REGENERATE_LOCKED_HINT } from "../overworld/overworldGen"; -import { canReshape } from "../workMode"; +import { canReshape, lockedHint } from "../workMode"; +import { canDo, guardWrite } from "../modeGate"; import { meshes } from "../overworld/regionWorld"; import { missingRegionHexes } from "../overworld/regionsVault"; import { renderRegionSettingsForm } from "./regionSettingsForm"; @@ -362,6 +363,12 @@ export class MapModal extends HexmakerModal { private renderPropertiesTab(el: HTMLElement): void { const currentMap = this.plugin.getMap(this.view.activeMapName); + // Properties are map structure: locked in Play (one line, not a wall of + // disabled fields). + if (!canDo(this.view.activeMapName, "map-properties")) { + el.createEl("p", { cls: "duckmage-editor-mode-locked", text: lockedHint("map-properties") }); + return; + } // Name (display only: nothing moves) and folder name (the slug; moves // the folder and map note, and updates every reference). @@ -588,6 +595,10 @@ export class MapModal extends HexmakerModal { private renderDeleteBlock(el: HTMLElement, name: string): void { el.createEl("h4", { text: "Delete map" }); + if (!canDo(name, "delete-map")) { + el.createEl("p", { text: lockedHint("delete-map"), cls: "duckmage-map-origin-desc" }); + return; + } if (this.plugin.settings.maps.length <= 1) { el.createEl("p", { text: "This is the only map, so it can't be deleted.", cls: "duckmage-map-origin-desc" }); return; @@ -768,6 +779,7 @@ export class MapModal extends HexmakerModal { // ── Delete ──────────────────────────────────────────────────────────────── private async deleteMap(name: string): Promise { + if (!guardWrite(name, "delete-map")) return; const hexFolder = normalizeFolder(this.plugin.settings.hexFolder); const folderPath = hexFolder ? `${hexFolder}/${name}` : name; const folder = this.app.vault.getAbstractFileByPath(folderPath); @@ -799,6 +811,7 @@ export class MapModal extends HexmakerModal { // Hexes pointing at the deleted map lose that link (region or location); // its own regions and locations become top-level maps. this.plugin.mapStore.forgetMap(name); + this.plugin.undoBook.forgetMap(name); for (const m of this.plugin.settings.maps) { for (const [key, h] of [...this.plugin.mapStore.all(m.name)]) { const patch = removeMapPatch(h, name); @@ -856,6 +869,8 @@ export class MapModal extends HexmakerModal { if (map) map.name = newName; // The map note moved with its folder; give it the new name too. await this.plugin.mapStore.renameMap(oldName, newName); + // Its undo queues follow it (WM6). + this.plugin.undoBook.renameMap(oldName, newName); if (this.plugin.settings.defaultMap === oldName) { this.plugin.settings.defaultMap = newName; } diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 2c2970d3..b35ecec9 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -138,7 +138,15 @@ Turn on any one of them from the hint (✦) where it would appear, or all of the **Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). Right-click a region → **Edit region…** for its name, the hex it's on, **Enter region**, **Open map note**, its biome, facts (size, palette, terrain counts, neighbouring regions, locations) and notes (kept in its map note under `## Notes`, editable in every mode). The biome can only be changed in God mode: there it's a picker with **Reroll** and **Settings…**; in Build and Play it's shown with "Switch to God to change it." The overworld has no hex editor: right-click shows only region-level items. The terrain tool always paints the regions: picking a terrain switches to the Regions view, the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. -**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (it's the `mode:` line in the map note) and opens in it next time. New maps are in **Build**. For now the mode guards two things on overworlds. Changing what's already placed (swapping a placed biome, **Reroll**, applying **Settings…** to an existing region) needs **God**; in Build and Play those buttons are greyed out and say "Switch to God to change a placed biome." Placing a biome on an empty hex (which makes its region) needs **Build** or God; in Play the biome picker is greyed out and says "Switch to Build to place a biome.", and **New map from this hex… → Region** says "Switch to Build to make a region." Notes stay editable in every mode, and settings and palettes are never locked. No confirm boxes: the mode is the safety catch. +**Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (the `mode:` line in its map note) and opens in it next time; new maps are in **Build**. + +- **Play** is for running a game: move, place and remove tokens, open and edit notes, roll tables, link tables and factions to hexes, turn layers on and off. The map itself stays as it is. The drawing panel shows only the tools Play allows, with one line naming the mode for the rest ("Switch to Build to edit the map."); the grid's **+** / **−** buttons are hidden, the hex editor shows "Switch to Build to paint terrain." where the terrain and icon pickers were, the map's properties say "Switch to Build to change the map's properties.", and the right-click menu leaves out what's locked and ends with one such line. +- **Build** adds and edits: paint terrain, icons and region areas, draw paths, link maps to hexes, grow the map, make maps and regions from a hex, change the map's properties, place a biome on an empty overworld hex. +- **God** can do everything, including changing a placed biome (**Reroll**, **Settings…**), swapping hexes, shrinking the grid and deleting the map. + +Notes, settings and palettes are never locked. There are no confirm boxes for these: the mode is the safety catch. + +**Undo per mode.** Each map has its own undo queue in each mode, kept until you close the vault. Undo (**↩** or Ctrl+Z) and redo take back the last thing done on this map in the mode it's in now: undoing a token move in Play never undoes Build's terrain, and switching back to Build picks its queue up where you left it. If something was changed again in another mode since (a token moved in Build, then again in Play), Build's undo skips it rather than moving it back. Terrain, icons, region areas, paths, tokens, swaps, hex editor edits and biome changes (reroll, swap) are all undoable. The buttons' tooltips name the mode. **Your own biomes.** Each biome is a note in the biomes folder (default `{world folder}/biomes`); the built-in ones are written there once, so you can edit them. A note lists terrain *types* with weights (**Mix**), **Transitions** (biomes it shouldn't touch, and what goes between), and `blend`, `land-share`, `min-islands` and an optional `generator` link. In the **Biomes** view, **Biomes…** lists them with **Add biome…**, **Edit…** (built-ins also have **Restore default**) and **Edit generator…**; the form has a live preview of one region. Needs Build or God. Inside a region, click the middle of the hex flower for **Edit region…**; right-click an overworld hex for **Create token here**. diff --git a/src/hex-map/modeMenu.ts b/src/hex-map/modeMenu.ts new file mode 100644 index 00000000..ca150f65 --- /dev/null +++ b/src/hex-map/modeMenu.ts @@ -0,0 +1,67 @@ +/** + * The map view's menus, through the work-mode table (src/workMode.ts). + * Every item names its MENU_ACTIONS id; an item the map's mode locks is + * left out, and the menu ends with ONE disabled line saying which mode + * unlocks them ("Switch to Build to paint terrain."), never a wall of + * greyed-out items. tests/workModeCoverage.test.ts checks that the map + * view builds its menus only through here. + */ +import { Menu } from "obsidian"; +import { allows, lockedSummary, MENU_ACTIONS, type MenuActionId, type ModeAction, type WorkMode } from "../workMode"; + +export class ModeMenu { + readonly menu = new Menu(); + private locked: ModeAction[] = []; + + constructor(private mode: WorkMode) {} + + /** Is the item allowed in this mode? */ + allows(id: MenuActionId): boolean { + return allows(this.mode, MENU_ACTIONS[id]); + } + + /** + * Add an item (when the mode allows it). `opts.disabled` (with its own + * reason in the title) is for other reasons an item can't run now. + */ + add(id: MenuActionId, title: string, icon: string | null, onClick: () => void, opts: { disabled?: boolean; checked?: boolean } = {}): void { + const action = MENU_ACTIONS[id]; + if (!allows(this.mode, action)) { + this.locked.push(action); + return; + } + this.menu.addItem((item) => { + item.setTitle(title).setDisabled(!!opts.disabled); + if (icon) item.setIcon(icon); + if (opts.checked !== undefined) item.setChecked(opts.checked); + if (!opts.disabled) item.onClick(onClick); + }); + } + + addSeparator(): void { + this.menu.addSeparator(); + } + + /** The one-line hint for what was left out (null when nothing was). */ + hint(): string | null { + return lockedSummary(this.locked); + } + + private finish(): void { + const hint = this.hint(); + if (!hint) return; + this.menu.addSeparator(); + this.menu.addItem((item) => item.setTitle(hint).setIcon("lock").setDisabled(true)); + this.locked = []; + } + + showAtMouseEvent(evt: MouseEvent): void { + this.finish(); + this.menu.showAtMouseEvent(evt); + } + + showAtPosition(at: { x: number; y: number }): void { + this.finish(); + this.menu.showAtPosition(at); + } +} diff --git a/src/hex-map/undoItems.ts b/src/hex-map/undoItems.ts new file mode 100644 index 00000000..225d1975 --- /dev/null +++ b/src/hex-map/undoItems.ts @@ -0,0 +1,88 @@ +/** + * What the map's undo queues hold (src/undoBook.ts: one queue per map per + * work mode). Each entry knows its "after" state, so an entry whose target + * changed since in another mode can be skipped instead of reverting the + * newer change (HexMapView.prepareUndo). + */ +import type { PinRecord } from "../paths/routePins"; +import type { MapPath, TokenShape, TokenSize } from "../types"; +import type { HexData } from "../maps/mapNote"; +import type { CellEdit } from "../undoBook"; + +export type TerrainUndoEntry = { + x: number; + y: number; + path: string; + oldTerrain: string | null; + newTerrain: string | null; +}; +export type IconUndoEntry = { + x: number; + y: number; + path: string; + oldIcon: string | null; + newIcon: string | null; + isGm: boolean; + /** Full GM-icon list before/after the stroke. Only populated when + * isGm=true and the new painter (multi-add) path mutated this hex. + * Undo restores the full list; legacy oldIcon/newIcon kept for + * back-compat with strokes recorded before the multi-add change. */ + oldGmList?: string[]; + newGmList?: string[]; +}; +export type FactionUndoEntry = { + hexPath: string; + factionBasename: string; + factionFilePath: string; + /** Whether the faction link was present before this stroke began. */ + wasPresent: boolean; +}; +export type RegionUndoEntry = { + hexPath: string; + oldRegion: string | null; + newRegion: string | null; +}; +/** A sub-hex painted in an overworld's full view: a hex of a region map. */ +export type SubHexUndoEntry = { + map: string; + key: string; + oldTerrain: string | null; + oldLocked: boolean; + newTerrain: string | null; +}; +export interface CalibrateSnapshot { + bg?: { offsetX: number; offsetY: number; scale: number; rotation: number; opacity: number }; + grid: { scaleX: number; scaleY: number; offsetX: number; offsetY: number; legacyScale: number }; +} + +/** A token's place on the map, and (for one that was made or removed) its look. */ +export interface TokenSnap { + hex: string; + map: string; + visible?: boolean; + look?: { + icon?: string; + shape?: TokenShape; + size?: TokenSize; + color?: string; + border?: string; + tokenLink?: string; + description?: string; + }; +} + +export type UndoItem = + /** `pins`: anchors the stroke made paths gain to keep their routes (undone with it). */ + | { kind: "terrain"; entries: TerrainUndoEntry[]; pins?: PinRecord[] } + | { kind: "icon"; entries: IconUndoEntry[] } + | { kind: "faction"; entries: FactionUndoEntry[] } + | { kind: "region"; entries: RegionUndoEntry[] } + | { kind: "subhex"; entries: SubHexUndoEntry[] } + /** `after`: the two hexes' map data after the swap (null: not checked). */ + | { kind: "swap"; x1: number; y1: number; x2: number; y2: number; after?: [HexData | null, HexData | null] } + | { kind: "path"; mapName: string; before: MapPath[]; after: MapPath[] } + | { kind: "calibrate"; mapName: string; before: CalibrateSnapshot; after: CalibrateSnapshot } + /** Any map data edit recorded field by field (hex editor, biome and region actions). */ + | { kind: "cells"; edits: CellEdit[] } + /** A token moved, placed or removed (null: not a token on a map). */ + | { kind: "token"; path: string; before: TokenSnap | null; after: TokenSnap | null }; diff --git a/src/hex-table/HexTerrainPickerModal.ts b/src/hex-table/HexTerrainPickerModal.ts index 40a7be1c..3a7c1dbf 100644 --- a/src/hex-table/HexTerrainPickerModal.ts +++ b/src/hex-table/HexTerrainPickerModal.ts @@ -1,4 +1,5 @@ -import { App } from "obsidian"; +import { App, Notice } from "obsidian"; +import { lockedHint } from "../workMode"; import type HexmakerPlugin from "../HexmakerPlugin"; import { HexmakerModal } from "../HexmakerModal"; import { getIconUrl, normalizeFolder, createIconEl } from "../utils"; @@ -47,7 +48,8 @@ export class HexTerrainPickerModal extends HexmakerModal { const mapName = relative.split("/")[0]; await this.plugin.createHexNote(hx, hy, mapName); } - await setTerrainInFile(this.app, this.hexPath, entry.name); + // Refused when the map's work mode locks terrain (src/workMode.ts). + if (!(await setTerrainInFile(this.app, this.hexPath, entry.name))) new Notice(lockedHint("paint-terrain")); this.onPicked(); this.close(); })(); @@ -61,7 +63,7 @@ export class HexTerrainPickerModal extends HexmakerModal { }); clearBtn.addEventListener("click", () => { void (async () => { - await setTerrainInFile(this.app, this.hexPath, null); + if (!(await setTerrainInFile(this.app, this.hexPath, null))) new Notice(lockedHint("paint-terrain")); this.onPicked(); this.close(); })(); diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index a129195f..2f9e41d4 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -23,6 +23,8 @@ import { import { renamedHexes, syncHexNameAlias } from "./hexNames"; import { regionMirrorFixes } from "./submaps"; import { writeJsonBackup } from "../backup"; +import { guardWrite } from "../modeGate"; +import type { ModeAction } from "../workMode"; import { impassableNames } from "../impassable"; import type { RouteContext } from "../paths/router"; import { RouteCache, type SegmentRouter } from "../paths/routeCache"; @@ -34,6 +36,14 @@ import { pathNameKey, uniquePathName } from "../paths/names"; import { mapRouteContext, pathTypeStyleFor } from "../paths/mapContext"; import { buildView, emptyView, reconcile, type PathView } from "../paths/chainView"; +/** One hex changed during MapStore.record: its data before and after. */ +export interface HexCellChange { + map: string; + key: string; + before: HexData | undefined; + after: HexData | undefined; +} + /** A map's routing context changed (terrain, palette impassability, size, stagger). */ export interface RouteContextChange { map: string; @@ -122,6 +132,8 @@ export class MapStore { /** Maps whose paths / hexes were all removed by an edit (not a reload): allowed to empty the note. */ private clearedPaths = new Set(); private clearedHexes = new Set(); + /** While `record` runs: hears each hex's value before its first change. */ + private recorder: ((map: string, key: string, before: HexData | undefined) => void) | null = null; constructor(private plugin: HexmakerPlugin) {} @@ -187,8 +199,15 @@ export class MapStore { /** * Patch one hex. `undefined`/`null`/empty values clear that field. The * note write is debounced; listeners hear about the change at once. + * + * `action`: the user action this write is part of. When given, the map's + * work mode must allow it (src/modeGate.ts) or nothing is written and + * `false` comes back. Writes without one (derived data, renames, the + * palette) are never locked. */ - set(map: string, key: string, patch: { [K in keyof HexData]?: HexData[K] | null }): void { + set(map: string, key: string, patch: { [K in keyof HexData]?: HexData[K] | null }, action?: ModeAction): boolean { + if (action && !guardWrite(map, action)) return false; + this.recorder?.(map, key, this.get(map, key)); const t = this.table(map); const h: HexData = { ...(t.get(key) ?? {}) }; for (const [k, v] of Object.entries(patch) as [keyof HexData, unknown][]) { @@ -201,12 +220,38 @@ export class MapStore { if ("terrain" in patch) this.terrainChanged(map); this.markDirty(map); this.emit(map); + return true; + } + + /** + * Run `fn` and return every hex it changed, with its value before and + * after (for undo: src/undoBook.ts). Writes made by anything else while + * `fn` runs are recorded too. Nested calls share the outer recording. + */ + async record(fn: () => T | Promise): Promise<{ result: T; cells: HexCellChange[] }> { + if (this.recorder) return { result: await fn(), cells: [] }; + const before = new Map(); + this.recorder = (map, key, b) => { + const id = `${map}\u0000${key}`; + if (!before.has(id)) before.set(id, { map, key, before: b ? { ...b } : undefined }); + }; + try { + const result = await fn(); + const cells = [...before.values()].map((c) => { + const now = this.get(c.map, c.key); + return { ...c, after: now ? { ...now } : undefined }; + }); + return { result, cells }; + } finally { + this.recorder = null; + } } /** Bulk set (generators, map creation): one dirty mark, one event. */ setMany(map: string, cells: Iterable<[string, Partial]>): void { const t = this.table(map); for (const [key, patch] of cells) { + this.recorder?.(map, key, t.get(key)); const h: HexData = { ...(t.get(key) ?? {}), ...patch }; for (const k of Object.keys(h) as (keyof HexData)[]) if (h[k] === undefined || h[k] === "") delete h[k]; if (Object.keys(h).length) t.set(key, h); else t.delete(key); diff --git a/src/modeGate.ts b/src/modeGate.ts new file mode 100644 index 00000000..8cd32fb1 --- /dev/null +++ b/src/modeGate.ts @@ -0,0 +1,34 @@ +/** + * THE write gate for work modes (src/workMode.ts). Data writers that carry a + * user action (MapStore.set with an action, the frontmatter hex setters, + * token writes, the path gate) ask `guardWrite(map, action)` first; a + * refused write is dropped with a console warning, never written. + * + * The plugin registers how to look a map up (`setModeMapLookup`); with no + * lookup (tests, early load) or an unknown map, everything is allowed. + * Pure, no Obsidian imports. + */ +import { lockedHint, mapAllows, type ModeAction } from "./workMode"; + +type MapLookup = (mapName: string) => { workMode?: string } | undefined; +let lookup: MapLookup | null = null; + +/** Tell the gate how to find a map (and so its work mode). */ +export function setModeMapLookup(fn: MapLookup | null): void { + lookup = fn; +} + +/** May `action` be done on map `mapName` in its current mode? */ +export function canDo(mapName: string, action: ModeAction): boolean { + if (!lookup) return true; + const map = lookup(mapName); + if (!map) return true; + return mapAllows(map, action); +} + +/** `canDo`, and a console warning when it refuses (the write is dropped). */ +export function guardWrite(mapName: string, action: ModeAction): boolean { + if (canDo(mapName, action)) return true; + console.warn(`[hexmaker] refused a ${action} write on "${mapName}": ${lockedHint(action)}`); + return false; +} diff --git a/src/paths/editGate.ts b/src/paths/editGate.ts index c279dc3b..0d7a5173 100644 --- a/src/paths/editGate.ts +++ b/src/paths/editGate.ts @@ -13,7 +13,7 @@ * no lookup (tests, early load) everything is allowed. * Pure, no Obsidian imports. */ -import { canAdd } from "../workMode"; +import { mapAllows } from "../workMode"; /** What kind of path edit is being asked for. */ export type PathEditAction = @@ -41,5 +41,5 @@ export const PATH_EDIT_LOCKED_HINT = "Switch to Build to change paths on this ma export function canEditPaths(mapName: string, action: PathEditAction): boolean { if (action === "pin") return true; // keeps what is drawn; never a user change if (!lookup) return true; - return canAdd(lookup(mapName)); + return mapAllows(lookup(mapName), "edit-path"); } diff --git a/src/undoBook.ts b/src/undoBook.ts new file mode 100644 index 00000000..edce7fba --- /dev/null +++ b/src/undoBook.ts @@ -0,0 +1,214 @@ +/** + * Parallel undo (owner WM6): one undo/redo queue per map per work mode, + * kept for as long as the vault is open (the plugin owns the book, so it + * outlives map views and map changes). + * + * - Undo in a mode undoes only what was done in that mode; switching back + * to a mode resumes its queue. + * - An entry whose target changed since (in another mode, or by hand) is + * skipped rather than reverting the newer change. The caller's `prepare` + * compares the entry's "after" snapshot with what's there now and returns + * the part that still matches (or null: the entry is dropped and the next + * one is tried). + * + * Pure, no Obsidian imports. Item shapes belong to the caller. + */ +import type { WorkMode } from "./workMode"; + +export const UNDO_DEPTH = 20; + +interface Queue { + undo: T[]; + redo: T[]; +} + +export type UndoDirection = "undo" | "redo"; + +/** + * What to do with an entry: the (possibly trimmed) entry to apply, or null + * when nothing of it still matches (it is dropped). + */ +export type UndoPrepare = (item: T, dir: UndoDirection) => T | null | Promise; + +export class UndoBook { + private queues = new Map>(); + private listeners = new Set<() => void>(); + + constructor(private depth = UNDO_DEPTH) {} + + private id(map: string, mode: WorkMode): string { + return `${mode}\u0000${map}`; + } + + private queue(map: string, mode: WorkMode): Queue { + const id = this.id(map, mode); + let q = this.queues.get(id); + if (!q) { q = { undo: [], redo: [] }; this.queues.set(id, q); } + return q; + } + + /** Record a new action done on `map` in `mode` (clears that queue's redo). */ + push(map: string, mode: WorkMode, item: T): void { + const q = this.queue(map, mode); + q.undo.push(item); + if (q.undo.length > this.depth) q.undo.shift(); + q.redo = []; + this.changed(); + } + + canUndo(map: string, mode: WorkMode): boolean { + return (this.queues.get(this.id(map, mode))?.undo.length ?? 0) > 0; + } + + canRedo(map: string, mode: WorkMode): boolean { + return (this.queues.get(this.id(map, mode))?.redo.length ?? 0) > 0; + } + + /** Sizes, for tooltips and tests. */ + size(map: string, mode: WorkMode): { undo: number; redo: number } { + const q = this.queues.get(this.id(map, mode)); + return { undo: q?.undo.length ?? 0, redo: q?.redo.length ?? 0 }; + } + + /** + * Take the next entry to undo (or redo) from `map`'s `mode` queue. Entries + * `prepare` rejects are dropped (popped) and the next one is tried. The + * returned entry (as prepared) moves to the other stack; the caller + * applies it. Null when nothing is left. + */ + async step(map: string, mode: WorkMode, dir: UndoDirection, prepare: UndoPrepare): Promise { + const q = this.queues.get(this.id(map, mode)); + if (!q) return null; + const from = dir === "undo" ? q.undo : q.redo; + const to = dir === "undo" ? q.redo : q.undo; + try { + while (from.length) { + const item = from.pop()!; + const ready = await prepare(item, dir); + if (ready === null) continue; // its target changed since: dropped + to.push(ready); + if (to.length > this.depth) to.shift(); + return ready; + } + return null; + } finally { + this.changed(); + } + } + + /** A map was renamed: its queues follow. */ + renameMap(oldName: string, newName: string): void { + for (const mode of ["play", "build", "god"] as WorkMode[]) { + const q = this.queues.get(this.id(oldName, mode)); + if (!q) continue; + this.queues.delete(this.id(oldName, mode)); + this.queues.set(this.id(newName, mode), q); + } + this.changed(); + } + + /** A map is gone (deleted): drop its queues. */ + forgetMap(name: string): void { + for (const mode of ["play", "build", "god"] as WorkMode[]) this.queues.delete(this.id(name, mode)); + this.changed(); + } + + /** Hear about any change (to refresh undo buttons). Returns the unsubscribe. */ + onChange(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + private changed(): void { + for (const fn of this.listeners) fn(); + } +} + +// ── Helpers for "does the target still look like it did after the action?" ── + +/** Structural equality for small JSON-ish values (arrays in order, objects by keys). */ +export function sameValue(a: unknown, b: unknown): boolean { + if (a === b) return true; + if (a === undefined || a === null || b === undefined || b === null) return (a ?? null) === (b ?? null); + if (Array.isArray(a) || Array.isArray(b)) { + if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false; + return a.every((v, i) => sameValue(v, b[i])); + } + if (typeof a === "object" && typeof b === "object") { + const ra = a as Record, rb = b as Record; + const ka = Object.keys(ra).filter((k) => ra[k] !== undefined); + const kb = Object.keys(rb).filter((k) => rb[k] !== undefined); + if (ka.length !== kb.length) return false; + return ka.every((k) => sameValue(ra[k], rb[k])); + } + return false; +} + +/** + * Keep the parts of an entry whose target still shows the value the entry + * left there (undo: its "after"; redo: its "before"). Parts that changed + * since are skipped, so undo never reverts a newer change. Empty → null. + */ +export function stillCurrent( + parts: readonly E[], + dir: UndoDirection, + current: (part: E) => unknown, + before: (part: E) => unknown, + after: (part: E) => unknown, +): E[] | null { + const kept = parts.filter((p) => sameValue(current(p), dir === "undo" ? after(p) : before(p))); + return kept.length ? kept : null; +} + +/** One hex's map data fields changed by an action: `field → [before, after]`. */ +export interface CellEdit { + map: string; + key: string; + fields: Record; +} + +/** + * Field-level edits from before/after snapshots of hexes (MapStore.record): + * only fields that actually changed, so undo leaves other fields alone. + */ +export function cellEdits(cells: readonly { map: string; key: string; before?: object; after?: object }[]): CellEdit[] { + const out: CellEdit[] = []; + for (const c of cells) { + const b = (c.before ?? {}) as Record; + const a = (c.after ?? {}) as Record; + const fields: Record = {}; + for (const k of new Set([...Object.keys(b), ...Object.keys(a)])) { + if (!sameValue(b[k], a[k])) fields[k] = [b[k], a[k]]; + } + if (Object.keys(fields).length) out.push({ map: c.map, key: c.key, fields }); + } + return out; +} + +/** + * The part of cell edits still in place (each field compared on its own), + * for undo or redo. `current(map, key)` is the hex's data now. + */ +export function currentCellEdits( + edits: readonly CellEdit[], + dir: UndoDirection, + current: (map: string, key: string) => Record | undefined, +): CellEdit[] | null { + const out: CellEdit[] = []; + for (const e of edits) { + const now = current(e.map, e.key) ?? {}; + const fields: Record = {}; + for (const [k, [b, a]] of Object.entries(e.fields)) { + if (sameValue(now[k], dir === "undo" ? a : b)) fields[k] = [b, a]; + } + if (Object.keys(fields).length) out.push({ ...e, fields }); + } + return out.length ? out : null; +} + +/** The patch that applies cell edits in a direction (undo → before values, null clears). */ +export function cellPatch(edit: CellEdit, dir: UndoDirection): Record { + const patch: Record = {}; + for (const [k, [b, a]] of Object.entries(edit.fields)) patch[k] = (dir === "undo" ? b : a) ?? null; + return patch; +} diff --git a/src/workMode.ts b/src/workMode.ts index 48cea020..1753ec9c 100644 --- a/src/workMode.ts +++ b/src/workMode.ts @@ -1,20 +1,28 @@ /** - * Work modes, per map (owner round 4, WM1–WM4): Play · Build · God. + * Work modes, per map (owner round 4, WM1–WM6): Play · Build · God. * * Stored readably in the map note (`mode: build`); a map opens in the mode - * saved with it, default Build. This first pass enforces two rules: - * - canReshape(): changing what's already placed on an overworld (swapping - * a placed biome, Reroll, regenerating, applying region settings to an - * existing region) needs God. - * - canAdd(): placing a biome on an empty overworld hex (which makes its - * region), or making regions at all, needs Build or God; Play only looks - * and moves. - * Note text is never locked, and settings and palettes aren't either (WM2, - * WM4). The rest of the modes plan (per-mode undo, other locks) is still - * to come. + * saved with it, default Build. + * + * The one rule: Play may change what a GM changes during a game (tokens, + * note text, rolls, view toggles) but no MAP DATA (terrain, icons, region + * areas, paths, links to other maps, the map's size or properties). Build + * adds and edits map content. God may do everything, including reshaping + * what's placed (biome swaps, rerolls, regenerating), swapping hexes, + * shrinking and deleting maps. + * + * Never locked: note text (WM2), settings and palettes (WM4). + * + * ACTION_POLICY is the classification of every user action; + * TOOL_ACTIONS / COMMAND_ACTIONS / MENU_ACTIONS map each drawing tool, + * command and map-view menu item onto it. tests/workModeCoverage.test.ts + * fails when one isn't classified. The data layer refuses locked writes + * (src/modeGate.ts → MapStore.set, the path gate), and the UI asks the + * same table to hide or disable. * * Pure: no Obsidian imports. */ +import type { DrawingMode } from "./hex-map/toolMode"; export type WorkMode = "play" | "build" | "god"; @@ -23,11 +31,203 @@ export const WORK_MODES: readonly WorkMode[] = ["play", "build", "god"]; export const DEFAULT_WORK_MODE: WorkMode = "build"; export const WORK_MODE_TEXT: Record = { - play: { label: "Play", desc: "Run a game: look around and move. Notes stay editable." }, - build: { label: "Build", desc: "Add to the map. Things already placed stay as they are." }, - god: { label: "God", desc: "Change anything, including placed biomes, rerolls and regenerating." }, + play: { label: "Play", desc: "Run a game: move tokens, read and write notes, roll. The map itself stays as it is." }, + build: { label: "Build", desc: "Add to and edit the map: paint, draw paths, make maps and regions." }, + god: { label: "God", desc: "Change anything, including placed biomes, rerolls, regenerating, swapping hexes and deleting." }, +}; + +/** + * Every kind of user action. One id per row of the plan's feature inventory + * (plan-work-modes §1), grouped by who may do it. + */ +export type ModeAction = + // ── every mode (what a GM does during a game) ── + | "view" // pan, zoom, layers, GM layer, legend, help, open views + | "navigate" // change maps, enter regions, center a hex + | "open-editor" // open the hex editor / region editor (its writes are gated one by one) + | "open-note" // open (or create) a hex note + | "edit-note" // note text: sections, link sections, a hex's name, map data callouts + | "link-note" // the Link table / Factions tools: wiki-links written into hex notes + | "roll" // random tables and workflows (result notes are new files) + | "token" // place, move, edit, hide, remove tokens + | "export" // PDF / Markdown / PNG exports (new files only) + | "tables" // random table files: ranges, checks (not map data) + | "settings" // plugin settings and palettes: never locked (WM4) + | "switch-mode" // the mode switch itself + | "new-top-map" // a new map that isn't made from a hex of another map + // ── Build and God ── + | "paint-terrain" + | "paint-icon" // icon overrides and GM icons + | "paint-region-area" // the Region areas tool (geo-region overlay) + | "link-map" // link / unlink / reorder a hex's maps + | "edit-path" + | "grow-map" // the "+" expand buttons + | "new-child-map" // new map / region / new land from a hex or a side + | "map-properties" // rename, palette, stagger, background, map tables + | "place-biome" // first biome on an empty overworld hex + | "edit-biomes" // biome library, world types + // ── God only ── + | "reshape" // swap a placed biome, reroll, regenerate, region settings after lock + | "swap-hexes" + | "shrink-map" + | "delete-map"; + +interface ActionPolicy { + /** Modes that allow it. */ + modes: readonly WorkMode[]; + /** "Switch to Build to ." */ + verb: string; +} + +const ALL: readonly WorkMode[] = ["play", "build", "god"]; +const BUILD: readonly WorkMode[] = ["build", "god"]; +const GOD: readonly WorkMode[] = ["god"]; + +/** THE classification: which modes allow each action. */ +export const ACTION_POLICY: Record = { + view: { modes: ALL, verb: "look around" }, + navigate: { modes: ALL, verb: "move around" }, + "open-editor": { modes: ALL, verb: "open the editor" }, + "open-note": { modes: ALL, verb: "open notes" }, + "edit-note": { modes: ALL, verb: "edit notes" }, + "link-note": { modes: ALL, verb: "link notes" }, + roll: { modes: ALL, verb: "roll" }, + token: { modes: ALL, verb: "move tokens" }, + export: { modes: ALL, verb: "export" }, + tables: { modes: ALL, verb: "edit tables" }, + settings: { modes: ALL, verb: "change settings" }, + "switch-mode": { modes: ALL, verb: "switch modes" }, + "new-top-map": { modes: ALL, verb: "make a map" }, + "paint-terrain": { modes: BUILD, verb: "paint terrain" }, + "paint-icon": { modes: BUILD, verb: "change icons" }, + "paint-region-area": { modes: BUILD, verb: "paint region areas" }, + "link-map": { modes: BUILD, verb: "link maps to hexes" }, + "edit-path": { modes: BUILD, verb: "change paths" }, + "grow-map": { modes: BUILD, verb: "grow the map" }, + "new-child-map": { modes: BUILD, verb: "make a map or region here" }, + "map-properties": { modes: BUILD, verb: "change the map's properties" }, + "place-biome": { modes: BUILD, verb: "place a biome" }, + "edit-biomes": { modes: BUILD, verb: "edit biomes" }, + reshape: { modes: GOD, verb: "change a placed biome" }, + "swap-hexes": { modes: GOD, verb: "swap hexes" }, + "shrink-map": { modes: GOD, verb: "shrink the map" }, + "delete-map": { modes: GOD, verb: "delete the map" }, +}; + +export const MODE_ACTIONS = Object.keys(ACTION_POLICY) as ModeAction[]; + +/** May `action` be done in `mode`? */ +export function allows(mode: WorkMode, action: ModeAction): boolean { + return ACTION_POLICY[action].modes.includes(mode); +} + +/** The lowest mode that allows `action` (Play < Build < God). */ +export function modeFor(action: ModeAction): WorkMode { + return WORK_MODES.find((m) => allows(m, action)) ?? "god"; +} + +/** "Switch to Build to paint terrain." */ +export function lockedHint(action: ModeAction): string { + return `Switch to ${WORK_MODE_TEXT[modeFor(action)].label} to ${ACTION_POLICY[action].verb}.`; +} + +/** + * One line for several locked actions (a menu that hid them): the lowest + * mode that unlocks any of them, with the verb when there's just one. + */ +export function lockedSummary(actions: readonly ModeAction[]): string | null { + if (!actions.length) return null; + const order = (m: WorkMode) => WORK_MODES.indexOf(m); + const lowest = actions.map(modeFor).sort((a, b) => order(a) - order(b))[0]; + const at = [...new Set(actions.filter((a) => modeFor(a) === lowest))]; + return at.length === 1 ? lockedHint(at[0]) : `Switch to ${WORK_MODE_TEXT[lowest].label} to edit the map.`; +} + +/** May `action` be done on this map, in its saved mode? */ +export function mapAllows(map: { workMode?: string } | undefined, action: ModeAction): boolean { + return allows(workModeOf(map), action); +} + +// ── Entry points → actions (checked by tests/workModeCoverage.test.ts) ── + +/** Every drawing tool (DrawingMode in src/hex-map/toolMode.ts). */ +export const TOOL_ACTIONS: Record = { + path: "edit-path", + terrain: "paint-terrain", + icon: "paint-icon", + tableLink: "link-note", + submapLink: "link-map", + factionLink: "link-note", + regionLink: "paint-region-area", + swap: "swap-hexes", + placeToken: "token", +}; + +/** Every registered command id (addCommand in src/). */ +export const COMMAND_ACTIONS: Record = { + "open-hex-map": "view", + "open-hex-table": "view", + "open-terrain-generator": "view", + "open-palette-editor": "settings", + "edit-world-types": "edit-biomes", + "new-overworld": "new-top-map", + "map-go-up": "navigate", + "map-go-back": "navigate", + "map-go-forward": "navigate", + "open-random-tables": "view", + "add-roll-ranges": "tables", + "check-tables": "tables", + "export-current-note-pdf": "export", + "export-current-note-markdown": "export", + "export-current-hex": "export", + "export-current-workflow": "export", + "add-map-data-to-hex-notes": "edit-note", + "update-region-faction-map-data": "edit-note", + "export-current-map": "export", }; +/** Every item of the map view's menus (ModeMenu in src/hex-map/modeMenu.ts). */ +export const MENU_ACTIONS = { + // hex right-click menu + "hex.center": "navigate", + "hex.open-note": "open-note", + "hex.enter-region": "navigate", + "hex.open-location": "navigate", + "hex.locations": "navigate", + "hex.new-map": "new-child-map", + "hex.link-map": "link-map", + "hex.manage-locations": "link-map", + "hex.link-table": "link-note", + "hex.swap": "swap-hexes", + "hex.create-token": "token", + "hex.clear-terrain": "paint-terrain", + "hex.remove-icon": "paint-icon", + // overworld hex menu + "ow.enter-region": "navigate", + "ow.edit-region": "open-editor", + "ow.set-biome": "place-biome", + "ow.center": "navigate", + "ow.locations": "navigate", + "ow.create-token": "token", + // token menu + "token.info": "view", + "token.edit": "token", + "token.open-note": "open-note", + "token.remove": "token", + // the mode switch + "mode.switch": "switch-mode", + // hex editor: the maps strip "+" and a section's table source + "editor.new-map": "new-child-map", + "editor.link-map": "link-map", + "editor.manage-locations": "link-map", + "editor.map-table": "map-properties", + "editor.hex-table": "edit-note", +} as const satisfies Record; + +export type MenuActionId = keyof typeof MENU_ACTIONS; + +// ── The map note's `mode:` ── + /** The hint on a locked reshape action. */ export const RESHAPE_LOCKED_HINT = "Switch to God to change a placed biome."; @@ -54,10 +254,10 @@ export function workModeOf(map: { workMode?: string } | undefined): WorkMode { /** May what's already placed on this map be changed (biome swap, reroll, regenerate)? */ export function canReshape(map: { workMode?: string } | undefined): boolean { - return workModeOf(map) === "god"; + return mapAllows(map, "reshape"); } /** May new things be added to this map (a first biome, a new region)? Build and God; not Play. */ export function canAdd(map: { workMode?: string } | undefined): boolean { - return workModeOf(map) !== "play"; + return mapAllows(map, "new-child-map"); } diff --git a/styles.css b/styles.css index aa6f8b3f..fd35656e 100644 --- a/styles.css +++ b/styles.css @@ -8751,3 +8751,22 @@ textarea.duckmage-edit-region-notes-input { font-size: var(--font-ui-smaller); color: var(--text-muted); } + +/* Work modes (src/workMode.ts): Play hides the grid's +/- (map structure); + the drawing panel hides locked tools behind one line. */ +.duckmage-hex-map-container.duckmage-mode-play .duckmage-expand-group { + display: none; +} +.duckmage-shrink-btn:disabled { + cursor: not-allowed; +} +.duckmage-tools-locked { + padding: 4px 2px; + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} +.duckmage-editor-mode-locked { + margin: 4px 0; + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} diff --git a/tests/hitTest.test.ts b/tests/hitTest.test.ts index 82d7b584..7e4cc942 100644 --- a/tests/hitTest.test.ts +++ b/tests/hitTest.test.ts @@ -41,7 +41,7 @@ describe("a token doesn't shrink its hex's click target (fresh-eyes round 5)", ( }); it("the info card moved to the token's right-click menu", () => { - expect(view).toMatch(/private showTokenContextMenu[\s\S]{0,200}setTitle\("Token info"\)[\s\S]{0,80}this\.openTokenInfo\(token\)/); + expect(view).toMatch(/private showTokenContextMenu[\s\S]{0,200}"Token info"[\s\S]{0,80}this\.openTokenInfo\(token\)/); }); it("with a tool on, clicks go through tokens to the hex", () => { diff --git a/tests/openNote.test.ts b/tests/openNote.test.ts index 1d5a6d86..902ef17a 100644 --- a/tests/openNote.test.ts +++ b/tests/openNote.test.ts @@ -59,7 +59,8 @@ describe("openNoteFocused", () => { expect(read(...f)).toMatch(/openNoteFocused\(this\.app, /); } const view = read("src", "hex-map", "HexMapView.ts").replace(/\r\n/g, "\n"); - const openNoteItems = view.split('.setTitle("Open note")').slice(1).map((s) => s.slice(0, 500)); + // Map menus go through ModeMenu: menu.add(, "Open note", …). + const openNoteItems = view.split('"Open note", "file-text"').slice(1).map((s) => s.slice(0, 500)); expect(openNoteItems.length).toBeGreaterThan(0); for (const item of openNoteItems) expect(item).toMatch(/openNoteFocused/); }); diff --git a/tests/workModeCoverage.test.ts b/tests/workModeCoverage.test.ts new file mode 100644 index 00000000..6b8725c5 --- /dev/null +++ b/tests/workModeCoverage.test.ts @@ -0,0 +1,138 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { + ACTION_POLICY, + allows, + COMMAND_ACTIONS, + lockedHint, + lockedSummary, + MENU_ACTIONS, + MODE_ACTIONS, + modeFor, + TOOL_ACTIONS, + type ModeAction, +} from "../src/workMode"; + +/** + * Regression guard for the work modes (plan-work-modes §2.6): every + * registered command, every drawing tool and every item of the map view's + * menus must be classified in src/workMode.ts, so a new feature can't ship + * without saying which modes may use it. + */ +const root = fileURLToPath(new URL("..", import.meta.url)); +const read = (p: string) => readFileSync(join(root, p), "utf8"); + +function sources(dir: string): string[] { + const out: string[] = []; + for (const name of readdirSync(join(root, dir))) { + const rel = `${dir}/${name}`; + if (statSync(join(root, rel)).isDirectory()) out.push(...sources(rel)); + else if (name.endsWith(".ts")) out.push(rel); + } + return out; +} + +const src = sources("src"); + +describe("work mode classification covers every entry point", () => { + it("every registered command is classified (and none is stale)", () => { + const ids = src.flatMap((f) => [...read(f).matchAll(/addCommand\(\{\s*id:\s*"([^"]+)"/g)].map((m) => m[1])); + expect(ids.length).toBeGreaterThan(10); + const missing = ids.filter((id) => !(id in COMMAND_ACTIONS)); + expect(missing).toEqual([]); + const stale = Object.keys(COMMAND_ACTIONS).filter((id) => !ids.includes(id)); + expect(stale).toEqual([]); + }); + + it("every drawing tool is classified (and none is stale)", () => { + const union = /export type DrawingMode =([^;]+);/.exec(read("src/hex-map/toolMode.ts"))![1]; + const tools = [...union.matchAll(/"([^"]+)"/g)].map((m) => m[1]).sort(); + expect(tools.length).toBeGreaterThan(5); + expect(Object.keys(TOOL_ACTIONS).sort()).toEqual(tools); + }); + + it("the map view builds its menus only through ModeMenu, with classified ids", () => { + const files = ["src/hex-map/HexMapView.ts", "src/hex-map/HexEditorModal.ts"]; + const used = new Set(); + for (const f of files) { + const text = read(f); + // A raw Obsidian Menu would bypass the mode table. + expect({ file: f, rawMenus: (text.match(/new Menu\(|\.addItem\(/g) ?? []).length }).toEqual({ file: f, rawMenus: 0 }); + for (const m of text.matchAll(/\bmenu\.add\(\s*"([^"]+)"/g)) used.add(m[1]); + } + // The overworld menu's ids come from overworldMenu() as `ow.`. + const owIds = /id:\s*("[^;]+?");/.exec(read("src/overworld/overworldInput.ts"))![1]; + for (const m of owIds.matchAll(/"([^"]+)"/g)) used.add(`ow.${m[1]}`); + const unclassified = [...used].filter((id) => !(id in MENU_ACTIONS)); + expect(unclassified).toEqual([]); + const stale = Object.keys(MENU_ACTIONS).filter((id) => !used.has(id)); + expect(stale).toEqual([]); + }); + + it("every mapping points at a real action", () => { + for (const a of [...Object.values(COMMAND_ACTIONS), ...Object.values(TOOL_ACTIONS), ...Object.values(MENU_ACTIONS)]) { + expect(MODE_ACTIONS).toContain(a); + } + }); +}); + +describe("work mode policy", () => { + it("God may do everything; every action is allowed somewhere", () => { + for (const a of MODE_ACTIONS) { + expect(allows("god", a)).toBe(true); + expect(ACTION_POLICY[a].modes.length).toBeGreaterThan(0); + } + }); + + it("each mode allows everything the mode below it does (Play ⊂ Build ⊂ God)", () => { + for (const a of MODE_ACTIONS) { + if (allows("play", a)) expect(allows("build", a)).toBe(true); + if (allows("build", a)) expect(allows("god", a)).toBe(true); + } + }); + + it("Play is what a GM does during a game: tokens, notes, rolls, looking around", () => { + const play: ModeAction[] = ["view", "navigate", "open-note", "edit-note", "link-note", "roll", "token", "export", "switch-mode"]; + for (const a of play) expect(allows("play", a)).toBe(true); + }); + + it("Play locks map data: painting, paths, links to maps, size, properties, new maps from it", () => { + const locked: ModeAction[] = ["paint-terrain", "paint-icon", "paint-region-area", "edit-path", "link-map", "grow-map", "shrink-map", "new-child-map", "map-properties", "place-biome", "reshape", "swap-hexes", "delete-map"]; + for (const a of locked) expect(allows("play", a)).toBe(false); + }); + + it("Build adds and edits; reshaping, swapping, shrinking and deleting need God", () => { + for (const a of ["paint-terrain", "paint-icon", "paint-region-area", "edit-path", "link-map", "grow-map", "new-child-map", "map-properties", "place-biome"] as ModeAction[]) { + expect(allows("build", a)).toBe(true); + } + for (const a of ["reshape", "swap-hexes", "shrink-map", "delete-map"] as ModeAction[]) { + expect(allows("build", a)).toBe(false); + expect(modeFor(a)).toBe("god"); + } + }); + + it("never locks note text, settings or palettes (WM2, WM4)", () => { + for (const a of ["edit-note", "settings", "tables"] as ModeAction[]) expect(ACTION_POLICY[a].modes).toEqual(["play", "build", "god"]); + }); + + it("tools: Play keeps tokens and note links, loses painting and paths", () => { + expect(allows("play", TOOL_ACTIONS.placeToken)).toBe(true); + expect(allows("play", TOOL_ACTIONS.factionLink)).toBe(true); + expect(allows("play", TOOL_ACTIONS.tableLink)).toBe(true); + for (const t of ["terrain", "icon", "path", "regionLink", "submapLink"] as const) expect(allows("play", TOOL_ACTIONS[t])).toBe(false); + expect(allows("build", TOOL_ACTIONS.swap)).toBe(false); + }); + + it("hints are one short line naming the mode that unlocks the action", () => { + expect(lockedHint("paint-terrain")).toBe("Switch to Build to paint terrain."); + expect(lockedHint("delete-map")).toBe("Switch to God to delete the map."); + expect(lockedSummary([])).toBeNull(); + expect(lockedSummary(["swap-hexes"])).toBe("Switch to God to swap hexes."); + // Several: the lowest mode that unlocks any of them. + expect(lockedSummary(["swap-hexes", "paint-terrain", "edit-path"])).toBe("Switch to Build to edit the map."); + expect(lockedSummary(["swap-hexes", "paint-terrain"])).toBe("Switch to Build to paint terrain."); + }); +}); diff --git a/tests/workModeUndo.test.ts b/tests/workModeUndo.test.ts new file mode 100644 index 00000000..112a464b --- /dev/null +++ b/tests/workModeUndo.test.ts @@ -0,0 +1,260 @@ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { cellEdits, cellPatch, currentCellEdits, sameValue, stillCurrent, UndoBook, type UndoDirection } from "../src/undoBook"; +import { canDo, guardWrite, setModeMapLookup } from "../src/modeGate"; +import { MapStore } from "../src/maps/MapStore"; +import { MemVault } from "./helpers/memVault"; +import type { MapData } from "../src/types"; + +(globalThis as Record).window ??= globalThis; + +/** + * Parallel undo (owner WM6): one queue per map per work mode, kept while + * the vault is open; undo in a mode undoes only that mode's actions; an + * entry whose target changed later (in another mode) is skipped. + */ + +/** A toy "world": token positions, and an entry that moved one. */ +type Move = { token: string; from: string; to: string }; + +function world() { + const where = new Map([["party", "0_0"]]); + const book = new UndoBook(); + /** Do a move in a mode, recording it. */ + const move = (mode: "play" | "build" | "god", token: string, to: string) => { + const from = where.get(token)!; + where.set(token, to); + book.push("m", mode, { token, from, to }); + }; + /** The entry is still current when the token is where it left it (undo) / where it found it (redo). */ + const prepare = (e: Move, dir: UndoDirection) => + sameValue(where.get(e.token), dir === "undo" ? e.to : e.from) ? e : null; + const step = async (mode: "play" | "build" | "god", dir: UndoDirection) => { + const e = await book.step("m", mode, dir, prepare); + if (e) where.set(e.token, dir === "undo" ? e.from : e.to); + return e; + }; + return { where, book, move, step }; +} + +describe("undo book: one queue per map per mode (WM6)", () => { + it("undo in a mode only undoes that mode's actions; switching back resumes its queue", async () => { + const w = world(); + w.move("build", "party", "1_0"); + w.move("play", "party", "2_0"); // the party moves on in Play + w.where.set("scout", "5_5"); + w.move("play", "scout", "6_5"); + // Play's undo: the scout first, then the party's Play move. + await w.step("play", "undo"); + expect(w.where.get("scout")).toBe("5_5"); + await w.step("play", "undo"); + expect(w.where.get("party")).toBe("1_0"); + // Back in Build: its queue is where it was; the Build move undoes now + // (the party is back where Build left it). + expect(w.book.canUndo("m", "build")).toBe(true); + await w.step("build", "undo"); + expect(w.where.get("party")).toBe("0_0"); + }); + + it("an entry whose target moved later in another mode is skipped (popped), not reverted", async () => { + const w = world(); + w.move("build", "party", "1_0"); // Build + w.move("play", "party", "3_3"); // then Play moves it again + const e = await w.step("build", "undo"); + expect(e).toBeNull(); // nothing to undo: the Build move was superseded + expect(w.where.get("party")).toBe("3_3"); // the newer Play move stands + expect(w.book.size("m", "build")).toEqual({ undo: 0, redo: 0 }); // popped, not kept + // Play still undoes its own move. + await w.step("play", "undo"); + expect(w.where.get("party")).toBe("1_0"); + }); + + it("a skipped entry doesn't block older ones in the same queue", async () => { + const w = world(); + w.where.set("scout", "9_9"); + w.move("build", "scout", "8_8"); // older Build action + w.move("build", "party", "1_0"); // newer Build action + w.move("god", "party", "4_4"); // superseded in God + await w.step("build", "undo"); // skips the party entry, undoes the scout + expect(w.where.get("scout")).toBe("9_9"); + expect(w.where.get("party")).toBe("4_4"); + }); + + it("redo replays only while the target is still where undo left it", async () => { + const w = world(); + w.move("build", "party", "1_0"); + await w.step("build", "undo"); + expect(w.book.canRedo("m", "build")).toBe(true); + await w.step("build", "redo"); + expect(w.where.get("party")).toBe("1_0"); + await w.step("build", "undo"); + w.move("play", "party", "7_7"); // moved meanwhile + expect(await w.step("build", "redo")).toBeNull(); + expect(w.where.get("party")).toBe("7_7"); + }); + + it("a new action clears only its own mode's redo; queues are per map", () => { + const book = new UndoBook(); + book.push("a", "build", 1); + book.push("a", "play", 2); + book.push("b", "build", 3); + expect(book.size("a", "build").undo).toBe(1); + expect(book.size("a", "play").undo).toBe(1); + expect(book.size("b", "build").undo).toBe(1); + expect(book.canUndo("a", "god")).toBe(false); + }); + + it("keeps at most `depth` entries per queue", () => { + const book = new UndoBook(3); + for (let i = 0; i < 5; i++) book.push("m", "build", i); + expect(book.size("m", "build").undo).toBe(3); + }); + + it("follows a renamed map and forgets a deleted one; tells listeners", () => { + const book = new UndoBook(); + let heard = 0; + const stop = book.onChange(() => heard++); + book.push("old", "build", 1); + book.renameMap("old", "new"); + expect(book.canUndo("new", "build")).toBe(true); + expect(book.canUndo("old", "build")).toBe(false); + book.forgetMap("new"); + expect(book.canUndo("new", "build")).toBe(false); + stop(); + book.push("x", "build", 1); + expect(heard).toBe(3); + }); +}); + +describe("undo checks: still-current parts of an entry", () => { + it("stillCurrent keeps the hexes that still show the stroke's paint", () => { + const terrain = new Map([["0_0", "forest"], ["1_0", "swamp"]]); // 1_0 repainted since + const stroke = [ + { key: "0_0", oldT: null, newT: "forest" }, + { key: "1_0", oldT: "hills", newT: "forest" }, + ]; + const kept = stillCurrent(stroke, "undo", (e) => terrain.get(e.key) ?? null, (e) => e.oldT, (e) => e.newT); + expect(kept!.map((e) => e.key)).toEqual(["0_0"]); + expect(stillCurrent([stroke[1]], "undo", (e) => terrain.get(e.key) ?? null, (e) => e.oldT, (e) => e.newT)).toBeNull(); + }); + + it("cell edits are per field: undo restores what changed and leaves the rest", () => { + const edits = cellEdits([ + { map: "m", key: "2_2", before: { terrain: "hills", name: "Old Keep" }, after: { terrain: "forest", name: "Old Keep" } }, + { map: "m", key: "3_3", before: undefined, after: undefined }, + ]); + expect(edits).toEqual([{ map: "m", key: "2_2", fields: { terrain: ["hills", "forest"] } }]); + expect(cellPatch(edits[0], "undo")).toEqual({ terrain: "hills" }); + expect(cellPatch(edits[0], "redo")).toEqual({ terrain: "forest" }); + // A field cleared by the action comes back; one added goes (null clears). + const added = cellEdits([{ map: "m", key: "1_1", before: {}, after: { icon: "tower.png" } }]); + expect(cellPatch(added[0], "undo")).toEqual({ icon: null }); + }); + + it("currentCellEdits drops fields changed since (in another mode)", () => { + const edits = cellEdits([{ map: "m", key: "2_2", before: { terrain: "hills", icon: "a.png" }, after: { terrain: "forest", icon: "b.png" } }]); + const now = { terrain: "swamp", icon: "b.png" }; // terrain repainted since + const kept = currentCellEdits(edits, "undo", () => now)!; + expect(kept[0].fields).toEqual({ icon: ["a.png", "b.png"] }); + expect(currentCellEdits(edits, "undo", () => ({ terrain: "swamp" }))).toBeNull(); + }); + + it("sameValue compares lists in order and ignores undefined fields", () => { + expect(sameValue(["a", "a"], ["a", "a"])).toBe(true); + expect(sameValue(["a", "b"], ["b", "a"])).toBe(false); + expect(sameValue({ hex: "1_1", map: "m", x: undefined }, { map: "m", hex: "1_1" })).toBe(true); + expect(sameValue(null, undefined)).toBe(true); + expect(sameValue(null, { hex: "1_1" })).toBe(false); + }); +}); + +describe("work mode write gate", () => { + afterEach(() => setModeMapLookup(null)); + + it("allows everything with no lookup or an unknown map", () => { + expect(canDo("x", "delete-map")).toBe(true); + setModeMapLookup(() => undefined); + expect(canDo("x", "delete-map")).toBe(true); + }); + + it("follows each map's own mode", () => { + const maps: Record = { p: { workMode: "play" }, b: {}, g: { workMode: "god" } }; + setModeMapLookup((n) => maps[n]); + expect(canDo("p", "paint-terrain")).toBe(false); + expect(canDo("p", "token")).toBe(true); + expect(canDo("p", "edit-note")).toBe(true); + expect(canDo("b", "paint-terrain")).toBe(true); + expect(canDo("b", "delete-map")).toBe(false); + expect(canDo("g", "delete-map")).toBe(true); + const warn = console.warn; + const said: unknown[] = []; + console.warn = (...a: unknown[]) => said.push(a.join(" ")); + try { + expect(guardWrite("p", "edit-path")).toBe(false); + } finally { + console.warn = warn; + } + expect(String(said[0])).toMatch(/Switch to Build to change paths/); + }); +}); + +describe("map store: mode-gated writes and recording for undo", () => { + afterEach(() => setModeMapLookup(null)); + + async function boot(mode: string) { + const maps: MapData[] = [{ name: "m", gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 0, y: 0 }, workMode: mode } as MapData]; + const vault = new MemVault({}); + const p = { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", maps }, + getMap: (n: string) => maps.find((m) => m.name === n), + saveData: async () => {}, + refreshHexMap: () => {}, + }; + const store = new MapStore(p as never); + await store.init(); + setModeMapLookup((n) => p.getMap(n)); + return { store, maps }; + } + + it("refuses a locked action in Play and writes nothing; Build writes", async () => { + const { store, maps } = await boot("play"); + const warn = console.warn; + console.warn = () => {}; + try { + expect(store.set("m", "1_1", { terrain: "forest" }, "paint-terrain")).toBe(false); + } finally { + console.warn = warn; + } + expect(store.get("m", "1_1")).toBeUndefined(); + // Note text (a hex's name) is never locked. + expect(store.set("m", "1_1", { name: "Old Keep" }, "edit-note")).toBe(true); + // Writes with no action (derived data, renames) are never locked. + expect(store.set("m", "2_2", { terrain: "hills" })).toBe(true); + maps[0].workMode = "build"; + expect(store.set("m", "1_1", { terrain: "forest" }, "paint-terrain")).toBe(true); + expect(store.get("m", "1_1")).toEqual({ name: "Old Keep", terrain: "forest" }); + }); + + it("record() returns every hex changed, before and after, for undo", async () => { + const { store } = await boot("build"); + store.set("m", "0_0", { terrain: "hills", name: "Keep" }); + const { result, cells } = await store.record(async () => { + store.set("m", "0_0", { terrain: "forest" }); + store.setMany("m", [["1_0", { terrain: "lake" }]]); + store.set("m", "0_0", { terrain: "swamp" }); // second change: first "before" kept + return 7; + }); + expect(result).toBe(7); + const edits = cellEdits(cells); + expect(edits).toEqual([ + { map: "m", key: "0_0", fields: { terrain: ["hills", "swamp"] } }, + { map: "m", key: "1_0", fields: { terrain: [undefined, "lake"] } }, + ]); + // Undo puts it back, field by field. + for (const e of edits) store.set(e.map, e.key, cellPatch(e, "undo")); + expect(store.get("m", "0_0")).toEqual({ terrain: "hills", name: "Keep" }); + expect(store.get("m", "1_0")).toBeUndefined(); + }); +}); From a446512460d83305b779a5617ff26896fdddc2c2 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 07:53:42 -0400 Subject: [PATCH 275/558] feat(callout): Map data callout phase 2 - hand edits go back to the map; Biome line for overworld hexes Terrain, Region and Name edited inside a hex note's Map data callout are put on the map (via mapStore.set through the work-mode gate, one undo step) when the note is left, opened in the hex editor, or by the 'Add map data' command. Never over a newer map value: the plugin remembers what each callout last showed (map-data-shown.json in the plugin folder). Refused, conflicting or unknown-terrain edits stay as 'Not applied:' lines; unreadable lines become 'Not read:' lines; a notice says what happened. Co-Authored-By: Claude Opus 5.5 --- src/HexmakerPlugin.ts | 149 ++++++++++++++++++++++++++++++---- src/hex-map/HexEditorModal.ts | 6 +- src/hexMapData.ts | 132 +++++++++++++++++++++++++++++- src/maps/calloutMemory.ts | 87 ++++++++++++++++++++ tests/hexEditorModal.test.ts | 1 + tests/hexMapData.test.ts | 92 ++++++++++++++++++++- 6 files changed, 442 insertions(+), 25 deletions(-) create mode 100644 src/maps/calloutMemory.ts diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index a03f4c08..b90c5593 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -71,7 +71,7 @@ import { MapStore, withoutNotePaths } from "./maps/MapStore"; import { setModeMapLookup } from "./modeGate"; import { cellEdits, UndoBook } from "./undoBook"; import type { UndoItem } from "./hex-map/undoItems"; -import { workModeOf } from "./workMode"; +import { lockedHint, workModeOf } from "./workMode"; import { withMapLink } from "./maps/mapNote"; import { addLocationPatch, @@ -84,7 +84,11 @@ import { setRegionPatch, } from "./maps/submaps"; import type { RegionSettings } from "./types"; -import { setMapData, type HexMapDataView } from "./hexMapData"; +import { mapDataLines, mapDataSyncMessage, planCalloutImport, setMapData, shownValues, type HexMapDataView } from "./hexMapData"; +import { CalloutMemory } from "./maps/calloutMemory"; +import { hexBiomeAt, overworldOf } from "./overworld/regionsVault"; +import { BIOMES, biomeNoteOf } from "./overworld/biomes"; +import { sameName } from "./hexBodyFields"; import { hasRegionMapData, regionUse, renameRegionInStore, renamedTokenMap, setRegionMapData, type RegionMapDataView } from "./regionMapData"; import { ConfirmModal } from "./worldgen/ConfirmModal"; import { displayNameFor, mapLabel } from "./maps/mapTree"; @@ -111,6 +115,8 @@ export default class HexmakerPlugin extends Plugin { worldTypeStore = new WorldTypeStore(this); /** Per-hex map data, backed by one map note per map (src/maps). */ mapStore = new MapStore(this); + /** What each hex note's Map data callout last showed (phase 2: tells a hand edit from a stale copy). */ + calloutMemory = new CalloutMemory(() => this.app.vault.adapter, () => this.manifest.dir ?? ""); /** Terrain names that have (or were offered) tables; new ones get theirs (HG5). */ private tableTerrainNames: Set | null = null; /** Table creation runs one batch at a time; awaiting any call waits for those before it. */ @@ -215,6 +221,7 @@ export default class HexmakerPlugin extends Plugin { this.paletteStore.onDelete(f); this.biomeStore.onDelete(f); this.worldTypeStore.onDelete(f); + this.calloutMemory.forget(f.path); }), ); this.registerEvent( @@ -223,6 +230,7 @@ export default class HexmakerPlugin extends Plugin { this.paletteStore.onRename(f, oldPath); this.biomeStore.onRename(f, oldPath); this.worldTypeStore.onRename(f, oldPath); + this.calloutMemory.rename(oldPath, f.path); if (f instanceof TFile) void this.onRegionNoteRenamed(f, oldPath); }), ); @@ -230,6 +238,7 @@ export default class HexmakerPlugin extends Plugin { this.registerEvent( this.app.workspace.on("file-open", (file) => { if (file && this.regionOrFactionKind(file)) void this.refreshRegionMapData(file); + this.onHexNoteFocus(file); }), ); // Palette notes edited by hand (or by sync) flow back into the palettes. @@ -663,6 +672,7 @@ export default class HexmakerPlugin extends Plugin { onunload() { this.pathPins.detach(); + void this.calloutMemory.save(); clearPendingTerrain(); } @@ -1841,7 +1851,11 @@ export default class HexmakerPlugin extends Plugin { content = withMapLink(content, mapName); if (terrain) this.mapStore.set(mapName, `${x}_${y}`, { terrain }); // The template's Map data callout shows what the map has for this hex. - content = setMapData(content, this.hexMapDataView(mapName, x, y)); + const mapDataView = this.hexMapDataView(mapName, x, y); + const withMapData = setMapData(content, mapDataView); + // Remember what it shows, so a later hand edit is told from a stale copy. + if (withMapData !== content) this.calloutMemory.set(path, shownValues(mapDataLines(mapDataView))); + content = withMapData; // The hex's terrain (just set, or painted before it had a note) gets // its encounter-table link now rather than patched in later. const encounterLink = this.terrainEncounterLinkFor(mapName, x, y, path); @@ -1893,6 +1907,30 @@ export default class HexmakerPlugin extends Plugin { } /** Read the hex template once (used by bulk generation to avoid N redundant reads). */ + /** The hex note last opened in an editor (its callout is synced when another file opens). */ + private focusedHexNote: string | null = null; + + /** + * A file opened in an editor: a hex note left behind has its Map data + * callout synced (hand edits made in it go to the map), and a hex note + * being opened gets its callout brought up to date before it's edited. + * Not while the user is still in the note: rewriting it mid-typing would + * fight the editor. + */ + private onHexNoteFocus(file: TFile | null): void { + const sync = (path: string) => { + const loc = this.mapStore.isReady() ? this.mapStore.resolve(path) : null; + if (!loc || !this.getMap(loc.map)) return; + const [x, y] = loc.key.split("_").map(Number); + void this.syncHexMapData(loc.map, x, y); + }; + const prev = this.focusedHexNote; + const next = file && this.mapStore.isReady() && this.mapStore.resolve(file.path) ? file.path : null; + if (prev && prev !== file?.path) sync(prev); + if (next && next !== prev) sync(next); + this.focusedHexNote = next; + } + /** What the map has for a hex, for its note's Map data callout (src/hexMapData.ts). */ hexMapDataView(mapName: string, x: number, y: number): HexMapDataView { const h = this.mapStore.get(mapName, `${x}_${y}`) ?? {}; @@ -1901,28 +1939,95 @@ export default class HexmakerPlugin extends Plugin { map: mapName, mapLabel: this.mapLabel(mapName), x, y, terrain: h.terrain, region: h.region, name: h.name, regionMap: h.regionMap ? ref(h.regionMap) : undefined, locations: h.locations?.length ? h.locations.map(ref) : undefined, + biome: this.hexBiomeRef(mapName, `${x}_${y}`), }; } + /** An overworld hex's biome for its Map data callout: its label, and its biome note when it has one. */ + private hexBiomeRef(mapName: string, key: string): { label: string; note?: string } | undefined { + if (!overworldOf(this, mapName)) return undefined; + const id = hexBiomeAt(this, mapName, key); + if (!id) return undefined; + const label = biomeNoteOf(id)?.label ?? BIOMES.find((b) => b.id === id)?.label ?? id; + return { label, note: this.biomeStore.pathOf(id) }; + } + /** * Bring a hex note's Map data callout up to date with the map (or add one - * when `insert`). Only writes when something changed; a note without a - * callout is left alone unless `insert`. Returns whether it wrote. + * when `insert`). Hand edits made inside the callout go to the map first + * (phase 2, see `syncHexMapData`). Only writes when something changed; a + * note without a callout is left alone unless `insert`. Returns whether + * it wrote. */ async refreshHexMapData(mapName: string, x: number, y: number, insert = false): Promise { - const file = this.app.vault.getAbstractFileByPath(this.hexPath(x, y, mapName)); - if (!(file instanceof TFile)) return false; - const view = this.hexMapDataView(mapName, x, y); + return (await this.syncHexMapData(mapName, x, y, { insert })).wrote; + } + + /** + * A hex note's Map data callout, both ways (phase 2): hand edits to + * Terrain, Region or Name made since the plugin last wrote it go to the + * map (through the work-mode gate, as one undo step), unless the map has + * changed them since (the map is newer); then the callout is rewritten + * to show the map. Edits that weren't applied stay in the callout as + * "Not applied:" lines and lines it can't read as "Not read:" lines, and + * a notice says so (unless `quiet`). + */ + async syncHexMapData( + mapName: string, x: number, y: number, opts: { insert?: boolean; quiet?: boolean } = {}, + ): Promise<{ wrote: boolean; applied: string[]; notApplied: string[]; unreadable: string[] }> { + const out = { wrote: false, applied: [] as string[], notApplied: [] as string[], unreadable: [] as string[] }; + const path = this.hexPath(x, y, mapName); + const file = this.app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) return out; + await this.calloutMemory.ready(); // Read first: most notes need nothing, and a no-op process() still writes. const current = await this.app.vault.read(file); - if (setMapData(current, view, insert) === current) return false; - let wrote = false; - await this.app.vault.process(file, (content) => { - const next = setMapData(content, view, insert); - wrote = next !== content; - return next; - }); - return wrote; + const now = () => shownValues(mapDataLines(this.hexMapDataView(mapName, x, y))); + const plan = planCalloutImport(current, this.calloutMemory.get(path), now()); + if (plan) { + out.notApplied.push(...plan.notApplied); + out.unreadable.push(...plan.unreadable); + const edits = Object.entries(plan.apply) as [keyof typeof plan.apply, string | null][]; + if (edits.length) { + await this.undoableEdit(mapName, async () => { + const key = `${x}_${y}`; + for (const [field, value] of edits) { + const shown = `${field[0].toUpperCase()}${field.slice(1)}: ${value ?? "—"}`; + if (field === "name") { + await this.setHexName(mapName, x, y, value ?? ""); + out.applied.push(shown); + } else if (field === "terrain") { + // A terrain must be one the map's palette has (matched ignoring case). + const terrain = value === null ? null : this.getMapPalette(mapName).find((t) => sameName(t.name, value))?.name; + if (terrain === undefined) { out.notApplied.push(`${shown} (not in this map's palette)`); continue; } + if (!this.mapStore.set(mapName, key, { terrain }, "paint-terrain")) { out.notApplied.push(`${shown} (${lockedHint("paint-terrain")})`); continue; } + await this.syncHexEncounterTableLink(path, terrain); + out.applied.push(shown); + } else { + if (!this.mapStore.set(mapName, key, { region: value }, "paint-region-area")) { out.notApplied.push(`${shown} (${lockedHint("paint-region-area")})`); continue; } + out.applied.push(shown); + } + } + }); + } + } + const view = this.hexMapDataView(mapName, x, y); + const notes = [...out.notApplied.map((s) => `Not applied: ${s}`), ...out.unreadable.map((s) => `Not read: ${s}`)]; + const latest = await this.app.vault.read(file); + if (setMapData(latest, view, opts.insert, notes) !== latest) { + await this.app.vault.process(file, (content) => { + const next = setMapData(content, view, opts.insert, notes); + out.wrote = next !== content; + return next; + }); + } + // Remember what the callout shows now, so the next edit is told from a stale copy. + if (plan || opts.insert) this.calloutMemory.set(path, now()); + if (!opts.quiet) { + const msg = mapDataSyncMessage(`${this.mapLabel(mapName)} ${x}, ${y}`, out); + if (msg) new Notice(msg, 8000); + } + return out; } /** Add (or update) the Map data callout in every hex note of a map. Returns how many notes changed. */ @@ -1931,11 +2036,19 @@ export default class HexmakerPlugin extends Plugin { const folder = this.app.vault.getAbstractFileByPath(hexBase ? `${hexBase}/${mapName}` : mapName); if (!(folder instanceof TFolder)) return 0; let n = 0; + const totals = { applied: [] as string[], notApplied: [] as string[], unreadable: [] as string[] }; for (const f of folder.children) { if (!(f instanceof TFile)) continue; const m = /^(-?\d+)_(-?\d+)\.md$/.exec(f.name); - if (m && await this.refreshHexMapData(mapName, Number(m[1]), Number(m[2]), true)) n++; - } + if (!m) continue; + const r = await this.syncHexMapData(mapName, Number(m[1]), Number(m[2]), { insert: true, quiet: true }); + if (r.wrote) n++; + totals.applied.push(...r.applied); + totals.notApplied.push(...r.notApplied); + totals.unreadable.push(...r.unreadable); + } + const msg = mapDataSyncMessage(this.mapLabel(mapName), totals); + if (msg) new Notice(msg, 8000); return n; } diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 5f660091..336d57ff 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -24,7 +24,6 @@ import { } from "../frontmatter"; import { cleanHexName } from "../maps/hexNames"; import { BODY_FIELDS, readBodyField, sameName, setBodyField, type BodyField } from "../hexBodyFields"; -import { hasMapData } from "../hexMapData"; import { addLinkToSection, removeLinkFromSection, @@ -140,6 +139,9 @@ export class HexEditorModal extends HexmakerModal { this.directGmIcons = []; const path = this.plugin.hexPath(this.x, this.y, this.mapName); + // Hand edits in the note's Map data callout go to the map first (phase + // 2), so the editor shows them; the callout then shows what the map has. + if (this.app.vault.getAbstractFileByPath(path) instanceof TFile) await this.plugin.syncHexMapData(this.mapName, this.x, this.y); // Terrain, icon and GM icons live in the map note (the map store), not in // the hex note — and a hex can have them before its note exists. Reading // only hex frontmatter left the current terrain never highlighted (E1). @@ -170,8 +172,6 @@ export class HexEditorModal extends HexmakerModal { const v = readBodyField(rawContent, f); if (v !== undefined) this.bodyFields.set(f, v); } - // The note's Map data callout shows what the map has now. - if (hasMapData(rawContent)) void this.plugin.refreshHexMapData(this.mapName, this.x, this.y); ({ text: this.allText, links: this.allLinks, headings: this.allHeadings } = await getAllSectionData( this.app, path, diff --git a/src/hexMapData.ts b/src/hexMapData.ts index f81d3961..a88b134d 100644 --- a/src/hexMapData.ts +++ b/src/hexMapData.ts @@ -18,6 +18,14 @@ * "Update map data in hex notes". The built-in hex template has the * callout; notes without one only get it from that command, so a user's * own notes and templates aren't changed behind their back. + * + * Phase 2: a person may edit Terrain, Region or Name inside the callout. + * Before the plugin rewrites it, those edits go to the map + * (`planCalloutImport`), unless the map changed since the callout was + * written (the map is newer) or the work mode locks the field. What isn't + * applied stays in the callout as a `Not applied:` line, and lines it can't + * read as `Not read:` lines, so nothing typed is lost. Overworld hexes get + * a "Biome:" line too. */ export const MAP_DATA_CALLOUT = "[!hexmaker]"; @@ -39,6 +47,8 @@ export interface HexMapDataView { regionMap?: { map: string; label: string }; /** The hex's Location maps, in order. */ locations?: { map: string; label: string }[]; + /** Overworld hexes: the hex's biome, linked to its biome note when it has one. */ + biome?: { label: string; note?: string }; } const NONE = "—"; @@ -51,6 +61,7 @@ export function mapDataLines(d: HexMapDataView): string[] { `> Terrain: ${d.terrain || NONE}`, `> Region: ${d.region || NONE}`, `> Name: ${d.name || NONE}`, + ...(d.biome ? [`> Biome: ${biomeRef(d.biome)}`] : []), ...(d.regionMap ? [`> Region map: ${mapRef(d.regionMap)}`] : []), ...(d.locations?.length ? [`> Locations: ${d.locations.map(mapRef).join(", ")}`] : []), ]; @@ -59,6 +70,12 @@ export function mapDataLines(d: HexMapDataView): string[] { /** A link to a map's note, shown by its label. */ const mapRef = (r: { map: string; label: string }) => `[[_${r.map}|${r.label.replace(/[|[\]]/g, "")}]]`; +/** A biome: a link to its note (shown by its label), or just the label. */ +function biomeRef(b: { label: string; note?: string }): string { + const label = b.label.replace(/[|[\]]/g, ""); + return b.note ? `[[${b.note.replace(/\.md$/i, "")}|${label}]]` : label; +} + interface CalloutSpan { start: number; end: number } /** The callout's line span (start inclusive, end exclusive), or null. */ @@ -79,12 +96,21 @@ export function hasMapData(content: string): boolean { * The note with its Map data callout showing `d`. A note without one is * returned unchanged unless `insert`, when the callout goes under the * title (or the frontmatter). Unchanged content is returned as is. + * + * `Not applied:` / `Not read:` lines already in the callout are kept (they + * hold what a person typed), followed by any new `notes` (each written as + * a callout line, skipped when an identical one is already there). */ -export function setMapData(content: string, d: HexMapDataView, insert = false): string { +export function setMapData(content: string, d: HexMapDataView, insert = false, notes: string[] = []): string { const eol = content.includes("\r\n") ? "\r\n" : "\n"; const lines = content.replace(/\r\n?/g, "\n").split("\n"); - const block = mapDataLines(d); const span = findCallout(lines); + const kept = span ? lines.slice(span.start + 1, span.end).filter(isKeptLine).map((l) => l.trimEnd()) : []; + for (const n of notes) { + const line = `> ${n}`; + if (!kept.some((k) => sameText(k.replace(/^\s*>\s*/, ""), n))) kept.push(line); + } + const block = [...mapDataLines(d), ...kept]; if (span) { const current = lines.slice(span.start, span.end); if (current.length === block.length && current.every((l, i) => l.trimEnd() === block[i])) return content; @@ -115,8 +141,108 @@ export function readMapData(content: string): { terrain?: string; region?: strin for (const l of lines.slice(span.start + 1, span.end)) { const m = /^\s*>\s*(terrain|region|name)\s*:\s*(.*?)\s*$/i.exec(l); if (!m) continue; - const v = m[2].replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_a, t: string, alias?: string) => alias ?? t).trim(); + const v = unlink(m[2]); if (v && v !== NONE && v !== "-") out[m[1].toLowerCase() as "terrain" | "region" | "name"] = v; } return out; } + +// ── Phase 2: hand edits in the callout flow back into the map ───────────── + +/** Callout fields a hand edit can change on the map (with the write's work-mode action). */ +export const IMPORT_FIELDS = ["terrain", "region", "name"] as const; +export type ImportField = (typeof IMPORT_FIELDS)[number]; + +/** Every line key the callout writes, lower case → how it's written. */ +const KEYS: Record = { + map: "Map", terrain: "Terrain", region: "Region", name: "Name", biome: "Biome", "region map": "Region map", locations: "Locations", +}; + +/** What a callout shows, key (lower case) → value as written. */ +export type MapDataShown = Record; + +/** Lines that hold what a person typed and are kept as they are. */ +const KEPT = /^\s*>\s*(not applied|not read)\s*:/i; +const isKeptLine = (l: string) => KEPT.test(l); +/** The built-in template's placeholder line. */ +const PLACEHOLDER = /^filled in from the map by hexmaker\.?$/i; + +/** `[[target|alias]]` → alias (or target). */ +const unlink = (v: string) => v.replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_a, t: string, alias?: string) => alias ?? t).trim(); +/** A shown value as compared: no links, spacing or case, and "—"/"-"/"" all mean none. */ +function norm(v: string | undefined): string { + const s = unlink(v ?? "").replace(/\s+/g, " ").trim().toLowerCase(); + return s === NONE || s === "-" || s === "none" ? "" : s; +} +const sameText = (a: string, b: string) => a.replace(/\s+/g, " ").trim().toLowerCase() === b.replace(/\s+/g, " ").trim().toLowerCase(); + +/** The values of callout lines (`mapDataLines` output, or a note's callout body). */ +export function shownValues(lines: string[]): MapDataShown { + const out: MapDataShown = {}; + for (const l of lines) { + const m = /^\s*>\s*([A-Za-z][A-Za-z ]*?)\s*:\s*(.*?)\s*$/.exec(l); + if (m && KEYS[m[1].toLowerCase()] && !(m[1].toLowerCase() in out)) out[m[1].toLowerCase()] = m[2]; + } + return out; +} + +export interface CalloutImport { + /** Hand edits to make on the map: field → value (null = cleared). */ + apply: Partial>; + /** Edits that weren't applied, each "Terrain: swamp (why)". */ + notApplied: string[]; + /** Callout lines that couldn't be read, as typed. */ + unreadable: string[]; +} + +/** + * What to import from a note's Map data callout. `shown` is what the + * callout showed when the plugin last wrote it (unknown: nothing is + * imported, the map wins, as before phase 2); `now` is what it would show + * now (`shownValues(mapDataLines(view))`). + * + * A line counts as edited when it no longer says what was shown. An edit + * is applied only when the map still has what was shown; when the map has + * changed since, the map's value is newer and the edit is reported instead. + * Lines the map owns elsewhere (Map, Biome, Region map, Locations) aren't + * read back. Lines that aren't `Key: value` for a known key are unreadable. + * Null without a callout. + */ +export function planCalloutImport(content: string, shown: MapDataShown | undefined, now: MapDataShown): CalloutImport | null { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const span = findCallout(lines); + if (!span) return null; + const out: CalloutImport = { apply: {}, notApplied: [], unreadable: [] }; + const typed: MapDataShown = {}; + for (const raw of lines.slice(span.start + 1, span.end)) { + const body = raw.replace(/^\s*>\s?/, "").trim(); + if (!body || isKeptLine(raw) || PLACEHOLDER.test(body)) continue; + const m = /^([A-Za-z][A-Za-z ]*?)\s*:\s*(.*)$/.exec(body); + const key = m?.[1].toLowerCase(); + if (!m || !key || !KEYS[key] || key in typed) { out.unreadable.push(body); continue; } + typed[key] = m[2].trim(); + } + if (!shown) return out; + for (const [key, value] of Object.entries(typed)) { + if (norm(value) === norm(shown[key]) || norm(value) === norm(now[key])) continue; + const line = `${KEYS[key]}: ${value || NONE}`; + if (!(IMPORT_FIELDS as readonly string[]).includes(key)) { + out.notApplied.push(`${line} (change this on the map)`); + } else if (norm(now[key]) !== norm(shown[key])) { + out.notApplied.push(`${line} (the map has changed it to ${unlink(now[key] ?? "") || NONE} since)`); + } else { + const v = unlink(value); + out.apply[key as ImportField] = norm(v) ? v : null; + } + } + return out; +} + +/** The notice after importing callout edits, or null when there's nothing to say. */ +export function mapDataSyncMessage(where: string, r: { applied: string[]; notApplied: string[]; unreadable: string[] }): string | null { + const parts: string[] = []; + if (r.applied.length) parts.push(`Put on the map from the note's Map data: ${r.applied.join("; ")}.`); + if (r.notApplied.length) parts.push(`Not applied: ${r.notApplied.join("; ")}.`); + if (r.unreadable.length) parts.push(`${r.unreadable.length} line${r.unreadable.length === 1 ? "" : "s"} in Map data couldn't be read; marked "Not read:" in the note.`); + return parts.length ? `${where}: ${parts.join(" ")}` : null; +} diff --git a/src/maps/calloutMemory.ts b/src/maps/calloutMemory.ts new file mode 100644 index 00000000..701d0c0a --- /dev/null +++ b/src/maps/calloutMemory.ts @@ -0,0 +1,87 @@ +/** + * What each hex note's Map data callout showed when the plugin last wrote + * it (hex-note path → key → value). Phase 2 of the callout compares a + * note's callout with this to tell a hand edit from a stale copy: without + * it, an old callout would look like an edit and could undo a newer paint. + * + * Kept in the plugin's folder (`map-data-shown.json`), not in the vault's + * notes: it's bookkeeping, like data.json. A note missing here (first run, + * a renamed note, another device) has no import: the map wins and the + * callout is rewritten, as before phase 2. + */ +import type { DataAdapter } from "obsidian"; +import type { MapDataShown } from "../hexMapData"; + +const FILE = "map-data-shown.json"; + +export class CalloutMemory { + private shown = new Map(); + private loading: Promise | null = null; + private saveTimer: number | null = null; + private dirty = false; + + constructor(private adapter: () => DataAdapter, private dir: () => string) {} + + private get path(): string { + return `${this.dir()}/${FILE}`; + } + + /** Read the file once (later calls wait for the same read). */ + ready(): Promise { + this.loading ??= (async () => { + try { + if (!(await this.adapter().exists(this.path))) return; + const raw = JSON.parse(await this.adapter().read(this.path)) as { notes?: Record }; + for (const [p, v] of Object.entries(raw.notes ?? {})) if (v && typeof v === "object" && !this.shown.has(p)) this.shown.set(p, v); + } catch (e) { + console.warn("[hexmaker] couldn't read map-data-shown.json; callout edits are imported again once notes are refreshed", e); + } + })(); + return this.loading; + } + + get(path: string): MapDataShown | undefined { + return this.shown.get(path); + } + + set(path: string, values: MapDataShown): void { + const old = this.shown.get(path); + if (old && JSON.stringify(old) === JSON.stringify(values)) return; + this.shown.set(path, values); + this.scheduleSave(); + } + + forget(path: string): void { + if (this.shown.delete(path)) this.scheduleSave(); + } + + rename(oldPath: string, newPath: string): void { + const v = this.shown.get(oldPath); + if (!v) return; + this.shown.delete(oldPath); + this.shown.set(newPath, v); + this.scheduleSave(); + } + + private scheduleSave(): void { + this.dirty = true; + if (this.saveTimer !== null) activeWindow.clearTimeout(this.saveTimer); + this.saveTimer = activeWindow.setTimeout(() => void this.save(), 1500); + } + + /** Write now, when anything changed (also on unload). */ + async save(): Promise { + if (this.saveTimer !== null) activeWindow.clearTimeout(this.saveTimer); + this.saveTimer = null; + if (!this.dirty) return; + this.dirty = false; + await this.ready(); + const notes: Record = {}; + for (const [p, v] of [...this.shown].sort(([a], [b]) => a.localeCompare(b))) notes[p] = v; + try { + await this.adapter().write(this.path, JSON.stringify({ version: 1, notes }, null, 1)); + } catch (e) { + console.warn("[hexmaker] couldn't save map-data-shown.json", e); + } + } +} diff --git a/tests/hexEditorModal.test.ts b/tests/hexEditorModal.test.ts index d21018f6..666aa722 100644 --- a/tests/hexEditorModal.test.ts +++ b/tests/hexEditorModal.test.ts @@ -39,6 +39,7 @@ function makePlugin(hexPathFn: (x: number, y: number) => string) { }, availableIcons: [], terrainEncounterLinkFor: () => null, + syncHexMapData: mock.fn(async () => ({ wrote: false, applied: [], notApplied: [], unreadable: [] })), } as unknown as import("../src/HexmakerPlugin").default; } diff --git a/tests/hexMapData.test.ts b/tests/hexMapData.test.ts index 1375ae6a..8365aa0c 100644 --- a/tests/hexMapData.test.ts +++ b/tests/hexMapData.test.ts @@ -2,7 +2,7 @@ import { describe, it } from "node:test"; import expect from "expect"; import { readFileSync } from "node:fs"; import { TFile } from "obsidian"; -import { hasMapData, mapDataLines, readMapData, setMapData, type HexMapDataView } from "../src/hexMapData"; +import { hasMapData, mapDataLines, mapDataSyncMessage, planCalloutImport, readMapData, setMapData, shownValues, type HexMapDataView } from "../src/hexMapData"; import { getAllSectionData } from "../src/sections"; const VIEW: HexMapDataView = { map: "the-coast", mapLabel: "The Coast", x: 0, y: 1, terrain: "desert rocky", region: "Dustbowl" }; @@ -65,3 +65,93 @@ describe("Map data callout: region map and locations", () => { expect(lines).toContain("> Locations: [[_inn|The Inn]], [[_mine|Mine]]"); }); }); + +describe("Map data callout: biome", () => { + it("shows an overworld hex's biome, linked to its note when it has one", () => { + const base = { map: "w", mapLabel: "World", x: 0, y: 0 }; + expect(mapDataLines(base).join("\n")).not.toMatch(/Biome/); + expect(mapDataLines({ ...base, biome: { label: "Swamp" } })).toContain("> Biome: Swamp"); + expect(mapDataLines({ ...base, biome: { label: "Ash|wastes", note: "world/biomes/Ash wastes.md" } })).toContain("> Biome: [[world/biomes/Ash wastes|Ashwastes]]"); + }); +}); + +describe("Map data callout phase 2: hand edits back to the map", () => { + const view: HexMapDataView = { map: "coast", mapLabel: "Coast", x: 3, y: 4, terrain: "forest", region: "Dustbowl", name: "Old Oak" }; + const shown = shownValues(mapDataLines(view)); + const note = (lines = mapDataLines(view)) => `# Hex 3, 4\n\n${lines.join("\n")}\n\n### Description\nText.\n`; + const edit = (from: string, to: string) => note().replace(from, to); + + it("finds nothing to do in an untouched callout", () => { + expect(planCalloutImport(note(), shown, shown)).toEqual({ apply: {}, notApplied: [], unreadable: [] }); + expect(planCalloutImport("no callout", shown, shown)).toBeNull(); + }); + + it("applies an edited field when the map still has what the callout showed", () => { + const r = planCalloutImport(edit("> Terrain: forest", "> terrain : Swamp "), shown, shown)!; + expect(r.apply).toEqual({ terrain: "Swamp" }); + expect(planCalloutImport(edit("> Name: Old Oak", "> Name: [[Oak note|The Great Oak]]"), shown, shown)!.apply).toEqual({ name: "The Great Oak" }); + }); + + it("reads a dash, 'none' or nothing as clearing the field", () => { + expect(planCalloutImport(edit("> Region: Dustbowl", "> Region: —"), shown, shown)!.apply).toEqual({ region: null }); + expect(planCalloutImport(edit("> Region: Dustbowl", "> Region:"), shown, shown)!.apply).toEqual({ region: null }); + expect(planCalloutImport(edit("> Name: Old Oak", "> Name: none"), shown, shown)!.apply).toEqual({ name: null }); + }); + + it("ignores a change of case or spacing", () => { + expect(planCalloutImport(edit("> Terrain: forest", "> Terrain: FOREST"), shown, shown)!.apply).toEqual({}); + }); + + it("never writes over a newer map value: the edit is reported instead", () => { + const now = shownValues(mapDataLines({ ...view, terrain: "hills" })); + const r = planCalloutImport(edit("> Terrain: forest", "> Terrain: swamp"), shown, now)!; + expect(r.apply).toEqual({}); + expect(r.notApplied).toEqual(["Terrain: swamp (the map has changed it to hills since)"]); + }); + + it("doesn't count a stale copy as an edit (the map moved on, the callout didn't)", () => { + const now = shownValues(mapDataLines({ ...view, terrain: "hills" })); + expect(planCalloutImport(note(), shown, now)).toEqual({ apply: {}, notApplied: [], unreadable: [] }); + }); + + it("imports nothing when it doesn't know what the callout showed (the map wins, as before)", () => { + const r = planCalloutImport(edit("> Terrain: forest", "> Terrain: swamp"), undefined, shown)!; + expect(r.apply).toEqual({}); + expect(r.notApplied).toEqual([]); + }); + + it("doesn't read back lines the map owns elsewhere", () => { + const v2 = { ...view, regionMap: { map: "fen", label: "Fen" } }; + const s2 = shownValues(mapDataLines(v2)); + const r = planCalloutImport(note(mapDataLines(v2)).replace("[[_fen|Fen]]", "[[_moor|Moor]]"), s2, s2)!; + expect(r.apply).toEqual({}); + expect(r.notApplied).toEqual(["Region map: [[_moor|Moor]] (change this on the map)"]); + }); + + it("reports lines it can't read, and skips the template's placeholder and kept lines", () => { + const text = note([...mapDataLines(view), "> Treasure: 40gp", "> just a thought", ">", "> Filled in from the map by Hexmaker.", "> Not read: older"]); + const r = planCalloutImport(text, shown, shown)!; + expect(r.unreadable).toEqual(["Treasure: 40gp", "just a thought"]); + // A field written twice: the second is unreadable. + expect(planCalloutImport(note([...mapDataLines(view), "> Terrain: swamp"]), shown, shown)!.unreadable).toEqual(["Terrain: swamp"]); + }); + + it("keeps what wasn't applied in the callout, once", () => { + const once = setMapData(edit("> Terrain: forest", "> Terrain: swamp"), view, false, ["Not applied: Terrain: swamp (Switch to Build to paint terrain.)", "Not read: Treasure: 40gp"]); + expect(once).toContain("> Terrain: forest"); + expect(once).toContain("> Not applied: Terrain: swamp (Switch to Build to paint terrain.)"); + expect(once).toContain("> Not read: Treasure: 40gp"); + // Rewriting keeps them, and the same note isn't added twice. + const twice = setMapData(once, { ...view, terrain: "hills" }, false, ["Not read: Treasure: 40gp"]); + expect(twice.match(/Not read: Treasure/g)?.length).toBe(1); + expect(twice).toContain("> Not applied: Terrain: swamp"); + expect(twice).toContain("> Terrain: hills"); + expect(setMapData(twice, { ...view, terrain: "hills" })).toBe(twice); + }); + + it("says what happened in one notice", () => { + expect(mapDataSyncMessage("Coast 3, 4", { applied: [], notApplied: [], unreadable: [] })).toBeNull(); + expect(mapDataSyncMessage("Coast 3, 4", { applied: ["Terrain: swamp"], notApplied: ["Region: Fen (x)"], unreadable: ["a", "b"] })) + .toBe(`Coast 3, 4: Put on the map from the note's Map data: Terrain: swamp. Not applied: Region: Fen (x). 2 lines in Map data couldn't be read; marked "Not read:" in the note.`); + }); +}); From 96bec14b3b14fadc3fa6cfdb5da0b44fce1c6c45 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:01:21 -0400 Subject: [PATCH 276/558] feat(world-types): stars and sector features as editable rows (WT1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The world types note gets two more tables, each under its own heading (format 2): Stars (Orbits' random star, by Weight) and Sector features (Star scatter's special hexes, each with a Chance per star system hex: "1 in 50", "2%", "never"). Tables are told apart by their header, read forgivingly, unreadable rows are kept as written and reported. - API (pure, src/space/worldTypes.ts): pickStar(table, ctx) and pickSectorFeature(table, ctx) — deterministic, one draw from ctx.rand (pickStar none when nothing fits; pickSectorFeature always one: the features take consecutive slices of that draw as wide as their chance). Plus starWeights / starOdds / rollStars and sectorFeatureChances / sectorFeatureOdds / rollSectorFeatures. - Default space reproduces today's odds exactly: stars 6/3/1.5/1/0.5, features 1 in 50 / 1 in 75 / 1 in 150 (= the old 4% split 3:2:1). Frozen-copy test: same star for the same stream; the same hexes become features and ordinary systems stay in step. - WorldTypeStore: get/list carry stars and features; update/create take them; Restore default restores them; a format 1 note is given the shipped tables once when read (a later deletion sticks). - Editor: Worlds / Stars / Sector features tabs, each with rows and a rolling preview. - Generators are not wired here (paths session). Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- package.json | 4 +- src/hex-map/help.md | 2 +- src/space/WorldTypeStore.ts | 67 ++++- src/space/WorldTypesModal.ts | 265 +++++++++++++---- src/space/worldTypePresets.ts | 33 ++- src/space/worldTypes.ts | 522 +++++++++++++++++++++++++++++++--- styles.css | 19 ++ tests/worldTypeStars.test.ts | 389 +++++++++++++++++++++++++ tests/worldTypes.test.ts | 6 +- 10 files changed, 1189 insertions(+), 120 deletions(-) create mode 100644 tests/worldTypeStars.test.ts diff --git a/README.md b/README.md index 50c66362..6fbc5a64 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it. - **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). -- **World types** (Advanced: Terrain generators) — which worlds the space generators place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types` (**Default space** ships, with the odds Star scatter and Orbits have always used; **Restore default** puts them back). Each row is a world (a terrain of your palette) with a **Weight** and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature**. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows, and a preview rolls the table for a map, orbit, star and temperature and shows how often each world comes up next to its odds. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. +- **World types** (Advanced: Terrain generators) — which worlds the space generators place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types` (**Default space** ships, with the odds Star scatter and Orbits have always used; **Restore default** puts them back). Each row is a world (a terrain of your palette) with a **Weight** and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature**. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows, and a preview rolls the table for a map, orbit, star and temperature and shows how often each world comes up next to its odds. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. diff --git a/package.json b/package.json index c1768281..7a47d937 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/hex-map/help.md b/src/hex-map/help.md index b35ecec9..491aaf66 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -160,7 +160,7 @@ Neighbouring regions share one set of hex numbers: a new region carries on from A road or river that ends on the edge of a region, next to where the neighbour's road of the same type ends, is drawn on to the shared edge on both maps, so the two join up. -**World types** (space; Advanced: Terrain generators). Which worlds Star scatter and Orbits place, how often, and how each world's own map is made, is a table note in `{world folder}/world-types` (**Default space** ships with the usual odds; **Restore default** puts them back). Each row: a **World** (a terrain of the palette), a **Weight**, optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base**. **Edit world types…** (in the Star scatter and Orbits options, or the command) edits the rows and previews how often each world comes up. Needs Build or God. +**World types** (space; Advanced: Terrain generators). Which worlds Star scatter and Orbits place, how often, and how each world's own map is made, is a table note in `{world folder}/world-types` (**Default space** ships with the usual odds; **Restore default** puts them back). Each row: a **World** (a terrain of the palette), a **Weight**, optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base**. **Edit world types…** (in the Star scatter and Orbits options, or the command) edits the rows and previews how often each world comes up. The same note also has a **Stars** table (the star Orbits picks when its Star choice is Random, by **Weight**) and a **Sector features** table (Star scatter's special hexes, each with a **Chance** per star system hex, like `1 in 50` or `2%`); the editor has a tab and a preview for each. Needs Build or God. With generators on, new maps can also use the built-in **biomes and presets** (Grassland, Taiga, Swamp, Archipelago, Volcanic and more). They place terrain by type, so they work with any palette whose terrains have types. diff --git a/src/space/WorldTypeStore.ts b/src/space/WorldTypeStore.ts index 5debaf83..98905dd0 100644 --- a/src/space/WorldTypeStore.ts +++ b/src/space/WorldTypeStore.ts @@ -9,6 +9,8 @@ * space maps are on (ensureDefault() does it on demand otherwise). * - Hand edits are read back live (vault events); rows that can't be read * are reported once per edit, never used, and kept as written. + * - A note from before stars and sector features were rows (format 1) + * is given the shipped Stars and Sector features tables once, when read. * - Every change is told to onChange listeners. */ @@ -21,22 +23,40 @@ import { biomeFileName } from "../overworld/biomeNote"; import { DEFAULT_WORLD_TYPES, buildWorldTypes, + copyFeatureRows, + copyStarRows, copyWorldTypeRows, parseWorldTypes, updateWorldTypes, + upgradeWorldTypes, + type SectorFeatureRow, + type StarTypeRow, + type WorldTypeExtras, type WorldTypeProblem, type WorldTypeRow, type WorldTypeTable, } from "./worldTypes"; -import { DEFAULT_WORLD_TYPE_ROWS } from "./worldTypePresets"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "./worldTypePresets"; interface Entry { path: string; name: string; rows: WorldTypeRow[]; + /** Undefined: the note has no Stars table. */ + stars?: StarTypeRow[]; + /** Undefined: the note has no Sector features table. */ + features?: SectorFeatureRow[]; problems: WorldTypeProblem[]; } +/** An entry as a table (copies, so callers may change it). */ +function tableOf(e: Entry): WorldTypeTable { + const t: WorldTypeTable = { name: e.name, rows: copyWorldTypeRows(e.rows) }; + if (e.stars) t.stars = copyStarRows(e.stars); + if (e.features) t.features = copyFeatureRows(e.features); + return t; +} + /** Settings the store reads (a subset of the plugin's). */ interface StoreSettings { worldFolder?: string; @@ -109,13 +129,13 @@ export class WorldTypeStore { /** Every table, by name. */ list(): WorldTypeTable[] { - return this.sorted().map((e) => ({ name: e.name, rows: copyWorldTypeRows(e.rows) })); + return this.sorted().map(tableOf); } /** A table by name (any case) or note path. */ get(name: string): WorldTypeTable | undefined { const e = this.find(name); - return e ? { name: e.name, rows: copyWorldTypeRows(e.rows) } : undefined; + return e ? tableOf(e) : undefined; } pathOf(name: string): string | undefined { @@ -131,8 +151,11 @@ export class WorldTypeStore { return name.trim().toLowerCase() === DEFAULT_WORLD_TYPES.toLowerCase(); } - /** Set a table's rows (rows the note has that can't be read are kept as written). */ - async update(name: string, rows: readonly WorldTypeRow[]): Promise { + /** + * Set a table's rows, and its Stars / Sector features rows when given + * (rows the note has that can't be read are kept as written). + */ + async update(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}): Promise { await this.queue; // hand edits read first const e = this.find(name); if (!e) return false; @@ -140,7 +163,7 @@ export class WorldTypeStore { if (!(f instanceof TFile)) return false; await this.enqueue(async () => { const content = await this.plugin.app.vault.read(f); - const next = updateWorldTypes(content, rows); + const next = updateWorldTypes(content, rows, extras); if (next !== content) await this.plugin.app.vault.modify(f, next); this.take(f.path, next); this.publish(); @@ -149,7 +172,11 @@ export class WorldTypeStore { } /** A new table note (rows default to a copy of the shipped table). Returns its name, or an error. */ - async create(name: string, rows: readonly WorldTypeRow[] = DEFAULT_WORLD_TYPE_ROWS): Promise<{ name: string } | { error: string }> { + async create( + name: string, + rows: readonly WorldTypeRow[] = DEFAULT_WORLD_TYPE_ROWS, + extras: WorldTypeExtras = DEFAULT_WORLD_TYPE_EXTRAS, + ): Promise<{ name: string } | { error: string }> { const clean = name.trim() ? biomeFileName(name.trim()) : ""; if (!clean) return { error: "Give the table a name." }; const folder = this.folder(); @@ -157,7 +184,7 @@ export class WorldTypeStore { if (this.find(clean) || this.plugin.app.vault.getAbstractFileByPath(path)) return { error: `There's already a table called ${clean}.` }; await this.enqueue(async () => { await this.ensureFolder(folder); - const text = buildWorldTypes(clean, copyWorldTypeRows(rows)); + const text = buildWorldTypes(clean, copyWorldTypeRows(rows), extras); await this.plugin.app.vault.create(path, text); this.take(path, text); this.publish(); @@ -178,7 +205,7 @@ export class WorldTypeStore { if (f instanceof TFile) { const content = await this.plugin.app.vault.read(f); await this.backup("default-space", { [f.path]: content }); - const next = updateWorldTypes(content, DEFAULT_WORLD_TYPE_ROWS); + const next = updateWorldTypes(content, DEFAULT_WORLD_TYPE_ROWS, DEFAULT_WORLD_TYPE_EXTRAS); if (next !== content) await this.plugin.app.vault.modify(f, next); this.take(f.path, next); } else { @@ -254,18 +281,30 @@ export class WorldTypeStore { return out.sort((a, b) => a.path.localeCompare(b.path)); } - /** Read one note. True when what it says changed. */ + /** Read one note (upgrading a format 1 note first). True when what it says changed. */ private async load(f: TFile): Promise { - const content = await this.plugin.app.vault.read(f); + let content = await this.plugin.app.vault.read(f); if (this.lastContent.get(f.path) === content && this.entries.has(f.path)) return false; + const upgraded = upgradeWorldTypes(content, DEFAULT_WORLD_TYPE_EXTRAS); + if (upgraded !== content) { + try { + await this.plugin.app.vault.modify(f, upgraded); + content = upgraded; + } catch (e) { + console.error("Hexmaker: couldn't add stars and sector features to", f.path, e); + } + } this.take(f.path, content); return true; } private take(path: string, content: string): void { - const { rows, problems } = parseWorldTypes(content); + const { rows, stars, features, problems } = parseWorldTypes(content); const name = path.slice(path.lastIndexOf("/") + 1).replace(/\.md$/i, ""); - this.entries.set(path, { path, name, rows, problems }); + const entry: Entry = { path, name, rows, problems }; + if (stars) entry.stars = stars; + if (features) entry.features = features; + this.entries.set(path, entry); this.lastContent.set(path, content); this.report(path, name, problems); } @@ -289,7 +328,7 @@ export class WorldTypeStore { const path = `${folder}/${DEFAULT_WORLD_TYPES}.md`; if (this.plugin.app.vault.getAbstractFileByPath(path)) return; await this.ensureFolder(folder); - const text = buildWorldTypes(DEFAULT_WORLD_TYPES, copyWorldTypeRows(DEFAULT_WORLD_TYPE_ROWS)); + const text = buildWorldTypes(DEFAULT_WORLD_TYPES, copyWorldTypeRows(DEFAULT_WORLD_TYPE_ROWS), DEFAULT_WORLD_TYPE_EXTRAS); try { await this.plugin.app.vault.create(path, text); this.take(path, text); diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts index 88cf7cfc..331d5731 100644 --- a/src/space/WorldTypesModal.ts +++ b/src/space/WorldTypesModal.ts @@ -1,8 +1,9 @@ /** * "World types": edit a world types table (worldTypes.ts) — which worlds * the space generators place, how often, and what each world's own map is - * made with — with a small preview that rolls the table for a chosen map, - * orbit zone, star and temperature and shows what comes up. + * made with — plus its Stars (Orbits' random star) and Sector features + * (Star scatter's special hexes), one tab each. Each tab has a small + * preview that rolls its table and shows what comes up. * * Rows are edited as their note cells (the same reading as the note), so * anything typed here reads back the same from the note. Rows the note @@ -19,17 +20,32 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import { canAdd } from "../workMode"; import { DEFAULT_WORLD_TYPES, + FEATURE_COLUMNS, ORBIT_ZONES, + STAR_COLUMNS, WORLD_TYPE_COLUMNS, + featureCells, + formatChance, + readFeatureCells, + readStarCells, readWorldTypeCells, + rollSectorFeatures, + rollStars, rollWorldTypes, + sectorFeatureOdds, + starCells, + starOdds, worldTypeCells, worldTypeOdds, type OrbitZone, + type SectorFeatureRow, + type StarTypeRow, type WorldTypeColumn, type WorldTypeContext, + type WorldTypeExtras, type WorldTypeMap, type WorldTypeRow, + type WorldTypeTable, } from "./worldTypes"; /** Why world types can't be edited from this map now, or undefined. */ @@ -46,7 +62,7 @@ function lockButton(btn: HTMLButtonElement, hint: string): void { btn.setAttr("aria-label", `${btn.getText()} (${hint})`); } -const PLACEHOLDERS: Partial> = { +const PLACEHOLDERS: Record = { World: "ocean planet", Weight: "1", Orbit: "any", @@ -58,6 +74,9 @@ const PLACEHOLDERS: Partial> = { Palette: "same", Base: "none", Notes: "", + Star: "red dwarf", + Feature: "black hole", + Chance: "1 in 50", }; /** Columns shown on a row's first line (what is picked, and where); the rest are its map setup. */ @@ -66,10 +85,37 @@ const SETUP_COLUMNS: WorldTypeColumn[] = ["Size", "Generator", "Options", "Palet const col = (c: WorldTypeColumn) => WORLD_TYPE_COLUMNS.indexOf(c); +export type WorldTypesTab = "worlds" | "stars" | "features"; + +/** One tab's table: its columns and how its cells read. */ +interface TabSpec { + label: string; + columns: readonly string[]; + read: (cells: readonly string[]) => { problem?: string }; +} + +const TABS: Record = { + worlds: { label: "Worlds", columns: WORLD_TYPE_COLUMNS, read: readWorldTypeCells }, + stars: { label: "Stars", columns: STAR_COLUMNS, read: readStarCells }, + features: { label: "Sector features", columns: FEATURE_COLUMNS, read: readFeatureCells }, +}; +const TAB_ORDER: WorldTypesTab[] = ["worlds", "stars", "features"]; + +/** Terrain types offered as suggestions for each name column. */ +const SUGGEST_TYPES: Record = { + World: ["world", "gas-giant", "asteroids", "moon", "star-system", "station", "starport", "anomaly"], + Stars: ["star"], + Star: ["star"], + Feature: ["station", "starport", "jump-point", "anomaly", "star-system", "rift"], +}; + export class WorldTypesModal extends HexmakerModal { private tableName: string; - /** The rows being edited, as note cells. */ - private cells: string[][] = []; + private tab: WorldTypesTab; + /** The rows being edited, as note cells, per tab. */ + private cells: Record = { worlds: [], stars: [], features: [] }; + /** Whether the note has a Stars / Sector features table (so an empty one isn't added on save). */ + private has = { stars: false, features: false }; private dirty = false; private off: (() => void) | undefined; private rowsEl!: HTMLElement; @@ -78,10 +124,11 @@ export class WorldTypesModal extends HexmakerModal { private statusEl!: HTMLElement; private preview: { map: WorldTypeMap | ""; zone: OrbitZone | ""; star: string; temperature: string; n: number } = { map: "", zone: "", star: "", temperature: "", n: 200 }; - /** `mapName`: the map it was opened for (work mode, preview's map kind). */ - constructor(app: App, private plugin: HexmakerPlugin, private mapName?: string, table?: string, previewMap?: WorldTypeMap) { + /** `mapName`: the map it was opened for (work mode, preview's map kind). `tab`: the tab to open on. */ + constructor(app: App, private plugin: HexmakerPlugin, private mapName?: string, table?: string, previewMap?: WorldTypeMap, tab: WorldTypesTab = "worlds") { super(app); this.tableName = table ?? DEFAULT_WORLD_TYPES; + this.tab = tab; if (previewMap) this.preview.map = previewMap; } @@ -115,18 +162,47 @@ export class WorldTypesModal extends HexmakerModal { private loadRows(): void { const t = this.plugin.worldTypeStore.get(this.tableName); - this.cells = (t?.rows ?? []).map((r) => worldTypeCells(r)); + this.cells = { + worlds: (t?.rows ?? []).map((r) => worldTypeCells(r)), + stars: (t?.stars ?? []).map((r) => starCells(r)), + features: (t?.features ?? []).map((r) => featureCells(r)), + }; + this.has = { stars: !!t?.stars, features: !!t?.features }; this.dirty = false; } private rows(): WorldTypeRow[] { - return this.cells.map((c) => readWorldTypeCells(c).row).filter((r): r is WorldTypeRow => !!r); + return this.cells.worlds.map((c) => readWorldTypeCells(c).row).filter((r): r is WorldTypeRow => !!r); + } + + private stars(): StarTypeRow[] { + return this.cells.stars.map((c) => readStarCells(c).row).filter((r): r is StarTypeRow => !!r); + } + + private features(): SectorFeatureRow[] { + return this.cells.features.map((c) => readFeatureCells(c).row).filter((r): r is SectorFeatureRow => !!r); + } + + /** The table as edited here (readable rows only). */ + private table(): WorldTypeTable { + return { name: this.tableName, rows: this.rows(), stars: this.stars(), features: this.features() }; + } + + /** The Stars / Sector features rows to save: only when the note has that table or rows were added here. */ + private extras(): WorldTypeExtras { + const out: WorldTypeExtras = {}; + if (this.has.stars || this.cells.stars.length) out.stars = this.stars(); + if (this.has.features || this.cells.features.length) out.features = this.features(); + return out; } private firstProblem(): string | undefined { - for (let i = 0; i < this.cells.length; i++) { - const { problem } = readWorldTypeCells(this.cells[i]); - if (problem) return `Row ${i + 1}: ${problem}.`; + for (const tab of TAB_ORDER) { + const rows = this.cells[tab]; + for (let i = 0; i < rows.length; i++) { + const { problem } = TABS[tab].read(rows[i]); + if (problem) return `${TABS[tab].label} row ${i + 1}: ${problem}.`; + } } return undefined; } @@ -134,7 +210,12 @@ export class WorldTypesModal extends HexmakerModal { private async save(): Promise { const problem = this.firstProblem(); if (problem) { new Notice(problem); return; } - if (await this.plugin.worldTypeStore.update(this.tableName, this.rows())) this.dirty = false; + const extras = this.extras(); + if (await this.plugin.worldTypeStore.update(this.tableName, this.rows(), extras)) { + this.dirty = false; + if (extras.stars) this.has.stars = true; + if (extras.features) this.has.features = true; + } } // ── rendering ────────────────────────────────────────────────────────── @@ -180,17 +261,33 @@ export class WorldTypesModal extends HexmakerModal { contentEl.createEl("p", { cls: "setting-item-description", - text: `Which worlds the space generators place and how often, and what each world's own map is made with. Each table is a note in ${store.folder()}. Weight is the odds against the other rows that fit; blank limits mean any.`, + text: `What the space generators place and how often. Each table is a note in ${store.folder()}.`, }); if (lock) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); const problems = store.problemsOf(this.tableName); if (problems.length) { contentEl.createEl("p", { cls: "duckmage-world-types-problems", - text: `${problems.length} row${problems.length === 1 ? "" : "s"} in the note can't be read and ${problems.length === 1 ? "is" : "are"} kept as written: ${problems.map((p) => p.text).join("; ")}`, + text: `The note has ${problems.length} problem${problems.length === 1 ? "" : "s"} (rows that can't be read are kept as written): ${problems.map((p) => p.text).join("; ")}`, }); } + const tabs = contentEl.createDiv({ cls: "duckmage-world-types-tabs", attr: { role: "tablist" } }); + for (const t of TAB_ORDER) { + const b = tabs.createEl("button", { + text: `${TABS[t].label} (${this.cells[t].length})`, + cls: "duckmage-world-types-tab", + attr: { role: "tab", "aria-selected": String(t === this.tab) }, + }); + b.toggleClass("is-active", t === this.tab); + b.addEventListener("click", () => { + if (t === this.tab) return; + this.tab = t; + this.render(); + }); + } + contentEl.createEl("p", { cls: "setting-item-description", text: this.tabHint() }); + this.rowsEl = contentEl.createDiv({ cls: "duckmage-world-types-rows" }); this.renderRows(); @@ -199,9 +296,9 @@ export class WorldTypesModal extends HexmakerModal { if (lock) lockButton(add, lock); add.addEventListener("click", () => { if (this.lock()) return; - const blank = WORLD_TYPE_COLUMNS.map(() => ""); - if (this.preview.map) blank[col("Map")] = this.preview.map; - this.cells.push(blank); + const blank = TABS[this.tab].columns.map(() => ""); + if (this.tab === "worlds" && this.preview.map) blank[col("Map")] = this.preview.map; + this.cells[this.tab].push(blank); this.changed(); this.renderRows(); }); @@ -216,6 +313,14 @@ export class WorldTypesModal extends HexmakerModal { this.updateStatus(); } + private tabHint(): string { + switch (this.tab) { + case "worlds": return "Which worlds Star scatter and Orbits place, and what each world's own map is made with. Weight is the odds against the other rows that fit; blank limits mean any."; + case "stars": return "The star Orbits puts at a system's centre when its Star option is Random. Weight is the odds against the other stars; 0 never rolls it."; + case "features": return "Star scatter's special hexes. Chance is how likely each star system hex is to be that feature instead, like 1 in 50, 2% or never."; + } + } + private newTable(head: HTMLElement): void { if (this.lock()) return; const box = head.createDiv({ cls: "duckmage-world-types-new" }); @@ -223,7 +328,7 @@ export class WorldTypesModal extends HexmakerModal { const ok = box.createEl("button", { text: "Create", cls: "mod-cta" }); input.focus(); const go = () => { - void this.plugin.worldTypeStore.create(input.value, this.rows()).then((res) => { + void this.plugin.worldTypeStore.create(input.value, this.rows(), { stars: this.stars(), features: this.features() }).then((res) => { if ("error" in res) { new Notice(res.error); return; } this.tableName = res.name; this.loadRows(); @@ -248,7 +353,7 @@ export class WorldTypesModal extends HexmakerModal { if (!this.lock()) this.saveBtn.disabled = !!problem || !this.dirty; } - /** Terrain names (all palettes) for the World / Stars / Base suggestions. */ + /** Terrain names (all palettes) of these types (any type when undefined), for suggestions. */ private suggestions(types: string[] | undefined): string[] { const out = new Set(); for (const p of this.plugin.settings.terrainPalettes) { @@ -269,24 +374,27 @@ export class WorldTypesModal extends HexmakerModal { const el = this.rowsEl; el.empty(); const lock = this.lock(); - const worldList = this.datalist("worlds", this.suggestions(["world", "gas-giant", "asteroids", "moon", "star-system", "station", "starport", "anomaly"])); - const starList = this.datalist("stars", this.suggestions(["star"])); - const baseList = this.datalist("base", this.suggestions(undefined)); - const paletteList = this.datalist("palettes", this.plugin.settings.terrainPalettes.map((p) => p.name)); - const lists: Partial> = { World: worldList, Stars: starList, Base: baseList, Palette: paletteList }; - if (!this.cells.length) el.createDiv({ cls: "setting-item-description", text: "No rows yet." }); - this.cells.forEach((cells, i) => { + const lists: Record = {}; + for (const [c, types] of Object.entries(SUGGEST_TYPES)) lists[c] = this.datalist(c.toLowerCase(), this.suggestions(types)); + lists.Base = this.datalist("base", this.suggestions(undefined)); + lists.Palette = this.datalist("palettes", this.plugin.settings.terrainPalettes.map((p) => p.name)); + const spec = TABS[this.tab]; + const rows = this.cells[this.tab]; + if (!rows.length) el.createDiv({ cls: "setting-item-description", text: "No rows yet." }); + rows.forEach((cells, i) => { const row = el.createDiv({ cls: "duckmage-world-types-row" }); - const problem = readWorldTypeCells(cells).problem; + const problem = spec.read(cells).problem; row.toggleClass("is-invalid", !!problem); if (problem) row.setAttr("title", problem); - const line = (cls: string, columns: WorldTypeColumn[]) => { + const line = (cls: string, columns: readonly string[]) => { const l = row.createDiv({ cls }); - for (const c of columns) this.cellInput(l, cells, c, lists[c], !!lock, row); + for (const c of columns) this.cellInput(l, cells, spec, c, lists[c], !!lock, row); return l; }; - const top = line("duckmage-world-types-line", PICK_COLUMNS); - line("duckmage-world-types-line is-setup", SETUP_COLUMNS); + const top = this.tab === "worlds" + ? line("duckmage-world-types-line", PICK_COLUMNS) + : line("duckmage-world-types-line", spec.columns); + if (this.tab === "worlds") line("duckmage-world-types-line is-setup", SETUP_COLUMNS); const tools = top.createDiv({ cls: "duckmage-world-types-tools" }); const btn = (text: string, label: string, fn: () => void, disabled: boolean) => { const b = tools.createEl("button", { text, attr: { "aria-label": label, title: label } }); @@ -299,40 +407,42 @@ export class WorldTypesModal extends HexmakerModal { this.renderRows(); }); }; - btn("↑", "Move up", () => { [this.cells[i - 1], this.cells[i]] = [this.cells[i], this.cells[i - 1]]; }, i === 0); - btn("↓", "Move down", () => { [this.cells[i + 1], this.cells[i]] = [this.cells[i], this.cells[i + 1]]; }, i === this.cells.length - 1); - btn("✕", "Remove row", () => { this.cells.splice(i, 1); }, false); + btn("↑", "Move up", () => { [rows[i - 1], rows[i]] = [rows[i], rows[i - 1]]; }, i === 0); + btn("↓", "Move down", () => { [rows[i + 1], rows[i]] = [rows[i], rows[i + 1]]; }, i === rows.length - 1); + btn("✕", "Remove row", () => { rows.splice(i, 1); }, false); }); } - private cellInput(parent: HTMLElement, cells: string[], c: WorldTypeColumn, list: string | undefined, locked: boolean, row: HTMLElement): void { - const i = col(c); + private cellInput(parent: HTMLElement, cells: string[], spec: TabSpec, c: string, list: string | undefined, locked: boolean, row: HTMLElement): void { + const i = spec.columns.indexOf(c); const wrap = parent.createEl("label", { cls: `duckmage-world-types-cell is-${c.toLowerCase()}` }); wrap.createSpan({ cls: "duckmage-world-types-cell-label", text: c }); - if (c === "Map") { + if (spec === TABS.worlds && c === "Map") { const sel = wrap.createEl("select", { attr: { "aria-label": c } }); for (const [v, text] of [["", "Any"], ["sector", "Sector"], ["system", "System"]]) sel.createEl("option", { value: v, text }); // A value the select doesn't list (typed in the note) stays as it was. if (cells[i] && !["sector", "system"].includes(cells[i])) sel.createEl("option", { value: cells[i], text: cells[i] }); sel.value = cells[i] ?? ""; sel.disabled = locked; - sel.addEventListener("change", () => { cells[i] = sel.value; this.cellChanged(cells, row); }); + sel.addEventListener("change", () => { cells[i] = sel.value; this.cellChanged(cells, spec, row); }); return; } const input = wrap.createEl("input", { type: "text", value: cells[i] ?? "", attr: { placeholder: PLACEHOLDERS[c] ?? "", "aria-label": c } }); if (list) input.setAttr("list", list); input.disabled = locked; - input.addEventListener("input", () => { cells[i] = input.value; this.cellChanged(cells, row); }); + input.addEventListener("input", () => { cells[i] = input.value; this.cellChanged(cells, spec, row); }); } - private cellChanged(cells: string[], row: HTMLElement): void { - const problem = readWorldTypeCells(cells).problem; + private cellChanged(cells: string[], spec: TabSpec, row: HTMLElement): void { + const problem = spec.read(cells).problem; row.toggleClass("is-invalid", !!problem); if (problem) row.setAttr("title", problem); else row.removeAttribute("title"); this.changed(); } + // ── preview ──────────────────────────────────────────────────────────── + private renderPreview(): void { const el = this.previewEl; if (!el) return; @@ -346,33 +456,72 @@ export class WorldTypesModal extends HexmakerModal { s.value = value; s.addEventListener("change", () => { set(s.value); this.renderPreview(); }); }; - select("Map", [["", "Any"], ["sector", "Sector"], ["system", "System"]], p.map, (v) => { p.map = v as WorldTypeMap | ""; }); - select("Orbit", [["", "Any"], ...ORBIT_ZONES.map((z): [string, string] => [z, z[0].toUpperCase() + z.slice(1)])], p.zone, (v) => { p.zone = v as OrbitZone | ""; }); - select("Star", [["", "Any"], ...this.suggestions(["star"]).map((s): [string, string] => [s, s])], p.star, (v) => { p.star = v; }); - select("Temperature", [["", "Any"], ["0.1", "Cold"], ["0.3", "Cool"], ["0.5", "Mild"], ["0.7", "Warm"], ["0.9", "Hot"]], p.temperature, (v) => { p.temperature = v; }); - select("Rolls", [["100", "100"], ["200", "200"], ["1000", "1000"]], String(p.n), (v) => { p.n = Number(v); }); + if (this.tab === "worlds") { + select("Map", [["", "Any"], ["sector", "Sector"], ["system", "System"]], p.map, (v) => { p.map = v as WorldTypeMap | ""; }); + select("Orbit", [["", "Any"], ...ORBIT_ZONES.map((z): [string, string] => [z, z[0].toUpperCase() + z.slice(1)])], p.zone, (v) => { p.zone = v as OrbitZone | ""; }); + select("Star", [["", "Any"], ...this.suggestions(["star"]).map((s): [string, string] => [s, s])], p.star, (v) => { p.star = v; }); + select("Temperature", [["", "Any"], ["0.1", "Cold"], ["0.3", "Cool"], ["0.5", "Mild"], ["0.7", "Warm"], ["0.9", "Hot"]], p.temperature, (v) => { p.temperature = v; }); + } + const rollChoices: [string, string][] = this.tab === "features" + ? [["100", "100 systems"], ["1000", "1000 systems"], ["10000", "10000 systems"]] + : [["100", "100"], ["200", "200"], ["1000", "1000"]]; + if (!rollChoices.some(([v]) => Number(v) === p.n)) p.n = Number(rollChoices[1][0]); + select("Rolls", rollChoices, String(p.n), (v) => { p.n = Number(v); }); + + const table = this.table(); + const list = () => el.createDiv({ cls: "duckmage-world-types-dist" }); + const bar = (parent: HTMLElement, name: string, n: number, odds: string) => { + const r = parent.createDiv({ cls: "duckmage-world-types-dist-row" }); + r.createSpan({ cls: "duckmage-world-types-dist-name", text: name }); + const b = r.createSpan({ cls: "duckmage-world-types-dist-bar" }); + b.createSpan({ cls: "duckmage-world-types-dist-fill" }).setCssProps({ "--duckmage-dist": `${Math.round((n / p.n) * 100)}%` }); + r.createSpan({ cls: "duckmage-world-types-dist-num", text: `${n} of ${p.n}` }); + r.createSpan({ cls: "duckmage-world-types-dist-odds", text: odds }); + }; + const pct = (x: number) => `${Math.round(x * 1000) / 10}%`; + + if (this.tab === "stars") { + const odds = starOdds(table); + if (!odds.length) { + el.createDiv({ cls: "setting-item-description", text: "No star rows: Orbits picks the star itself." }); + return; + } + const rolled = new Map(rollStars(table, {}, p.n).map((r) => [r.star.toLowerCase(), r.count])); + const l = list(); + for (const o of odds) bar(l, o.star, rolled.get(o.star.toLowerCase()) ?? 0, `odds ${pct(o.odds)}`); + return; + } + + if (this.tab === "features") { + const { features, total } = sectorFeatureOdds(table); + if (!features.length) { + el.createDiv({ cls: "setting-item-description", text: "No feature rows: every star system hex stays a system." }); + return; + } + const rolled = new Map(rollSectorFeatures(table, {}, p.n).map((r) => [r.feature.toLowerCase(), r.count])); + const l = list(); + let special = 0; + for (const f of features) { + const n = rolled.get(f.feature.toLowerCase()) ?? 0; + special += n; + bar(l, f.feature, n, `${formatChance(f.chance)} (${pct(f.chance)})`); + } + bar(l, "an ordinary system", p.n - special, pct(1 - total)); + return; + } const ctx: Omit = {}; if (p.map) ctx.map = p.map; if (p.zone) ctx.zone = p.zone; if (p.star) ctx.starType = p.star; if (p.temperature) ctx.temperature = Number(p.temperature); - const table = { name: this.tableName, rows: this.rows() }; const odds = worldTypeOdds(table, ctx); if (!odds.length) { el.createDiv({ cls: "setting-item-description", text: "No row fits: nothing would be placed here." }); return; } const rolled = new Map(rollWorldTypes(table, ctx, p.n).map((r) => [r.world.toLowerCase(), r.count])); - const list = el.createDiv({ cls: "duckmage-world-types-dist" }); - for (const o of odds) { - const n = rolled.get(o.world.toLowerCase()) ?? 0; - const r = list.createDiv({ cls: "duckmage-world-types-dist-row" }); - r.createSpan({ cls: "duckmage-world-types-dist-name", text: o.world }); - const bar = r.createSpan({ cls: "duckmage-world-types-dist-bar" }); - bar.createSpan({ cls: "duckmage-world-types-dist-fill" }).setCssProps({ "--duckmage-dist": `${Math.round((n / p.n) * 100)}%` }); - r.createSpan({ cls: "duckmage-world-types-dist-num", text: `${n} of ${p.n}` }); - r.createSpan({ cls: "duckmage-world-types-dist-odds", text: `odds ${Math.round(o.odds * 1000) / 10}%` }); - } + const l = list(); + for (const o of odds) bar(l, o.world, rolled.get(o.world.toLowerCase()) ?? 0, `odds ${pct(o.odds)}`); } } diff --git a/src/space/worldTypePresets.ts b/src/space/worldTypePresets.ts index 3be81aab..d3b2fe4e 100644 --- a/src/space/worldTypePresets.ts +++ b/src/space/worldTypePresets.ts @@ -13,14 +13,17 @@ * weighed 0.5 there), the rocky ones opening as 20×14 Planet surface * maps tuned to the planet; * - the moon (weight 0: Orbits puts moons beside planets, it never rolls - * them) for its map setup. + * them) for its map setup; + * - Stars: Orbits' random star weights (red dwarfs dominate); + * - Sector features: Star scatter's special hexes, 1 in 25 star system + * hexes split 3 : 2 : 1 between station, anomaly and black hole. * tests/worldTypes.test.ts holds a frozen copy of the old tables and * checks this against it. * * Pure: no Obsidian imports. */ -import type { OrbitZone, WorldTypeRow } from "./worldTypes"; +import type { OrbitZone, SectorFeatureRow, StarTypeRow, WorldTypeRow } from "./worldTypes"; const SYSTEM_PALETTE = "Space - System"; const SURFACE_PALETTE = "Expanded"; @@ -80,3 +83,29 @@ export const DEFAULT_WORLD_TYPE_ROWS: readonly WorldTypeRow[] = [ ...body("asteroid belt", { inner: 0.5, habitable: 1, outer: 1.5 }), { world: "moon", weight: 0, map: "system", ...surface("10", "frozen", "desert", "rugged"), notes: "placed beside planets, never rolled" }, ]; + +/** Orbits' random star (its old built-in weights). */ +export const DEFAULT_STAR_ROWS: readonly StarTypeRow[] = [ + { star: "red dwarf", weight: 6 }, + { star: "yellow star", weight: 3 }, + { star: "brown dwarf", weight: 1.5 }, + { star: "white dwarf", weight: 1 }, + { star: "blue giant", weight: 0.5 }, +]; + +/** + * Star scatter's special hexes: it made 4% (1 in 25) of star system hexes + * a feature, split 3 : 2 : 1 by weight. As chances per hex that is exactly + * 1 in 50, 1 in 75 and 1 in 150. + */ +export const DEFAULT_SECTOR_FEATURE_ROWS: readonly SectorFeatureRow[] = [ + { feature: "deep-space station", chance: 1 / 50 }, + { feature: "anomaly", chance: 1 / 75 }, + { feature: "black hole", chance: 1 / 150 }, +]; + +/** The shipped Stars and Sector features tables, together. */ +export const DEFAULT_WORLD_TYPE_EXTRAS = { + get stars(): StarTypeRow[] { return DEFAULT_STAR_ROWS.map((r) => ({ ...r })); }, + get features(): SectorFeatureRow[] { return DEFAULT_SECTOR_FEATURE_ROWS.map((r) => ({ ...r })); }, +}; diff --git a/src/space/worldTypes.ts b/src/space/worldTypes.ts index fd386eef..7ed605a1 100644 --- a/src/space/worldTypes.ts +++ b/src/space/worldTypes.ts @@ -48,6 +48,25 @@ * gives exactly the odds (and, for the same random stream, the same * choices) Star scatter and Orbits had built in. * + * Two more tables follow in the same note, each under its own heading + * (format 2; found by their header, so the heading is only for people): + * + * ## Stars + * | Star | Weight | Notes | + * | red dwarf | 6 | | + * + * ## Sector features + * | Feature | Chance | Notes | + * | deep-space station | 1 in 50 | | + * + * - *Stars*: which star Orbits puts at a system's centre (when its Star + * option is Random), by weight. pickStar. + * - *Sector features*: Star scatter's special hexes. Each star system hex + * has the row's *Chance* (`1 in 50`, `2%`, `0.02`) of being that feature + * instead of a system. pickSectorFeature. + * A format 1 note (no such tables yet) is given the shipped rows once + * (upgradeWorldTypes); after that a deleted table stays deleted. + * * Pure: no Obsidian imports. */ @@ -61,7 +80,8 @@ import { } from "../overworld/biomeClimate"; export const WORLD_TYPES_MARKER = "hexmaker-world-types"; -export const WORLD_TYPES_FORMAT = 1; +/** 2: the note also has the Stars and Sector features tables. */ +export const WORLD_TYPES_FORMAT = 2; /** The shipped table's name (and note name). */ export const DEFAULT_WORLD_TYPES = "Default space"; @@ -119,9 +139,31 @@ export interface WorldTypeRow { notes?: string; } +/** A row of the Stars table: a star terrain and its odds. */ +export interface StarTypeRow { + /** The star terrain, as written ("red dwarf"). */ + star: string; + /** Relative odds among the stars; default 1; 0 = never rolled. */ + weight?: number; + notes?: string; +} + +/** A row of the Sector features table: a special hex and its chance per star system hex. */ +export interface SectorFeatureRow { + /** The feature terrain, as written ("black hole"). */ + feature: string; + /** Chance (0..1) that a star system hex is this feature instead. */ + chance: number; + notes?: string; +} + export interface WorldTypeTable { name: string; rows: WorldTypeRow[]; + /** The Stars table (none = the note has none). */ + stars?: StarTypeRow[]; + /** The Sector features table (none = the note has none). */ + features?: SectorFeatureRow[]; } export interface WorldTypeProblem { @@ -135,6 +177,14 @@ export interface ParsedWorldTypes { problems: WorldTypeProblem[]; /** Table rows that couldn't be read, exactly as written (kept on rewrite). */ unreadable: string[]; + /** The Stars table's rows; undefined when the note has no Stars table. */ + stars?: StarTypeRow[]; + /** The Sector features table's rows; undefined when the note has none. */ + features?: SectorFeatureRow[]; + unreadableStars: string[]; + unreadableFeatures: string[]; + /** The `hexmaker-world-types:` number in the frontmatter, if any. */ + format?: number; } /** What the generator knows where it is placing a world. Every field but `seed` is optional. */ @@ -306,6 +356,160 @@ export function worldTypeSubmapDefault(row: WorldTypeRow, size?: { cols: number; return out; } +// ── stars and sector features ──────────────────────────────────────────── + +/** What a generator passes when picking a star or a sector feature. */ +export interface SpacePickContext { + seed: number; + /** + * The generator's own random stream. pickStar takes exactly one draw + * from it when it returns a star (none when nothing fits); + * pickSectorFeature always takes exactly one. + */ + rand?: () => number; + /** + * The palette's terrains (names, or terrains with a name): only rows + * naming one of them count, in palette order. + */ + palette?: readonly (string | { name: string })[]; +} + +/** + * Rows grouped by name (a name's rows add up), in palette order when a + * palette is given (names not in it left out), else table order. Each + * group keeps its first row and the palette's spelling of the name. + */ +function groupByName( + rows: readonly R[], + nameOf: (r: R) => string, + amountOf: (r: R) => number, + palette: SpacePickContext["palette"], +): { key: string; terrain: string; row: R; amount: number }[] { + const groups = new Map(); + for (const r of rows) { + const name = nameOf(r).trim(); + const amount = amountOf(r); + if (!name || !(amount > 0)) continue; + const k = lc(name); + const g = groups.get(k); + if (g) g.amount += amount; + else groups.set(k, { key: k, terrain: name, row: r, amount }); + } + const names = paletteNames(palette); + if (!names) return [...groups.values()]; + const out: { key: string; terrain: string; row: R; amount: number }[] = []; + const seen = new Set(); + for (const n of names) { + const g = groups.get(lc(n)); + if (!g || seen.has(g.key)) continue; + seen.add(g.key); + out.push({ ...g, terrain: n }); + } + return out; +} + +const starGroups = (table: WorldTypeTable, palette?: SpacePickContext["palette"]) => + groupByName(table.stars ?? [], (r) => r.star, (r) => r.weight ?? 1, palette); +const featureGroups = (table: WorldTypeTable, palette?: SpacePickContext["palette"]) => + groupByName(table.features ?? [], (r) => r.feature, (r) => r.chance, palette); + +export interface StarPick { + row: StarTypeRow; + /** The palette's own name for the star (its case), else the row's. */ + terrain: string; +} + +export interface SectorFeaturePick { + row: SectorFeatureRow; + /** The palette's own name for the feature (its case), else the row's. */ + terrain: string; +} + +/** Each star's total weight (lower-case name → weight), weight 0 left out. */ +export function starWeights(table: WorldTypeTable, ctx: Omit & { seed?: number } = {}): Record { + return Object.fromEntries(starGroups(table, ctx.palette).map((g) => [g.key, g.amount])); +} + +/** + * Pick the star at a system's centre: one weighted draw over the stars + * (in palette order when a palette is given). Null when no star row fits; + * then no draw is taken, so a generator can fall back to its own pick. + */ +export function pickStar(table: WorldTypeTable, ctx: SpacePickContext): StarPick | null { + const groups = starGroups(table, ctx.palette); + if (!groups.length) return null; + const rand = ctx.rand ?? mulberry32(ctx.seed >>> 0); + const g = groups[pickIndex(rand, groups.map((x) => x.amount))]; + return { row: g.row, terrain: g.terrain }; +} + +/** Each star's exact odds (0..1), most likely first. */ +export function starOdds(table: WorldTypeTable, ctx: Omit = {}): { star: string; odds: number }[] { + const groups = starGroups(table, ctx.palette); + const total = groups.reduce((a, g) => a + g.amount, 0); + if (total <= 0) return []; + return groups.map((g) => ({ star: g.terrain, odds: g.amount / total })).sort((a, b) => b.odds - a.odds || a.star.localeCompare(b.star)); +} + +/** Roll `n` stars (seeds `seed`, `seed + 1`, …) and count them, most rolled first. */ +export function rollStars(table: WorldTypeTable, ctx: Omit, n: number, seed = 1): { star: string; count: number }[] { + const counts = new Map(); + for (let i = 0; i < n; i++) { + const p = pickStar(table, { ...ctx, seed: seed + i }); + if (p) counts.set(p.terrain, (counts.get(p.terrain) ?? 0) + 1); + } + return [...counts].map(([star, count]) => ({ star, count })).sort((a, b) => b.count - a.count || a.star.localeCompare(b.star)); +} + +/** Each feature's chance per star system hex (lower-case name → 0..1), chance 0 left out. */ +export function sectorFeatureChances(table: WorldTypeTable, ctx: Omit & { seed?: number } = {}): Record { + return Object.fromEntries(featureGroups(table, ctx.palette).map((g) => [g.key, g.amount])); +} + +/** + * Whether a star system hex is a special feature instead, and which: + * exactly one draw `u`; the features (in palette order when a palette is + * given) take consecutive slices of 0..1 as wide as their chance, so `u` + * below the total chance lands on a feature, anything else is null (an + * ordinary system). The draw is taken even when no feature fits, so the + * generator's later rolls don't depend on the palette. + */ +export function pickSectorFeature(table: WorldTypeTable, ctx: SpacePickContext): SectorFeaturePick | null { + const rand = ctx.rand ?? mulberry32(ctx.seed >>> 0); + const u = rand(); + let edge = 0; + for (const g of featureGroups(table, ctx.palette)) { + edge += g.amount; + if (u < edge) return { row: g.row, terrain: g.terrain }; + } + return null; +} + +/** Each feature's chance per star system hex, most likely first, and their total (capped at 1). */ +export function sectorFeatureOdds(table: WorldTypeTable, ctx: Omit = {}): { features: { feature: string; chance: number }[]; total: number } { + const groups = featureGroups(table, ctx.palette); + let left = 1; + const features = groups.map((g) => { + const chance = Math.max(0, Math.min(g.amount, left)); + left -= chance; + return { feature: g.terrain, chance }; + }).filter((f) => f.chance > 0); + return { + features: features.sort((a, b) => b.chance - a.chance || a.feature.localeCompare(b.feature)), + total: features.reduce((a, f) => a + f.chance, 0), + }; +} + +/** Roll `n` star system hexes (seeds `seed`, `seed + 1`, …): how many became each feature, most first. */ +export function rollSectorFeatures(table: WorldTypeTable, ctx: Omit, n: number, seed = 1): { feature: string; count: number }[] { + const counts = new Map(); + for (let i = 0; i < n; i++) { + const p = pickSectorFeature(table, { ...ctx, seed: seed + i }); + if (p) counts.set(p.terrain, (counts.get(p.terrain) ?? 0) + 1); + } + return [...counts].map(([feature, count]) => ({ feature, count })).sort((a, b) => b.count - a.count || a.feature.localeCompare(b.feature)); +} + // ── cells ──────────────────────────────────────────────────────────────── /** "2", "50%", "0.5" → a weight ≥ 0, or NaN. */ @@ -413,6 +617,37 @@ export function readOptions(raw: string): Record | undefined { export const formatOptions = (o: Record | undefined) => o ? Object.entries(o).map(([k, v]) => `${k}=${v}`).join(", ") : ""; +/** + * A chance per star system hex: "1 in 50", "1/50", "2%", "0.02", "never" + * or "0" → 0..1; NaN when unreadable (blank, over 100%, a bare number + * above 1, or "0 in 5"). + */ +export function readChance(raw: string): number { + const t = raw.trim().toLowerCase(); + if (!t) return NaN; + if (t === "never" || t === "none") return 0; + const inN = /^(\d+(?:\.\d+)?)\s*(?:in|\/|out of)\s*(\d+(?:\.\d+)?)$/.exec(t); + if (inN) { + const a = Number(inN[1]), b = Number(inN[2]); + return b > 0 && a <= b ? a / b : NaN; + } + const pct = t.endsWith("%"); + const n = Number(t.replace(/%$/, "").trim()); + if (!Number.isFinite(n) || n < 0) return NaN; + const c = pct ? n / 100 : n; + return c <= 1 ? c : NaN; +} + +/** 1/50 → "1 in 50", 0.03 → "3%", 0 → "never". */ +export function formatChance(c: number): string { + if (!(c > 0)) return "never"; + if (c >= 1) return "100%"; + const inv = 1 / c; + const n = Math.round(inv); + if (n >= 2 && Math.abs(inv - n) < 1e-9 * n) return `1 in ${n}`; + return `${String(Math.round(c * 100 * 1000) / 1000)}%`; +} + const readList = (raw: string) => { const t = raw.trim(); if (!t || t.toLowerCase() === "any") return []; @@ -446,6 +681,35 @@ const HEADER_ALIASES: Record = { notes: "Notes", note: "Notes", comment: "Notes", }; +export const STARS_HEADING = "## Stars"; +export const STARS_HELP = [ + "> [!info] Stars", + "> Which star Orbits puts at the centre of a system when its Star option is Random. **Star** is a star terrain of the palette; **Weight** (1 if blank) is its odds against the other stars; 0 never rolls it.", +]; +export const FEATURES_HEADING = "## Sector features"; +export const FEATURES_HELP = [ + "> [!info] Sector features", + "> Star scatter's special hexes. **Feature** is a terrain of the palette; **Chance** is how likely each star system hex is to be that feature instead, like 1 in 50, 2% or never.", +]; + +/** The Stars table's columns, in order. */ +export const STAR_COLUMNS = ["Star", "Weight", "Notes"] as const; +export type StarColumn = (typeof STAR_COLUMNS)[number]; +const STAR_ALIASES: Record = { + star: "Star", stars: "Star", "star type": "Star", "star types": "Star", sun: "Star", + weight: "Weight", odds: "Weight", + notes: "Notes", note: "Notes", comment: "Notes", +}; + +/** The Sector features table's columns, in order. */ +export const FEATURE_COLUMNS = ["Feature", "Chance", "Notes"] as const; +export type FeatureColumn = (typeof FEATURE_COLUMNS)[number]; +const FEATURE_ALIASES: Record = { + feature: "Feature", features: "Feature", "sector feature": "Feature", "sector features": "Feature", special: "Feature", "special hex": "Feature", + chance: "Chance", odds: "Chance", "chance per system": "Chance", "per system": "Chance", "chance per system hex": "Chance", + notes: "Notes", note: "Notes", comment: "Notes", +}; + function splitRow(line: string): string[] { let s = line.trim(); if (s.startsWith("|")) s = s.slice(1); @@ -468,20 +732,94 @@ function splitRow(line: string): string[] { const SEPARATOR_ROW = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/; const normHeader = (h: string) => h.trim().toLowerCase().replace(/[*_]/g, "").replace(/\s+/g, " "); -interface Span { start: number; end: number; cols: (Column | undefined)[] } +interface Span { start: number; end: number; cols: (C | undefined)[] } + +type TableKind = "worlds" | "stars" | "features"; -function findTable(lines: string[]): Span | null { +/** + * The note's first table of a kind, told apart by its header: Sector + * features has a Feature column; Stars a Star column and no World; + * the worlds table a World column and no Feature. + */ +function findKind(lines: string[], kind: TableKind, aliases: Record): Span | null { for (let i = 0; i < lines.length - 1; i++) { if (!lines[i].trim().startsWith("|") || !SEPARATOR_ROW.test(lines[i + 1])) continue; - const cols = splitRow(lines[i]).map((h) => HEADER_ALIASES[normHeader(h)]); - if (!cols.includes("World")) continue; + const heads = splitRow(lines[i]).map(normHeader); + const isFeatures = heads.some((h) => FEATURE_ALIASES[h] === "Feature"); + const hasWorld = heads.some((h) => HEADER_ALIASES[h] === "World"); + const fits = kind === "features" ? isFeatures + : kind === "stars" ? !isFeatures && !hasWorld && heads.some((h) => STAR_ALIASES[h] === "Star") + : !isFeatures && hasWorld; + if (!fits) continue; let end = i + 2; while (end < lines.length && lines[end].trim().startsWith("|")) end++; - return { start: i, end, cols }; + return { start: i, end, cols: heads.map((h) => aliases[h]) }; } return null; } +const findTable = (lines: string[]) => findKind(lines, "worlds", HEADER_ALIASES); +const findStars = (lines: string[]) => findKind(lines, "stars", STAR_ALIASES); +const findFeatures = (lines: string[]) => findKind(lines, "features", FEATURE_ALIASES); + +/** A cell by column name (blank when the column is missing). */ +const cellOf = (cells: string[], cols: (C | undefined)[], c: C) => { + const i = cols.indexOf(c); + return i >= 0 ? (cells[i] ?? "").trim() : ""; +}; +/** A name cell: a `[[link]]`'s target, else the text. */ +const nameCell = (raw: string) => (/\[\[([^\]|#]+)/.exec(raw)?.[1] ?? raw).trim(); + +function readStarRow(cells: string[], cols: (StarColumn | undefined)[]): { row?: StarTypeRow; problem?: string } { + const star = nameCell(cellOf(cells, cols, "Star")); + if (!star) return { problem: "no star" }; + const row: StarTypeRow = { star }; + const w = cellOf(cells, cols, "Weight"); + if (w) { + const n = readWeight(w); + if (!Number.isFinite(n)) return { problem: `weight "${w}" isn't a number` }; + row.weight = n; + } + const notes = cellOf(cells, cols, "Notes"); + if (notes) row.notes = notes; + return { row }; +} + +function readFeatureRow(cells: string[], cols: (FeatureColumn | undefined)[]): { row?: SectorFeatureRow; problem?: string } { + const feature = nameCell(cellOf(cells, cols, "Feature")); + if (!feature) return { problem: "no feature" }; + const c = cellOf(cells, cols, "Chance"); + const chance = readChance(c); + if (!Number.isFinite(chance)) return { problem: c ? `chance "${c}" should look like 1 in 50 or 2%` : "no chance (like 1 in 50 or 2%)" }; + const row: SectorFeatureRow = { feature, chance }; + const notes = cellOf(cells, cols, "Notes"); + if (notes) row.notes = notes; + return { row }; +} + +/** The frontmatter's `hexmaker-world-types:` number. */ +function readFormat(lines: string[]): number | undefined { + if (lines[0]?.trim() !== "---") return undefined; + for (let i = 1; i < lines.length && lines[i].trim() !== "---"; i++) { + const m = new RegExp(`^\\s*${WORLD_TYPES_MARKER}:\\s*(\\d+)\\s*$`).exec(lines[i]); + if (m) return Number(m[1]); + } + return undefined; +} + +/** The lines with the frontmatter's format number set to the current one (when it has one). */ +function withFormat(lines: string[]): string[] { + if (lines[0]?.trim() !== "---") return lines; + for (let i = 1; i < lines.length && lines[i].trim() !== "---"; i++) { + const m = new RegExp(`^(\\s*${WORLD_TYPES_MARKER}:\\s*)\\d+(\\s*)$`).exec(lines[i]); + if (!m) continue; + const out = [...lines]; + out[i] = `${m[1]}${WORLD_TYPES_FORMAT}${m[2]}`; + return out; + } + return lines; +} + /** One table row → a row, or why it can't be read. */ function readRow(cells: string[], cols: (Column | undefined)[]): { row?: WorldTypeRow; problem?: string } { const cell = (c: Column) => { @@ -531,25 +869,50 @@ function readRow(cells: string[], cols: (Column | undefined)[]): { row?: WorldTy return { row }; } -/** Read a world types note. Never throws. */ -export function parseWorldTypes(content: string): ParsedWorldTypes { - const lines = content.replace(/\r\n?/g, "\n").split("\n"); - const rows: WorldTypeRow[] = []; - const problems: WorldTypeProblem[] = []; - const unreadable: string[] = []; - const t = findTable(lines); - if (!t) return { rows, problems: [{ text: "no table with a World column" }], unreadable }; +/** Read one table's rows into `rows`; rows that can't be read go to `unreadable` and `problems`. */ +function readInto( + lines: string[], + t: Span, + read: (cells: string[], cols: (C | undefined)[]) => { row?: R; problem?: string }, + label: string, + rows: R[], + problems: WorldTypeProblem[], + unreadable: string[], +): void { for (let i = t.start + 2; i < t.end; i++) { const cells = splitRow(lines[i]); if (cells.every((c) => c === "")) continue; - const { row, problem } = readRow(cells, t.cols); + const { row, problem } = read(cells, t.cols); if (row) rows.push(row); else { - problems.push({ line: i + 1, text: `row ${i + 1}: ${problem ?? "can't be read"} (left as written, not used)` }); + problems.push({ line: i + 1, text: `${label}row ${i + 1}: ${problem ?? "can't be read"} (left as written, not used)` }); unreadable.push(lines[i]); } } - return { rows, problems, unreadable }; +} + +/** Read a world types note (worlds, and the Stars and Sector features tables when it has them). Never throws. */ +export function parseWorldTypes(content: string): ParsedWorldTypes { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const out: ParsedWorldTypes = { rows: [], problems: [], unreadable: [], unreadableStars: [], unreadableFeatures: [] }; + const format = readFormat(lines); + if (format !== undefined) out.format = format; + const t = findTable(lines); + if (t) readInto(lines, t, readRow, "", out.rows, out.problems, out.unreadable); + else out.problems.push({ text: "no table with a World column" }); + const s = findStars(lines); + if (s) { + out.stars = []; + readInto(lines, s, readStarRow, "Stars ", out.stars, out.problems, out.unreadableStars); + } + const f = findFeatures(lines); + if (f) { + out.features = []; + readInto(lines, f, readFeatureRow, "Sector features ", out.features, out.problems, out.unreadableFeatures); + const total = out.features.reduce((a, r) => a + r.chance, 0); + if (total > 1 + 1e-9) out.problems.push({ text: `Sector features: the chances add up to over 100% (${Math.round(total * 1000) / 10}%), so the last ones come up less` }); + } + return out; } const esc = (s: string) => s.replace(/\|/g, "\\|"); @@ -573,47 +936,115 @@ export function worldTypeCells(r: WorldTypeRow): string[] { ]; } -function tableLines(rows: readonly WorldTypeRow[], keep: readonly string[] = []): string[] { +/** A Stars row as the note's cells, in STAR_COLUMNS order. */ +export function starCells(r: StarTypeRow): string[] { + return [r.star, r.weight === undefined ? "" : fmtNum(r.weight), r.notes ?? ""]; +} + +/** A Sector features row as the note's cells, in FEATURE_COLUMNS order. */ +export function featureCells(r: SectorFeatureRow): string[] { + return [r.feature, formatChance(r.chance), r.notes ?? ""]; +} + +function markdownTable(columns: readonly string[], rightAligned: string, cells: string[][], keep: readonly string[]): string[] { return [ - `| ${COLUMNS.join(" | ")} |`, - `| ${COLUMNS.map((c) => (c === "Weight" ? "---:" : "---")).join(" | ")} |`, - ...rows.map((r) => `| ${worldTypeCells(r).map((c) => (c.startsWith("[[") ? c : esc(c))).join(" | ")} |`), + `| ${columns.join(" | ")} |`, + `| ${columns.map((c) => (c === rightAligned ? "---:" : "---")).join(" | ")} |`, + ...cells.map((row) => `| ${row.map((c) => (c.startsWith("[[") ? c : esc(c))).join(" | ")} |`), ...keep, ]; } -/** A fresh table note. */ -export function buildWorldTypes(name: string, rows: readonly WorldTypeRow[]): string { +const tableLines = (rows: readonly WorldTypeRow[], keep: readonly string[] = []) => + markdownTable(COLUMNS, "Weight", rows.map(worldTypeCells), keep); +const starTableLines = (rows: readonly StarTypeRow[], keep: readonly string[] = []) => + markdownTable(STAR_COLUMNS, "Weight", rows.map(starCells), keep); +const featureTableLines = (rows: readonly SectorFeatureRow[], keep: readonly string[] = []) => + markdownTable(FEATURE_COLUMNS, "Chance", rows.map(featureCells), keep); + +/** The Stars and Sector features tables a note is given (each optional). */ +export interface WorldTypeExtras { + stars?: readonly StarTypeRow[]; + features?: readonly SectorFeatureRow[]; +} + +/** A fresh table note (Stars and Sector features are written even when empty). */ +export function buildWorldTypes(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}): string { return [ "---", `${WORLD_TYPES_MARKER}: ${WORLD_TYPES_FORMAT}`, "---", "", `# ${name}`, "", ...WORLD_TYPES_HELP, "", ...tableLines(rows), "", + STARS_HEADING, "", + ...STARS_HELP, "", + ...starTableLines(extras.stars ?? []), "", + FEATURES_HEADING, "", + ...FEATURES_HELP, "", + ...featureTableLines(extras.features ?? []), "", ].join("\n"); } -const rowKey = (r: WorldTypeRow) => JSON.stringify(worldTypeCells(r).map((c, i) => (i === 0 ? c.toLowerCase() : c))); +/** Rows compared as their cells (the name in any case). */ +function sameRows(a: readonly R[], b: readonly R[], cellsOf: (r: R) => string[]): boolean { + const key = (r: R) => JSON.stringify(cellsOf(r).map((c, i) => (i === 0 ? c.toLowerCase() : c))); + return a.length === b.length && a.every((r, i) => key(r) === key(b[i])); +} + +/** `table` in place of the span, or appended at the end after `head` (a heading and help). */ +function putTable(lines: string[], span: Span | null, table: string[], head: string[]): string[] { + if (span) return [...lines.slice(0, span.start), ...table, ...lines.slice(span.end)]; + const out = [...lines]; + while (out.length && out[out.length - 1].trim() === "") out.pop(); + out.push("", ...head, ...table, ""); + return out; +} /** - * The note with its table set to `rows`; everything else is kept, and so - * are rows that couldn't be read (after the new rows, as written). Same - * string when nothing changes. + * The note with its worlds table set to `rows` and, when given, its Stars + * and Sector features tables set too (added under their heading when the + * note has none). Everything else is kept, and so are rows that couldn't + * be read (after the new rows of their table, as written). A table that + * didn't change isn't rewritten; same string when nothing changes. */ -export function updateWorldTypes(content: string, rows: readonly WorldTypeRow[]): string { +export function updateWorldTypes(content: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}): string { const eol = content.includes("\r\n") ? "\r\n" : "\n"; - const lines = content.replace(/\r\n?/g, "\n").split("\n"); - const t = findTable(lines); + let lines = content.replace(/\r\n?/g, "\n").split("\n"); const parsed = parseWorldTypes(content); - if (t && parsed.rows.length === rows.length && parsed.rows.every((r, i) => rowKey(r) === rowKey(rows[i]))) return content; - const table = tableLines(rows, parsed.unreadable); - let out: string[]; - if (t) out = [...lines.slice(0, t.start), ...table, ...lines.slice(t.end)]; - else { - out = [...lines]; - while (out.length && out[out.length - 1].trim() === "") out.pop(); - out.push("", ...table, ""); + let changed = false; + const t = findTable(lines); + if (!t || !sameRows(parsed.rows, rows, worldTypeCells)) { + lines = putTable(lines, t, tableLines(rows, parsed.unreadable), []); + changed = true; + } + if (extras.stars && !(parsed.stars && sameRows(parsed.stars, extras.stars, starCells))) { + lines = putTable(lines, findStars(lines), starTableLines(extras.stars, parsed.unreadableStars), [STARS_HEADING, "", ...STARS_HELP, ""]); + changed = true; } - return out.join(eol); + if (extras.features && !(parsed.features && sameRows(parsed.features, extras.features, featureCells))) { + lines = putTable(lines, findFeatures(lines), featureTableLines(extras.features, parsed.unreadableFeatures), [FEATURES_HEADING, "", ...FEATURES_HELP, ""]); + changed = true; + } + if (!changed) return content; + if (findStars(lines) && findFeatures(lines)) lines = withFormat(lines); + return lines.join(eol); +} + +/** + * A format 1 note (written before stars and sector features were rows) + * given the shipped Stars and Sector features tables it doesn't have, and + * marked format 2, so it keeps placing what the generators always did. + * Anything else (format 2, or a note without the marker) comes back as is. + */ +export function upgradeWorldTypes(content: string, defaults: Required): string { + const p = parseWorldTypes(content); + if (p.format === undefined || p.format >= WORLD_TYPES_FORMAT) return content; + const next = updateWorldTypes(content, p.rows, { + stars: p.stars ? undefined : defaults.stars, + features: p.features ? undefined : defaults.features, + }); + const eol = next.includes("\r\n") ? "\r\n" : "\n"; + const marked = withFormat(next.replace(/\r\n?/g, "\n").split("\n")).join(eol); + return marked; } /** A deep copy of rows (callers may change it). */ @@ -639,6 +1070,19 @@ export function readWorldTypeCells(cells: readonly string[]): { row?: WorldTypeR return readRow([...cells], [...COLUMNS]); } +/** Cells in STAR_COLUMNS order → a Stars row, or what's wrong. */ +export function readStarCells(cells: readonly string[]): { row?: StarTypeRow; problem?: string } { + return readStarRow([...cells], [...STAR_COLUMNS]); +} + +/** Cells in FEATURE_COLUMNS order → a Sector features row, or what's wrong. */ +export function readFeatureCells(cells: readonly string[]): { row?: SectorFeatureRow; problem?: string } { + return readFeatureRow([...cells], [...FEATURE_COLUMNS]); +} + +export const copyStarRows = (rows: readonly StarTypeRow[]): StarTypeRow[] => rows.map((r) => ({ ...r })); +export const copyFeatureRows = (rows: readonly SectorFeatureRow[]): SectorFeatureRow[] => rows.map((r) => ({ ...r })); + /** Each fitting world's exact odds (0..1) for a context, most likely first. */ export function worldTypeOdds(table: WorldTypeTable, ctx: Omit & { seed?: number }): { world: string; odds: number }[] { const w = worldTypeWeights(table, ctx); diff --git a/styles.css b/styles.css index fd35656e..f72c49a8 100644 --- a/styles.css +++ b/styles.css @@ -8722,6 +8722,25 @@ textarea.duckmage-edit-region-notes-input { gap: 2px; margin-left: auto; } +.duckmage-world-types-tabs { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-top: 6px; + border-bottom: 1px solid var(--background-modifier-border); + padding-bottom: 4px; +} +.duckmage-world-types-tab.is-active { + background: var(--interactive-accent); + color: var(--text-on-accent); +} +.duckmage-world-types-cell.is-star input, +.duckmage-world-types-cell.is-feature input { + width: 13em; +} +.duckmage-world-types-cell.is-chance input { + width: 7em; +} .duckmage-world-types-dist { display: grid; grid-template-columns: minmax(8em, max-content) minmax(6em, 1fr) max-content max-content; diff --git a/tests/worldTypeStars.test.ts b/tests/worldTypeStars.test.ts new file mode 100644 index 00000000..40f7f971 --- /dev/null +++ b/tests/worldTypeStars.test.ts @@ -0,0 +1,389 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { mulberry32 } from "../packages/hex-wfc/src/rng"; +import { MemVault } from "./helpers/memVault"; +import { + DEFAULT_WORLD_TYPES, + buildWorldTypes, + featureCells, + formatChance, + parseWorldTypes, + pickSectorFeature, + pickStar, + pickWorldType, + readChance, + readFeatureCells, + readStarCells, + rollSectorFeatures, + rollStars, + sectorFeatureChances, + sectorFeatureOdds, + starCells, + starOdds, + starWeights, + updateWorldTypes, + upgradeWorldTypes, + type SectorFeatureRow, + type StarTypeRow, + type WorldTypeTable, +} from "../src/space/worldTypes"; +import { + DEFAULT_SECTOR_FEATURE_ROWS, + DEFAULT_STAR_ROWS, + DEFAULT_WORLD_TYPE_EXTRAS, + DEFAULT_WORLD_TYPE_ROWS, +} from "../src/space/worldTypePresets"; +import { WorldTypeStore } from "../src/space/WorldTypeStore"; +import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; +import type { TerrainColor } from "../src/types"; + +const DEFAULT: WorldTypeTable = { + name: DEFAULT_WORLD_TYPES, + rows: [...DEFAULT_WORLD_TYPE_ROWS], + stars: [...DEFAULT_STAR_ROWS], + features: [...DEFAULT_SECTOR_FEATURE_ROWS], +}; + +// ── frozen copy of the old built-in numbers (before stars and features were rows) ── +// src/worldgen/procedural/orbits.ts and starScatter.ts at 5133006. Do not +// update these to match new code: they are what Default space must equal. + +const OLD_STAR_WEIGHTS: Record = { + "red dwarf": 6, "yellow star": 3, "brown dwarf": 1.5, "white dwarf": 1, "blue giant": 0.5, +}; +const OLD_FEATURE_CHANCE = 0.04; // `roll < 0.04` +const OLD_FEATURE_WEIGHTS: Record = { "deep-space station": 3, anomaly: 2, "black hole": 1 }; +const OLD_FEATURE_TYPE_WEIGHTS: Record = { station: 3, starport: 3, "jump-point": 3, anomaly: 1.5 }; +const OLD_WORLD_WEIGHTS: Record = { + "garden world": 3, "desert world": 3, "barren world": 3.5, "ocean world": 2, + "ice world": 2, "asteroid belt": 1.5, "molten world": 1, "gas giant": 1, +}; +function oldWeightedPick(rand: () => number, names: string[], weights: Record, fallback = 1): string | undefined { + if (names.length === 0) return undefined; + const w = names.map((n) => Math.max(0, weights[n.toLowerCase()] ?? fallback)); + const total = w.reduce((a, b) => a + b, 0); + if (total <= 0) return names[Math.floor(rand() * names.length)]; + let r = rand() * total; + for (let i = 0; i < names.length; i++) { + r -= w[i]; + if (r < 0) return names[i]; + } + return names[names.length - 1]; +} +const ofTypes = (terrains: TerrainColor[], types: string[]) => terrains.filter((t) => types.includes(t.type ?? "")).map((t) => t.name); +/** Old starScatter weightsFor(features): name weight, else type weight. */ +function oldFeatureWeights(terrains: TerrainColor[]): Record { + const out: Record = {}; + for (const t of terrains) { + if (!["station", "starport", "jump-point", "anomaly"].includes(t.type ?? "")) continue; + const k = t.name.toLowerCase(); + const w = OLD_FEATURE_WEIGHTS[k] ?? OLD_FEATURE_TYPE_WEIGHTS[t.type ?? ""]; + if (w !== undefined) out[k] = w; + } + return out; +} + +describe("Default space reproduces the old star and sector feature odds", () => { + const stars = ofTypes(SPACE_SYSTEM_TERRAINS, ["star"]); + const features = ofTypes(SPACE_SECTOR_TERRAINS, ["station", "starport", "jump-point", "anomaly"]); + const worlds = ofTypes(SPACE_SECTOR_TERRAINS, ["world", "gas-giant", "asteroids"]); + + it("Orbits: the star weights are the old ones", () => { + expect(starWeights(DEFAULT, { palette: SPACE_SYSTEM_TERRAINS })).toEqual(Object.fromEntries(stars.map((s) => [s, OLD_STAR_WEIGHTS[s]]))); + }); + + it("Star scatter: each feature's chance per system hex is the old 4% split by the old weights", () => { + const fw = oldFeatureWeights(SPACE_SECTOR_TERRAINS); + const total = Object.values(fw).reduce((a, b) => a + b, 0); + const chances = sectorFeatureChances(DEFAULT, { palette: SPACE_SECTOR_TERRAINS }); + expect(Object.keys(chances).sort()).toEqual(Object.keys(fw).sort()); + for (const [k, w] of Object.entries(fw)) expect(chances[k]).toBeCloseTo((OLD_FEATURE_CHANCE * w) / total, 15); + expect(sectorFeatureOdds(DEFAULT, { palette: SPACE_SECTOR_TERRAINS }).total).toBeCloseTo(OLD_FEATURE_CHANCE, 15); + }); + + it("pickStar: the same random stream gives the same star, one draw", () => { + for (let seed = 1; seed <= 1000; seed++) { + const a = mulberry32(seed), b = mulberry32(seed); + const old = oldWeightedPick(a, stars, OLD_STAR_WEIGHTS); + expect(pickStar(DEFAULT, { seed, rand: b, palette: SPACE_SYSTEM_TERRAINS })?.terrain).toBe(old); + expect(b()).toBe(a()); + } + }); + + it("pickSectorFeature: the same hexes become features, and ordinary systems stay in step", () => { + let featureHexes = 0; + for (let seed = 1; seed <= 300; seed++) { + const a = mulberry32(seed), b = mulberry32(seed); + for (let hex = 0; hex < 40; hex++) { + // Old: `roll < 0.04` then a feature pick (a second draw), else a world pick. + const roll = a(); + const f = pickSectorFeature(DEFAULT, { seed, rand: b, palette: SPACE_SECTOR_TERRAINS }); + expect(!!f).toBe(roll < OLD_FEATURE_CHANCE); + if (f) { + // One draw instead of the old two: the streams part here. + featureHexes++; + expect(features).toContain(f.terrain); + break; + } + const old = oldWeightedPick(a, worlds, OLD_WORLD_WEIGHTS); + expect(pickWorldType(DEFAULT, { map: "sector", seed, rand: b, palette: SPACE_SECTOR_TERRAINS })?.terrain).toBe(old); + expect(b()).toBe(a()); + } + } + expect(featureHexes).toBeGreaterThan(50); + }); + + it("each feature takes its slice of the one draw, in palette order", () => { + const at = (u: number) => pickSectorFeature(DEFAULT, { seed: 0, rand: () => u, palette: SPACE_SECTOR_TERRAINS })?.terrain ?? null; + // Palette order: deep-space station, black hole, anomaly. + expect(at(0)).toBe("deep-space station"); + expect(at(0.0199)).toBe("deep-space station"); + expect(at(0.0201)).toBe("black hole"); + expect(at(0.0266)).toBe("black hole"); + expect(at(0.0267)).toBe("anomaly"); + expect(at(0.0399)).toBe("anomaly"); + expect(at(0.04)).toBeNull(); + expect(at(0.99)).toBeNull(); + }); + + it("over many hexes the features come up 3 : 2 : 1 in 4% of systems", () => { + const counts = Object.fromEntries(rollSectorFeatures(DEFAULT, { palette: SPACE_SECTOR_TERRAINS }, 60000).map((c) => [c.feature, c.count])); + const n = (k: string) => counts[k] / 60000; + expect(n("deep-space station")).toBeGreaterThan(0.017); + expect(n("deep-space station")).toBeLessThan(0.023); + expect(n("anomaly")).toBeGreaterThan(0.011); + expect(n("anomaly")).toBeLessThan(0.016); + expect(n("black hole")).toBeGreaterThan(0.005); + expect(n("black hole")).toBeLessThan(0.0085); + }); +}); + +describe("pickStar and pickSectorFeature", () => { + const t: WorldTypeTable = { + name: "T", + rows: [], + stars: [{ star: "Red dwarf", weight: 3 }, { star: "Pulsar", weight: 0 }, { star: "red dwarf", weight: 1 }, { star: "Blue giant" }], + features: [{ feature: "Wreck", chance: 0.1 }, { feature: "Gate", chance: 0 }, { feature: "wreck", chance: 0.05 }, { feature: "Rift", chance: 0.2 }], + }; + + it("are deterministic for a seed", () => { + for (let seed = 0; seed < 50; seed++) { + expect(pickStar(t, { seed })).toEqual(pickStar(t, { seed })); + expect(pickSectorFeature(t, { seed })).toEqual(pickSectorFeature(t, { seed })); + } + }); + + it("add up a name's rows, never pick weight or chance 0, and keep to the palette (its spelling, its order)", () => { + expect(starWeights(t)).toEqual({ "red dwarf": 4, "blue giant": 1 }); + expect(starOdds(t)).toEqual([{ star: "Red dwarf", odds: 0.8 }, { star: "Blue giant", odds: 0.2 }]); + const counts = Object.fromEntries(rollStars(t, {}, 2000).map((c) => [c.star, c.count])); + expect(counts.Pulsar).toBeUndefined(); + expect(counts["Red dwarf"] / 2000).toBeGreaterThan(0.75); + expect(pickStar(t, { seed: 1, palette: [{ name: "BLUE GIANT" }, "pulsar"] })?.terrain).toBe("BLUE GIANT"); + expect(sectorFeatureChances(t)).toEqual({ wreck: 0.15000000000000002, rift: 0.2 }); + expect(sectorFeatureChances(t, { palette: ["rift", "gate"] })).toEqual({ rift: 0.2 }); + const at = (u: number, palette?: string[]) => pickSectorFeature(t, { seed: 0, rand: () => u, palette })?.terrain ?? null; + expect(at(0.1)).toBe("Wreck"); + expect(at(0.16)).toBe("Rift"); + expect(at(0.1, ["RIFT", "Wreck"])).toBe("RIFT"); + expect(at(0.36)).toBeNull(); + }); + + it("draw exactly once from the given stream (pickStar not at all when no star fits)", () => { + let draws = 0; + const rand = () => { draws++; return 0.5; }; + pickStar(t, { seed: 1, rand }); + expect(draws).toBe(1); + expect(pickStar(t, { seed: 1, rand, palette: ["pulsar"] })).toBeNull(); + expect(draws).toBe(1); + pickSectorFeature(t, { seed: 1, rand }); + expect(draws).toBe(2); + expect(pickSectorFeature({ name: "none", rows: [] }, { seed: 1, rand })).toBeNull(); + expect(draws).toBe(3); + expect(pickStar({ name: "none", rows: [] }, { seed: 1 })).toBeNull(); + }); + + it("caps chances that add up past 100%", () => { + const over: WorldTypeTable = { name: "O", rows: [], features: [{ feature: "A", chance: 0.7 }, { feature: "B", chance: 0.6 }] }; + expect(sectorFeatureOdds(over)).toEqual({ features: [{ feature: "A", chance: 0.7 }, { feature: "B", chance: 0.30000000000000004 }], total: 1 }); + }); +}); + +describe("chance cells", () => { + it("reads 1 in N, N/M, percents, fractions and never", () => { + expect(readChance("1 in 50")).toBe(1 / 50); + expect(readChance("1/75")).toBe(1 / 75); + expect(readChance("2 out of 100")).toBe(0.02); + expect(readChance("2%")).toBe(0.02); + expect(readChance("0.5 %")).toBe(0.005); + expect(readChance("0.04")).toBe(0.04); + expect(readChance("never")).toBe(0); + expect(readChance("0")).toBe(0); + for (const bad of ["", "lots", "5", "150%", "3 in 2", "1 in 0", "-1%"]) expect(readChance(bad)).toBeNaN(); + }); + + it("writes 1 in N when it is one, else a percent", () => { + expect(formatChance(1 / 50)).toBe("1 in 50"); + expect(formatChance(1 / 150)).toBe("1 in 150"); + expect(formatChance(0.02)).toBe("1 in 50"); + expect(formatChance(0.03)).toBe("3%"); + expect(formatChance(0.375)).toBe("37.5%"); + expect(formatChance(0)).toBe("never"); + expect(formatChance(1)).toBe("100%"); + for (const c of [1 / 50, 1 / 75, 1 / 150, 0.03, 0.375, 0, 1]) expect(readChance(formatChance(c))).toBeCloseTo(c, 12); + }); +}); + +describe("Stars and Sector features in the note", () => { + it("round-trips the shipped rows, each table under its heading", () => { + const text = buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS, DEFAULT_WORLD_TYPE_EXTRAS); + const p = parseWorldTypes(text); + expect(p.problems).toEqual([]); + expect(p.format).toBe(2); + expect(p.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); + expect(p.stars).toEqual(DEFAULT_STAR_ROWS); + expect(p.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); + expect(text).toContain("## Stars"); + expect(text).toContain("| red dwarf | 6 | |"); + expect(text).toContain("## Sector features"); + expect(text).toContain("| deep-space station | 1 in 50 | |"); + expect(text).toContain("| black hole | 1 in 150 | |"); + expect(text.indexOf("## Stars")).toBeLessThan(text.indexOf("## Sector features")); + }); + + it("reads forgivingly: any order, aliases, links, without headings; the worlds table's Stars column isn't a Stars table", () => { + const text = [ + "| Odds | Sun |", + "|--:|---|", + "| 2 | [[Red dwarf]] |", + "", + "| World | Stars |", + "|---|---|", + "| rock | red dwarf |", + "", + "| Notes | Special | Chance per system |", + "|---|---|---|", + "| spooky | Black hole | 1/150 |", + "| | Station | 2% |", + ].join("\n"); + const p = parseWorldTypes(text); + expect(p.problems).toEqual([]); + expect(p.rows).toEqual([{ world: "rock", stars: ["red dwarf"] }]); + expect(p.stars).toEqual([{ star: "Red dwarf", weight: 2 }]); + expect(p.features).toEqual([{ feature: "Black hole", chance: 1 / 150, notes: "spooky" }, { feature: "Station", chance: 0.02 }]); + expect(p.format).toBeUndefined(); + // A note with no such tables has none (not empty ones). + const only = parseWorldTypes("| World |\n|---|\n| rock |"); + expect(only.stars).toBeUndefined(); + expect(only.features).toBeUndefined(); + }); + + it("keeps rows it can't read, reports them, never uses them", () => { + const text = buildWorldTypes("T", [{ world: "A" }], { stars: [{ star: "Sun" }], features: [{ feature: "Gate", chance: 0.1 }] }) + .replace("| Sun |", "| Dim | lots | |\n| Sun |") + .replace("| Gate |", "| Wreck | often | |\n| | | just a note |\n| Gate |"); + const p = parseWorldTypes(text); + expect(p.stars).toEqual([{ star: "Sun" }]); + expect(p.features).toEqual([{ feature: "Gate", chance: 0.1 }]); + expect(p.problems.map((x) => x.text)).toEqual([ + expect.stringMatching(/^Stars row \d+: weight "lots"/), + expect.stringMatching(/^Sector features row \d+: chance "often" should look like 1 in 50 or 2%/), + expect.stringMatching(/^Sector features row \d+: no feature/), + ]); + const next = updateWorldTypes(text, [{ world: "A" }], { stars: [{ star: "Sun", weight: 2 }], features: [] }); + expect(next).toContain("| Dim | lots |"); + expect(next).toContain("| Wreck | often |"); + const q = parseWorldTypes(next); + expect(q.stars).toEqual([{ star: "Sun", weight: 2 }]); + expect(q.features).toEqual([]); + for (const bad of [["", "2", ""], ["X", "much", ""]]) expect(readStarCells(bad).problem).toBeTruthy(); + for (const bad of [["", "2%", ""], ["X", "", ""], ["X", "7", ""]]) expect(readFeatureCells(bad).problem).toBeTruthy(); + expect(parseWorldTypes(buildWorldTypes("T", [], { features: [{ feature: "A", chance: 0.8 }, { feature: "B", chance: 0.5 }] })).problems[0].text).toMatch(/over 100%/); + }); + + it("the editor's cells read back as the row", () => { + for (const r of [...DEFAULT_STAR_ROWS, { star: "Pulsar", weight: 0.25, notes: "rare | odd" }] as StarTypeRow[]) expect(readStarCells(starCells(r)).row).toEqual(r); + for (const r of [...DEFAULT_SECTOR_FEATURE_ROWS, { feature: "Gate", chance: 0.03, notes: "n" }] as SectorFeatureRow[]) expect(readFeatureCells(featureCells(r)).row).toEqual(r); + }); + + it("rewrites only the tables that changed; same note when nothing did", () => { + const text = buildWorldTypes("T", [{ world: "A" }], { stars: [{ star: "Sun" }], features: [{ feature: "Gate", chance: 0.02 }] }) + .replace("| Gate | 1 in 50 |", "| Gate | 2% |"); + expect(updateWorldTypes(text, [{ world: "A" }], { stars: [{ star: "Sun" }], features: [{ feature: "Gate", chance: 0.02 }] })).toBe(text); + const next = updateWorldTypes(text, [{ world: "A" }], { stars: [{ star: "Sun", weight: 3 }] }); + expect(next).toContain("| Gate | 2% |"); // features untouched, as written + expect(next).toContain("| Sun | 3 | |"); + // Without extras the Stars / Sector features tables are left alone. + expect(updateWorldTypes(text, [{ world: "B" }])).toContain("| Gate | 2% |"); + }); + + it("a format 1 note is given the shipped stars and features once, and marked format 2", () => { + const v2 = buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS); + const v1 = v2.slice(0, v2.indexOf("## Stars")).replace("hexmaker-world-types: 2", "hexmaker-world-types: 1").trimEnd() + "\n\nMy own words.\n"; + const up = upgradeWorldTypes(v1, DEFAULT_WORLD_TYPE_EXTRAS); + const p = parseWorldTypes(up); + expect(p.format).toBe(2); + expect(p.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); + expect(p.stars).toEqual(DEFAULT_STAR_ROWS); + expect(p.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); + expect(up).toContain("My own words."); + expect(up.startsWith(v1.slice(0, v1.indexOf("My own words.")).replace("world-types: 1", "world-types: 2"))).toBe(true); + expect(upgradeWorldTypes(up, DEFAULT_WORLD_TYPE_EXTRAS)).toBe(up); + // A format 2 note whose Stars table was deleted stays without it. + const deleted = up.slice(0, up.indexOf("## Stars")) + up.slice(up.indexOf("## Sector features")); + expect(upgradeWorldTypes(deleted, DEFAULT_WORLD_TYPE_EXTRAS)).toBe(deleted); + // A format 1 note that already has a Stars table keeps its own. + const own = v1 + "\n| Star | Weight |\n| --- | --- |\n| Sun | 1 |\n"; + const ownUp = parseWorldTypes(upgradeWorldTypes(own, DEFAULT_WORLD_TYPE_EXTRAS)); + expect(ownUp.stars).toEqual([{ star: "Sun", weight: 1 }]); + expect(ownUp.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); + // CRLF notes stay CRLF. + expect(upgradeWorldTypes(v1.replace(/\n/g, "\r\n"), DEFAULT_WORLD_TYPE_EXTRAS)).toBe(up.replace(/\n/g, "\r\n")); + }); +}); + +// ── the store ──────────────────────────────────────────────────────────── + +function storePlugin(vault: MemVault, settings: Record = {}) { + return { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { worldFolder: "world", ...settings } as Record, + saveSettings: async () => {}, + }; +} +const NOTE = `world/world-types/${DEFAULT_WORLD_TYPES}.md`; + +describe("WorldTypeStore: stars and sector features", () => { + it("seeds them, edits them, restores them", async () => { + const v = new MemVault(); + const store = new WorldTypeStore(storePlugin(v) as never); + await store.init(); + const t = store.get(DEFAULT_WORLD_TYPES)!; + expect(t.stars).toEqual(DEFAULT_STAR_ROWS); + expect(t.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); + await store.update(DEFAULT_WORLD_TYPES, t.rows, { stars: [{ star: "red dwarf", weight: 1 }], features: [{ feature: "anomaly", chance: 0.5 }] }); + expect(v.files.get(NOTE)).toContain("| anomaly | 1 in 2 | |"); + expect(store.get(DEFAULT_WORLD_TYPES)!.stars).toEqual([{ star: "red dwarf", weight: 1 }]); + await store.restoreDefault(); + expect(store.get(DEFAULT_WORLD_TYPES)!.stars).toEqual(DEFAULT_STAR_ROWS); + expect(store.get(DEFAULT_WORLD_TYPES)!.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); + await store.create("Mine"); + expect(store.get("Mine")!.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); + await store.create("Bare", [], { stars: [], features: [] }); + expect(store.get("Bare")!.stars).toEqual([]); + }); + + it("upgrades a format 1 note when it reads it", async () => { + const v2 = buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS); + const v1 = v2.slice(0, v2.indexOf("## Stars")).replace("hexmaker-world-types: 2", "hexmaker-world-types: 1"); + const v = new MemVault({ [NOTE]: v1 }); + const store = new WorldTypeStore(storePlugin(v, { worldTypesSeeded: true }) as never); + await store.init(); + expect(v.files.get(NOTE)).toContain("hexmaker-world-types: 2"); + expect(v.files.get(NOTE)).toContain("## Sector features"); + expect(store.get(DEFAULT_WORLD_TYPES)!.stars).toEqual(DEFAULT_STAR_ROWS); + expect(store.get(DEFAULT_WORLD_TYPES)!.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); + expect(store.problemsOf(DEFAULT_WORLD_TYPES)).toEqual([]); + }); +}); diff --git a/tests/worldTypes.test.ts b/tests/worldTypes.test.ts index f9e235a3..2ce1a693 100644 --- a/tests/worldTypes.test.ts +++ b/tests/worldTypes.test.ts @@ -126,7 +126,7 @@ describe("Default space reproduces the old built-in odds", () => { const back = parseWorldTypes(text); expect(back.problems).toEqual([]); expect(back.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); - expect(text).toContain("hexmaker-world-types: 1"); + expect(text).toContain("hexmaker-world-types: 2"); expect(text).toContain("| ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush, relief=normal | Expanded | ocean | |"); }); }); @@ -140,7 +140,7 @@ describe("world types note", () => { it("round-trips every column and keeps prose", () => { const text = buildWorldTypes("Mine", rows).replace("# Mine", "# Mine\n\nMy own words."); - expect(parseWorldTypes(text)).toEqual({ rows, problems: [], unreadable: [] }); + expect(parseWorldTypes(text)).toEqual({ rows, problems: [], unreadable: [], stars: [], features: [], unreadableStars: [], unreadableFeatures: [], format: 2 }); expect(updateWorldTypes(text, rows)).toBe(text); const next = updateWorldTypes(text, rows.slice(1)); expect(next).toContain("My own words."); @@ -271,7 +271,7 @@ describe("WorldTypeStore", () => { const plugin = storePlugin(v); const store = new WorldTypeStore(plugin as never); await store.init(); - expect(v.files.get(NOTE)).toContain("hexmaker-world-types: 1"); + expect(v.files.get(NOTE)).toContain("hexmaker-world-types: 2"); expect(store.get(DEFAULT_WORLD_TYPES)!.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); expect(plugin.settings.worldTypesSeeded).toBe(true); v.files.delete(NOTE); From 3cbb0917f3863e9c90af58c3710be4f554cc5ce9 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:11:17 -0400 Subject: [PATCH 277/558] feat(space): a faint tether ties each moon to its planet on the map (S11) By terrain type (moon next to world / gas giant), never names. Drawn in the path layer, under the paths, and hidden with them. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 ++-- src/hex-map/HexMapView.ts | 27 ++++++++++++++++++++++-- src/hex-map/moonLinks.ts | 44 +++++++++++++++++++++++++++++++++++++++ styles.css | 5 +++++ tests/moonLinks.test.ts | 35 +++++++++++++++++++++++++++++++ 5 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 src/hex-map/moonLinks.ts create mode 100644 tests/moonLinks.test.ts diff --git a/package.json b/package.json index c1768281..8c16b458 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 90039b45..cd9ef1e3 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -67,6 +67,7 @@ import { type LatticeAffine, type LatticeGrid, } from "../paths/pathGeometry"; +import { moonPlanetLinks, tether } from "./moonLinks"; import { GotoHexModal } from "./GotoHexModal"; import { HexHelpModal } from "./HexHelpModal"; import { FolderTreePickerModal } from "./FolderTreePickerModal"; @@ -6193,6 +6194,18 @@ export class HexMapView extends ItemView { dash: s.dash.map((d) => fmt(d * scale)).join(" "), }; }); + // Moons tied to their planet (S11): a faint tether across the edge they + // share, by terrain type (src/hex-map/moonLinks.ts). Under the paths. + const moonLines: { d: string; width: string; dash: string }[] = []; + if (calib) { + const terrain = new Map(); + for (const [k, h] of this.plugin.mapStore.all(region.name)) if (h.terrain) terrain.set(k, h.terrain); + const links = moonPlanetLinks(terrain, this.plugin.getMapPalette(region.name), calib.lattice.orientation, calib.lattice.stagger); + for (const [moon, planet] of links) { + const [a, b] = em(tether(latticeCenter(moon, calib.lattice), latticeCenter(planet, calib.lattice))); + moonLines.push({ d: `M${fmt(a.cx)} ${fmt(a.cy)}L${fmt(b.cx)} ${fmt(b.cy)}`, width: fmt(0.07 * scale), dash: `${fmt(0.1 * scale)} ${fmt(0.08 * scale)}` }); + } + } // The path tool: the selected path highlighted, its anchor handles // (ends bigger: continue from there) and the dot where clicks add. const tool = calib && this.drawingMode === "path" ? this.pathTool.overlay() : null; @@ -6222,10 +6235,10 @@ export class HexMapView extends ItemView { } } const selected = tool?.selected ?? null; - const key = JSON.stringify([lines.map((l) => [l.s.path, l.s.branch, l.d, l.width, l.dash, l.s.color]), dot, handles, selected]); + const key = JSON.stringify([lines.map((l) => [l.s.path, l.s.branch, l.d, l.width, l.dash, l.s.color]), dot, handles, selected, moonLines]); const existing = gridContainer.querySelector("svg.duckmage-path-svg"); const existingHandles = gridContainer.querySelector("svg.duckmage-path-handles-svg"); - const wantLines = lines.length > 0; + const wantLines = lines.length > 0 || moonLines.length > 0; const wantHandles = !!dot || handles.length > 0; // ── Writes ── @@ -6245,6 +6258,16 @@ export class HexMapView extends ItemView { }; if (wantLines) { const svg = emSvg("duckmage-path-svg"); + for (const m of moonLines) { + const tie = activeDocument.createElementNS(svgNS, "path"); + tie.setAttribute("class", "duckmage-svg-path-line duckmage-moon-link"); + tie.setAttribute("d", m.d); + tie.setAttribute("stroke-width", m.width); + tie.setAttribute("stroke-dasharray", m.dash); + tie.setAttribute("stroke-linecap", "round"); + tie.setAttribute("fill", "none"); + svg.appendChild(tie); + } // The selected path's halo, under every line. for (const l of lines) { if (l.s.path !== selected) continue; diff --git a/src/hex-map/moonLinks.ts b/src/hex-map/moonLinks.ts new file mode 100644 index 00000000..084d5c9f --- /dev/null +++ b/src/hex-map/moonLinks.ts @@ -0,0 +1,44 @@ +/** + * Which planet a moon belongs to (S11): on a map, every hex whose terrain + * is of type moon is tied to each neighbouring hex whose terrain is a + * planet (type world or gas giant). The map view draws a faint tether + * across the edge they share. By terrain TYPE only, never names, so a + * custom palette ("Luna" typed moon) works the same as the shipped one. + * Pure: no Obsidian imports. + */ +import type { TerrainColor } from "../types"; +import { effectiveTerrainType } from "../terrainTypes"; +import { hexNeighbors, type Orientation, type Stagger } from "../../packages/hex-wfc/src/grid"; + +export const MOON_TYPES: readonly string[] = ["moon"]; +export const PLANET_TYPES: readonly string[] = ["world", "gas-giant"]; + +/** [moon hex, planet hex] pairs ("x_y" keys), in a stable order. */ +export function moonPlanetLinks( + terrainAt: ReadonlyMap, + palette: readonly TerrainColor[], + orientation: Orientation, + stagger: Stagger, +): [string, string][] { + const type = new Map(palette.map((t) => [t.name.toLowerCase(), effectiveTerrainType(t)])); + const typeAt = (key: string) => { + const t = terrainAt.get(key); + return t ? type.get(t.toLowerCase()) : undefined; + }; + const out: [string, string][] = []; + for (const key of [...terrainAt.keys()].sort()) { + if (!MOON_TYPES.includes(typeAt(key) ?? "")) continue; + const [x, y] = key.split("_").map(Number); + for (const [nx, ny] of hexNeighbors(x, y, orientation, stagger)) { + const n = `${nx}_${ny}`; + if (PLANET_TYPES.includes(typeAt(n) ?? "")) out.push([key, n]); + } + } + return out; +} + +/** The tether between two hex centres: the middle part of the line joining them (from `t` to 1 - t). */ +export function tether(a: { cx: number; cy: number }, b: { cx: number; cy: number }, t = 0.3): [{ cx: number; cy: number }, { cx: number; cy: number }] { + const at = (f: number) => ({ cx: a.cx + (b.cx - a.cx) * f, cy: a.cy + (b.cy - a.cy) * f }); + return [at(t), at(1 - t)]; +} diff --git a/styles.css b/styles.css index fd35656e..6f1b39ad 100644 --- a/styles.css +++ b/styles.css @@ -8770,3 +8770,8 @@ textarea.duckmage-edit-region-notes-input { font-size: var(--font-ui-smaller); color: var(--text-muted); } +/* S11: a moon tied to its planet (a faint dashed tether). */ +.duckmage-moon-link { + stroke: #d7deff; + opacity: 0.55; +} diff --git a/tests/moonLinks.test.ts b/tests/moonLinks.test.ts new file mode 100644 index 00000000..4608258e --- /dev/null +++ b/tests/moonLinks.test.ts @@ -0,0 +1,35 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { moonPlanetLinks, tether } from "../src/hex-map/moonLinks"; +import type { TerrainColor } from "../src/types"; + +const palette: TerrainColor[] = [ + { name: "void", color: "#000000", type: "void" }, + { name: "Luna", color: "#cccccc", type: "moon" }, + { name: "Terra", color: "#33aa55", type: "world" }, + { name: "Jove", color: "#cc9966", type: "gas-giant" }, + { name: "moon rock", color: "#999999" }, // untyped: never a moon, whatever its name + { name: "planet x", color: "#999999" }, // untyped: never a planet +] as TerrainColor[]; + +describe("moons tied to their planet (S11)", () => { + it("ties a moon-typed hex to each planet-typed neighbour, by type not name", () => { + const t = new Map([["2_2", "Luna"], ["2_1", "Terra"], ["3_2", "void"], ["5_5", "luna"], ["5_6", "Jove"], ["8_8", "moon rock"], ["8_9", "Terra"], ["10_10", "Luna"], ["10_9", "planet x"]]); + expect(moonPlanetLinks(t, palette, "flat", "odd")).toEqual([["2_2", "2_1"], ["5_5", "5_6"]]); + }); + + it("draws nothing without moons or beside nothing", () => { + expect(moonPlanetLinks(new Map([["0_0", "Luna"], ["4_4", "Terra"]]), palette, "pointy", "even")).toEqual([]); + }); + + it("follows the grid's orientation and stagger", () => { + // Flat, odd: (1,0) touches (2,1); pointy, odd: it does not. + const t = new Map([["1_0", "Luna"], ["2_1", "Terra"]]); + expect(moonPlanetLinks(t, palette, "flat", "odd")).toEqual([["1_0", "2_1"]]); + expect(moonPlanetLinks(t, palette, "pointy", "odd")).toEqual([]); + }); + + it("draws the middle of the line between the two centres", () => { + expect(tether({ cx: 0, cy: 0 }, { cx: 10, cy: 0 })).toEqual([{ cx: 3, cy: 0 }, { cx: 7, cy: 0 }]); + }); +}); From cc90cfe67ae287960a690651e2c8c17e0e9bb71c Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:11:59 -0400 Subject: [PATCH 278/558] feat(path-tool): no edit mode - every path of the tool's type is live With the path tool on type T, every path of type T shows its anchor handles and can be worked on directly: - left-drag a point moves it (live reroute preview, one undo step), also while drawing (except the active end: dragging that draws on) - left-drag the line inserts a point there and moves it - right-click a point deletes it; a branch/path left with one point goes too, with a notice (undo brings it back) - Shift+right-click a point, or right-click a line: the path menu - click an end continues; click the line selects, again forks; click empty ground starts a new path of T Paths of other types are inert: a click there is ground, hovering says "switch to to edit it", right-click offers Switch to. Picking a path from "Paths on this map" switches the tool to its type. Pure tables: pathClickOutcome, pathPressOutcome, pathContextOutcome, hitTestPaths(editable), inertHint, anchorDeleteNotice (tested). Mode bar, help and README describe exactly these actions. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- src/hex-map/HexMapView.ts | 10 +- src/hex-map/help.md | 20 ++- src/hex-map/pathTool.ts | 342 +++++++++++++++++++++++++++----------- src/hex-map/toolMode.ts | 13 +- tests/autoRoute.test.ts | 5 +- tests/pathTool.test.ts | 122 ++++++++++++-- tests/toolMode.test.ts | 14 +- 8 files changed, 390 insertions(+), 140 deletions(-) diff --git a/README.md b/README.md index 50c66362..b024fc94 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,9 @@ Click the **pencil** icon on the right edge of the map to open the drawing tools - **Meander** — gentle curve through the midpoints between hex centres (good for rivers). - **Edge** — traces strictly along the hex polygon boundary lines between hexes. -**Auto-route:** the picker (and the bar at the top of the map while drawing) switches between **Hex by hex** and **Auto-route**: in the picker, choose how to draw (step 1), then the path type (step 2). With Auto-route, click a start hex and then an end hex: the path takes the shortest way inside the map, around impassable terrain, keeping close to the straight line between the two, and then carries on from that end, so you can route leg by leg. Path types whose **Auto-route** option is *winding* (River, by default) wind gently instead of running straight; *direct* ones keep to the line. It's an option on each type, never a matter of its name. A route continues an existing path only when its start is that path's end; starting anywhere else (such as the first hex of another road) makes a new path, and existing paths are never changed. The result is an ordinary path: right-click hexes to remove them, or switch back to hex by hex to extend it. +**Editing paths:** there is no separate edit mode. While the path tool is on a type, every path of that type shows its points as handles: drag a point to move it, drag the line to add a point there and move it, right-click a point to delete it (a branch or path left with one point goes too, with a notice; undo brings it back), click an end to carry on from it, and click empty ground to start a new path. Click a line to select that path, and click it again to start a fork. Right-click a line (or Shift+right-click a point) for the path menu: Split here, Delete this fork, Delete path, Rename…, Change type…, Reverse. Paths of other types are left alone while you work: a click on one is a click on the ground, and hovering it names the type to switch to (right-click it for **Switch to** that type). Each drag or delete is one undo step, and editing paths needs Build or God mode. The bar at the top of the map lists these actions. + +**Auto-route:** the picker (and the bar at the top of the map while drawing) switches between **Hex by hex** and **Auto-route**: in the picker, choose how to draw (step 1), then the path type (step 2). With Auto-route, click a start hex and then an end hex: the path takes the shortest way inside the map, around impassable terrain, keeping close to the straight line between the two, and then carries on from that end, so you can route leg by leg. Path types whose **Auto-route** option is *winding* (River, by default) wind gently instead of running straight; *direct* ones keep to the line. It's an option on each type, never a matter of its name. A route continues an existing path only when its start is that path's end; starting anywhere else (such as the first hex of another road) makes a new path, and existing paths are never changed. The result is an ordinary path: drag its points to reshape it, right-click a point to remove it, or click an end to extend it. - **Impassable terrain** — set per terrain in the palette editor (Impassable column) or the terrain editor. Defaults go by terrain *type*, never by name, so they work in any palette, custom ones included: every terrain of a water type (deep water, water, shallows) is impassable unless you untick it. A terrain with no type has no default (an untyped "Black Lake" is passable); give it a type, or use **Guess types from names** in the palette editor. A palette with no impassable terrain says so in the bar. Learned generators' **Connected land** uses the same impassable terrains until you save your own list. - **Per path type** — each path type has **Avoid impassable terrain** and **Auto-route** (direct or winding) in its editor and in the palette note's Path types table. The built-in Road avoids impassable terrain and routes direct; River does neither. Any type can be set either way, whatever it's called. Path types saved by older versions get these filled in once, from how those versions treated them, so no map changes look. diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 90039b45..5cafc9b5 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -372,6 +372,7 @@ export class HexMapView extends ItemView { redraw: () => this.updatePathOverlay(), refreshBar: () => this.updateModeBar(), setGrabCursor: (on) => this.viewportEl?.toggleClass("duckmage-path-grab", on), + typeChanged: () => this.updateToolbarButtonStates(), }); this.overworldLayer = new OverworldLayer(plugin); this.minimap = new OverworldMinimap(plugin, this); @@ -1194,7 +1195,7 @@ export class HexMapView extends ItemView { beginDrag(); return; // skip pan setup } - // The path tool takes a press on the selected path (drag to reshape). + // The path tool takes a press on a point or line of its type (drag to reshape). if (this.drawingMode === "path" && this.pathTool.pointerDown(e, this.isErasingMode)) return; // Any other active tool (road, river, tableLink, swap): // let the click event handle it — don't set up drag/pan so hasDragged @@ -1215,7 +1216,7 @@ export class HexMapView extends ItemView { // document (issue #32). Stroke-time highlight is owned by onDragMove. this.registerDomEvent(contentEl, "mousemove", (e: MouseEvent) => { if (isTerrainPainting) return; - if (this.drawingMode === "path" && e.buttons === 0) this.pathTool.pointerMove(e); + if (this.drawingMode === "path" && e.buttons === 0) this.pathTool.pointerMove(e, this.isErasingMode); if (this.drawingMode === "terrain" || this.drawingMode === "icon") { const hexEl = (e.target as HTMLElement | null)?.closest( ".duckmage-hex", @@ -1358,8 +1359,9 @@ export class HexMapView extends ItemView { this.removeOneGmIconFromHex(hexEl, hexX, hexY, this.paintIconName); return; } - // Path tool: right-click an anchor handle of the selected path - // deletes it; on a path, the menu adds that path's actions. + // Path tool: right-click an anchor of a path of the tool's type + // deletes it; on such a path (or Shift on an anchor), the menu adds + // that path's actions; on another type's path, "Switch to ". let pathItems: { label: string; onClick: () => void }[] = []; if (this.drawingMode === "path" && !this.isErasingMode) { const r = this.pathTool.contextMenu(e); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index b35ecec9..fe5d8624 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -64,14 +64,18 @@ The **+** buttons at the edges of the map grow the grid one column or row in tha ## Drawing tools ### Paths -Pick a path type in the path picker (choose **Hex by hex** or **Auto-route** first; switch either way later from the bar at the top). Every path has a name and shows up under **Paths on this map** in the picker, with its ends, forks and size; click one there to select it. - -- **Draw:** click a hex to start, then keep clicking. Each click adds a point and the path finds its way there from the end, around impassable terrain, so you can click far away. In hex-by-hex mode, click neighbouring hexes (a click further away is routed too, and the bar says so), or press and drag: every hex you pass becomes a point, and going back a hex takes the last one away. The whole drag is one undo step. Click the end again, press **Esc** or **Done** to finish. -- **Select:** click a path. Its points show as handles; the bigger ones are its ends. -- **Continue or fork:** with a path selected, click an end to carry on from it, or click anywhere else on it to start a fork there. A path and its forks are one path in the map note. -- **Reshape:** drag any part of the selected path (in hex-by-hex mode, dragging from an end carries the path on instead). Grabbing a point moves it; grabbing the line adds a point there. The new route shows as you drag; let go to keep it, or drop it back where it was to cancel. -- **New path:** **Alt-click**, or **New path** in the bar, starts a new path even on top of another one (a crossroads of two roads). -- **Delete:** right-click a handle, or hover one and press **Backspace**. Backspace while drawing removes the last point. Right-click a path: its own items come first (**Split here**, **Delete this fork**, **Delete path**, **Rename…**, **Change type…**, **Reverse**), then the tool's. In erase mode (the picker's ✕), click a path to split it there. +Pick a path type in the path picker (choose **Hex by hex** or **Auto-route** first; switch either way later from the bar at the top). Every path has a name and shows up under **Paths on this map** in the picker, with its ends, forks and size; click one there to select it (the tool switches to its type). + +There's no separate edit mode. While the tool is on a type (say Road), every Road on the map shows its points as handles (the bigger ones are ends), and you can work on any of them straight away. Paths of other types are left alone: clicking on a river starts a new road there, and hovering one says which type to switch to. Right-click it for **Switch to River**. + +- **Draw:** click empty ground to start, then keep clicking. Each click adds a point and the path finds its way there from the end, around impassable terrain, so you can click far away. In hex-by-hex mode, click neighbouring hexes (a click further away is routed too, and the bar says so), or press and drag: every hex you pass becomes a point, and going back a hex takes the last one away. The whole drag is one undo step. Click the end again, press **Esc** or **Done** to finish. +- **Move a point:** drag it. The new route shows as you drag; let go to keep it (one undo step), or drop it back where it was to cancel. This works while drawing too. +- **Reshape the line:** drag the line itself: a new point is added where you grabbed it, and moves with the pointer. +- **Delete a point:** right-click it, or hover it and press **Backspace**. A branch left with one point goes, and so does a path; the map says so and undo brings it back. Backspace while drawing removes the last point. +- **Continue:** click an end to carry on from it. +- **Select and fork:** click a path's line to select it (it's highlighted and its name shows in the bar; click the name to rename it). Click the selected path's line again to start a fork there. A path and its forks are one path in the map note. +- **New path:** click empty ground. **Alt-click**, or **New path** in the bar, starts a new path even on top of a path of the same type (a crossroads of two roads). +- **Path menu:** right-click a path's line, or **Shift**+right-click a point: its own items come first (**Split here**, **Delete this fork**, **Delete path**, **Rename…**, **Change type…**, **Reverse**), then the tool's. In erase mode (the picker's ✕), click a path of the tool's type to split it there. - **Esc** steps out one level: finish the branch, then deselect, then leave the tool. **Ctrl/Cmd+Z** undoes each change. Mark terrains impassable in the palette editor (every water-type terrain is impassable by default). Each path type chooses whether it goes around them (roads do, rivers don't) and whether it winds. Tick **Cross impassable** in the bar to let the next legs go through. If painting terrain, changing the palette, resizing the map or changing a type's routing would move an existing path, it keeps its route (points are added to hold it) and a notice offers **Reroute instead**; undoing the paint stroke undoes that too. diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index 1c742ec4..a8754455 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -6,6 +6,13 @@ * (mapStore.setPaths). Every edit goes through `commit`, which asks the * path edit gate (src/paths/editGate.ts) first. * + * There is no separate edit mode: with the tool on type T, every path of + * type T shows live anchor handles (drag a point to move it, drag the line + * to add one, right-click a point to delete it, click an end to continue); + * paths of other types are inert (a click there is ground; hovering says + * "switch to to edit it"). The tables are pathClickOutcome, + * pathPressOutcome and pathContextOutcome. + * * Hit-testing is pure math in lattice units: the pointer is turned into * lattice coordinates by the view (one read of the grid's box per event, * never per hex) and compared with the same polylines the map draws. @@ -93,19 +100,26 @@ export function anchorEnd(rb: Pick, an export interface PathHit { path: string; branch: number; - /** The branch's routed hex nearest the pointer. */ + /** The branch's routed hex nearest the pointer (the anchor's own hex when `anchor` is set). */ hexIdx: number; - /** The anchor whose handle is under the pointer (selected path only), else null. */ + /** That routed hex. */ + hex: HexKey; + /** The anchor whose handle is under the pointer (editable paths only), else null. */ anchor: number | null; /** When `anchor` is a branch end. */ end: "head" | "tail" | null; + /** The path is of the tool's type (it can be reshaped); false: another type's, inert. */ + editable: boolean; } /** - * What's under lattice point `p`: an anchor handle of the selected path - * first (the nearest within its radius), else the nearest path line within - * half its stroke plus LINE_SLACK (the selected path wins where lines - * overlap). Null when nothing is. + * What's under lattice point `p`. Anchor handles of every editable path + * (`editable(name)`; all paths when null) come first, the nearest within + * its radius; else the nearest path line within half its stroke plus + * LINE_SLACK. Where lines overlap, an editable path beats an inert one and + * the selected path beats the rest. Inert paths are still reported (for + * the "switch to … to edit it" hint) with `editable: false`. Null when + * nothing is under the pointer. */ export function hitTestPaths( p: Pt, @@ -113,44 +127,50 @@ export function hitTestPaths( resolved: readonly ResolvedBranch[], grid: LatticeGrid, selected: string | null, + editable: ((path: string) => boolean) | null = null, ): PathHit | null { - if (selected !== null) { - let best: PathHit | null = null; - let bestD = Infinity; - for (const rb of resolved) { - if (rb.path !== selected) continue; - rb.anchorIdx.forEach((hexIdx, a) => { - const end = anchorEnd(rb, a); - const c = latticeCenter(rb.hexes[hexIdx], grid); - const d = Math.hypot(p.cx - c.cx, p.cy - c.cy); - if (d <= (end ? END_HANDLE_R : HANDLE_R) && d < bestD - 1e-9) { - bestD = d; - best = { path: rb.path, branch: rb.branch, hexIdx, anchor: a, end }; - } - }); - } - if (best) return best; + const canEdit = (path: string) => editable === null || editable(path); + let best: PathHit | null = null; + let bestD = Infinity; + let bestSel = false; + for (const rb of resolved) { + if (!canEdit(rb.path)) continue; + const sel = rb.path === selected; + rb.anchorIdx.forEach((hexIdx, a) => { + const end = anchorEnd(rb, a); + const c = latticeCenter(rb.hexes[hexIdx], grid); + const d = Math.hypot(p.cx - c.cx, p.cy - c.cy); + if (d > (end ? END_HANDLE_R : HANDLE_R)) return; + // Stacked handles (paths sharing a hex): the selected path's first, then the nearest. + if ((sel && !bestSel) || (sel === bestSel && d < bestD - 1e-9)) { + bestD = d; + bestSel = sel; + best = { path: rb.path, branch: rb.branch, hexIdx, hex: rb.hexes[hexIdx], anchor: a, end, editable: true }; + } + }); } + if (best) return best; let pick: PathStroke | null = null; let pickD = Infinity; - let pickSel = false; + let pickRank = -1; for (const s of strokes) { const d = distToPolyline(p, s.pts); if (d > s.width / 2 + LINE_SLACK) continue; - const sel = s.path === selected; - if ((sel && !pickSel) || (sel === pickSel && d < pickD - 1e-9)) { + const rank = (canEdit(s.path) ? 2 : 0) + (s.path === selected ? 1 : 0); + if (rank > pickRank || (rank === pickRank && d < pickD - 1e-9)) { pick = s; pickD = d; - pickSel = sel; + pickRank = rank; } } if (!pick) return null; const rb = resolved.find((r) => r.path === pick.path && r.branch === pick.branch); if (!rb) return null; - return { path: rb.path, branch: rb.branch, hexIdx: nearestHexIdx(p, rb.hexes, grid), anchor: null, end: null }; + const hexIdx = nearestHexIdx(p, rb.hexes, grid); + return { path: rb.path, branch: rb.branch, hexIdx, hex: rb.hexes[hexIdx], anchor: null, end: null, editable: canEdit(rb.path) }; } -// ── Pure: what a click does ────────────────────────────────────────────────── +// ── Pure: what a click, a press and a right-click do ───────────────────────── export type PathClick = | { kind: "none" } @@ -161,8 +181,7 @@ export type PathClick = /** The active end clicked again: finish the branch (the path stays selected). */ | { kind: "finish" } | { kind: "select"; path: string } - | { kind: "deselect" } - /** Continue the selected path from this end. */ + /** Continue a path from this end. */ | { kind: "continue"; path: string; branch: number; end: "head" | "tail" } /** Start a fork of the selected path at this hex of it. */ | { kind: "fork"; path: string; branch: number; hexIdx: number } @@ -179,22 +198,77 @@ export interface PathClickState { } /** - * The click table (replaces the old hex-by-hex pathClickOutcome): - * erase splits; Alt / New path starts a new path; while drawing, every - * click adds an anchor (the active end again finishes); on the selected - * path an end continues it and anywhere else forks; another path is - * selected; empty map deselects, or starts a path when nothing is selected. + * The click table. Paths of the tool's type are always live (there's no + * separate edit mode); other types' paths are inert, so a click on one is + * a click on the ground. + * - Erase: split the tool's-type path under the pointer. + * - Alt / New path: start a new path, whatever is under the pointer. + * - Drawing: every click adds an anchor; the active end again finishes. + * - An end of a tool's-type path: continue it from there. + * - Elsewhere on such a path: select it; on the selected one, fork there. + * - Empty ground (or another type's path): start a new path. */ export function pathClickOutcome(s: PathClickState, key: HexKey, hit: PathHit | null): PathClick { - if (s.erasing) return hit ? { kind: "split", path: hit.path, branch: hit.branch, hexIdx: hit.hexIdx } : { kind: "none" }; + const live = hit?.editable ? hit : null; + if (s.erasing) return live ? { kind: "split", path: live.path, branch: live.branch, hexIdx: live.hexIdx } : { kind: "none" }; if (s.forceNew) return { kind: "start" }; if (s.activeHex !== null) return key === s.activeHex ? { kind: "finish" } : { kind: "append" }; - if (hit && hit.path === s.selected) { - if (hit.end) return { kind: "continue", path: hit.path, branch: hit.branch, end: hit.end }; - return { kind: "fork", path: hit.path, branch: hit.branch, hexIdx: hit.hexIdx }; + if (live) { + if (live.end) return { kind: "continue", path: live.path, branch: live.branch, end: live.end }; + if (live.path === s.selected) return { kind: "fork", path: live.path, branch: live.branch, hexIdx: live.hexIdx }; + return { kind: "select", path: live.path }; + } + return { kind: "start" }; +} + +/** + * What a left press does before it's known to be a click or a drag: + * "move" an anchor (any anchor of a tool's-type path, also while drawing, + * except the active end: dragging from that draws on), "insert" an anchor + * into a tool's-type line and move it (not while drawing: then the line is + * ground), else "draw" (hex-by-hex press-and-drag drawing, or a plain + * click). Alt / New path always draw. A press that doesn't move is a click. + */ +export function pathPressOutcome(s: { forceNew: boolean; activeHex: HexKey | null }, hit: PathHit | null): "move" | "insert" | "draw" { + if (s.forceNew || !hit?.editable) return "draw"; + if (hit.anchor !== null) return hit.hex === s.activeHex ? "draw" : "move"; + return s.activeHex === null ? "insert" : "draw"; +} + +export type PathContext = + /** Right-click on an anchor of a tool's-type path: delete it. */ + | { kind: "delete-anchor"; path: string; branch: number; anchor: number } + /** On a tool's-type line (or Shift+right-click on an anchor): the path's menu. */ + | { kind: "menu"; path: string; branch: number; hexIdx: number } + /** On another type's path: offer to switch to its type. */ + | { kind: "switch"; path: string } + /** Nothing under the pointer: the tool's own menu. */ + | { kind: "none" }; + +/** What a right-click does in the path tool (Shift held: the menu, even on an anchor). */ +export function pathContextOutcome(hit: PathHit | null, shift: boolean): PathContext { + if (!hit) return { kind: "none" }; + if (!hit.editable) return { kind: "switch", path: hit.path }; + if (hit.anchor !== null && !shift) return { kind: "delete-anchor", path: hit.path, branch: hit.branch, anchor: hit.anchor }; + return { kind: "menu", path: hit.path, branch: hit.branch, hexIdx: hit.hexIdx }; +} + +/** The mode-bar hint over another type's path. */ +export function inertHint(p: Pick): string { + return `${p.name} is a ${p.typeName}: switch to ${p.typeName} to edit it`; +} + +/** + * The notice when deleting an anchor took a whole branch or path with it + * (fewer than two anchors left), else null. Undo brings it back. + */ +export function anchorDeleteNotice(before: MapPath, after: MapPath | null, branch: number): string | null { + if (!after) return `Deleted ${before.name}: it had one point left. Undo brings it back.`; + if (after.branches.length < before.branches.length) { + const what = branch === 0 ? "the main line" : "a fork"; + return `Deleted ${what} of ${before.name}: it had one point left. Undo brings it back.`; } - if (hit) return { kind: "select", path: hit.path }; - return s.selected !== null ? { kind: "deselect" } : { kind: "start" }; + return null; } /** "Road, 2 forks" for the mode bar. */ @@ -261,8 +335,10 @@ export interface PathToolHost { redraw(): void; /** Refresh the mode bar. */ refreshBar(): void; - /** Show (or clear) the "grab" cursor over the selected path. */ + /** Show (or clear) the "grab" cursor over a point or line that can be dragged. */ setGrabCursor(on: boolean): void; + /** The tool's path type changed (the toolbar swatch follows it). */ + typeChanged(): void; } /** A path or fork started by one click: it's created when the second anchor comes. */ @@ -362,7 +438,10 @@ export class PathTool { private forceNew = false; /** A short note for the mode bar about the last click. */ hint: string | null = null; - private hover: { branch: number; anchor: number } | null = null; + /** The mode-bar hint while the pointer is over another type's path. */ + private hoverHint: string | null = null; + /** The anchor handle under the pointer (Backspace deletes it). */ + private hover: { path: string; branch: number; anchor: number } | null = null; private drag: Drag | null = null; private drawDrag: DrawDrag | null = null; private suppressClick = false; @@ -407,11 +486,22 @@ export class PathTool { return this.strokeMemo.strokes; } + /** + * Which paths the tool edits: those of its type (all of them before a + * type is picked). Other types' paths are inert while the tool is on. + */ + private editableNames(): ReadonlySet | null { + const type = this.typeName; + if (type === null) return null; + return new Set(this.paths().filter((p) => p.typeName === type).map((p) => p.name)); + } + private hitAt(e: { clientX: number; clientY: number }): PathHit | null { const p = this.host.pointerLattice(e); const grid = this.grid(); if (!p || !grid) return null; - return hitTestPaths(p, this.strokes(), this.resolved(), grid, this.selected); + const names = this.editableNames(); + return hitTestPaths(p, this.strokes(), this.resolved(), grid, this.selected, names ? (n) => names.has(n) : null); } /** The hex clicks add to, if any. */ @@ -449,24 +539,25 @@ export class PathTool { selected: p?.name ?? null, summary: p ? pathSummary(p) : null, drawing: this.isDrawing(), - note: this.hint, + note: [this.hint, this.hoverHint].filter(Boolean).join(" · ") || null, forceNew: this.forceNew, }; } + /** Handles on every anchor of every path of the tool's type: they're always live. */ overlay(): PathToolOverlay { const handles: PathToolOverlay["handles"] = []; - if (this.selected !== null) { - for (const rb of this.resolved()) { - if (rb.path !== this.selected) continue; - rb.anchorIdx.forEach((hexIdx, a) => { - handles.push({ - hex: rb.hexes[hexIdx], - end: anchorEnd(rb, a) !== null, - hover: this.hover?.branch === rb.branch && this.hover.anchor === a, - }); + const names = this.editableNames(); + const h = this.hover; + for (const rb of this.resolved()) { + if (names && !names.has(rb.path)) continue; + rb.anchorIdx.forEach((hexIdx, a) => { + handles.push({ + hex: rb.hexes[hexIdx], + end: anchorEnd(rb, a) !== null, + hover: h?.path === rb.path && h.branch === rb.branch && h.anchor === a, }); - } + }); } return { selected: this.selected, handles, active: this.activeHex() }; } @@ -539,19 +630,39 @@ export class PathTool { this.pending = null; this.forceNew = false; this.hint = null; + this.hoverHint = null; this.hover = null; this.host.setGrabCursor(false); } - /** Pick the type for new paths. A new type ends the branch being drawn. */ + /** + * Pick the tool's type: new paths take it, and its paths are the ones + * that can be reshaped. A new type ends the branch being drawn and drops + * a selection of another type. + */ setType(typeName: string): void { if (typeName !== this.typeName) { this.pending = null; this.active = null; + this.hover = null; + this.hoverHint = null; + if (this.pathNamed(this.selected)?.typeName !== typeName) this.selected = null; } this.typeName = typeName; } + /** "Switch to River" (right-click on another type's path): take its type, select it. */ + private switchTo(path: string): void { + const p = this.pathNamed(path); + if (!p) return; + this.setType(p.typeName); + this.selected = p.name; + this.hint = null; + this.host.typeChanged(); + this.host.redraw(); + this.host.refreshBar(); + } + setAutoRoute(on: boolean): void { this.autoRoute = on; this.hint = null; @@ -562,8 +673,10 @@ export class PathTool { selectPath(name: string): void { const p = this.pathNamed(name); if (!p) return; - // Picked from the list before any type: new paths take this one. - if (!this.typeName) this.typeName = p.typeName; + // The tool takes the path's type, so the path can be reshaped. + const retyped = p.typeName !== this.typeName; + this.setType(p.typeName); + if (retyped) this.host.typeChanged(); this.selected = p.name; this.active = null; this.pending = null; @@ -659,9 +772,6 @@ export class PathTool { this.selected = outcome.path; this.active = null; break; - case "deselect": - this.selected = null; - break; case "continue": this.selected = outcome.path; this.active = { branch: outcome.branch, end: outcome.end }; @@ -814,6 +924,9 @@ export class PathTool { // The active end steps back with its anchor; a branch that went takes it along. this.afterPathEdit(p.name, next, (q) => { if (!q || q.branches.length < p.branches.length) this.active = null; + // A branch (or the path) with one point left goes too: say so. + const note = anchorDeleteNotice(p, q, branch); + if (note) new Notice(note); }); } @@ -872,13 +985,13 @@ export class PathTool { this.host.refreshBar(); return true; } - const p = this.pathNamed(this.selected); - if (!p) return false; if (this.hover) { - const { branch, anchor } = this.hover; - this.deleteAnchor(p.name, branch, anchor); + const { path, branch, anchor } = this.hover; + this.deleteAnchor(path, branch, anchor); return true; } + const p = this.pathNamed(this.selected); + if (!p) return false; if (this.active) { const a = p.branches[this.active.branch].anchors; this.deleteAnchor(p.name, this.active.branch, this.active.end === "head" ? 0 : a.length - 1); @@ -890,18 +1003,26 @@ export class PathTool { // ── right-click ── /** - * Right-click in the path tool: on an anchor handle of the selected path - * it deletes that anchor ("handled"); on a path it selects it and returns - * the path's menu items; elsewhere null (the usual tool menu). + * Right-click in the path tool (pathContextOutcome): on an anchor of a + * path of the tool's type it deletes that anchor ("handled"); on such a + * line, or Shift+right-click on an anchor, it selects the path and + * returns its menu items; on another type's path, a "Switch to " + * item; elsewhere null (the usual tool menu). */ - contextMenu(e: { clientX: number; clientY: number }): { handled: true } | { items: { label: string; onClick: () => void }[] } | null { + contextMenu(e: { clientX: number; clientY: number; shiftKey?: boolean }): { handled: true } | { items: { label: string; onClick: () => void }[] } | null { if (!this.plugin.paths.isReady(this.map)) return null; const hit = this.hitAt(e); - if (!hit) return null; - if (hit.path === this.selected && hit.anchor !== null) { - this.deleteAnchor(hit.path, hit.branch, hit.anchor); + const outcome = pathContextOutcome(hit, !!e.shiftKey); + if (outcome.kind === "none" || !hit) return null; + if (outcome.kind === "delete-anchor") { + this.deleteAnchor(outcome.path, outcome.branch, outcome.anchor); return { handled: true }; } + if (outcome.kind === "switch") { + const other = this.pathNamed(outcome.path); + if (!other) return null; + return { items: [{ label: `Switch to ${other.typeName} to edit ${other.name}`, onClick: () => this.switchTo(other.name) }] }; + } if (this.selected !== hit.path) { this.selected = hit.path; this.active = null; @@ -926,40 +1047,54 @@ export class PathTool { // ── pointer: hover and drag ── - /** Pointer moved (no button): hover an anchor handle, show "grab" over the selected path. */ - pointerMove(e: { clientX: number; clientY: number }): void { - if (this.drag || this.drawDrag || this.selected === null || this.isDrawing()) { - if (this.hover) { this.hover = null; this.host.redraw(); } - this.host.setGrabCursor(false); - return; - } - const hit = this.hitAt(e); - const over = hit && hit.path === this.selected ? hit : null; - const hover = over && over.anchor !== null ? { branch: over.branch, anchor: over.anchor } : null; - const changed = (hover?.branch ?? -1) !== (this.hover?.branch ?? -1) || (hover?.anchor ?? -1) !== (this.hover?.anchor ?? -1); + /** + * Pointer moved (no button): light up the anchor handle under it, show + * "grab" where a press would drag (an anchor, or a line of the tool's + * type when not drawing), and over another type's path say how to edit it. + */ + pointerMove(e: { clientX: number; clientY: number; altKey?: boolean }, erasing = false): void { + const quiet = !!this.drag || !!this.drawDrag || !this.plugin.paths.isReady(this.map); + const hit = quiet ? null : this.hitAt(e); + // Erasing: nothing is dragged (a click splits), but the hint still shows. + const press = erasing ? "draw" : pathPressOutcome({ forceNew: this.forceNew || !!e.altKey, activeHex: this.activeHex() }, hit); + const hover = hit && press === "move" && hit.anchor !== null ? { path: hit.path, branch: hit.branch, anchor: hit.anchor } : null; + const h = this.hover; + const changed = hover?.path !== h?.path || hover?.branch !== h?.branch || hover?.anchor !== h?.anchor; this.hover = hover; - this.host.setGrabCursor(!!over); + this.host.setGrabCursor(press === "move" || press === "insert"); + const other = hit && !hit.editable ? this.pathNamed(hit.path) : undefined; + const hint = other ? inertHint(other) : null; + const hintChanged = hint !== this.hoverHint; + this.hoverHint = hint; if (changed) this.host.redraw(); + if (hintChanged) this.host.refreshBar(); } /** - * Left button down. Hex by hex: where a click would draw (start a path, - * add to the active end, or continue from an end handle), get ready to - * drag-draw. Otherwise, on the selected path (not while drawing, erasing - * or with Alt), get ready to drag it into a new shape. Returns true when - * it took the press (and stops the browser's own image drag, so a press - * on a hex icon works too). + * Left button down (pathPressOutcome). On an anchor of a path of the + * tool's type, or on such a line when not drawing, get ready to drag it + * into a new shape (the line gets a new anchor where it was grabbed). + * Otherwise, hex by hex, where a click would draw (start a path, add to + * the active end, continue from an end), get ready to drag-draw. A press + * that doesn't move is left to the click. Returns true when it took the + * press (and stops the browser's own image drag, so a press on a hex + * icon works too). */ pointerDown(e: MouseEvent, erasing: boolean): boolean { if (e.button !== 0 || erasing) return false; if (!this.plugin.paths.isReady(this.map)) return false; - if (!this.autoRoute && this.beginDrawDrag(e)) { - e.preventDefault(); - return true; + const forceNew = this.forceNew || e.altKey; + const hit = forceNew ? null : this.hitAt(e); + const press = pathPressOutcome({ forceNew, activeHex: this.activeHex() }, hit); + if (press === "draw" || !hit) { + if (!this.autoRoute && this.beginDrawDrag(e, hit)) { + e.preventDefault(); + return true; + } + return false; } - if (e.altKey || this.forceNew || this.isDrawing() || this.selected === null) return false; - const hit = this.hitAt(e); - if (!hit || hit.path !== this.selected) return false; + // Locked map (Play): no drag preview; the click says why. + if (!canEditPaths(this.map, "draw")) return false; const rb = this.branchRoute(hit.path, hit.branch); if (!rb) return false; const startHex = rb.hexes[hit.anchor !== null ? rb.anchorIdx[hit.anchor] : hit.hexIdx]; @@ -993,12 +1128,12 @@ export class PathTool { // ── hex-by-hex press-and-drag drawing ── /** Hex by hex: a press where a click would draw gets ready to drag-draw (nothing changes until the pointer leaves the hex). */ - private beginDrawDrag(e: MouseEvent): boolean { + private beginDrawDrag(e: MouseEvent, pressHit: PathHit | null): boolean { const key = this.host.hexAtPoint(e.clientX, e.clientY); if (!key) return false; const forceNew = this.forceNew || e.altKey; const activeHex = this.activeHex(); - const hit = !forceNew && activeHex === null ? this.hitAt(e) : null; + const hit = !forceNew && activeHex === null ? pressHit : null; const outcome = pathClickOutcome({ erasing: false, forceNew, activeHex, selected: this.selected }, key, hit); if (outcome.kind !== "start" && outcome.kind !== "append" && outcome.kind !== "finish" && outcome.kind !== "continue") return false; if (outcome.kind === "start" && !(this.typeName ?? this.currentType())) return false; @@ -1154,7 +1289,16 @@ export class PathTool { const d = this.drag; if (!d) return; if (!d.started && Math.hypot(e.clientX - d.startX, e.clientY - d.startY) <= 4) return; - d.started = true; + if (!d.started) { + d.started = true; + // The dragged path is highlighted (a branch being drawn keeps its own selection). + if (!this.isDrawing() && this.selected !== d.path) { + this.selected = d.path; + this.active = null; + this.host.refreshBar(); + } + this.hover = null; + } const hex = this.host.hexAtPoint(e.clientX, e.clientY); if (!hex || hex === d.lastHex) return; d.lastHex = hex; diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts index b38580b2..2bc8c668 100644 --- a/src/hex-map/toolMode.ts +++ b/src/hex-map/toolMode.ts @@ -71,20 +71,23 @@ export function toolModeLabel(s: ToolModeState): string | null { return `Painting ${what}: ${baseName(s.iconName)}`; } case "path": { - if (erasing) return "Erasing paths: click a path to split it there"; + // Paths of the tool's type are always live: these are exactly what + // pathClickOutcome / pathPressOutcome / pathContextOutcome do. const type = s.pathTypeName ?? "Path"; - const how = s.pathAuto ? "auto-routes" : "hex by hex"; const note = s.pathNote ? ` · ${s.pathNote}` : ""; + if (erasing) return `Erasing paths: click a ${s.pathTypeName ?? "path"} to split it there${note}`; + const how = s.pathAuto ? "auto-routes" : "hex by hex"; + const edit = "drag a point or the line to reshape · right-click a point to delete it"; if (s.pathNew) return `New ${type}: click where it starts`; if (s.pathDrawing) { const name = s.pathSelected ?? `New ${type}`; - return `${name}: click to add (${how}) · Esc to finish${note}`; + return `${name}: click to add (${how}) · drag a point to move it · Esc to finish${note}`; } if (s.pathSelected) { const what = s.pathSummary && s.pathSummary !== s.pathSelected ? ` (${s.pathSummary})` : ""; - return `${s.pathSelected}${what}: drag the line to reshape · click an end to continue · click the line to fork${note}`; + return `${s.pathSelected}${what}: ${edit} · click an end to continue · click the line to fork · click empty ground for a new ${type}${note}`; } - return `${type}: click to start a path · click a path to edit it${note}`; + return `${type}: click empty ground to start · ${edit} · click an end to continue${note}`; } case "tableLink": return erasing ? "Unlinking tables" : `Linking table: ${baseName(s.tablePath) || "…"}`; diff --git a/tests/autoRoute.test.ts b/tests/autoRoute.test.ts index 2f412435..8d210959 100644 --- a/tests/autoRoute.test.ts +++ b/tests/autoRoute.test.ts @@ -234,13 +234,14 @@ describe("auto-routed rivers wind (round 7 U17)", () => { describe("a new path never joins or reshapes another (round 7 R11, anchored paths)", () => { // The region tester's map: road keep (12_8) → Gullmouth (7_5), then a // second road from the keep to the east edge. With anchored paths a - // click on a path selects it; Alt-click or "New path" starts a new one. + // click on a path of the tool's type selects it (an end + // continues it); another type's path is ground; Alt-click or "New path" starts a new one. const ctx = { orientation: "flat" as const, stagger: "odd" as const, bounds: bounds(20, 16), blocked: new Set() }; const first = (): MapPath[] => [ { name: "Road", typeName: "Road", branches: [{ anchors: ["12_8", "7_5"] }] }, { name: "River", typeName: "River", branches: [{ anchors: ["11_13", "9_13"] }] }, ]; - const onRoad = (hexIdx: number, o: Partial = {}): PathHit => ({ path: "Road", branch: 0, hexIdx, anchor: null, end: null, ...o }); + const onRoad = (hexIdx: number, o: Partial = {}): PathHit => ({ path: "Road", branch: 0, hexIdx, hex: "", anchor: null, end: null, editable: true, ...o }); const idle = { erasing: false, forceNew: false, activeHex: null, selected: null }; it("clicking the first road's first hex selects that road; it doesn't start a road joined to it", () => { diff --git a/tests/pathTool.test.ts b/tests/pathTool.test.ts index 64c26b42..123b47fe 100644 --- a/tests/pathTool.test.ts +++ b/tests/pathTool.test.ts @@ -1,7 +1,8 @@ /** * The path tool's pure parts (plan-path-anchors section 4, phase 5): * hit-testing a pointer against the drawn polylines and anchor handles, - * the click table (replacing the old hex-by-hex pathClickOutcome), and + * the click, press and right-click tables (paths of the tool's type are + * always live, other types inert: no separate edit mode), and * where a drag on the line inserts its anchor. */ import { describe, it } from "node:test"; @@ -12,7 +13,11 @@ import { distToPolyline, hitTestPaths, nearestHexIdx, + anchorDeleteNotice, + inertHint, pathClickOutcome, + pathContextOutcome, + pathPressOutcome, pathSummary, type PathClickState, type PathHit, @@ -20,7 +25,7 @@ import { import { buildPathStrokes, latticeCenter, type LatticeGrid } from "../src/paths/pathGeometry"; import { resolvePaths } from "../src/paths/resolve"; import type { RouteContext } from "../src/paths/router"; -import { insertAnchorAt, moveAnchor } from "../src/paths/edit"; +import { deleteAnchor, insertAnchorAt, moveAnchor } from "../src/paths/edit"; import { UNKNOWN_PATH_TYPE } from "../src/constants"; const ROAD: PathType = { name: "Road", color: "#a33", width: 4, lineStyle: "solid", routing: "through", avoidImpassable: true, autoRoute: "direct" }; @@ -57,23 +62,45 @@ describe("hit-testing paths (pure, lattice units)", () => { expect(distToPolyline({ cx: 0, cy: 1 }, [{ cx: -1, cy: 0 }, { cx: 1, cy: 0 }])).toBeCloseTo(1); }); - it("anchor handles count only on the selected path; ends are marked head / tail, a fork's start isn't an end", () => { + it("every path of the tool's type has live anchor handles (no selecting first); ends are marked head / tail, a fork's start isn't an end", () => { const { resolved, strokes } = scene(); - expect(hitTestPaths(at("9_5"), strokes, resolved, grid, null)?.anchor).toBeNull(); - expect(hitTestPaths(at("9_5"), strokes, resolved, grid, "King's Road")).toMatchObject({ branch: 0, anchor: 1, end: "tail" }); - expect(hitTestPaths(at("1_5"), strokes, resolved, grid, "King's Road")).toMatchObject({ branch: 0, anchor: 0, end: "head" }); + expect(hitTestPaths(at("9_5"), strokes, resolved, grid, null)).toMatchObject({ branch: 0, anchor: 1, end: "tail", hex: "9_5", editable: true }); + expect(hitTestPaths(at("1_5"), strokes, resolved, grid, null)).toMatchObject({ branch: 0, anchor: 0, end: "head" }); + const roads = (n: string) => n === "King's Road"; + expect(hitTestPaths(at("9_5"), strokes, resolved, grid, null, roads)).toMatchObject({ path: "King's Road", anchor: 1, editable: true }); const fork = resolved.find((r) => r.path === "King's Road" && r.branch === 1)!; expect(fork.forkFrom).toBeDefined(); expect(anchorEnd(fork, 0)).toBeNull(); expect(anchorEnd(fork, 1)).toBe("tail"); }); - it("where lines overlap, the selected path wins", () => { + it("another type's path is inert: no anchor handles, its line is reported as not editable", () => { + const { resolved, strokes } = scene(); + const roadsOnly = (n: string) => n === "King's Road"; + // The river's start anchor: no handle for the road tool, and a point on its line is inert. + const river = resolved.find((r) => r.path === "Glass River")!; + expect(hitTestPaths(at("12_1"), strokes, resolved, grid, null)).toMatchObject({ path: "Glass River", anchor: 0, editable: true }); + expect(hitTestPaths(at("12_1"), strokes, resolved, grid, null, roadsOnly)?.anchor ?? null).toBeNull(); + const s = strokes.find((x) => x.path === "Glass River")!; + const mid = s.pts[Math.floor(s.pts.length / 2)]; + expect(hitTestPaths(mid, strokes, resolved, grid, null, roadsOnly)).toMatchObject({ path: "Glass River", anchor: null, end: null, editable: false }); + expect(river.hexes.length).toBeGreaterThan(2); + }); + + it("where lines overlap, the tool's type beats an inert path, then the selected path wins", () => { // Old Track runs along part of the King's Road (every hex an anchor: exact). const kings = resolvePaths([KINGS], ctx).find((r) => r.branch === 0)!.hexes; const over: MapPath = { name: "Old Track", typeName: "Road", branches: [{ anchors: kings.slice(2, 6) }] }; const { resolved, strokes } = scene([over, KINGS]); - for (const sel of ["Old Track", "King's Road"]) expect(hitTestPaths(at(kings[3]), strokes, resolved, grid, sel)?.path).toBe(sel); + // A point on the line between two of Old Track's anchors (no handle there). + const a = latticeCenter(kings[3], grid); + const b = latticeCenter(kings[4], grid); + const mid = { cx: (a.cx + b.cx) / 2, cy: (a.cy + b.cy) / 2 }; + for (const sel of ["Old Track", "King's Road"]) expect(hitTestPaths(mid, strokes, resolved, grid, sel)?.path).toBe(sel); + // Only the King's Road is editable: it wins even when Old Track is selected. + expect(hitTestPaths(mid, strokes, resolved, grid, "Old Track", (n) => n === "King's Road")).toMatchObject({ path: "King's Road", editable: true }); + // Stacked anchor handles: the selected path's first. + expect(hitTestPaths(at(kings[3]), strokes, resolved, grid, "Old Track")).toMatchObject({ path: "Old Track", anchor: 1 }); }); it("nearestHexIdx breaks ties toward the lower index", () => { @@ -107,13 +134,21 @@ describe("dragging the line inserts an anchor in the segment under the pointer", }); }); -describe("pathClickOutcome: the click table", () => { +describe("pathClickOutcome: the click table (paths of the tool's type are always live)", () => { const S = (o: Partial = {}): PathClickState => ({ erasing: false, forceNew: false, activeHex: null, selected: null, ...o }); - const hit = (o: Partial = {}): PathHit => ({ path: "King's Road", branch: 0, hexIdx: 3, anchor: null, end: null, ...o }); + const hit = (o: Partial = {}): PathHit => ({ path: "King's Road", branch: 0, hexIdx: 3, hex: "4_5", anchor: null, end: null, editable: true, ...o }); - it("nothing selected: an empty hex starts a path, a path is selected", () => { + it("empty ground starts a path; a line of the tool's type is selected; an end continues it with nothing selected first", () => { expect(pathClickOutcome(S(), "4_4", null)).toEqual({ kind: "start" }); expect(pathClickOutcome(S(), "4_5", hit())).toEqual({ kind: "select", path: "King's Road" }); + expect(pathClickOutcome(S(), "9_5", hit({ anchor: 1, end: "tail" }))).toEqual({ kind: "continue", path: "King's Road", branch: 0, end: "tail" }); + expect(pathClickOutcome(S(), "1_5", hit({ anchor: 0, end: "head" }))).toEqual({ kind: "continue", path: "King's Road", branch: 0, end: "head" }); + }); + + it("another type's path is ground: a click there starts a new path (no hijacking)", () => { + expect(pathClickOutcome(S(), "12_3", hit({ path: "Glass River", editable: false }))).toEqual({ kind: "start" }); + expect(pathClickOutcome(S(), "12_9", hit({ path: "Glass River", editable: false, anchor: null, end: null }))).toEqual({ kind: "start" }); + expect(pathClickOutcome(S({ selected: "King's Road" }), "12_3", hit({ path: "Glass River", editable: false }))).toEqual({ kind: "start" }); }); it("drawing: every click adds an anchor (far or near); the active end again finishes", () => { @@ -122,13 +157,12 @@ describe("pathClickOutcome: the click table", () => { expect(pathClickOutcome(S({ activeHex: "9_5" }), "9_5", hit())).toEqual({ kind: "finish" }); }); - it("selected: an end continues it, anywhere else on it forks, another path is selected, empty map deselects", () => { + it("selected: the line again forks, an end continues, another path of the type is selected, empty ground starts a new one", () => { const sel = S({ selected: "King's Road" }); expect(pathClickOutcome(sel, "9_5", hit({ anchor: 1, end: "tail" }))).toEqual({ kind: "continue", path: "King's Road", branch: 0, end: "tail" }); - expect(pathClickOutcome(sel, "1_5", hit({ anchor: 0, end: "head" }))).toEqual({ kind: "continue", path: "King's Road", branch: 0, end: "head" }); expect(pathClickOutcome(sel, "4_5", hit())).toEqual({ kind: "fork", path: "King's Road", branch: 0, hexIdx: 3 }); - expect(pathClickOutcome(sel, "12_3", hit({ path: "Glass River" }))).toEqual({ kind: "select", path: "Glass River" }); - expect(pathClickOutcome(sel, "3_12", null)).toEqual({ kind: "deselect" }); + expect(pathClickOutcome(sel, "12_3", hit({ path: "Old Track" }))).toEqual({ kind: "select", path: "Old Track" }); + expect(pathClickOutcome(sel, "3_12", null)).toEqual({ kind: "start" }); }); it("Alt-click / New path always starts a new path, even on another path", () => { @@ -136,11 +170,67 @@ describe("pathClickOutcome: the click table", () => { expect(pathClickOutcome(S({ forceNew: true, activeHex: "9_5" }), "4_5", null)).toEqual({ kind: "start" }); }); - it("erase mode splits the path under the pointer, and does nothing elsewhere", () => { + it("erase mode splits a path of the tool's type under the pointer, and does nothing elsewhere or on another type", () => { expect(pathClickOutcome(S({ erasing: true }), "4_5", hit())).toEqual({ kind: "split", path: "King's Road", branch: 0, hexIdx: 3 }); expect(pathClickOutcome(S({ erasing: true }), "4_4", null)).toEqual({ kind: "none" }); + expect(pathClickOutcome(S({ erasing: true }), "12_3", hit({ path: "Glass River", editable: false }))).toEqual({ kind: "none" }); + }); +}); + +describe("pathPressOutcome: what a left press gets ready to do", () => { + const P = (o: Partial<{ forceNew: boolean; activeHex: string | null }> = {}) => ({ forceNew: false, activeHex: null, ...o }); + const hit = (o: Partial = {}): PathHit => ({ path: "King's Road", branch: 0, hexIdx: 3, hex: "4_5", anchor: null, end: null, editable: true, ...o }); + + it("an anchor of the tool's type moves (ends too: a click on an end still continues), the line inserts an anchor and moves it", () => { + expect(pathPressOutcome(P(), hit({ anchor: 1, hex: "6_5" }))).toBe("move"); + expect(pathPressOutcome(P(), hit({ anchor: 2, end: "tail", hex: "9_5" }))).toBe("move"); + expect(pathPressOutcome(P(), hit())).toBe("insert"); + }); + + it("while drawing: other anchors still move, the active end and lines draw on", () => { + expect(pathPressOutcome(P({ activeHex: "15_2" }), hit({ anchor: 1, hex: "6_5" }))).toBe("move"); + expect(pathPressOutcome(P({ activeHex: "9_5" }), hit({ anchor: 2, end: "tail", hex: "9_5" }))).toBe("draw"); + expect(pathPressOutcome(P({ activeHex: "15_2" }), hit())).toBe("draw"); + }); + + it("another type's path, empty ground, Alt / New path: draw", () => { + expect(pathPressOutcome(P(), hit({ editable: false }))).toBe("draw"); + expect(pathPressOutcome(P(), null)).toBe("draw"); + expect(pathPressOutcome(P({ forceNew: true }), hit({ anchor: 1 }))).toBe("draw"); }); +}); + +describe("pathContextOutcome: right-click", () => { + const hit = (o: Partial = {}): PathHit => ({ path: "King's Road", branch: 1, hexIdx: 3, hex: "4_5", anchor: null, end: null, editable: true, ...o }); + + it("an anchor of the tool's type is deleted; Shift opens the path's menu instead", () => { + expect(pathContextOutcome(hit({ anchor: 2 }), false)).toEqual({ kind: "delete-anchor", path: "King's Road", branch: 1, anchor: 2 }); + expect(pathContextOutcome(hit({ anchor: 2 }), true)).toEqual({ kind: "menu", path: "King's Road", branch: 1, hexIdx: 3 }); + }); + + it("the line opens the path's menu; another type's path offers a switch; nothing: the tool menu", () => { + expect(pathContextOutcome(hit(), false)).toEqual({ kind: "menu", path: "King's Road", branch: 1, hexIdx: 3 }); + expect(pathContextOutcome(hit({ path: "Glass River", editable: false }), false)).toEqual({ kind: "switch", path: "Glass River" }); + expect(pathContextOutcome(null, false)).toEqual({ kind: "none" }); + }); + + it("the hover hint over an inert path names its type", () => { + expect(inertHint(GLASS)).toBe("Glass River is a River: switch to River to edit it"); + }); +}); + +describe("deleting an anchor that leaves one point", () => { + it("says the branch or path went, and that undo brings it back; an ordinary delete says nothing", () => { + const one: MapPath = { name: "Lane", typeName: "Road", branches: [{ anchors: ["0_0", "3_0"] }] }; + expect(anchorDeleteNotice(one, deleteAnchor(one, 0, 1), 0)).toBe("Deleted Lane: it had one point left. Undo brings it back."); + expect(anchorDeleteNotice(KINGS, deleteAnchor(KINGS, 1, 1), 1)).toBe("Deleted a fork of King's Road: it had one point left. Undo brings it back."); + expect(anchorDeleteNotice(KINGS, deleteAnchor(KINGS, 0, 0), 0)).toBe("Deleted the main line of King's Road: it had one point left. Undo brings it back."); + const three: MapPath = { name: "Lane", typeName: "Road", branches: [{ anchors: ["0_0", "3_0", "6_0"] }] }; + expect(anchorDeleteNotice(three, deleteAnchor(three, 0, 1), 0)).toBeNull(); + }); +}); +describe("pathTool summaries", () => { it("the mode bar summary names the type and forks", () => { expect(pathSummary(KINGS)).toBe("Road, 1 fork"); expect(pathSummary(GLASS)).toBe("River"); diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index fa13de79..c221b40e 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -68,7 +68,9 @@ describe("Path tool right-click and tokens (fresh-eyes T2)", () => { const menu = toolMethod("contextMenu"); expect(menu).toMatch(/pathMenuItems\(p, branch, \{/); // The labels and their order: tests/pathToolPolish.test.ts (#48). - expect(menu).toMatch(/hit\.anchor !== null\) \{\s*this\.deleteAnchor\(/); + expect(menu).toMatch(/outcome\.kind === "delete-anchor"\) \{\s*this\.deleteAnchor\(/); + // Shift+right-click reaches the menu (the click table: tests/pathTool.test.ts). + expect(menu).toMatch(/pathContextOutcome\(hit, !!e\.shiftKey\)/); }); it("tokens let clicks through while a drawing tool is active", () => { @@ -93,11 +95,13 @@ describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => expect(toolModeLabel({ mode: "terrain", erasing: false, terrainPick: true })).toMatch(/^Picking terrain/); expect(toolModeLabel({ mode: "icon", erasing: false, iconName: "bw-castle.svg" })).toBe("Painting icon: bw-castle"); expect(toolModeLabel({ mode: "icon", erasing: false, iconName: "x.png", iconGmOnly: true })).toBe("Painting GM icon: x"); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road" })).toBe("Road: click to start a path · click a path to edit it"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road" })).toBe("Road: click empty ground to start · drag a point or the line to reshape · right-click a point to delete it · click an end to continue"); expect(toolModeLabel({ mode: "path", erasing: true })).toMatch(/^Erasing paths: click a path to split it/); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathAuto: true, pathDrawing: true, pathSelected: "King's Road" })).toBe("King's Road: click to add (auto-routes) · Esc to finish"); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathDrawing: true, pathNote: "not next to the end, so the gap was routed" })).toBe("New Road: click to add (hex by hex) · Esc to finish · not next to the end, so the gap was routed"); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathSelected: "King's Road", pathSummary: "Road, 2 forks" })).toBe("King's Road (Road, 2 forks): drag the line to reshape · click an end to continue · click the line to fork"); + expect(toolModeLabel({ mode: "path", erasing: true, pathTypeName: "Road" })).toBe("Erasing paths: click a Road to split it there"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathNote: "Glass River is a River: switch to River to edit it" })).toMatch(/ · Glass River is a River: switch to River to edit it$/); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathAuto: true, pathDrawing: true, pathSelected: "King's Road" })).toBe("King's Road: click to add (auto-routes) · drag a point to move it · Esc to finish"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathDrawing: true, pathNote: "not next to the end, so the gap was routed" })).toBe("New Road: click to add (hex by hex) · drag a point to move it · Esc to finish · not next to the end, so the gap was routed"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathSelected: "King's Road", pathSummary: "Road, 2 forks" })).toBe("King's Road (Road, 2 forks): drag a point or the line to reshape · right-click a point to delete it · click an end to continue · click the line to fork · click empty ground for a new Road"); expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathNew: true })).toBe("New Road: click where it starts"); expect(toolModeLabel({ mode: "regionLink", erasing: false, regionPath: "world/regions/Kerrigan.md" })).toBe("Painting region area: Kerrigan"); expect(toolModeLabel({ mode: "factionLink", erasing: true })).toBe("Erasing factions"); From f9459694c5479ef37264746fb9935d0bae5aadff Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:12:04 -0400 Subject: [PATCH 279/558] fix(world-types): editor tab counts follow added and removed rows Co-Authored-By: Claude Opus 5.5 --- src/space/WorldTypesModal.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts index 331d5731..9d5e9d0f 100644 --- a/src/space/WorldTypesModal.ts +++ b/src/space/WorldTypesModal.ts @@ -122,6 +122,7 @@ export class WorldTypesModal extends HexmakerModal { private previewEl!: HTMLElement; private saveBtn!: HTMLButtonElement; private statusEl!: HTMLElement; + private tabButtons = new Map(); private preview: { map: WorldTypeMap | ""; zone: OrbitZone | ""; star: string; temperature: string; n: number } = { map: "", zone: "", star: "", temperature: "", n: 200 }; /** `mapName`: the map it was opened for (work mode, preview's map kind). `tab`: the tab to open on. */ @@ -273,6 +274,7 @@ export class WorldTypesModal extends HexmakerModal { } const tabs = contentEl.createDiv({ cls: "duckmage-world-types-tabs", attr: { role: "tablist" } }); + this.tabButtons.clear(); for (const t of TAB_ORDER) { const b = tabs.createEl("button", { text: `${TABS[t].label} (${this.cells[t].length})`, @@ -280,6 +282,7 @@ export class WorldTypesModal extends HexmakerModal { attr: { role: "tab", "aria-selected": String(t === this.tab) }, }); b.toggleClass("is-active", t === this.tab); + this.tabButtons.set(t, b); b.addEventListener("click", () => { if (t === this.tab) return; this.tab = t; @@ -341,6 +344,7 @@ export class WorldTypesModal extends HexmakerModal { private changed(): void { this.dirty = true; + for (const [t, b] of this.tabButtons) b.setText(`${TABS[t].label} (${this.cells[t].length})`); this.updateStatus(); this.renderPreview(); } From 1e089a957deb82d84657cf9027e9d8b9be92791f Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:20:42 -0400 Subject: [PATCH 280/558] feat(palettes): palette pickers preview the picked palette's terrains (E4) Setup wizard, New map and the submap picker show a compact swatch grid (terrain count, colours, names on hover) under the one-line description. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 ++-- src/HexmakerPlugin.ts | 4 +++- src/palettes/paletteOptions.ts | 40 ++++++++++++++++++++++++++++++++-- styles.css | 26 ++++++++++++++++++++++ tests/palettePreview.test.ts | 27 +++++++++++++++++++++++ 5 files changed, 96 insertions(+), 5 deletions(-) create mode 100644 tests/palettePreview.test.ts diff --git a/package.json b/package.json index 8c16b458..6d2e8fbe 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index b90c5593..8ac36efa 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -42,7 +42,7 @@ import { setPathEditMapLookup } from "./paths/editGate"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; import { enabledKinds, isIconHiddenByKind, isSpacePalette, newTerrains, resolveMapKinds, sectionKindFor, sectionWordsFor, terrainsForTables, type SectionWordsFn } from "./mapKinds"; import { enableFeature, hasFeature, resolveFeatureLevel, shouldNudge, type AdvancedFeature, type FeatureLevel } from "./featureLevel"; -import { defaultPaletteFor, resolveDefaultPalette, resolveExpandedDefault } from "./palettes/paletteOptions"; +import { defaultPaletteFor, resolveDefaultPalette, resolveExpandedDefault, setPaletteTerrainSource } from "./palettes/paletteOptions"; import { AdvancedNudgeModal, EnableFeatureModal } from "./advancedHints"; import { mapAncestors } from "./hex-map/submapNav"; import { @@ -152,6 +152,8 @@ export default class HexmakerPlugin extends Plugin { this.tableTerrainNames = new Set(this.tableTerrains().map((t) => t.name)); // Icon pickers open on the Space tab for space-only setups. setIconPackDefault(() => defaultIconPack(this.settings)); + // Palette pickers preview the picked palette's terrains (E4). + setPaletteTerrainSource((name) => this.getPaletteOrPresetTerrains(name)); setHexDataSource(this.mapStore); setPathEditMapLookup((name) => this.getMap(name)); setModeMapLookup((name) => this.getMap(name)); diff --git a/src/palettes/paletteOptions.ts b/src/palettes/paletteOptions.ts index b12626ea..80515927 100644 --- a/src/palettes/paletteOptions.ts +++ b/src/palettes/paletteOptions.ts @@ -20,17 +20,53 @@ export function paletteHint(name: string): string { const hintUpdaters = new WeakMap void>(); +/** A palette's (or preset's) terrains by name; the plugin sets it on load. */ +let terrainSource: ((paletteName: string) => readonly { name: string; color: string }[]) | null = null; + +/** Where palette previews read a palette's terrains (HexmakerPlugin.onload). */ +export function setPaletteTerrainSource(fn: typeof terrainSource): void { + terrainSource = fn; +} + +/** + * The swatches a palette preview shows (E4): each terrain once, in palette + * order, with its colour; a terrain without a colour shows grey. + */ +export function paletteSwatchList(terrains: readonly { name: string; color?: string }[]): { name: string; color: string }[] { + const seen = new Set(); + const out: { name: string; color: string }[] = []; + for (const t of terrains) { + const key = t.name.trim().toLowerCase(); + if (!key || seen.has(key)) continue; + seen.add(key); + out.push({ name: t.name.trim(), color: /^#[0-9a-f]{3,8}$/i.test(t.color ?? "") ? t.color! : "#888888" }); + } + return out; +} + /** * Add a muted line to `parent` that says what the palette picked in - * `select` is for (Limited / Expanded); empty for other palettes. Follows - * the select's changes, and refills by fillPaletteSelect. + * `select` is for (Limited / Expanded; empty for other palettes), and a + * compact grid of its terrains' colours, named on hover (E4). Follows the + * select's changes, and refills by fillPaletteSelect. */ export function attachPaletteHint(parent: HTMLElement, select: HTMLSelectElement): void { const hint = parent.createDiv({ cls: "setting-item-description duckmage-palette-hint" }); + const preview = parent.createDiv({ cls: "duckmage-palette-preview" }); const update = () => { const text = paletteHint(select.value); hint.setText(text); hint.toggle(!!text); + const swatches = paletteSwatchList(terrainSource?.(select.value) ?? []); + preview.empty(); + preview.toggle(swatches.length > 0); + if (!swatches.length) return; + preview.createSpan({ cls: "duckmage-palette-preview-count", text: `${swatches.length} terrain${swatches.length === 1 ? "" : "s"}` }); + const grid = preview.createDiv({ cls: "duckmage-palette-swatches" }); + for (const s of swatches) { + const sw = grid.createSpan({ cls: "duckmage-palette-swatch", attr: { title: s.name, "aria-label": s.name } }); + sw.setCssProps({ "--duckmage-swatch": s.color }); + } }; hintUpdaters.set(select, update); select.addEventListener("change", update); diff --git a/styles.css b/styles.css index 6f1b39ad..6b2bcbab 100644 --- a/styles.css +++ b/styles.css @@ -8775,3 +8775,29 @@ textarea.duckmage-edit-region-notes-input { stroke: #d7deff; opacity: 0.55; } +/* E4: a palette picker shows the picked palette's terrains (named on hover). */ +.duckmage-palette-preview { + display: flex; + align-items: flex-start; + gap: 6px; + margin-top: 4px; + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} +.duckmage-palette-preview-count { + flex: none; + line-height: 14px; +} +.duckmage-palette-swatches { + display: flex; + flex-wrap: wrap; + gap: 2px; + max-width: 280px; +} +.duckmage-palette-swatch { + width: 14px; + height: 14px; + border-radius: 3px; + background: var(--duckmage-swatch, #888888); + border: 1px solid var(--background-modifier-border); +} diff --git a/tests/palettePreview.test.ts b/tests/palettePreview.test.ts new file mode 100644 index 00000000..b4406542 --- /dev/null +++ b/tests/palettePreview.test.ts @@ -0,0 +1,27 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { paletteSwatchList } from "../src/palettes/paletteOptions"; +import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; + +describe("palette preview swatches (E4)", () => { + it("lists each terrain once, in palette order, with its colour", () => { + expect(paletteSwatchList([ + { name: "grass", color: "#88cc66" }, + { name: " Grass ", color: "#000000" }, + { name: "sea", color: "#2255aa" }, + { name: "", color: "#ffffff" }, + ])).toEqual([{ name: "grass", color: "#88cc66" }, { name: "sea", color: "#2255aa" }]); + }); + + it("shows a terrain without a usable colour as grey", () => { + expect(paletteSwatchList([{ name: "fog" }, { name: "ash", color: "red; background: url(x)" }])) + .toEqual([{ name: "fog", color: "#888888" }, { name: "ash", color: "#888888" }]); + }); + + it("tells Limited from Expanded at a glance", () => { + const limited = paletteSwatchList(LIMITED_TERRAIN_PALETTE); + const expanded = paletteSwatchList(DEFAULT_TERRAIN_PALETTE); + expect(limited.length).toBeGreaterThan(0); + expect(expanded.length).toBeGreaterThan(limited.length); + }); +}); From 9ce210d525f26f8913ae1c1a5e1a8bcab3d0e956 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:26:42 -0400 Subject: [PATCH 281/558] fix(region-detail): a land neighbour's terrain always shows as a strip along its side (U6) A side where the blend made few hexes of the neighbour's kind (a swamp beside a forest hex) now stamps the hexes that side reaches hardest, so the south-west swamp carries in as a corner patch instead of one hex. Co-Authored-By: Claude Opus 5.5 --- src/worldgen/procedural/planetSurface.ts | 16 ++++++++++++++++ tests/regionContext.test.ts | 14 ++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/worldgen/procedural/planetSurface.ts b/src/worldgen/procedural/planetSurface.ts index a8647cd2..57155b38 100644 --- a/src/worldgen/procedural/planetSurface.ts +++ b/src/worldgen/procedural/planetSurface.ts @@ -901,6 +901,8 @@ function regionField( } const SEA_TYPES = new Set(["water", "deep-water", "shallows"]); +/** Fewest hexes a land neighbour's terrain gets along its side (when its land reaches that far). */ +const MIN_SIDE_STAMP = 3; /** * Region detail's card promises e.g. "evergreen heavy on the north-east and @@ -946,6 +948,20 @@ function stampNeighbourTerrains( cells.set(k, name); stamped++; }); + // Few or none of its kind turned up (a swamp beside a forest hex: the + // blend rarely makes wetland): the hexes that side reaches hardest + // still take its terrain, a ragged strip along that edge (round 6 U6: + // the swamp to the south-west showed as one corner hex at most). + if (stamped < MIN_SIDE_STAMP) { + hexes.forEach(([x, y], i) => { + const o = owner[i]; + if (!o || o.s !== s || isSea[i] || o.w < 0.45 + (noise[i] - 0.5) * 0.3) return; + const k = cellKey(x, y); + if (cells.get(k) === name) return; + cells.set(k, name); + stamped++; + }); + } if (stamped > 0) continue; let best = -1; hexes.forEach((_, i) => { diff --git a/tests/regionContext.test.ts b/tests/regionContext.test.ts index e906ca4b..67443a98 100644 --- a/tests/regionContext.test.ts +++ b/tests/regionContext.test.ts @@ -169,3 +169,17 @@ describe("Region detail keeps its card's promise (fresh-eyes round 7)", () => { expect(ever).toBeLessThan(forest / 2); }); }); + +describe("Region detail carries a corner neighbour in (round 6 U6)", () => { + it("a swamp to the south-west of a forest hex shows as a patch in that corner, not one hex at most", () => { + const ty = (n: string) => DEFAULT_TERRAIN_PALETTE.find((t) => t.name === n)?.type; + const c = (n: string) => ({ terrain: n, type: ty(n) }); + const ctx: GenerationContext = { parent: c("mixed forest heavy"), sides: { N: c("grass"), NE: c("mixed forest"), NW: c("mixed forest"), SE: c("mixed forest hills"), SW: c("swamp") } }; + const g: ProcGrid = { cols: 13, rows: 13, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; + for (let seed = 1; seed <= 10; seed++) { + const swampy = [...planetSurface(DEFAULT_TERRAIN_PALETTE, g, seed, {}, ctx).cells] + .filter(([k, t]) => t === "swamp" && Number(k.split("_")[0]) <= 3 && Number(k.split("_")[1]) >= 9); + expect(swampy.length).toBeGreaterThanOrEqual(3); + } + }); +}); From fb2551822848489dbe283fa8603bb38cc6a0d330 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:27:34 -0400 Subject: [PATCH 282/558] docs: Map data callout edits, moon tethers, palette swatches, Region detail corner neighbours Co-Authored-By: Claude Opus 5.5 --- README.md | 10 ++++++---- src/hex-map/help.md | 6 +++++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 50c66362..0144f029 100644 --- a/README.md +++ b/README.md @@ -111,8 +111,8 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **World biomes** (Advanced) — an overworld: one biome per hex, laid out by temperature, moisture and height, with transition biomes (taiga between tundra and forest, savanna between jungle and badlands) where two shouldn't touch. Its hexes open into regions that blend with each other. - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. -- **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it. -- **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). +- **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it; a land neighbour always shows as at least a small strip or corner patch on its side (a swamp to the south-west, say). +- **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one; the map draws a faint dashed tether from each moon to the world or gas giant beside it, hidden with the paths), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). - **World types** (Advanced: Terrain generators) — which worlds the space generators place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types` (**Default space** ships, with the odds Star scatter and Orbits have always used; **Restore default** puts them back). Each row is a world (a terrain of your palette) with a **Weight** and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature**. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows, and a preview rolls the table for a map, orbit, star and temperature and shows how often each world comes up next to its odds. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. @@ -308,7 +308,7 @@ Every command, as it appears in the command palette: | **Hexmap World Creator: Go up to parent map** | From a submap, back to the map it belongs to. | | **Hexmap World Creator: Go back to previous map** | Returns to the map you were on before. | | **Hexmap World Creator: Go forward to the next map** | After going back, forward again (like a browser). | -| **Hexmap World Creator: Add map data to this map's hex notes** | Adds a Map data box (terrain, region, name, from the map) under the title of every hex note of the open map, kept up to date when you open a hex. New hex notes from the built-in template already have one. | +| **Hexmap World Creator: Add map data to this map's hex notes** | Adds a Map data box (terrain, region, name, from the map) under the title of every hex note of the open map, kept up to date when you open a hex. New hex notes from the built-in template already have one. Edits you typed into existing boxes are put on the map first (see Map data in hex notes). | | **Hexmap World Creator: Update map data in region and faction notes** | Adds or updates a Map data box under the title of every region and faction note: the maps that use it (with hex counts) and, for regions, the encounter table. Kept up to date when you open the note. | | **Hexmap World Creator: Export current map…** | Opens the map export form (PNG, PDF, hexcrawl manual). | | **Hexmap World Creator: Export current note to PDF** | Exports the open note as a PDF. | @@ -346,7 +346,7 @@ Open **Settings → Hexmap World Creator** to configure: | **Biome pools folder** | Folder holding the biome pool notes used by Generate overworld (default `{world folder}/biome-pools`). | | **World types folder** | Folder holding the world types tables used by the space generators (default `{world folder}/world-types`). | | **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | -| **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too. | +| **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too, and show the picked palette's terrains as a row of colour swatches (names on hover) under the menu. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | --- @@ -359,6 +359,8 @@ Paths are stored by name in two tables. **Paths** has one row per path: *Path* ( The plugin also writes a few things for you to read, worked out from the tables and the map's palette. A **Summary** section above the Hexes table shows the palette (as a link), the map's extent (`−7…30 × −8…16 (38×25)`), the base terrain, a terrain legend with hex counts, the regions on the map, its region settings, how many region maps and locations open from its hexes, and any terrain or path type that isn't in the palette (⚠). In **Paths**, the *Route* column shows where each path's main line starts and ends, how many forks it has and how many hexes it covers (`0, 8 → 13, 8 · 2 forks · 31 hexes`), with a ⚠ when its type isn't one of the palette's path types, it has no type yet, or a stretch can't be routed and is drawn straight. These are never read back: they're rewritten on each save, so edits to them are replaced, and a deleted Summary comes back. Text you type under the Summary, or a Summary heading of your own, is left alone. Map notes from before this are given them once, after a backup. +**Map data in hex notes.** A hex note from the built-in template has a **Map data** box under its title: the hex's map and coordinates, terrain, region and name, plus its region map and locations (as links) when it has them, and its biome on an overworld (linked to the biome note). The map note is where these live; the box is a copy, refreshed when you open the hex in the hex editor or open the note. You can edit **Terrain**, **Region** and **Name** in the box: when you leave the note (or open the hex editor, or run *Add map data to this map's hex notes*), the change goes onto the map, as one undo step. It doesn't if the map has changed that value since the box was last written (the map's value is newer), if the map's mode locks it (Play can't paint terrain or regions; names are fine), or if the terrain isn't in the map's palette. Those edits stay in the box as a `Not applied:` line saying why, lines it can't read become `Not read:` lines, and a notice tells you; delete those lines when you're done with them. Change the map, region map, locations and biome on the map itself. The plugin keeps what each box last showed in `map-data-shown.json` in its folder; a note it has no record of (first run, another device) just gets its box refreshed from the map. + Hand edits are forgiving. Each setting is one plain property (the parent map and background image are links, e.g. `parent: "[[_coast]]"` with `parent-hex: 3, 4`), so the Properties panel can edit them too, and deleting a property resets that setting. In the tables, headers can be in any case and any order, you can add your own columns (they're kept), the `| --- |` row is optional, hexes can be written `3_4`, `3, 4` or as a link, and `yes`/`true`/`x`/`✓` all mean yes; the next save tidies the formatting without changing your values. Terrain and palette names in the wrong case are matched to the palette. A row or setting that can't be read is kept exactly as you wrote it and listed in a warning box in the note (and a notice), until you fix it. If the note can't be read at all (say the `---` lines around its properties get broken), the plugin won't write to it and shows a notice until you fix it; your text is never rebuilt over. Map notes written by earlier builds (with JSON values such as `parent: {"map":…}`) still load; the first start of this version converts them once, after saving a copy in the plugin folder's `backups/`. diff --git a/src/hex-map/help.md b/src/hex-map/help.md index b35ecec9..a02de98c 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -51,6 +51,8 @@ The **How to edit this note** box at the top of the map note explains the column The map note's **Summary** (above the Hexes table) and the *Route* column in Paths are written by the plugin: extent, base terrain, a terrain legend with counts, regions, each path's ends, forks and length, and a ⚠ for any terrain or path type not in the palette. They update on each save, so edits there are replaced. +**Map data in hex notes.** Hex notes from the built-in template have a **Map data** box: the hex's terrain, region and name (and its region map, locations and, on an overworld, biome). You can edit Terrain, Region or Name there: when you leave the note or open the hex editor, the change goes onto the map. It doesn't if the map changed that value since (the map wins), if the mode locks it (Play), or if the terrain isn't in the palette; then the box keeps a `Not applied:` line saying why. Lines it can't read become `Not read:` lines. + Paths are named. The **Paths** table lists each path (name, type, your notes); **Path routes** lists the hexes each one passes through in order, like `0, 8 → 9, 8 → 13, 8`, and the map draws the way between them. A path's `main` row is its main line; other rows are forks that leave it at their first hex. The tables are linked by name, so to rename a path edit it in both. Older notes that listed every hex of a path are converted once, after a backup, with a report of what changed beside it. --- @@ -178,7 +180,9 @@ Every new terrain (from the terrain tool, the palette editor, a new palette or a **Expanded** is the default fantasy palette on new installs (if you used the plugin before, new maps keep starting on your first palette): more terrains (coasts, wetlands, forest and mountain kinds) and it matches the generators. **Limited** has fewer, simpler terrains and is quicker to paint. Pick any palette as the start for new maps in **Settings → Palette for new maps**. Expanded now has **savanna** and **river delta** too (World biomes paints those biomes with them); an Expanded palette you already have gets them once, after a backup, unless it already has terrains of those names. Delete them and they stay deleted. -No palette or terrain is special because of its name. What a terrain does comes from its **Type**: water types are impassable to auto-routes, generators place terrain by type, Orbits puts the *moon*-type terrain beside planets and the *jump point* past the last orbit. Rename anything, or build a palette from scratch, and it works the same once its terrains have types. A terrain with no type gets no defaults and generators skip it; **Guess types from names** in the palette editor fills the Type column for you to check. +No palette or terrain is special because of its name. What a terrain does comes from its **Type**: water types are impassable to auto-routes, generators place terrain by type, Orbits puts the *moon*-type terrain beside planets and the *jump point* past the last orbit. Rename anything, or build a palette from scratch, and it works the same once its terrains have types. On space maps a faint dashed tether joins each moon to the planet beside it (hidden with the paths). + +Palette menus (setup, New map, new submap) show the picked palette's terrains as colour swatches; hover one for its name. A terrain with no type gets no defaults and generators skip it; **Guess types from names** in the palette editor fills the Type column for you to check. ## Rolling from a hex From e448eeb47fd5c757f4a260b923284f362f9edd3f Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:27:57 -0400 Subject: [PATCH 283/558] fix(path-tool): shorter mode-bar text with a selection; hint reads 'switch to River to edit Glass River' Co-Authored-By: Claude Opus 5.5 --- src/hex-map/pathTool.ts | 2 +- src/hex-map/toolMode.ts | 3 ++- tests/pathTool.test.ts | 2 +- tests/toolMode.test.ts | 4 ++-- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index a8754455..659471ab 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -255,7 +255,7 @@ export function pathContextOutcome(hit: PathHit | null, shift: boolean): PathCon /** The mode-bar hint over another type's path. */ export function inertHint(p: Pick): string { - return `${p.name} is a ${p.typeName}: switch to ${p.typeName} to edit it`; + return `switch to ${p.typeName} to edit ${p.name}`; } /** diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts index 2bc8c668..51d5897a 100644 --- a/src/hex-map/toolMode.ts +++ b/src/hex-map/toolMode.ts @@ -78,6 +78,7 @@ export function toolModeLabel(s: ToolModeState): string | null { if (erasing) return `Erasing paths: click a ${s.pathTypeName ?? "path"} to split it there${note}`; const how = s.pathAuto ? "auto-routes" : "hex by hex"; const edit = "drag a point or the line to reshape · right-click a point to delete it"; + const short = "drag to reshape · right-click a point to delete it"; if (s.pathNew) return `New ${type}: click where it starts`; if (s.pathDrawing) { const name = s.pathSelected ?? `New ${type}`; @@ -85,7 +86,7 @@ export function toolModeLabel(s: ToolModeState): string | null { } if (s.pathSelected) { const what = s.pathSummary && s.pathSummary !== s.pathSelected ? ` (${s.pathSummary})` : ""; - return `${s.pathSelected}${what}: ${edit} · click an end to continue · click the line to fork · click empty ground for a new ${type}${note}`; + return `${s.pathSelected}${what}: ${short} · click an end to continue, the line to fork${note}`; } return `${type}: click empty ground to start · ${edit} · click an end to continue${note}`; } diff --git a/tests/pathTool.test.ts b/tests/pathTool.test.ts index 123b47fe..cc28529a 100644 --- a/tests/pathTool.test.ts +++ b/tests/pathTool.test.ts @@ -215,7 +215,7 @@ describe("pathContextOutcome: right-click", () => { }); it("the hover hint over an inert path names its type", () => { - expect(inertHint(GLASS)).toBe("Glass River is a River: switch to River to edit it"); + expect(inertHint(GLASS)).toBe("switch to River to edit Glass River"); }); }); diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index c221b40e..86cb3ff5 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -98,10 +98,10 @@ describe("toolModeLabel (fresh-eyes T3: sticky modes need an indicator)", () => expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road" })).toBe("Road: click empty ground to start · drag a point or the line to reshape · right-click a point to delete it · click an end to continue"); expect(toolModeLabel({ mode: "path", erasing: true })).toMatch(/^Erasing paths: click a path to split it/); expect(toolModeLabel({ mode: "path", erasing: true, pathTypeName: "Road" })).toBe("Erasing paths: click a Road to split it there"); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathNote: "Glass River is a River: switch to River to edit it" })).toMatch(/ · Glass River is a River: switch to River to edit it$/); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathNote: "switch to River to edit Glass River" })).toMatch(/ · switch to River to edit Glass River$/); expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathAuto: true, pathDrawing: true, pathSelected: "King's Road" })).toBe("King's Road: click to add (auto-routes) · drag a point to move it · Esc to finish"); expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathDrawing: true, pathNote: "not next to the end, so the gap was routed" })).toBe("New Road: click to add (hex by hex) · drag a point to move it · Esc to finish · not next to the end, so the gap was routed"); - expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathSelected: "King's Road", pathSummary: "Road, 2 forks" })).toBe("King's Road (Road, 2 forks): drag a point or the line to reshape · right-click a point to delete it · click an end to continue · click the line to fork · click empty ground for a new Road"); + expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathSelected: "King's Road", pathSummary: "Road, 2 forks" })).toBe("King's Road (Road, 2 forks): drag to reshape · right-click a point to delete it · click an end to continue, the line to fork"); expect(toolModeLabel({ mode: "path", erasing: false, pathTypeName: "Road", pathNew: true })).toBe("New Road: click where it starts"); expect(toolModeLabel({ mode: "regionLink", erasing: false, regionPath: "world/regions/Kerrigan.md" })).toBe("Painting region area: Kerrigan"); expect(toolModeLabel({ mode: "factionLink", erasing: true })).toBe("Erasing factions"); From 073a437e994ddebc83704cf93029f884c8c6c11e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:35:14 -0400 Subject: [PATCH 284/558] feat(overworld): confirm overworld paths into their regions, carve terrain by path type Roads and rivers drawn on an overworld are drafts until confirmed. "Confirm into regions" (path tool bar, path right-click menu, Edit region) projects a path into every region it crosses: - seams: neighbouring regions agree on the crossing pair of cells, derived only from the layout, the two parent hexes and world seed + path name, so regions made in any order join up (pathProjection.seamCrossing) - inside a region: routed through the region's own terrain with the type's routing (router.routeSegment), other paths' hexes passable (bridges); stored as the fewest anchors that reproduce the route exactly - ownership: region paths carry an "Overworld path" column; re-confirm replaces only those (keeping a user's rename/notes), never user paths; the overworld path's "Applied" column marks it confirmed, and a reshape, retype or rename makes it a draft again - carving: new PathType.carves / carveWidth (palette Path types table Carves / Carve width columns, written only when used): a terrain name or type; locked hexes never repainted; old-route carves restored from the region plan on update/remove. Default River carves "water"; Road nothing. - one undo step (kind "projection": every map's paths + carved cells) - createRegion / regenerateRegion re-apply confirmed paths after generation; generator path replacement keeps overworld-owned paths Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + package.json | 4 +- src/constants.ts | 2 +- src/hex-map/EditRegionModal.ts | 28 ++ src/hex-map/HexMapView.ts | 69 ++++- src/hex-map/PathTypeEditorModal.ts | 28 ++ src/hex-map/help.md | 2 + src/hex-map/undoItems.ts | 3 + src/overworld/overworldPaths.ts | 349 +++++++++++++++++++++++ src/overworld/pathProjection.ts | 312 ++++++++++++++++++++ src/overworld/regionsVault.ts | 5 + src/palettes/pathTypeTable.ts | 38 ++- src/types.ts | 8 + src/worldgen/generators.ts | 4 +- styles.css | 22 ++ tests/overworldPaths.test.ts | 439 +++++++++++++++++++++++++++++ tests/pathTypeOptions.test.ts | 5 +- 17 files changed, 1306 insertions(+), 14 deletions(-) create mode 100644 src/overworld/overworldPaths.ts create mode 100644 src/overworld/pathProjection.ts create mode 100644 tests/overworldPaths.test.ts diff --git a/README.md b/README.md index 50c66362..eb41b91a 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: - **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Each hex is written to its region as you draw, so the overworld and any open view of those regions update during the stroke. Picking a terrain on an overworld switches to this view; where there's no region yet the brush does nothing ("No region here yet; place a biome first"), and in Play it's locked ("Switch to Build to paint the regions."). In both views, clicking a hex or brick with a region goes into it in every mode; clicking an empty one sets its biome (Build and God). Right-click a region for **Enter region** and **Edit region…**: one window with the region's name (editable), the overworld hex it's on, **Enter region** and **Open map note**, its biome, a few facts (size and shape, palette, terrain counts, neighbouring regions you can click to go to, locations) and its notes. The notes are kept in the region's map note under a plain `## Notes` heading, so you can also edit them there; they're editable in every mode. In God mode the biome is a picker (choosing another remakes the region), with **Reroll** and **Settings…** (biome, blend, seed, live preview); in Build and Play it's shown with "Switch to God to change it." On an empty hex the menu offers **Set biome…** (Build and God). The overworld is the big-picture view, so it has no hex editor: right-click shows only these region-level items, **Center on this hex** and the hex's **Locations**. Painted hexes are locked, so remaking a region keeps them. +- **Roads and rivers on an overworld** are drafts (drawn faded) until you confirm them. Select one with the path tool and click **Confirm into regions** (in the bar at the top, or right-click the path; **Edit region…** lists the paths through that hex with the same button). The path is routed through every region it crosses: neighbouring regions agree on the hex where it crosses their shared edge, so it joins up at every seam, and inside each region it follows that region's own terrain with the path type's routing. Each region gets one path of the same type and name (forks become its branches); its **Overworld path** column in the region's map note says where it came from. Paths you drew in a region yourself are never touched, and a region path you renamed keeps your name. If the type **carves** terrain (River carves water by default; see Path types), the hexes it crosses become that terrain, except locked (hand-painted) hexes. The overworld path's **Applied** column says it's confirmed; reshaping, retyping or renaming it makes it a draft again, and **Update regions** puts the new route in (the old one's carved hexes go back to their generated terrain). **Remove from regions** takes it out again. Regions made or rerolled later get every confirmed path that crosses them. Confirming needs Build or God, and undo takes the whole thing back in one step. - **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one; hover a hex for its region's name). Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (the `mode:` line in its map note) and opens in it next time; new maps are in **Build**. @@ -231,6 +232,7 @@ Click the **pencil** icon on the right edge of the map to open the drawing tools **Auto-route:** the picker (and the bar at the top of the map while drawing) switches between **Hex by hex** and **Auto-route**: in the picker, choose how to draw (step 1), then the path type (step 2). With Auto-route, click a start hex and then an end hex: the path takes the shortest way inside the map, around impassable terrain, keeping close to the straight line between the two, and then carries on from that end, so you can route leg by leg. Path types whose **Auto-route** option is *winding* (River, by default) wind gently instead of running straight; *direct* ones keep to the line. It's an option on each type, never a matter of its name. A route continues an existing path only when its start is that path's end; starting anywhere else (such as the first hex of another road) makes a new path, and existing paths are never changed. The result is an ordinary path: right-click hexes to remove them, or switch back to hex by hex to extend it. - **Impassable terrain** — set per terrain in the palette editor (Impassable column) or the terrain editor. Defaults go by terrain *type*, never by name, so they work in any palette, custom ones included: every terrain of a water type (deep water, water, shallows) is impassable unless you untick it. A terrain with no type has no default (an untyped "Black Lake" is passable); give it a type, or use **Guess types from names** in the palette editor. A palette with no impassable terrain says so in the bar. Learned generators' **Connected land** uses the same impassable terrains until you save your own list. +- **Carves terrain** — a path type can also say what an overworld path of that type turns the hexes it crosses into when you confirm it into its regions (**Carves**: a terrain's name, or a terrain type such as `water` for the palette's first water terrain; **Carve width** 0 for the path's own hexes, 1 to take the hexes beside them too). New palettes' River carves `water`; Road carves nothing. It's an option of the type, never of its name: palettes you already have keep carving off until you set it. The columns appear in the palette note's Path types table once a type uses them. - **Per path type** — each path type has **Avoid impassable terrain** and **Auto-route** (direct or winding) in its editor and in the palette note's Path types table. The built-in Road avoids impassable terrain and routes direct; River does neither. Any type can be set either way, whatever it's called. Path types saved by older versions get these filled in once, from how those versions treated them, so no map changes look. - **Cross impassable** — tick it in the bar to let one route go through anyway. If no route exists the map tells you, and suggests this or changing which terrains are impassable. diff --git a/package.json b/package.json index c1768281..494830c0 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/overworldPaths.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/overworldPaths.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/constants.ts b/src/constants.ts index 6c089f54..f2b51a87 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -337,7 +337,7 @@ export const LIMITED_TERRAIN_PALETTE: TerrainColor[] = [ export const DEFAULT_PATH_TYPES: PathType[] = [ { name: "Road", color: "#a16207", width: 4, lineStyle: "solid", routing: "through", avoidImpassable: true, autoRoute: "direct" }, - { name: "River", color: "#3b82f6", width: 3, lineStyle: "solid", routing: "meander", avoidImpassable: false, autoRoute: "winding" }, + { name: "River", color: "#3b82f6", width: 3, lineStyle: "solid", routing: "meander", avoidImpassable: false, autoRoute: "winding", carves: "water" }, ]; /** How a path is drawn when its type isn't in the map's palette (renamed or diff --git a/src/hex-map/EditRegionModal.ts b/src/hex-map/EditRegionModal.ts index a0cc6a81..0e2a10b1 100644 --- a/src/hex-map/EditRegionModal.ts +++ b/src/hex-map/EditRegionModal.ts @@ -28,6 +28,8 @@ import { openBiomeGenerator } from "./BiomeLibraryModal"; import { editRegionPlan, terrainCountsText } from "../overworld/overworldInput"; import { mayReshape, paintableBiomes, RegionGenModal, reshapeUndoable, type BiomeHost } from "./BiomeModals"; import { openNoteFocused } from "../openNote"; +import { confirmOverworldPath, overworldPathsAt } from "../overworld/overworldPaths"; +import { canDo } from "../modeGate"; import { createIconEl, getIconUrl } from "../utils"; export interface EditRegionHost extends BiomeHost { @@ -232,6 +234,23 @@ export class EditRegionModal extends HexmakerModal { this.host.openLocations(this.px, this.py); }); + // Overworld paths through this hex: drafts can be confirmed into the regions from here. + const through = overworldPathsAt(plugin, this.overworld, `${this.px}_${this.py}`); + if (through.length) { + const ul = fact("Paths").createEl("ul", { cls: "duckmage-edit-region-paths" }); + const mayConfirm = canDo(this.overworld, "edit-path"); + for (const p of through) { + const li = ul.createEl("li"); + li.createSpan({ text: p.name }); + li.createSpan({ cls: "duckmage-edit-region-path-state", text: p.applied ? "in the regions" : "draft" }); + if (!mayConfirm) continue; + li.createEl("button", { + text: p.applied ? "Update regions" : "Confirm into regions", + attr: { title: "Put this path into every region it crosses, joined at the seams (one undo step)" }, + }).addEventListener("click", () => void this.confirmPath(p.name)); + } + } + // ── notes (never locked) ────────────────────────────────────────────── const notesSec = contentEl.createDiv({ cls: "duckmage-editor-section duckmage-edit-region-notes" }); const notesHead = notesSec.createDiv({ cls: "duckmage-edit-region-notes-head" }); @@ -278,6 +297,15 @@ export class EditRegionModal extends HexmakerModal { this.render(); } + private async confirmPath(pathName: string): Promise { + const res = await confirmOverworldPath(this.host.plugin, this.overworld, pathName); + if ("error" in res) new Notice(res.error); + else new Notice(`${pathName}: in ${res.regions.length === 1 ? "1 region" : `${res.regions.length} regions`}.`); + this.host.changed(); + await this.saveNotes(); + this.render(); + } + private async reroll(name: string): Promise { if (!mayReshape(this.host, this.overworld, this.px, this.py)) return; await reshapeUndoable(this.host.plugin, this.overworld, this.px, this.py, () => regenerateRegion(this.host.plugin, name, { seed: Math.floor(Math.random() * 1e9) })); diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 90039b45..41d8dadf 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -85,6 +85,8 @@ import { OverworldMinimap } from "./overworldMinimap"; import { BiomePickerModal, type BiomeHost } from "./BiomeModals"; import { EditRegionModal } from "./EditRegionModal"; import { inOverworldGrid, overworldOf, regionHome, regionPalette, walkLock } from "../overworld/regionsVault"; +import { applyProjectionUndo, confirmOverworldPath, draftPathNames, isPathOverworld, prepareProjectionUndo, removeOverworldPath } from "../overworld/overworldPaths"; +import { draftsAfterEdit, isApplied } from "../overworld/pathProjection"; import { brushCells, FrameThrottle, terrainDiff, overworldLeftClick, overworldMenu, PAINT_LOCKED_HINT, PAINT_NO_REGION_HINT, paintTargets } from "../overworld/overworldInput"; import { WalkRegionModal, type OverworldWalk } from "../worldgen/WalkRegionModal"; import type { Side } from "../worldgen/world"; @@ -1364,7 +1366,7 @@ export class HexMapView extends ItemView { if (this.drawingMode === "path" && !this.isErasingMode) { const r = this.pathTool.contextMenu(e); if (r && "handled" in r) return; - if (r) pathItems = r.items; + if (r) pathItems = [...r.items, ...this.overworldPathItems(this.pathTool.labelState().selected)]; } this.showPainterContextMenu(e.clientX, e.clientY, hexX, hexY, pathItems); }, @@ -5581,6 +5583,8 @@ export class HexMapView extends ItemView { const edits = currentCellEdits(item.edits, dir, (m, k) => store.get(m, k) as Record | undefined); return edits ? { ...item, edits } : null; } + case "projection": + return prepareProjectionUndo(this.plugin, item, dir); case "token": { const now = await readTokenPlace(this.app, item.path); const want = dir === "undo" ? item.after : item.before; @@ -5627,6 +5631,11 @@ export class HexMapView extends ItemView { } else if (item.kind === "cells") { for (const e of item.edits) this.plugin.mapStore.set(e.map, e.key, cellPatch(e, dir)); this.renderGrid(); + } else if (item.kind === "projection") { + applyProjectionUndo(this.plugin, item, dir); + void this.plugin.saveSettings(); + this.renderGrid(); + this.updateModeBar(); } else { await this.applyTokenSnap(item.path, dir === "undo" ? item.before : item.after); } @@ -6072,9 +6081,61 @@ export class HexMapView extends ItemView { const show = this.drawingMode === "path" && !this.isErasingMode; el.toggle(show); if (show) this.pathTool.renderBarControls(el); + // An overworld's selected path: confirm it into its regions from the bar too. + const selected = show ? this.pathTool.labelState().selected : null; + const confirm = this.overworldPathItems(selected)[0]; + if (confirm) { + const btn = el.createEl("button", { + text: confirm.label, + cls: "duckmage-mode-bar-route-toggle duckmage-path-confirm-btn", + attr: { title: "Put this path into every region it crosses, joined at the seams (one undo step)." }, + }); + btn.addEventListener("click", confirm.onClick); + } + } + + /** + * An overworld path's region actions (path menu, mode bar): "Confirm into + * regions" for a draft, "Update regions" + "Remove from regions" for a + * confirmed one. None on other maps, or when the mode doesn't allow it. + */ + private overworldPathItems(pathName: string | null): { label: string; onClick: () => void }[] { + const mapName = this.activeMapName; + if (!pathName || !isPathOverworld(this.plugin, mapName) || !canDo(mapName, "edit-path")) return []; + const p = this.plugin.mapStore.paths(mapName).find((q) => q.name === pathName); + if (!p) return []; + const run = (remove: boolean) => () => void this.runPathProjection(pathName, remove); + return isApplied(p) + ? [{ label: "Update regions", onClick: run(false) }, { label: "Remove from regions", onClick: run(true) }] + : [{ label: "Confirm into regions", onClick: run(false) }]; + } + + /** Confirm (or remove) an overworld path into its regions, and say what happened. */ + async runPathProjection(pathName: string, remove: boolean): Promise { + const mapName = this.activeMapName; + const res = remove ? await removeOverworldPath(this.plugin, mapName, pathName) : await confirmOverworldPath(this.plugin, mapName, pathName); + if ("error" in res) { + new Notice(res.error); + return; + } + const n = res.regions.length; + const where = n === 1 ? "1 region" : `${n} regions`; + const msg = remove ? `${pathName}: taken out of ${where}.` : `${pathName}: ${n ? `in ${where}` : "crosses no regions yet"}.`; + const skipped = res.skipped.length ? ` ${res.skipped.length} still loading: confirm again in a moment.` : ""; + new Notice(msg + skipped); + this.updateUndoButton(); + this.renderGrid(); + this.updateModeBar(); } private pushPathUndo(mapName: string, before: MapPath[], after: MapPath[]): void { + // A confirmed overworld path that was just reshaped, retyped or renamed + // is a draft again until it's confirmed into its regions once more. + const drafted = draftsAfterEdit(before, after); + if (drafted !== after) { + this.plugin.mapStore.setPaths(mapName, drafted); + after = drafted; + } this.pushUndo({ kind: "path", mapName, before, after }, mapName); this.updateUndoButton(); } @@ -6222,7 +6283,9 @@ export class HexMapView extends ItemView { } } const selected = tool?.selected ?? null; - const key = JSON.stringify([lines.map((l) => [l.s.path, l.s.branch, l.d, l.width, l.dash, l.s.color]), dot, handles, selected]); + // On an overworld, paths not yet confirmed into their regions are drafts (drawn faded). + const drafts = draftPathNames(this.plugin, region.name); + const key = JSON.stringify([lines.map((l) => [l.s.path, l.s.branch, l.d, l.width, l.dash, l.s.color, drafts.has(l.s.path)]), dot, handles, selected]); const existing = gridContainer.querySelector("svg.duckmage-path-svg"); const existingHandles = gridContainer.querySelector("svg.duckmage-path-handles-svg"); const wantLines = lines.length > 0; @@ -6261,7 +6324,7 @@ export class HexMapView extends ItemView { } for (const l of lines) { const path = activeDocument.createElementNS(svgNS, "path"); - path.setAttribute("class", "duckmage-svg-path-line"); + path.setAttribute("class", drafts.has(l.s.path) ? "duckmage-svg-path-line duckmage-svg-path-draft" : "duckmage-svg-path-line"); path.setAttribute("d", l.d); path.setAttribute("stroke", l.s.color); path.setAttribute("stroke-width", l.width); diff --git a/src/hex-map/PathTypeEditorModal.ts b/src/hex-map/PathTypeEditorModal.ts index 30a229eb..35e20f0b 100644 --- a/src/hex-map/PathTypeEditorModal.ts +++ b/src/hex-map/PathTypeEditorModal.ts @@ -22,6 +22,8 @@ export class PathTypeEditorModal extends HexmakerModal { private pendingRouting: PathRouting; private pendingAvoid: boolean; private pendingAutoRoute: PathAutoRoute; + private pendingCarves: string; + private pendingCarveWidth: number; private readonly originalName: string; private savedOrDeleted = false; @@ -43,6 +45,8 @@ export class PathTypeEditorModal extends HexmakerModal { this.pendingRouting = entry.routing; this.pendingAvoid = pathAvoidsImpassable(entry); this.pendingAutoRoute = pathMeanders(entry) ? "winding" : "direct"; + this.pendingCarves = entry.carves ?? ""; + this.pendingCarveWidth = entry.carveWidth === 1 ? 1 : 0; } onOpen(): void { @@ -156,6 +160,27 @@ export class PathTypeEditorModal extends HexmakerModal { }), ); + new Setting(contentEl) + .setName("Carves terrain") + .setDesc("When you confirm an overworld path of this type into its regions, the hexes it crosses there become this: a terrain's name, or a terrain type such as water (the palette's first water terrain). Leave empty to keep the terrain. Locked hexes are never changed.") + .addText(text => + text + .setPlaceholder("None") + .setValue(this.pendingCarves) + .onChange(value => { this.pendingCarves = value.trim(); }), + ); + + new Setting(contentEl) + .setName("Carve width") + .setDesc("0: only the path's hexes. 1: those and the hexes beside them.") + .addDropdown(dd => + dd + .addOption("0", "0") + .addOption("1", "1") + .setValue(String(this.pendingCarveWidth)) + .onChange(value => { this.pendingCarveWidth = value === "1" ? 1 : 0; }), + ); + // Save button const btnRow = contentEl.createDiv({ cls: "duckmage-terrain-editor-actions" }); btnRow.createEl("button", { text: "Save", cls: "mod-cta" }).addEventListener("click", () => { @@ -217,6 +242,9 @@ export class PathTypeEditorModal extends HexmakerModal { this.entry.routing = this.pendingRouting; this.entry.avoidImpassable = this.pendingAvoid; this.entry.autoRoute = this.pendingAutoRoute; + if (this.pendingCarves) this.entry.carves = this.pendingCarves; + else delete this.entry.carves; + this.entry.carveWidth = this.pendingCarveWidth; // If name changed, point every path of this type at the new name. // PHASE-3: while maps store pathChains (src/paths/mapPaths.ts) this edits diff --git a/src/hex-map/help.md b/src/hex-map/help.md index b35ecec9..93e8bb88 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -156,6 +156,8 @@ Notes, settings and palettes are never locked. There are no confirm boxes for th **Walking into new land.** In a region, the hex flower on the toolbar shows a **+** on each neighbour that has no region yet ("New region to the east"). Click it, pick the biome that lies there or **Roll** for one (the seed is shown; the same seed rolls the same biome), watch the preview of the new region blended with the regions around it, then **Create and go**. A different biome makes border country in between. Past the overworld's edge, the overworld grows by a hex to fit the new region. The hex editor's neighbour flower does the same on the hexes past the region's edge, and maps joined side by side get a **+** on the empty sides of their arrow pad. Needs Build or God: in Play the **+** says "Switch to Build to make a region." +**Roads and rivers on an overworld** are drafts (drawn faded) until you confirm them: select one with the path tool and click **Confirm into regions** (top bar, the path's right-click menu, or **Edit region…**). It's routed through every region it crosses, through each region's own terrain, and the neighbouring regions agree where it crosses each seam, so it joins up. If its path type **carves** terrain (River carves water by default; set it in the path type's editor), those hexes change too, except locked ones. Paths you drew in a region are never touched. Reshaping the overworld path makes it a draft again; **Update regions** redoes it, **Remove from regions** takes it out. New and rerolled regions pick up confirmed paths. Build or God; one undo step. + Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. A road or river that ends on the edge of a region, next to where the neighbour's road of the same type ends, is drawn on to the shared edge on both maps, so the two join up. diff --git a/src/hex-map/undoItems.ts b/src/hex-map/undoItems.ts index 225d1975..6e908e7f 100644 --- a/src/hex-map/undoItems.ts +++ b/src/hex-map/undoItems.ts @@ -8,6 +8,7 @@ import type { PinRecord } from "../paths/routePins"; import type { MapPath, TokenShape, TokenSize } from "../types"; import type { HexData } from "../maps/mapNote"; import type { CellEdit } from "../undoBook"; +import type { ProjectionUndo } from "../overworld/overworldPaths"; export type TerrainUndoEntry = { x: number; @@ -84,5 +85,7 @@ export type UndoItem = | { kind: "calibrate"; mapName: string; before: CalibrateSnapshot; after: CalibrateSnapshot } /** Any map data edit recorded field by field (hex editor, biome and region actions). */ | { kind: "cells"; edits: CellEdit[] } + /** An overworld path confirmed into (or taken out of) its regions: paths of several maps and the terrain carved. */ + | ProjectionUndo /** A token moved, placed or removed (null: not a token on a map). */ | { kind: "token"; path: string; before: TokenSnap | null; after: TokenSnap | null }; diff --git a/src/overworld/overworldPaths.ts b/src/overworld/overworldPaths.ts new file mode 100644 index 00000000..8bbcde76 --- /dev/null +++ b/src/overworld/overworldPaths.ts @@ -0,0 +1,349 @@ +/** + * Overworld paths into regions, the vault part: "Confirm into regions", + * "Remove from regions", and the hook that puts confirmed paths into a + * region when it is made or regenerated. The rules are in pathProjection.ts + * (pure, tested). + * + * Writes go through the map store (terrain: setMany, paths: setPaths), so + * the region map notes are written as usual. Confirm and remove are one undo + * step on the overworld's queue (kind "projection"); the regeneration hook + * is part of making the region and records nothing of its own. + * + * Gated like every path edit: Build or God on the overworld. + */ + +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { HexKey, MapData, MapPath, PathType } from "../types"; +import type { ResolvedBranch } from "../paths/resolve"; +import type { RouteContext } from "../paths/router"; +import { routeSegment, DEFAULT_SEGMENT_STYLE } from "../paths/router"; +import { anchorsFor, dedupeSteps } from "../paths/fromHexes"; +import { pathNameKey } from "../paths/names"; +import { clonePaths } from "../paths/edit"; +import { regionMapAt } from "../maps/submaps"; +import { cellEdits, cellPatch, currentCellEdits, sameValue, type CellEdit, type UndoDirection } from "../undoBook"; +import { mapAllows } from "../workMode"; +import { inRegion, type RegionLayout } from "./layout"; +import { worldSeed } from "./regionWorld"; +import { overworldOf, planRegionAt } from "./regionsVault"; +import { + carveCells, + carveTerrainFor, + carveWidthOf, + carveWrites, + childNeighbourKeys, + isApplied, + mergeOwned, + ownerOf, + projectPath, + seamSalt, + withApplied, + type OverworldBranch, +} from "./pathProjection"; + +/** Shown when confirming is refused by the overworld's work mode. */ +export const CONFIRM_LOCKED_HINT = "Switch to Build to confirm paths into regions."; + +/** The undo entry of a confirm / remove: every map's paths before and after, and the terrain it carved. */ +export interface ProjectionUndo { + kind: "projection"; + maps: { mapName: string; before: MapPath[]; after: MapPath[] }[]; + edits: CellEdit[]; +} + +export interface ProjectionReport { + /** Region maps whose paths or terrain changed. */ + regions: string[]; + /** Hexes whose terrain was carved (or put back). */ + carved: number; + /** Regions that couldn't be routed (not loaded yet). */ + skipped: string[]; +} + +const xy = (k: HexKey): [number, number] => { + const [x, y] = k.split("_").map(Number); + return [x, y]; +}; + +/** Is this map an overworld whose regions mesh (the paths can go into them)? */ +export function isPathOverworld(plugin: HexmakerPlugin, mapName: string): boolean { + return !!overworldOf(plugin, mapName); +} + +/** The region maps of an overworld, by their parent hex. */ +function regionsOf(plugin: HexmakerPlugin, owName: string): Map { + const out = new Map(); + for (const m of plugin.settings.maps) { + if (m.submapKind === "region" && m.parent?.map === owName && !out.has(m.parent.hex)) out.set(m.parent.hex, m); + } + return out; +} + +/** The region maps an overworld path crosses (that exist), in path order. */ +export function regionsCrossed(plugin: HexmakerPlugin, owName: string, pathName: string): string[] { + const out: string[] = []; + for (const rb of plugin.paths.resolved(owName)) { + if (pathNameKey(rb.path) !== pathNameKey(pathName)) continue; + for (const h of rb.hexes) { + const r = regionMapAt(plugin.settings.maps, owName, h); + if (r && !out.includes(r.name)) out.push(r.name); + } + } + return out; +} + +/** The overworld's paths that run through hex `hex`, and whether each is confirmed. */ +export function overworldPathsAt(plugin: HexmakerPlugin, owName: string, hex: HexKey): { name: string; applied: boolean }[] { + if (!isPathOverworld(plugin, owName)) return []; + const names = new Set(plugin.paths.resolved(owName).filter((rb) => rb.hexes.includes(hex)).map((rb) => pathNameKey(rb.path))); + return plugin.mapStore.paths(owName).filter((p) => names.has(pathNameKey(p.name))).map((p) => ({ name: p.name, applied: isApplied(p) })); +} + +function typeOn(plugin: HexmakerPlugin, mapName: string, typeName: string): PathType | undefined { + try { + return plugin.getMapPathTypes(mapName).find((t) => t.name === typeName); + } catch { + return undefined; + } +} + +interface ProjectOptions { + /** Only these parent hexes (a region being made). */ + only?: ReadonlySet; + /** Also replace region paths whose overworld path no longer exists (a renamed one). */ + adoptOrphans?: boolean; +} + +/** + * Put overworld path `pathName` into the regions it crosses (or, with + * `path` null, take it out of every region). Writes terrain and paths; no + * undo, no gate (callers do both). + */ +function projectInto(plugin: HexmakerPlugin, owName: string, pathName: string, path: MapPath | null, opts: ProjectOptions = {}): ProjectionReport { + const report: ProjectionReport = { regions: [], carved: 0, skipped: [] }; + const ow = overworldOf(plugin, owName); + if (!ow) return report; + const layout: RegionLayout = ow.layout; + const salt = seamSalt(worldSeed(ow.settings.worldId ?? ow.map.name), pathName); + const regions = regionsOf(plugin, owName); + const owNames = new Set(plugin.mapStore.paths(owName).map((p) => pathNameKey(p.name))); + const orphan = opts.adoptOrphans + ? (p: MapPath) => { + const o = ownerOf(p); + return !!o && !owNames.has(pathNameKey(o)) && (!path || p.typeName === path.typeName); + } + : () => false; + const owned = (p: MapPath) => { + const o = ownerOf(p); + return !!o && (pathNameKey(o) === pathNameKey(pathName) || orphan(p)); + }; + + const branches: OverworldBranch[] = path + ? plugin.paths.resolved(owName) + .filter((rb: ResolvedBranch) => pathNameKey(rb.path) === pathNameKey(path.name)) + .map((rb) => ({ branch: rb.branch, hexes: rb.hexes, forkFrom: rb.forkFrom, joinTo: rb.joinTo })) + : []; + const crossed = new Set(branches.flatMap((b) => b.hexes)); + + // Regions to visit: the ones crossed, and the ones holding an old copy. + const targets = new Map(); + for (const [hex, m] of regions) { + if (opts.only && !opts.only.has(hex)) continue; + if (crossed.has(hex) || plugin.mapStore.paths(m.name).some(owned)) targets.set(hex, m); + } + + // Each region's router: its own terrain and the type's routing, with the + // hexes of its other paths passable (a road may bridge a carved river). + const routers = new Map HexKey[]) | null>(); + const routerFor = (hex: HexKey) => { + if (routers.has(hex)) return routers.get(hex)!; + const m = targets.get(hex)!; + const ctx = plugin.paths.isReady(m.name) ? plugin.paths.context(m.name) : null; + let fn: ((a: HexKey, b: HexKey) => HexKey[]) | null = null; + if (ctx && path) { + const style = plugin.paths.styleOf(m.name, path.typeName); + const bridges = new Set(); + const mine = new Set(plugin.mapStore.paths(m.name).filter(owned).map((p) => pathNameKey(p.name))); + for (const rb of plugin.paths.resolved(m.name)) if (!mine.has(pathNameKey(rb.path))) rb.hexes.forEach((h) => bridges.add(h)); + const blocked = new Set([...ctx.blocked].filter((h) => !bridges.has(h))); + const routeCtx: RouteContext = { ...ctx, blocked }; + fn = (a, b) => routeSegment(a, b, { ...routeCtx, ...style }).hexes; + } + routers.set(hex, fn); + return fn; + }; + const projected = path + ? projectPath(layout, salt, branches, (R, a, b) => routerFor(R)!(a, b), (R) => targets.has(R) && !!routerFor(R)) + : new Map(); + + const nb = childNeighbourKeys(layout); + for (const [hex, m] of targets) { + if (path && !routerFor(hex)) { + report.skipped.push(m.name); + continue; + } + const [px, py] = xy(hex); + const inside = (k: HexKey) => inRegion(layout, px, py, ...xy(k)); + const chains = projected.get(hex) ?? []; + const store = plugin.mapStore; + const palette = plugin.getMapPalette(m.name); + const current = store.paths(m.name); + const oldOwned = current.filter(owned); + + // ── terrain: carve the new route, put back what only the old one carved ── + const type = path ? typeOn(plugin, m.name, path.typeName) ?? typeOn(plugin, owName, path.typeName) : undefined; + const carveT = carveTerrainFor(type?.carves, palette); + const newCells = carveT ? carveCells(chains, carveWidthOf(type), inside, nb) : new Set(); + const writes: [HexKey, { terrain: string }][] = carveT ? carveWrites(newCells, carveT, (k) => store.get(m.name, k)) : []; + if (oldOwned.length) { + const oldNames = new Set(oldOwned.map((p) => pathNameKey(p.name))); + const oldResolved = plugin.paths.resolved(m.name); + // Hexes other carving paths keep. + const keep = new Set(); + for (const p of current) { + if (oldNames.has(pathNameKey(p.name))) continue; + const t = typeOn(plugin, m.name, p.typeName); + if (!carveTerrainFor(t?.carves, palette)) continue; + const hexes = oldResolved.filter((rb) => pathNameKey(rb.path) === pathNameKey(p.name)).map((rb) => rb.hexes); + carveCells(hexes, carveWidthOf(t), inside, nb).forEach((k) => keep.add(k)); + } + let plan: Map | null | undefined; + for (const p of oldOwned) { + const t = typeOn(plugin, m.name, p.typeName) ?? typeOn(plugin, owName, p.typeName); + const oldT = carveTerrainFor(t?.carves, palette); + if (!oldT) continue; + const hexes = oldResolved.filter((rb) => pathNameKey(rb.path) === pathNameKey(p.name)).map((rb) => rb.hexes); + for (const k of carveCells(hexes, carveWidthOf(t), inside, nb)) { + if (newCells.has(k) || keep.has(k)) continue; + const h = store.get(m.name, k); + if (h?.locked || h?.terrain !== oldT) continue; + if (plan === undefined) { + try { plan = planRegionAt(plugin, owName, px, py)?.cells ?? null; } catch { plan = null; } + } + const back = plan?.get(k); + if (back && back !== oldT) writes.push([k, { terrain: back }]); + } + } + } + if (writes.length) { + store.setMany(m.name, writes); + report.carved += writes.length; + } + + // ── the region's path: anchors that route back to exactly the chains ── + let next: MapPath | null = null; + if (path && chains.length) { + const ctx = plugin.paths.context(m.name); + const style = ctx ? plugin.paths.styleOf(m.name, path.typeName) : DEFAULT_SEGMENT_STYLE; + next = { + name: path.name, + typeName: path.typeName, + branches: chains.map((c) => ({ anchors: ctx ? anchorsFor(c, { ...ctx, ...style }) : dedupeSteps(c) })), + }; + } + const list = mergeOwned(store.paths(m.name), pathName, next, orphan); + if (!sameValue(list, store.paths(m.name))) store.setPaths(m.name, list); + if (writes.length || !sameValue(list, current)) report.regions.push(m.name); + } + return report; +} + +/** Snapshot of every overworld + region map's paths (for undo). */ +function snapshot(plugin: HexmakerPlugin, owName: string): Map { + const out = new Map([[owName, clonePaths(plugin.mapStore.paths(owName))]]); + for (const m of regionsOf(plugin, owName).values()) out.set(m.name, clonePaths(plugin.mapStore.paths(m.name))); + return out; +} + +/** Confirm (or, with `remove`, take out) one overworld path, as one undo step. */ +async function runProjection( + plugin: HexmakerPlugin, + owName: string, + pathName: string, + remove: boolean, +): Promise { + const ow = plugin.getMap(owName); + if (!ow || !overworldOf(plugin, owName)) return { error: "This map has no rectangle regions to put paths into." }; + if (!mapAllows(ow, "edit-path")) return { error: CONFIRM_LOCKED_HINT }; + if (!plugin.paths.isReady(owName)) return { error: "The map is still loading. Try again in a moment." }; + const path = plugin.mapStore.paths(owName).find((p) => pathNameKey(p.name) === pathNameKey(pathName)); + if (!path) return { error: `There's no path called ${pathName} on this map.` }; + const before = snapshot(plugin, owName); + const { result: report, cells } = await plugin.mapStore.record(() => { + const r = projectInto(plugin, owName, path.name, remove ? null : path, { adoptOrphans: !remove }); + const owPaths = plugin.mapStore.paths(owName).map((p) => (pathNameKey(p.name) === pathNameKey(path.name) ? withApplied(p, !remove) : p)); + if (!sameValue(owPaths, plugin.mapStore.paths(owName))) plugin.mapStore.setPaths(owName, owPaths); + return r; + }); + const maps: ProjectionUndo["maps"] = []; + for (const [mapName, b] of before) { + const after = clonePaths(plugin.mapStore.paths(mapName)); + if (!sameValue(b, after)) maps.push({ mapName, before: b, after }); + } + const edits = cellEdits(cells); + if (maps.length || edits.length) plugin.pushUndo(owName, { kind: "projection", maps, edits }); + await plugin.saveSettings(); + await plugin.mapStore.flush(); + return report; +} + +/** + * "Confirm into regions": route overworld path `pathName` through every + * region it crosses (seams agree, so it joins up), carve terrain if its type + * says so, and mark it Applied. Confirming again updates the region paths + * it made before. One undo step. + */ +export function confirmOverworldPath(plugin: HexmakerPlugin, owName: string, pathName: string): Promise { + return runProjection(plugin, owName, pathName, false); +} + +/** "Remove from regions": take a confirmed path's copies out of its regions (carved terrain put back) and make it a draft. */ +export function removeOverworldPath(plugin: HexmakerPlugin, owName: string, pathName: string): Promise { + return runProjection(plugin, owName, pathName, true); +} + +/** + * A region was just made or regenerated: put every confirmed path of its + * overworld that crosses it back in (routed after generation, then carved). + * Quiet: nothing is recorded or reported; never throws. + */ +export function applyConfirmedPaths(plugin: HexmakerPlugin, regionName: string): number { + try { + const region = plugin.getMap(regionName); + if (region?.submapKind !== "region" || !region.parent) return 0; + const owName = region.parent.map; + if (typeof plugin.mapStore?.paths !== "function" || !plugin.paths?.resolved || !overworldOf(plugin, owName)) return 0; + const only = new Set([region.parent.hex]); + let n = 0; + for (const p of plugin.mapStore.paths(owName)) { + if (!isApplied(p)) continue; + n += projectInto(plugin, owName, p.name, p, { only }).regions.length; + } + return n; + } catch (e) { + console.error("Hexmaker: putting confirmed paths into a region failed", e); + return 0; + } +} + +/** Overworld paths shown as drafts (not confirmed) on this map: none unless it's an overworld. */ +export function draftPathNames(plugin: HexmakerPlugin, mapName: string): Set { + if (!isPathOverworld(plugin, mapName)) return new Set(); + return new Set(plugin.mapStore.paths(mapName).filter((p) => !isApplied(p)).map((p) => p.name)); +} + +// ── undo ───────────────────────────────────────────────────────────────── + +/** The part of a projection entry still in place (null: nothing to do). */ +export function prepareProjectionUndo(plugin: HexmakerPlugin, item: ProjectionUndo, dir: UndoDirection): ProjectionUndo | null { + const maps = item.maps.filter((m) => sameValue(plugin.mapStore.paths(m.mapName), dir === "undo" ? m.after : m.before)); + const edits = currentCellEdits(item.edits, dir, (m, k) => plugin.mapStore.get(m, k) as Record | undefined) ?? []; + if (!maps.length && !edits.length) return null; + return { ...item, maps, edits }; +} + +/** Undo (back to "before") or redo a projection: terrain first, then the paths. */ +export function applyProjectionUndo(plugin: HexmakerPlugin, item: ProjectionUndo, dir: UndoDirection): void { + for (const e of item.edits) plugin.mapStore.set(e.map, e.key, cellPatch(e, dir)); + for (const m of item.maps) plugin.mapStore.setPaths(m.mapName, clonePaths(dir === "undo" ? m.before : m.after)); +} diff --git a/src/overworld/pathProjection.ts b/src/overworld/pathProjection.ts new file mode 100644 index 00000000..4178e369 --- /dev/null +++ b/src/overworld/pathProjection.ts @@ -0,0 +1,312 @@ +/** + * Overworld paths into regions, the pure part (owner 2026-10-11: "Once you + * hit 'confirm' for a biome-level path, it should get applied in a + * reasonable way to the regions it crosses through"). + * + * A path drawn on an overworld is a draft until it is confirmed. Confirming + * projects it into every region it crosses: + * + * - **Seams.** Where the overworld path steps from hex P to hex Q, the two + * regions agree on the pair of cells it crosses by: one in P's region, + * its neighbour in Q's. The pair depends only on the layout, the two hexes + * and a salt (world seed + path name), never on terrain or which region + * was made first, so a region made later joins up with one made earlier. + * - **Inside a region** the route runs from where it enters to where it + * leaves (or the region's centre, where the path starts or ends there) + * through the region's own terrain with the path type's routing. + * - **Ownership.** A projected path carries the overworld path's name in + * its "Overworld path" column; re-confirming replaces only those, never a + * path the user drew in the region. The overworld path's "Applied" column + * says it was confirmed. + * - **Carving.** A path type may carve terrain (PathType.carves): its hexes + * (and, at width 1, the hexes beside them) become that terrain. Locked + * (hand-painted) cells are never repainted. + * + * Both columns are ordinary extra columns of the map note's Paths table + * (kept and written back by every reader), so the data stays readable. + * + * Pure: no Obsidian imports. + */ + +import type { HexKey, MapPath, PathType, TerrainColor } from "../types"; +import { hashString } from "../paths/router"; +import { pathNameKey, uniquePathName } from "../paths/names"; +import { childNeighbours, childPoint, regionCells, regionCentreCell, regionCentrePoint, type RegionLayout } from "./layout"; + +/** Overworld Paths column: "yes" once a path is confirmed into its regions. */ +export const APPLIED_COL = "Applied"; +/** Region Paths column: the overworld path a projected path came from. */ +export const OWNER_COL = "Overworld path"; + +const xy = (k: HexKey): [number, number] => { + const [x, y] = k.split("_").map(Number); + return [x, y]; +}; +const key = (x: number, y: number): HexKey => `${x}_${y}`; + +// ── the two columns ────────────────────────────────────────────────────── + +/** An extra column's value, by header ignoring case and spacing. */ +export function extraCell(extra: Record | undefined, header: string): string | undefined { + if (!extra) return undefined; + const want = header.toLowerCase().replace(/\s+/g, ""); + for (const [h, v] of Object.entries(extra)) if (h.toLowerCase().replace(/\s+/g, "") === want) return v; + return undefined; +} + +/** `extra` with one column set (or removed, for undefined), keeping the header as the note spells it. */ +export function withExtraCell(extra: Record | undefined, header: string, value: string | undefined): Record | undefined { + const out: Record = {}; + let spelled = header; + const want = header.toLowerCase().replace(/\s+/g, ""); + for (const [h, v] of Object.entries(extra ?? {})) { + if (h.toLowerCase().replace(/\s+/g, "") === want) spelled = h; + else out[h] = v; + } + if (value) out[spelled] = value; + return Object.keys(out).length ? out : undefined; +} + +const APPLIED_WORDS = ["yes", "y", "true", "x", "done", "applied", "confirmed", "✓", "✔"]; + +/** Read forgivingly: yes, y, true, x, ✓, done, applied. */ +export function isApplied(p: Pick): boolean { + const first = (extraCell(p.extra, APPLIED_COL) ?? "").trim().toLowerCase().split(/[\s,.;]+/)[0]; + return APPLIED_WORDS.includes(first); +} + +/** The path with its Applied cell set (yes) or cleared. */ +export function withApplied

(p: P, on: boolean): P { + const extra = withExtraCell(p.extra, APPLIED_COL, on ? "yes" : undefined); + const out = { ...p }; + if (extra) out.extra = extra; + else delete out.extra; + return out; +} + +/** The overworld path a region path was projected from, if any. */ +export function ownerOf(p: Pick): string | undefined { + return extraCell(p.extra, OWNER_COL)?.trim() || undefined; +} + +/** Geometry and type of a path (what a projection depends on). */ +function shapeKey(p: MapPath): string { + return JSON.stringify([p.typeName, p.branches.map((b) => b.anchors)]); +} + +/** + * After an edit to an overworld map's paths: a confirmed path whose route, + * type or name changed is a draft again (its regions show the old route + * until it is confirmed again). Returns `after` itself when nothing changes. + */ +export function draftsAfterEdit(before: readonly MapPath[], after: MapPath[]): MapPath[] { + const old = new Map(before.map((p) => [pathNameKey(p.name), p])); + let changed = false; + const out = after.map((p) => { + if (!isApplied(p)) return p; + const was = old.get(pathNameKey(p.name)); + if (was && isApplied(was) && shapeKey(was) === shapeKey(p)) return p; + changed = true; + return withApplied(p, false); + }); + return changed ? out : after; +} + +// ── seams ──────────────────────────────────────────────────────────────── + +/** + * The cells where a path crossing from parent hex P's region into Q's + * crosses: [cell in P's region, its neighbour in Q's], or null when the two + * regions don't touch. The same for P→Q and Q→P (swapped), so both regions + * agree. The pair is taken near the middle of the shared edge, nudged by + * `salt` so two paths over one seam don't overlap. + */ +export function seamCrossing(layout: RegionLayout, p: [number, number], q: [number, number], salt: string): [HexKey, HexKey] | null { + const pk = key(p[0], p[1]), qk = key(q[0], q[1]); + const [u, v] = pk < qk ? [p, q] : [q, p]; + const vCells = new Set(regionCells(layout, v[0], v[1]).map(([x, y]) => key(x, y))); + const pairs: [HexKey, HexKey][] = []; + for (const [x, y] of regionCells(layout, u[0], u[1])) { + for (const [a, b] of childNeighbours(layout, x, y)) { + const nk = key(a, b); + if (vCells.has(nk)) pairs.push([key(x, y), nk]); + } + } + if (!pairs.length) return null; + // Along the shared edge: across the line between the two regions' centres. + const [ux, uy] = regionCentrePoint(layout, u[0], u[1]); + const [vx, vy] = regionCentrePoint(layout, v[0], v[1]); + const tx = -(vy - uy), ty = vx - ux; + const along = ([a, b]: [HexKey, HexKey]) => { + const [ax, ay] = childPoint(layout, ...xy(a)); + const [bx, by] = childPoint(layout, ...xy(b)); + return ((ax + bx) / 2) * tx + ((ay + by) / 2) * ty; + }; + const sorted = pairs + .map((pr) => ({ pr, t: along(pr) })) + .sort((a, b) => a.t - b.t || (a.pr[0] < b.pr[0] ? -1 : a.pr[0] > b.pr[0] ? 1 : a.pr[1] < b.pr[1] ? -1 : 1)) + .map((s) => s.pr); + const n = sorted.length; + const spread = Math.floor(n / 4); + const h = hashString(`${salt}|${pk < qk ? pk : qk}|${pk < qk ? qk : pk}`) / 4294967296; + const idx = Math.min(n - 1, Math.max(0, Math.floor((n - 1) / 2) + Math.round((h * 2 - 1) * spread))); + const [a, b] = sorted[idx]; + return pk < qk ? [a, b] : [b, a]; +} + +/** The salt that keeps one path's seams its own: world seed and path name. */ +export function seamSalt(worldSeed: number, pathName: string): string { + return `${worldSeed >>> 0}|${pathNameKey(pathName)}`; +} + +// ── projecting one path ────────────────────────────────────────────────── + +/** One resolved overworld branch (resolve.ts ResolvedBranch, the parts used here). */ +export interface OverworldBranch { + branch: number; + hexes: HexKey[]; + forkFrom?: { branch: number }; + joinTo?: { branch: number }; +} + +/** The route inside region `region` (parent hex key) between two of its cells, inclusive. */ +export type RegionRouteFn = (region: HexKey, from: HexKey, to: HexKey) => HexKey[]; + +/** + * An overworld path's routes in the regions it crosses: parent hex key → + * hex chains (child-grid keys), in order (the first is the region path's + * main line; a later one that starts on an earlier one is a fork). Only + * regions `wanted` says yes to are routed. + */ +export function projectPath( + layout: RegionLayout, + salt: string, + branches: readonly OverworldBranch[], + route: RegionRouteFn, + wanted: (region: HexKey) => boolean, +): Map { + const out = new Map(); + const firstIn = new Map(); + const centre = (r: HexKey) => key(...regionCentreCell(layout, ...xy(r))); + const midOf = (branch: number, region: HexKey) => { + const c = firstIn.get(`${branch}|${region}`); + return c ? c[Math.floor((c.length - 1) / 2)] : undefined; + }; + const seamMemo = new Map(); + const seam = (a: HexKey, b: HexKey) => { + const k = `${a}>${b}`; + if (!seamMemo.has(k)) seamMemo.set(k, seamCrossing(layout, xy(a), xy(b), salt)); + return seamMemo.get(k)!; + }; + for (const b of branches) { + const H = b.hexes; + if (H.length < 2) continue; + const last = H.length - 1; + for (let i = 0; i <= last; i++) { + const R = H[i]; + if (!wanted(R)) continue; + const enter = i > 0 ? seam(H[i - 1], R)?.[1] : undefined; + const leave = i < last ? seam(R, H[i + 1])?.[0] : undefined; + const from = enter ?? (i === 0 && b.forkFrom ? midOf(b.forkFrom.branch, R) : undefined) ?? centre(R); + const to = leave ?? (i === last && b.joinTo ? midOf(b.joinTo.branch, R) : undefined) ?? centre(R); + const chain = route(R, from, to); + if (chain.length < 2) continue; + const list = out.get(R) ?? []; + list.push(chain); + out.set(R, list); + const fk = `${b.branch}|${R}`; + if (!firstIn.has(fk)) firstIn.set(fk, chain); + } + } + return out; +} + +// ── region paths ───────────────────────────────────────────────────────── + +/** + * A region's paths with the ones owned by overworld path `owner` replaced by + * `next` (or removed, for null). The replacement keeps the old one's place, + * its name (the user may have renamed it) and notes; a new one gets the + * overworld path's name, made unique. `alsoOwned` adopts more paths as + * owned (orphans of a renamed overworld path). User-drawn paths are kept + * as they are. + */ +export function mergeOwned( + existing: readonly MapPath[], + owner: string, + next: MapPath | null, + alsoOwned: (p: MapPath) => boolean = () => false, +): MapPath[] { + const mine = (p: MapPath) => { + const o = ownerOf(p); + return (o !== undefined && pathNameKey(o) === pathNameKey(owner)) || (o !== undefined && alsoOwned(p)); + }; + const at = existing.findIndex(mine); + const old = at >= 0 ? existing[at] : undefined; + const kept = existing.filter((p) => !mine(p)); + if (!next) return kept; + const placed: MapPath = { ...next, extra: withExtraCell({ ...(old?.extra ?? {}), ...(next.extra ?? {}) }, OWNER_COL, owner) }; + placed.name = old ? old.name : uniquePathName(next.name, kept.map((p) => p.name)); + if (old?.notes !== undefined && placed.notes === undefined) placed.notes = old.notes; + const out = [...kept]; + const before = at >= 0 ? existing.slice(0, at).filter((p) => !mine(p)).length : out.length; + out.splice(before, 0, placed); + return out; +} + +// ── carving ────────────────────────────────────────────────────────────── + +/** + * The terrain a carve setting means on a palette: a terrain of that name + * (any case), else the palette's first terrain of that terrain type + * ("water"). Undefined when it names nothing on the palette, or is unset. + */ +export function carveTerrainFor(carves: string | undefined, palette: readonly TerrainColor[]): string | undefined { + const v = carves?.trim().toLowerCase(); + if (!v) return undefined; + const byName = palette.find((t) => t.name.toLowerCase() === v); + if (byName) return byName.name; + return palette.find((t) => t.type?.toLowerCase() === v)?.name; +} + +/** A path type's carve width: 0 (its own hexes) or 1 (and the hexes beside them). */ +export function carveWidthOf(t: Pick | undefined): 0 | 1 { + return t?.carveWidth === 1 ? 1 : 0; +} + +/** The cells a carve covers: the chains' hexes, widened by `width`, kept to `inside`. */ +export function carveCells( + chains: readonly (readonly HexKey[])[], + width: 0 | 1, + inside: (k: HexKey) => boolean, + neighbours: (k: HexKey) => HexKey[], +): Set { + const out = new Set(); + for (const c of chains) { + for (const k of c) { + if (inside(k)) out.add(k); + if (width === 1) for (const n of neighbours(k)) if (inside(n)) out.add(n); + } + } + return out; +} + +/** The writes a carve makes: every cell that isn't locked and isn't that terrain already. */ +export function carveWrites( + cells: Iterable, + terrain: string, + now: (k: HexKey) => { terrain?: string; locked?: boolean } | undefined, +): [HexKey, { terrain: string }][] { + const out: [HexKey, { terrain: string }][] = []; + for (const k of [...cells].sort()) { + const h = now(k); + if (h?.locked || h?.terrain === terrain) continue; + out.push([k, { terrain }]); + } + return out; +} + +/** Child-grid neighbours as keys (for carveCells). */ +export function childNeighbourKeys(layout: RegionLayout): (k: HexKey) => HexKey[] { + return (k) => childNeighbours(layout, ...xy(k)).map(([x, y]) => key(x, y)); +} diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index 0ad9af74..60422fa4 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -41,6 +41,7 @@ import { type RegionPlan, } from "./regionWorld"; import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; +import { applyConfirmedPaths } from "./overworldPaths"; export function gridRulesOf(plugin: HexmakerPlugin): GridRules { return { orientation: plugin.settings.hexOrientation, stagger: plugin.settings.staggerOffset ?? "odd" }; @@ -352,6 +353,8 @@ export async function createRegion(plugin: HexmakerPlugin, parentName: string, p if (plan?.paths?.length) addGeneratedPaths(plugin, res.name, plan.paths); if (plan?.note) new Notice(`${plugin.mapLabel(res.name)}: ${plan.note}`); await plugin.linkRegion(parentName, px, py, res.name); + // Confirmed overworld paths that cross this hex: routed through the new terrain, then carved. + applyConfirmedPaths(plugin, res.name); await fillBlankParent(plugin, parentName, px, py, res.name); return res; } @@ -462,6 +465,8 @@ export async function regenerateRegion(plugin: HexmakerPlugin, regionName: strin plugin.mapStore.setMany(regionName, cells); // A generator's paths replace the ones of the same types it drew before. if (plan.paths?.length) addGeneratedPaths(plugin, regionName, plan.paths, new Set(plan.paths.map((p) => p.typeName))); + // Confirmed overworld paths go back in, over the new terrain. + applyConfirmedPaths(plugin, regionName); if (plan.note) new Notice(`${plugin.mapLabel(regionName)}: ${plan.note}`); if (plan.biome) region.biome = plan.biome; if (opts.seed !== undefined) region.regionSeed = opts.seed; diff --git a/src/palettes/pathTypeTable.ts b/src/palettes/pathTypeTable.ts index 7b56a31b..72ad651b 100644 --- a/src/palettes/pathTypeTable.ts +++ b/src/palettes/pathTypeTable.ts @@ -34,14 +34,21 @@ export const PATH_TYPES_INTRO = "through the middles of the edges between hexes) or edge (straight along the hex borders). Avoid impassable " + "is yes or no: whether auto-route goes around impassable terrain (no also lets generated submaps run it " + "through water, like a river). Auto-route is direct (keeps to the straight line) or winding (wanders). " + + "Carves is what an overworld path of this type turns the hexes it crosses into when you confirm it into " + + "its regions: a terrain's name, a terrain type (water), or none. Carve width is 0 (the path's hexes) or 1 " + + "(and the hexes beside them). " + "To have no path types, delete the rows but keep the header line."; const HEADERS = ["Path", "Color", "Width", "Style", "Routing", "Avoid impassable", "Auto-route"] as const; +/** Written when a type carves, or the table already has them (kept compact otherwise). */ +const CARVE_HEADERS = ["Carves", "Carve width"] as const; -type Column = "name" | "color" | "width" | "style" | "routing" | "avoid" | "autoRoute"; +type Column = "name" | "color" | "width" | "style" | "routing" | "avoid" | "autoRoute" | "carves" | "carveWidth"; function columnFor(header: string): Column | null { const h = header.trim().toLowerCase().replace(/\s+/g, " "); + if (/^carves? ?(width|wide|size)$/.test(h)) return "carveWidth"; + if (/^carves?( terrain| into| to)?$/.test(h)) return "carves"; if (["path", "paths", "path type", "name", "type"].includes(h)) return "name"; if (h === "color" || h === "colour") return "color"; if (h === "width" || h === "thickness" || h === "size") return "width"; @@ -135,6 +142,19 @@ function parseAutoRoute(raw: string | undefined): PathAutoRoute | undefined { return undefined; } +/** A Carves cell: blank, none, no or - → nothing; anything else as typed. */ +function parseCarves(raw: string | undefined): string | undefined { + const v = (raw ?? "").trim(); + if (!v || /^(none|no|nothing|-+|off)$/i.test(v)) return undefined; + return v; +} + +/** A Carve width cell: 1 (or wide) → 1, else 0. */ +function parseCarveWidth(raw: string | undefined): number { + const v = (raw ?? "").trim().toLowerCase(); + return /^(1|wide|one)/.test(v) || Number.parseFloat(v) >= 1 ? 1 : 0; +} + function parseWidth(raw: string | undefined): number { const n = Number.parseFloat((raw ?? "").replace(/px$/i, "")); if (!Number.isFinite(n)) return 3; @@ -206,6 +226,9 @@ export function parsePathTypes(content: string, opts: ParsePathTypesOptions = {} avoidImpassable, autoRoute: auto ?? (opts.legacy ? legacyAutoRoute(name, avoidImpassable) : "direct"), }; + const carves = parseCarves(row.carves); + if (carves) t.carves = carves; + if (parseCarveWidth(row.carveWidth) === 1) t.carveWidth = 1; types.push(t); if (Object.keys(own).length) extra.set(name, own); } @@ -220,14 +243,18 @@ function escapeCell(value: string | undefined): string { export function serializePathTypes( types: PathType[], extra?: { headers: string[]; rows: Map> }, + opts: { carveColumns?: boolean } = {}, ): string { const extraHeaders = extra?.headers ?? []; - const headers = [...HEADERS, ...extraHeaders]; + const carving = !!opts.carveColumns || types.some((t) => !!t.carves?.trim() || t.carveWidth === 1); + const headers = [...HEADERS, ...(carving ? CARVE_HEADERS : []), ...extraHeaders]; const lines = [`| ${headers.join(" | ")} |`, `| ${headers.map(() => "---").join(" | ")} |`]; for (const t of types) { const own = extra?.rows.get(t.name) ?? {}; const avoid = t.avoidImpassable === false ? "no" : "yes"; - const cells = [t.name, colorCell(t.color), String(t.width), t.lineStyle, t.routing, avoid, t.autoRoute ?? "direct", ...extraHeaders.map((h) => own[h])]; + const carves = t.carves?.trim() || "none"; + const carveCells = carving ? [carves, String(t.carveWidth === 1 ? 1 : 0)] : []; + const cells = [t.name, colorCell(t.color), String(t.width), t.lineStyle, t.routing, avoid, t.autoRoute ?? "direct", ...carveCells, ...extraHeaders.map((h) => own[h])]; lines.push(`| ${cells.map(escapeCell).join(" | ")} |`); } return lines.join("\n"); @@ -235,7 +262,7 @@ export function serializePathTypes( /** Order-sensitive comparison key (order is the picker's order). */ export function pathTypesKey(types: PathType[] | undefined): string { - return JSON.stringify((types ?? []).map((t) => [t.name, t.color, t.width, t.lineStyle, t.routing, t.avoidImpassable ?? null, t.autoRoute ?? null])); + return JSON.stringify((types ?? []).map((t) => [t.name, t.color, t.width, t.lineStyle, t.routing, t.avoidImpassable ?? null, t.autoRoute ?? null, t.carves?.trim() || null, t.carveWidth === 1 ? 1 : 0])); } /** @@ -252,7 +279,8 @@ export function setPathTypes(content: string, types: PathType[]): string { const lines = text.split("\n"); const span = findPathTypesTable(lines); if (span) { - const table = serializePathTypes(types, parsed ? { headers: parsed.extraHeaders, rows: parsed.extra } : undefined); + const carveColumns = span.columns.includes("carves") || span.columns.includes("carveWidth"); + const table = serializePathTypes(types, parsed ? { headers: parsed.extraHeaders, rows: parsed.extra } : undefined, { carveColumns }); // Whatever we couldn't read stays in the note under the table (as an // indented block, so it isn't read as a table), so nothing typed is lost. const unread = parsed ? parsed.skipped : lines.slice(span.start, span.end).map((l) => l.trim()); diff --git a/src/types.ts b/src/types.ts index d24fe6fd..e239be3b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -40,6 +40,14 @@ export interface PathType { avoidImpassable: boolean; /** Auto-route keeps to the straight line ("direct") or wanders ("winding"). */ autoRoute: PathAutoRoute; + /** When an overworld path of this type is confirmed into its regions, the + * hexes it crosses there become this terrain: a terrain's name, or a + * terrain type ("water": the palette's first water terrain). Unset = + * terrain is left alone. Locked hexes are never repainted. */ + carves?: string; + /** How wide the carve is: 0 = the path's own hexes, 1 = those and the + * hexes beside them. Unset = 0. */ + carveWidth?: number; } export interface PathChain { diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index fb19f107..284d291f 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -20,6 +20,7 @@ import type { MapPath, PathType, TerrainColor } from "../types"; import { generatedToMapPaths } from "../paths/fromGenerated"; import { pathTypeStyleFor } from "../paths/mapContext"; import type { RouteContext } from "../paths/router"; +import { ownerOf } from "../overworld/pathProjection"; import type { StyleFor } from "../paths/resolve"; import { learnModel, @@ -213,7 +214,8 @@ export function toPathsOn( */ export function addGeneratedPaths(plugin: HexmakerPlugin, mapName: string, paths: MapPath[], replaceTypes?: ReadonlySet): void { const current = plugin.mapStore.paths(mapName); - const kept = replaceTypes ? current.filter((p) => !replaceTypes.has(p.typeName)) : [...current]; + // Paths put there from the overworld (an "Overworld path" cell) are the overworld's, never the generator's. + const kept = replaceTypes ? current.filter((p) => !replaceTypes.has(p.typeName) || !!ownerOf(p)) : [...current]; if (!paths.length && kept.length === current.length) return; plugin.mapStore.setPaths(mapName, [...kept, ...paths]); } diff --git a/styles.css b/styles.css index fd35656e..7fcbd33c 100644 --- a/styles.css +++ b/styles.css @@ -7471,6 +7471,28 @@ button.duckmage-terrain-legend-chip { opacity: 0.85; cursor: help; } +/* Overworld paths: a draft (not confirmed into its regions) is drawn faded. */ +.duckmage-svg-path-line.duckmage-svg-path-draft { + opacity: 0.5; +} +.duckmage-hex-map-controls .duckmage-path-confirm-btn { + opacity: 1; + font-weight: 600; +} +.duckmage-edit-region-paths { + margin: 0; + padding-left: 1.2em; +} +.duckmage-edit-region-paths li { + display: flex; + align-items: center; + gap: 0.5em; + margin: 2px 0; +} +.duckmage-edit-region-path-state { + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} /* Path picker: Hex by hex / Auto-route switch. */ .duckmage-path-draw-mode { diff --git a/tests/overworldPaths.test.ts b/tests/overworldPaths.test.ts new file mode 100644 index 00000000..a5ae5236 --- /dev/null +++ b/tests/overworldPaths.test.ts @@ -0,0 +1,439 @@ +/** + * Overworld paths confirmed into their regions (owner 2026-10-11): seams + * that both neighbouring regions agree on, determinism, ownership (user + * paths untouched, re-confirm replaces, rename kept), undo as one step, + * terrain carving driven by the path TYPE (locked cells kept), and new or + * regenerated regions picking confirmed paths up. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { hexNeighbors, type Orientation, type Stagger } from "../packages/hex-wfc/src/grid"; +import { inRegion, regionBox, regionCells, type RegionLayout } from "../src/overworld/layout"; +import { + APPLIED_COL, + carveCells, + carveTerrainFor, + carveWrites, + draftsAfterEdit, + isApplied, + mergeOwned, + OWNER_COL, + ownerOf, + projectPath, + seamCrossing, + withApplied, + type OverworldBranch, +} from "../src/overworld/pathProjection"; +import { + applyConfirmedPaths, + applyProjectionUndo, + confirmOverworldPath, + overworldPathsAt, + prepareProjectionUndo, + removeOverworldPath, + type ProjectionUndo, +} from "../src/overworld/overworldPaths"; +import { PathsService } from "../src/paths/PathsService"; +import { parsePathTypes, serializePathTypes } from "../src/palettes/pathTypeTable"; +import { setModeMapLookup } from "../src/modeGate"; +import type { HexData } from "../src/maps/mapNote"; +import type { MapData, MapPath, PathType, TerrainColor } from "../src/types"; + +const ORIENTS: Orientation[] = ["flat", "pointy"]; +const STAGGERS: Stagger[] = ["odd", "even"]; +const xy = (k: string): [number, number] => k.split("_").map(Number) as [number, number]; +const adjacent = (l: RegionLayout, a: string, b: string) => hexNeighbors(...xy(a), l.orientation, l.childStagger).some(([x, y]) => `${x}_${y}` === b); + +describe("seam crossings", () => { + it("both regions agree: the cells are neighbours, one in each region, the same either way round", () => { + for (const orientation of ORIENTS) for (const parentStagger of STAGGERS) for (const childStagger of STAGGERS) for (const size of [3, 4, 8]) { + const l: RegionLayout = { footprint: "rect", size, orientation, parentStagger, childStagger }; + for (const p of [[1, 1], [2, 1], [2, 2]] as [number, number][]) { + for (const q of hexNeighbors(p[0], p[1], orientation, parentStagger)) { + const pq = seamCrossing(l, p, q, "salt"); + const qp = seamCrossing(l, q, p, "salt"); + expect(pq).not.toBeNull(); + expect(qp).toEqual([pq![1], pq![0]]); + expect(inRegion(l, p[0], p[1], ...xy(pq![0]))).toBe(true); + expect(inRegion(l, q[0], q[1], ...xy(pq![1]))).toBe(true); + expect(adjacent(l, pq![0], pq![1])).toBe(true); + } + } + } + }); + + it("is deterministic, and the salt (path name) moves it along the seam", () => { + const l: RegionLayout = { footprint: "rect", size: 8, orientation: "flat", parentStagger: "odd", childStagger: "odd" }; + expect(seamCrossing(l, [1, 1], [2, 1], "a")).toEqual(seamCrossing(l, [1, 1], [2, 1], "a")); + const seen = new Set(["a", "b", "c", "d", "e", "f"].map((s) => JSON.stringify(seamCrossing(l, [1, 1], [2, 1], s)))); + expect(seen.size).toBeGreaterThan(1); + }); + + it("a projected path runs inside each region and joins at every seam", () => { + const l: RegionLayout = { footprint: "rect", size: 5, orientation: "flat", parentStagger: "odd", childStagger: "odd" }; + const branch: OverworldBranch = { branch: 0, hexes: ["0_1", "1_1", "2_1", "2_2"] }; + const line = (a: string, b: string) => { + // A plain neighbour walk (any route works for the seam property). + const out = [a]; + let cur = a; + for (let guard = 0; cur !== b && guard < 100; guard++) { + const [bx, by] = xy(b); + const next = hexNeighbors(...xy(cur), l.orientation, l.childStagger) + .sort((p, q) => Math.hypot(p[0] - bx, p[1] - by) - Math.hypot(q[0] - bx, q[1] - by))[0]; + cur = `${next[0]}_${next[1]}`; + out.push(cur); + } + return out; + }; + const out = projectPath(l, "s", [branch], (_r, a, b) => line(a, b), () => true); + expect([...out.keys()]).toEqual(branch.hexes); + for (const [r, chains] of out) for (const k of chains[0]) expect(inRegion(l, ...xy(r), ...xy(k))).toBe(true); + for (let i = 0; i + 1 < branch.hexes.length; i++) { + const a = out.get(branch.hexes[i])![0], b = out.get(branch.hexes[i + 1])![0]; + expect(adjacent(l, a[a.length - 1], b[0])).toBe(true); + } + // Only wanted regions are routed; the rest still line up with them. + const some = projectPath(l, "s", [branch], (_r, a, b) => line(a, b), (r) => r === "1_1"); + expect(some.get("1_1")).toEqual(out.get("1_1")); + expect(some.size).toBe(1); + }); + + it("a fork starts on the main line's route in the region it leaves from", () => { + const l: RegionLayout = { footprint: "rect", size: 5, orientation: "flat", parentStagger: "odd", childStagger: "odd" }; + const route = (_r: string, a: string, b: string) => (a === b ? [a] : [a, b]); + const out = projectPath(l, "s", [ + { branch: 0, hexes: ["0_1", "1_1", "2_1"] }, + { branch: 1, hexes: ["1_1", "1_2"], forkFrom: { branch: 0 } }, + ], route, () => true); + const [main, fork] = out.get("1_1")!; + expect(main.includes(fork[0])).toBe(true); + }); +}); + +describe("ownership and drafts", () => { + const owned = (name: string, owner: string, anchors = ["0_0", "1_0"]): MapPath => ({ name, typeName: "River", branches: [{ anchors }], extra: { [OWNER_COL]: owner } }); + const user: MapPath = { name: "Mill Lane", typeName: "Road", branches: [{ anchors: ["0_0", "0_2"] }] }; + + it("replaces only the paths of that overworld path, in place, keeping a name the user gave", () => { + const before = [user, owned("Silver Run", "Great River"), owned("Other", "Other River")]; + const next: MapPath = { name: "Great River", typeName: "River", branches: [{ anchors: ["2_2", "3_3"] }] }; + const after = mergeOwned(before, "Great River", next); + expect(after.map((p) => p.name)).toEqual(["Mill Lane", "Silver Run", "Other"]); + expect(after[0]).toBe(user); + expect(after[1].branches[0].anchors).toEqual(["2_2", "3_3"]); + expect(ownerOf(after[1])).toBe("Great River"); + expect(mergeOwned(before, "Great River", null).map((p) => p.name)).toEqual(["Mill Lane", "Other"]); + }); + + it("a new projected path gets the overworld name, made unique against user paths", () => { + const after = mergeOwned([{ ...user, name: "Great River" }], "Great River", { name: "Great River", typeName: "River", branches: [{ anchors: ["1_1", "2_1"] }] }); + expect(after.map((p) => p.name)).toEqual(["Great River", "Great River 2"]); + expect(ownerOf(after[0])).toBeUndefined(); + }); + + it("Applied reads forgivingly and is cleared by a reshape, retype or rename", () => { + expect(isApplied({ extra: { applied: "Yes" } })).toBe(true); + expect(isApplied({ extra: { [APPLIED_COL]: "✓" } })).toBe(true); + expect(isApplied({ extra: { [APPLIED_COL]: "no" } })).toBe(false); + const p = withApplied({ name: "R", typeName: "River", branches: [{ anchors: ["0_0", "3_0"] }] }, true); + expect(draftsAfterEdit([p], [p])).toEqual([p]); + const moved = { ...p, branches: [{ anchors: ["0_0", "3_1"] }] }; + expect(isApplied(draftsAfterEdit([p], [moved])[0])).toBe(false); + expect(isApplied(draftsAfterEdit([p], [{ ...p, typeName: "Road" }])[0])).toBe(false); + expect(isApplied(draftsAfterEdit([p], [{ ...p, name: "S" }])[0])).toBe(false); + // Other columns stay. + const withNotes = withApplied({ ...p, extra: { ...p.extra, Travel: "3 days" } }, false); + expect(withNotes.extra).toEqual({ Travel: "3 days" }); + }); +}); + +describe("carving is the path type's, never its name's", () => { + const palette: TerrainColor[] = [ + { name: "grass", type: "grassland", color: "#0f0" }, + { name: "ocean", type: "water", color: "#00f" }, + { name: "lake", type: "water", color: "#09f" }, + ]; + it("a terrain name first, then a terrain type, else nothing", () => { + expect(carveTerrainFor("Lake", palette)).toBe("lake"); + expect(carveTerrainFor("water", palette)).toBe("ocean"); + expect(carveTerrainFor("lava", palette)).toBeUndefined(); + expect(carveTerrainFor(undefined, palette)).toBeUndefined(); + }); + it("width 1 takes the hexes beside the path; locked and already-carved cells are left", () => { + const nb = (k: string) => hexNeighbors(...xy(k), "flat", "odd").map(([x, y]) => `${x}_${y}`); + const inside = (k: string) => { const [x, y] = xy(k); return x >= 0 && y >= 0 && x < 6 && y < 6; }; + expect(carveCells([["2_2", "3_2"]], 0, inside, nb)).toEqual(new Set(["2_2", "3_2"])); + expect(carveCells([["2_2", "3_2"]], 1, inside, nb).size).toBeGreaterThan(8); + const now = (k: string) => (k === "2_2" ? { terrain: "grass", locked: true } : k === "3_2" ? { terrain: "lake" } : { terrain: "grass" }); + expect(carveWrites(["2_2", "3_2", "4_2"], "lake", now)).toEqual([["4_2", { terrain: "lake" }]]); + }); + it("the palette note's Carves columns round-trip, and stay out of tables that don't use them", () => { + const types: PathType[] = [ + { name: "Road", color: "#a16207", width: 4, lineStyle: "solid", routing: "through", avoidImpassable: true, autoRoute: "direct" }, + { name: "Lava flow", color: "#f00", width: 3, lineStyle: "solid", routing: "meander", avoidImpassable: false, autoRoute: "winding", carves: "lava", carveWidth: 1 }, + ]; + const table = serializePathTypes(types); + expect(table).toContain("| Carves | Carve width |"); + expect(table).toContain("| Road | `#a16207` | 4 | solid | through | yes | direct | none | 0 |"); + expect(parsePathTypes(`## Path types\n\n${table}\n`)!.types).toEqual(types); + expect(serializePathTypes([types[0]])).not.toContain("Carves"); + }); +}); + +// ── the vault part, over a small world ────────────────────────────────── + +const PALETTE: TerrainColor[] = [ + { name: "grass", type: "grassland", color: "#0f0" }, + { name: "forest", type: "forest", color: "#060" }, + { name: "ocean", type: "water", color: "#00f", impassable: true }, +]; +const TYPES: PathType[] = [ + { name: "River", color: "#3b82f6", width: 3, lineStyle: "solid", routing: "meander", avoidImpassable: false, autoRoute: "winding", carves: "water" }, + { name: "Road", color: "#a16207", width: 4, lineStyle: "solid", routing: "through", avoidImpassable: true, autoRoute: "direct" }, +]; +const LAYOUT: RegionLayout = { footprint: "rect", size: 5, orientation: "flat", parentStagger: "odd", childStagger: "odd" }; + +function world(opts: { skipRegions?: string[]; mode?: string } = {}) { + const maps: MapData[] = []; + const hexes = new Map>(); + const table = (m: string) => { + let t = hexes.get(m); + if (!t) hexes.set(m, (t = new Map())); + return t; + }; + const ow = { + name: "ow", paletteName: "P", workMode: opts.mode, + gridSize: { cols: 4, rows: 3 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", + regions: { footprint: "rect", size: 5, blend: "normal", worldId: "w1", stagger: "odd" }, + pathChains: [], paths: [], + } as unknown as MapData; + maps.push(ow); + const addRegion = (px: number, py: number) => { + const b = regionBox(LAYOUT, px, py); + const name = `r-${px}-${py}`; + maps.push({ name, paletteName: "P", submapKind: "region", parent: { map: "ow", hex: `${px}_${py}` }, gridSize: { cols: b.cols, rows: b.rows }, gridOffset: { x: b.x, y: b.y }, staggerOffset: "odd", pathChains: [], paths: [] } as unknown as MapData); + for (const [x, y] of regionCells(LAYOUT, px, py)) table(name).set(`${x}_${y}`, { terrain: (x + y) % 3 ? "grass" : "forest" }); + return name; + }; + for (let py = 0; py < 3; py++) for (let px = 0; px < 4; px++) { + table("ow").set(`${px}_${py}`, { terrain: "grass" }); + if (!opts.skipRegions?.includes(`${px}_${py}`)) addRegion(px, py); + } + const getMap = (n: string) => maps.find((m) => m.name === n); + let recorder: ((m: string, k: string, before: HexData | undefined) => void) | null = null; + const mapStore = { + get: (m: string, k: string) => hexes.get(m)?.get(k), + all: (m: string) => table(m), + set: (m: string, k: string, patch: Record) => { + recorder?.(m, k, table(m).get(k)); + const h: Record = { ...(table(m).get(k) ?? {}) }; + for (const [f, v] of Object.entries(patch)) { + if (v === null || v === undefined || v === "" || v === false) delete h[f]; + else h[f] = v; + } + table(m).set(k, h as HexData); + return true; + }, + setMany: (m: string, cells: Iterable<[string, Partial]>) => { + for (const [k, patch] of cells) { + recorder?.(m, k, table(m).get(k)); + table(m).set(k, { ...(table(m).get(k) ?? {}), ...patch }); + } + }, + paths: (m: string) => getMap(m)?.paths ?? [], + setPaths: (m: string, ps: MapPath[]) => { getMap(m)!.paths = ps; }, + record: async (fn: () => T | Promise) => { + const before = new Map(); + recorder = (map, key, b) => { const id = `${map}|${key}`; if (!before.has(id)) before.set(id, { map, key, before: b ? { ...b } : undefined }); }; + try { + const result = await fn(); + return { result, cells: [...before.values()].map((c) => ({ ...c, after: table(c.map).get(c.key) ? { ...table(c.map).get(c.key)! } : undefined })) }; + } finally { recorder = null; } + }, + flush: async () => {}, + }; + const paths = new PathsService({ + isMapReady: () => true, + getMap, + orientation: () => "flat", + stagger: (m) => m.staggerOffset ?? "odd", + pathTypes: () => TYPES, + palette: () => PALETTE, + hexData: (m) => table(m), + }); + const undo: ProjectionUndo[] = []; + const plugin = { + settings: { maps, hexOrientation: "flat", staggerOffset: "odd" }, + getMap, + getMapPalette: () => PALETTE, + getMapPathTypes: () => TYPES, + getPaletteOrPresetTerrains: () => PALETTE, + mapStore, + paths, + pushUndo: (_m: string, item: ProjectionUndo) => undo.push(item), + saveSettings: async () => {}, + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { plugin: plugin as any, maps, hexes: table, ow, undo, addRegion, getMap }; +} + +const routeOf = (w: ReturnType, map: string, path: string) => + w.plugin.paths.resolved(map).filter((rb: { path: string }) => rb.path === path) as { hexes: string[]; branch: number }[]; + +describe("Confirm into regions", () => { + const river: MapPath = { name: "Great River", typeName: "River", branches: [{ anchors: ["0_1", "3_1"] }] }; + + it("routes through every region crossed, joined at each seam, and marks the path Applied", async () => { + const w = world(); + w.ow.paths = [river]; + const res = await confirmOverworldPath(w.plugin, "ow", "Great River"); + if ("error" in res) throw new Error(res.error); + const owRoute = routeOf(w, "ow", "Great River")[0].hexes; + expect(res.regions.length).toBe(owRoute.length); + for (let i = 0; i + 1 < owRoute.length; i++) { + const a = routeOf(w, `r-${owRoute[i].replace("_", "-")}`, "Great River")[0].hexes; + const b = routeOf(w, `r-${owRoute[i + 1].replace("_", "-")}`, "Great River")[0].hexes; + expect(adjacent(LAYOUT, a[a.length - 1], b[0])).toBe(true); + } + expect(isApplied(w.ow.paths![0])).toBe(true); + const r = w.getMap(`r-${owRoute[1].replace("_", "-")}`)!; + expect(ownerOf(r.paths![0])).toBe("Great River"); + expect(overworldPathsAt(w.plugin, "ow", owRoute[1])).toEqual([{ name: "Great River", applied: true }]); + }); + + it("is deterministic: confirming again changes nothing", async () => { + const a = world(), b = world(); + a.ow.paths = [river]; + b.ow.paths = [river]; + await confirmOverworldPath(a.plugin, "ow", "Great River"); + await confirmOverworldPath(b.plugin, "ow", "Great River"); + const snap = (w: ReturnType) => JSON.stringify(w.maps.map((m) => [m.name, m.paths])); + expect(snap(a)).toBe(snap(b)); + const before = snap(a); + await confirmOverworldPath(a.plugin, "ow", "Great River"); + expect(snap(a)).toBe(before); + }); + + it("carves the river's type terrain, never a locked hex, and leaves a road's terrain alone", async () => { + const w = world(); + w.ow.paths = [river, { name: "King's Road", typeName: "Road", branches: [{ anchors: ["0_0", "0_2"] }] }]; + await confirmOverworldPath(w.plugin, "ow", "Great River"); + const owRoute = routeOf(w, "ow", "Great River")[0].hexes; + const region = `r-${owRoute[1].replace("_", "-")}`; + const chain = routeOf(w, region, "Great River")[0].hexes; + for (const k of chain) expect(w.hexes(region).get(k)?.terrain).toBe("ocean"); + // Undo, lock a hex on the route, confirm again: the locked hex stays. + const item = w.undo.pop()!; + applyProjectionUndo(w.plugin, item, "undo"); + expect(w.hexes(region).get(chain[2])?.terrain).not.toBe("ocean"); + w.hexes(region).set(chain[2], { terrain: "forest", locked: true }); + await confirmOverworldPath(w.plugin, "ow", "Great River"); + expect(w.hexes(region).get(chain[2])).toEqual({ terrain: "forest", locked: true }); + expect(w.hexes(region).get(chain[3])?.terrain).toBe("ocean"); + // A road (its type carves nothing) changes no terrain. + const roadRegions = routeOf(w, "ow", "King's Road")[0].hexes.map((h) => `r-${h.replace("_", "-")}`); + const before = JSON.stringify(roadRegions.map((r) => [...w.hexes(r)])); + await confirmOverworldPath(w.plugin, "ow", "King's Road"); + expect(JSON.stringify(roadRegions.map((r) => [...w.hexes(r)]))).toBe(before); + expect(routeOf(w, roadRegions[0], "King's Road").length).toBe(1); + }); + + it("never touches a path drawn in the region; re-confirming after an edit replaces its own copy", async () => { + const w = world(); + w.ow.paths = [river]; + await confirmOverworldPath(w.plugin, "ow", "Great River"); + const owRoute = routeOf(w, "ow", "Great River")[0].hexes; + const region = w.getMap(`r-${owRoute[1].replace("_", "-")}`)!; + const mine: MapPath = { name: "Mill Lane", typeName: "Road", branches: [{ anchors: [`${region.gridOffset.x}_${region.gridOffset.y}`, `${region.gridOffset.x}_${region.gridOffset.y + 2}`] }] }; + region.paths = [mine, { ...region.paths![0], name: "Silver Run" }]; + // The overworld path is reshaped (a draft again), then confirmed again. + w.ow.paths = draftsAfterEdit(w.ow.paths!, [{ ...w.ow.paths![0], branches: [{ anchors: ["0_1", "3_2"] }] }]); + expect(isApplied(w.ow.paths[0])).toBe(false); + await confirmOverworldPath(w.plugin, "ow", "Great River"); + expect(region.paths![0]).toBe(mine); + const owned = w.maps.flatMap((m) => (m.paths ?? []).filter((p) => ownerOf(p) === "Great River")); + const newRoute = routeOf(w, "ow", "Great River")[0].hexes; + expect(owned.length).toBe(newRoute.length); + if (newRoute.includes(owRoute[1])) expect(region.paths!.map((p) => p.name)).toEqual(["Mill Lane", "Silver Run"]); + }); + + it("undo takes the whole projection back in one step, and redo puts it back", async () => { + const w = world(); + w.ow.paths = [river]; + const terrainBefore = JSON.stringify(w.maps.map((m) => [...w.hexes(m.name)])); + await confirmOverworldPath(w.plugin, "ow", "Great River"); + expect(w.undo.length).toBe(1); + const item = w.undo[0]; + const after = JSON.stringify(w.maps.map((m) => [m.name, m.paths])); + const prepared = prepareProjectionUndo(w.plugin, item, "undo")!; + applyProjectionUndo(w.plugin, prepared, "undo"); + expect(w.maps.every((m) => !(m.paths ?? []).some((p) => ownerOf(p)))).toBe(true); + expect(isApplied(w.ow.paths![0])).toBe(false); + expect(JSON.stringify(w.maps.map((m) => [...w.hexes(m.name)]))).toBe(terrainBefore); + applyProjectionUndo(w.plugin, prepareProjectionUndo(w.plugin, item, "redo")!, "redo"); + expect(JSON.stringify(w.maps.map((m) => [m.name, m.paths]))).toBe(after); + }); + + it("Remove from regions takes its copies out and makes it a draft", async () => { + const w = world(); + w.ow.paths = [river]; + await confirmOverworldPath(w.plugin, "ow", "Great River"); + await removeOverworldPath(w.plugin, "ow", "Great River"); + expect(w.maps.every((m) => !(m.paths ?? []).some((p) => ownerOf(p)))).toBe(true); + expect(isApplied(w.ow.paths![0])).toBe(false); + }); + + it("is refused in Play", async () => { + const w = world({ mode: "play" }); + setModeMapLookup((n) => w.getMap(n)); + try { + w.ow.paths = [river]; + expect(await confirmOverworldPath(w.plugin, "ow", "Great River")).toEqual({ error: "Switch to Build to confirm paths into regions." }); + } finally { + setModeMapLookup(null); + } + }); +}); + +describe("new and regenerated regions keep confirmed paths", () => { + it("a region made after the confirm gets the path, joined to the regions already there", async () => { + const river: MapPath = { name: "Great River", typeName: "River", branches: [{ anchors: ["0_1", "3_1"] }] }; + const probe = world(); + probe.ow.paths = [river]; + const owRoute = routeOf(probe, "ow", "Great River")[0].hexes; + const gap = owRoute[1]; + const w = world({ skipRegions: [gap] }); + w.ow.paths = [river]; + await confirmOverworldPath(w.plugin, "ow", "Great River"); + const name = w.addRegion(...xy(gap)); + expect(applyConfirmedPaths(w.plugin, name)).toBe(1); + const mid = routeOf(w, name, "Great River")[0].hexes; + const before = routeOf(w, `r-${owRoute[0].replace("_", "-")}`, "Great River")[0].hexes; + const after = routeOf(w, `r-${owRoute[2].replace("_", "-")}`, "Great River")[0].hexes; + expect(adjacent(LAYOUT, before[before.length - 1], mid[0])).toBe(true); + expect(adjacent(LAYOUT, mid[mid.length - 1], after[0])).toBe(true); + for (const k of mid) expect(w.hexes(name).get(k)?.terrain).toBe("ocean"); + }); + + it("regenerating (new terrain written) re-routes and re-carves it", async () => { + const w = world(); + w.ow.paths = [{ name: "Great River", typeName: "River", branches: [{ anchors: ["0_1", "3_1"] }] }]; + await confirmOverworldPath(w.plugin, "ow", "Great River"); + const owRoute = routeOf(w, "ow", "Great River")[0].hexes; + const name = `r-${owRoute[1].replace("_", "-")}`; + const chain = routeOf(w, name, "Great River")[0].hexes; + for (const [x, y] of regionCells(LAYOUT, ...xy(owRoute[1]))) w.hexes(name).set(`${x}_${y}`, { terrain: "grass" }); + applyConfirmedPaths(w.plugin, name); + expect(routeOf(w, name, "Great River")[0].hexes).toEqual(chain); + for (const k of chain) expect(w.hexes(name).get(k)?.terrain).toBe("ocean"); + expect(w.getMap(name)!.paths!.filter((p) => ownerOf(p)).length).toBe(1); + }); + + it("draft paths are left out of new regions", async () => { + const w = world({ skipRegions: ["1_1"] }); + w.ow.paths = [{ name: "Great River", typeName: "River", branches: [{ anchors: ["0_1", "3_1"] }] }]; + const name = w.addRegion(1, 1); + expect(applyConfirmedPaths(w.plugin, name)).toBe(0); + expect(w.getMap(name)!.paths).toEqual([]); + }); +}); diff --git a/tests/pathTypeOptions.test.ts b/tests/pathTypeOptions.test.ts index c28e9368..90fe0aea 100644 --- a/tests/pathTypeOptions.test.ts +++ b/tests/pathTypeOptions.test.ts @@ -43,7 +43,7 @@ describe("path type options (PA5)", () => { const trackway = blank("Trackway"); Object.assign(trackway, { color: "#a16207", width: 4 }); const flow = blank("Flow"); - Object.assign(flow, { color: "#3b82f6", width: 3, routing: "meander", avoidImpassable: false, autoRoute: "winding" }); + Object.assign(flow, { color: "#3b82f6", width: 3, routing: "meander", avoidImpassable: false, autoRoute: "winding", carves: "water" }); scratch.push(trackway, flow); const [road, river] = DEFAULT_PATH_TYPES; const look = (t: PathType) => ({ ...t, name: "" }); @@ -91,6 +91,7 @@ describe("path type migration from the old name rules (PA5)", () => { const river = { name: "River", color: "#3b82f6", width: 3, lineStyle: "solid", routing: "meander", avoidImpassable: false } as PathType; fillLegacyPathType(road); fillLegacyPathType(river); - expect([road, river]).toEqual(DEFAULT_PATH_TYPES); + // The look and routing; carving (an option added later) is never given by name. + expect([road, river]).toEqual(DEFAULT_PATH_TYPES.map(({ carves: _c, carveWidth: _w, ...t }) => t)); }); }); From 4777c5fde3fe71b66dcdd81e65ccad3e91c9cd0c Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:36:57 -0400 Subject: [PATCH 285/558] chore: window timers in calloutMemory (reviewer lint) Co-Authored-By: Claude Opus 5.5 --- src/maps/calloutMemory.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/maps/calloutMemory.ts b/src/maps/calloutMemory.ts index 701d0c0a..68eb4bf4 100644 --- a/src/maps/calloutMemory.ts +++ b/src/maps/calloutMemory.ts @@ -65,13 +65,13 @@ export class CalloutMemory { private scheduleSave(): void { this.dirty = true; - if (this.saveTimer !== null) activeWindow.clearTimeout(this.saveTimer); - this.saveTimer = activeWindow.setTimeout(() => void this.save(), 1500); + if (this.saveTimer !== null) window.clearTimeout(this.saveTimer); + this.saveTimer = window.setTimeout(() => void this.save(), 1500); } /** Write now, when anything changed (also on unload). */ async save(): Promise { - if (this.saveTimer !== null) activeWindow.clearTimeout(this.saveTimer); + if (this.saveTimer !== null) window.clearTimeout(this.saveTimer); this.saveTimer = null; if (!this.dirty) return; this.dirty = false; From 4b9c5f3958d645af8c2a4b3decba5e219dafa4ca Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:37:23 -0400 Subject: [PATCH 286/558] perf(callout): skip hex notes with no Map data callout early Co-Authored-By: Claude Opus 5.5 --- src/HexmakerPlugin.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 8ac36efa..7bf25a55 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -1986,6 +1986,8 @@ export default class HexmakerPlugin extends Plugin { const current = await this.app.vault.read(file); const now = () => shownValues(mapDataLines(this.hexMapDataView(mapName, x, y))); const plan = planCalloutImport(current, this.calloutMemory.get(path), now()); + // No callout and none to add: nothing to do. + if (!plan && !opts.insert) return out; if (plan) { out.notApplied.push(...plan.notApplied); out.unreadable.push(...plan.unreadable); From 77229b42720d7086023157e3904e72bed26bbd98 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:42:08 -0400 Subject: [PATCH 287/558] feat(overworld): Biome painter, Biome column always, blank biomes, BC2 setting, Coast on coasts Owner round-5 decisions BC1, BC2, BC3, MM1: - BC1: the overworld map note's Biome column is written for every hex with a biome (by label), by the first pass, set-biome, the painter and region creation; older overworlds are filled once per vault (settings.biomeColumnsFilled). New "Custom (blank)" preset and a per-biome `blank: yes` option: regions start empty, the overworld hex has no terrain, neighbours don't blend into it; offered in every biome picker, and New overworld has "Blank hexes: N". - Biome painter tool on overworlds (both views): pick a biome in a compact palette, click/drag; first placement Build/God, a placed region's biome God only and only when it differs (same biome = no-op); a stroke's remakes are one undo entry in the mode's queue. The terrain tool is disabled in the Biomes view (MM1). - BC2: "Biomes without a climate: Fill gaps only / Never place them" at the top of New/Generate overworld, kept as `no-climate-biomes:`. - BC3: Coast gets a climate (coastal lowland, chance 35%) in the shipped preset data (existing notes get it once via seedClimates). Frozen-copy test (biomeClimate.test.ts), updated deliberately: Coast's climate changes the shipped placement, so the legacy copy is compared with the old biome set (all presets but Coast). Limited still matches exactly. Expanded keeps sea, river and climate fields identical but not every biome: the repairs (majority filter, patch splits, rare swaps, transitions) used to move coastal-only Coastal fjord inland (~90 hexes over the cases, a bug); they now keep coastal-only biomes on the coast except as a last resort, and the patch-split loop gets more iterations because fjord was the only biome compatible with everything. >= 90% of hexes keep their old biome. A biome the palette can't paint (no notes loaded) is no longer placed. Existing overworlds change only when regenerated. Co-Authored-By: Claude Opus 5.5 --- README.md | 12 +- package.json | 4 +- src/HexmakerPlugin.ts | 5 +- src/hex-map/BiomeLibraryModal.ts | 7 +- src/hex-map/BiomeModals.ts | 28 ++- src/hex-map/BiomePaletteModal.ts | 71 ++++++ src/hex-map/EditRegionModal.ts | 4 +- src/hex-map/HexMapView.ts | 157 +++++++++++- src/hex-map/OverworldModals.ts | 82 +++++-- src/hex-map/help.md | 11 +- src/hex-map/overworldMinimap.ts | 12 +- src/hex-map/toolMode.ts | 8 +- src/maps/mapNote.ts | 2 + src/overworld/biomeForm.ts | 17 +- src/overworld/biomeNote.ts | 16 +- src/overworld/biomePainter.ts | 93 +++++++ src/overworld/biomePool.ts | 4 +- src/overworld/biomePresets.ts | 11 +- src/overworld/biomes.ts | 15 ++ src/overworld/overworldGen.ts | 49 +++- src/overworld/overworldInput.ts | 3 + src/overworld/overworldPass.ts | 96 +++++++- src/overworld/regionWorld.ts | 5 +- src/overworld/regionsVault.ts | 90 +++++-- src/overworld/worldBiomes.ts | 57 ++++- src/types.ts | 6 + src/workMode.ts | 2 + src/worldgen/WalkRegionModal.ts | 3 +- styles.css | 20 ++ tests/biomeClimate.test.ts | 82 +++++-- tests/biomeNotes.test.ts | 5 +- tests/biomePool.test.ts | 27 ++- tests/overworldTools.test.ts | 404 +++++++++++++++++++++++++++++++ 33 files changed, 1264 insertions(+), 144 deletions(-) create mode 100644 src/hex-map/BiomePaletteModal.ts create mode 100644 src/overworld/biomePainter.ts create mode 100644 tests/overworldTools.test.ts diff --git a/README.md b/README.md index 50c66362..de3488e2 100644 --- a/README.md +++ b/README.md @@ -123,8 +123,8 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: -- **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Each hex is written to its region as you draw, so the overworld and any open view of those regions update during the stroke. Picking a terrain on an overworld switches to this view; where there's no region yet the brush does nothing ("No region here yet; place a biome first"), and in Play it's locked ("Switch to Build to paint the regions."). In both views, clicking a hex or brick with a region goes into it in every mode; clicking an empty one sets its biome (Build and God). Right-click a region for **Enter region** and **Edit region…**: one window with the region's name (editable), the overworld hex it's on, **Enter region** and **Open map note**, its biome, a few facts (size and shape, palette, terrain counts, neighbouring regions you can click to go to, locations) and its notes. The notes are kept in the region's map note under a plain `## Notes` heading, so you can also edit them there; they're editable in every mode. In God mode the biome is a picker (choosing another remakes the region), with **Reroll** and **Settings…** (biome, blend, seed, live preview); in Build and Play it's shown with "Switch to God to change it." On an empty hex the menu offers **Set biome…** (Build and God). The overworld is the big-picture view, so it has no hex editor: right-click shows only these region-level items, **Center on this hex** and the hex's **Locations**. Painted hexes are locked, so remaking a region keeps them. -- **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one; hover a hex for its region's name). Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. +- **Regions** (the full view): every region's own hexes, drawn small and stitched together, with blank bricks (just an outline) where there's no region yet; the overworld's own hexes and coordinates aren't drawn in this view. Hover for the region's name; click to go into that region at the spot you clicked. The terrain tool paints the regions' hexes directly, across seams, so a river valley or a road corridor through several regions is one stroke; undo takes it all back. Each hex is written to its region as you draw, so the overworld and any open view of those regions update during the stroke. The terrain tool only works in this view (the Biomes view shows biomes only); where there's no region yet the brush does nothing ("No region here yet; place a biome first"), and in Play it's locked ("Switch to Build to paint the regions."). In both views, clicking a hex or brick with a region goes into it in every mode; clicking an empty one sets its biome (Build and God). Right-click a region for **Enter region** and **Edit region…**: one window with the region's name (editable), the overworld hex it's on, **Enter region** and **Open map note**, its biome, a few facts (size and shape, palette, terrain counts, neighbouring regions you can click to go to, locations) and its notes. The notes are kept in the region's map note under a plain `## Notes` heading, so you can also edit them there; they're editable in every mode. In God mode the biome is a picker (choosing another remakes the region), with **Reroll** and **Settings…** (biome, blend, seed, live preview); in Build and Play it's shown with "Switch to God to change it." On an empty hex the menu offers **Set biome…** (Build and God). The overworld is the big-picture view, so it has no hex editor: right-click shows only these region-level items, **Center on this hex** and the hex's **Locations**. Painted hexes are locked, so remaking a region keeps them. +- **Biomes**: one biome per hex, labelled, with transitions outlined (no region outlines: every hex has one; hover a hex for its region's name). The terrain tool is off here. Click a hex to set its biome. On a hex with no region yet that makes the region. On one that has a region it remakes it, which replaces its generated terrain, so that needs the map in **God** mode (below); **Reroll** and **Settings…** (blend, borders, seed, with a preview) are in the same box. Right-click → **Set biome…** works in either view. The switch highlights the view that's showing. **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (the `mode:` line in its map note) and opens in it next time; new maps are in **Build**. @@ -140,9 +140,15 @@ Which biome a hex is comes from its terrain's **Type**, never its name: forest-t **Your own biomes.** Every biome is a plain note in the biomes folder (default `{world folder}/biomes`, see Settings). The built-in ones are written there once when the plugin starts, so you can edit them like any other note; delete one and it stays deleted. A biome note has a name, a colour, a **Mix** table of terrain *types* with weights (never terrain names, so it works on any palette with types), a **Transitions** table (biomes it shouldn't touch and the biome put between them), and in its frontmatter `blend` (narrow, normal or wide), `land-share` and `min-islands` (for watery biomes) and an optional `generator: [[…]]` link. Rows that can't be read are reported and left as you wrote them; your own text in the note is kept. On an overworld's **Biomes** view, **Biomes…** lists them: **Add biome…** opens a form (pick **Blend (built-in mixing)** or one of your generators, name, colour, type weights, blend, land share, fewest islands, transitions) with a live preview of one region, and **Save** writes the note. **Edit…** opens the same form for an existing biome (built-in ones also have **Restore default**, which backs up the old note first). **Edit generator…** (also in **Edit region…**) opens the biome's generator, or its note for now. Biomes linked to a generator say "available once generator regions land" and blend until then. Your biomes appear in the biome picker and make regions with the blend field straight away. Adding and editing biomes needs Build or God. A region keeps its biome when you rename the biome's note; if you delete the note, the region keeps its terrain and **Edit region…** shows "Unknown biome". Inside a region, click the middle of the hex flower to open **Edit region…** for it; the overworld's right-click menu has **Create token here** to mark the party. +**The Biome painter.** On an overworld the drawing tools have **Biome**: pick a biome in a palette like the terrain painter's, then click or drag over hexes in either view. Each hex gets the biome and its region is made as you go, no window. A hex with no region yet can be painted in Build or God; changing the biome of a hex that has a region needs God and only remakes that region when the biome is different (painting the same biome again does nothing). Regions remade by one stroke are one undo step, in the queue of the mode they were made in; making a region for the first time makes a map and isn't undone. **Edit region…** is still there for names, notes and settings, but setting a biome never needs it. + +**The Biome column.** An overworld's map note keeps every hex's biome in the **Hexes** table's **Biome** column, by name (`| 3_2 | | forest | Temperate forest |`), not only the ones a terrain can't tell apart. It's read forgivingly (a biome's name, id or note name, any case); a name that isn't a biome is left as written and that hex goes by its terrain. Overworlds made before this get the column filled once when the plugin starts. + +**Blank biomes.** **Custom (blank)** is a shipped biome with `blank: yes`: its regions start empty for you to paint, its overworld hex has no terrain (the Biome column names it), and neighbouring regions don't blend into it. Any biome can be blank (`blank: yes` in its note, or **Regions start blank** in its form); blank biomes are never placed by World biomes or listed in pools. They're offered wherever you pick a biome: the Biome painter, **Set biome…**, **Edit region…**, walking into new land, and **New overworld…**'s **Blank hexes** (that many hexes start blank, land first and spread out). + **Biome climates.** A biome note can say where generated overworlds put it, with optional plain keys: `temperature` (cold, cool, mild, warm, hot, a range like `cold–mild`, or numbers like `0.2–0.5`), `moisture` (dry, moderate, wet, or numbers), `elevation` (`low`, `mid` for hills, `high` for peaks, `sea`, or `mouth` for the river's mouth), `coastal: yes` (only next to the coast), `chance` (like `50%`: the share of fitting hexes it takes) and `rare: yes` (at most one hex in about 20). With any of them set, World biomes can choose the biome like a built-in one; left blank, the biome is only placed by hand. The built-in biomes carry their climates in their notes too (older built-in notes get them added once), so you can see and change why tundra goes north. Where several biomes fit a hex, the rarer and then the narrower one is tried first. The biome form has the same fields in a folded **Climate (optional, for generated overworlds)** section. Values the plugin can't read are reported and ignored. -**Generate overworld (first pass).** **New overworld…** lays out the biomes of a **biome pool**: a plain note in the biome pools folder (default `{world folder}/biome-pools`) with a `Biome | Weight | Notes` table linking biome notes. **All biomes** (every built-in) is written there once. In the form, pick a pool and add or remove biomes (built-in, your own, or ones made by a generator), set a weight (1 as its note says, 0.5 half as often, 2 twice, 0 never), and **Save** or **Save as…** a new pool; the preview updates as you go. Climate, land, which way is colder, water and seed are the World biomes settings. A biome in the pool without a climate is only placed where no other biome in the pool fits. **Create** makes the map (it remembers its pool as `biome-pool: "[[…]]"`) and every region with its biome; a biome whose terrain doesn't tell it apart (one of yours) is kept in the overworld's optional **Biome** column. It's only a first pass: edit, reroll or swap any region afterwards. To redo the whole map, open the map menu → **Regions** → **Generate overworld…** (God only): locked hexes keep their terrain and their regions are left alone, every other region is remade in place (its name, notes and locked hexes stay), and missing regions are made. +**Generate overworld (first pass).** **New overworld…** lays out the biomes of a **biome pool**: a plain note in the biome pools folder (default `{world folder}/biome-pools`) with a `Biome | Weight | Notes` table linking biome notes. **All biomes** (every built-in) is written there once. In the form, pick a pool and add or remove biomes (built-in, your own, or ones made by a generator), set a weight (1 as its note says, 0.5 half as often, 2 twice, 0 never), and **Save** or **Save as…** a new pool; the preview updates as you go. Climate, land, which way is colder, water and seed are the World biomes settings. **Biomes without a climate**, at the top of the form next to the name and pool, says what the pool's biomes with no climate do: **Fill gaps only** (default: only where no other biome in the pool fits) or **Never place them** (place them by hand with the Biome painter); the overworld keeps the choice as `no-climate-biomes: fill gaps` or `never`, and regenerating uses it. **Coast** has a climate (coastal lowland, roughly 3 in 10 land hexes by the sea), so it lines generated coasts; existing overworlds only change when regenerated. **Create** makes the map (it remembers its pool as `biome-pool: "[[…]]"`) and every region with its biome; every hex's biome is kept in the overworld's **Biome** column. It's only a first pass: edit, reroll or swap any region afterwards. To redo the whole map, open the map menu → **Regions** → **Generate overworld…** (God only): locked hexes keep their terrain and their regions are left alone, every other region is remade in place (its name, notes and locked hexes stay), and missing regions are made. A small **minimap** of the overworld (bottom right) shows on the overworld and on each of its regions, with the region you're in outlined; click a hex on it to go there. **Neighbouring maps** (below) and overworlds both stay available: pick per map. A map can have N/E/S/W neighbours and regions at once; a region itself joins its neighbours by itself, so it doesn't offer the neighbour tools. diff --git a/package.json b/package.json index c1768281..9c1e542f 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldTools.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldTools.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index a03f4c08..63adc0f4 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -33,6 +33,7 @@ import { } from "./constants"; import { SetupWizardView } from "./SetupWizardView"; import { BiomeStore } from "./overworld/BiomeStore"; +import { fillBiomeColumns } from "./overworld/overworldGen"; import { WorldTypeStore } from "./space/WorldTypeStore"; import { WorldTypesModal } from "./space/WorldTypesModal"; import { PaletteStore } from "./palettes/PaletteStore"; @@ -157,9 +158,11 @@ export default class HexmakerPlugin extends Plugin { this.loadAvailableIcons(); // Palettes first (maps reference them), then map notes — which may // migrate per-hex data out of hex notes on the first run. - void this.biomeStore.init(); + const biomesReady = this.biomeStore.init(); void this.worldTypeStore.init(); const storesReady = this.paletteStore.init().then(() => this.mapStore.init()); + // BC1, once per vault: every overworld hex's biome in its Biome column. + void Promise.all([biomesReady, storesReady]).then(() => fillBiomeColumns(this)).catch((e) => console.error("Hexmaker: filling Biome columns", e)); void storesReady.then(() => this.ensureTablesForNewTerrains()); // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. void this.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { diff --git a/src/hex-map/BiomeLibraryModal.ts b/src/hex-map/BiomeLibraryModal.ts index 3d294343..3f0effd7 100644 --- a/src/hex-map/BiomeLibraryModal.ts +++ b/src/hex-map/BiomeLibraryModal.ts @@ -169,6 +169,11 @@ export class BiomeFormModal extends HexmakerModal { const showGenNote = () => genNote.setText(routeNote({ generator: state.generator || undefined }) ?? "Blend mixes the terrain types below, and blends into the biomes next to it."); showGenNote(); gen.addEventListener("change", () => { state.generator = gen.value; showGenNote(); this.schedule(); }); + const blankRow = form.createEl("label", { cls: "duckmage-region-gen-row" }); + const blankBox = blankRow.createEl("input", { type: "checkbox", attr: { "aria-label": "Regions start blank" } }); + blankBox.checked = state.blank; + blankRow.createSpan({ text: "Regions start blank (painted by hand; never placed by the generator)" }); + blankBox.addEventListener("change", () => { state.blank = blankBox.checked; this.check(); this.schedule(); }); // Name and colour. const name = field("Name").createEl("input", { type: "text", attr: { "aria-label": "Name", placeholder: "Glass wastes" } }); @@ -389,7 +394,7 @@ export class BiomeFormModal extends HexmakerModal { const fields = fieldsFromForm(this.state, existing?.id); if (existing) { // Unset optional fields are written as removed. - const full: Partial = { color: undefined, generator: undefined, blend: undefined, landShare: undefined, minIslands: undefined, shore: undefined, climate: undefined, ...fields }; + const full: Partial = { color: undefined, generator: undefined, blend: undefined, landShare: undefined, minIslands: undefined, shore: undefined, blank: undefined, climate: undefined, ...fields }; delete full.id; if (!(await plugin.biomeStore.update(existing.id, full))) return; } else { diff --git a/src/hex-map/BiomeModals.ts b/src/hex-map/BiomeModals.ts index 0a959d99..68c3006c 100644 --- a/src/hex-map/BiomeModals.ts +++ b/src/hex-map/BiomeModals.ts @@ -16,7 +16,7 @@ import { App, Notice } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { regionMapAt } from "../maps/submaps"; -import { allBiomeIds, biomeInfo, representableBiomes, representativeTerrain, type BiomeId } from "../overworld/biomes"; +import { allBiomeIds, biomeInfo, biomeNoteOf, isBlankBiome, representableBiomes, representativeTerrain, type BiomeId } from "../overworld/biomes"; import { REGION_WARP, type BlendWidth } from "../overworld/blendField"; import { regionCells } from "../overworld/layout"; import { composeAffine, drawRegionCells, cellsBox, type RegionCell } from "../overworld/overworldRender"; @@ -75,19 +75,35 @@ export function lockButton(btn: HTMLButtonElement, hint: string): void { btn.setAttr("aria-label", `${btn.getText()} (${hint})`); } -/** The biomes this overworld's palette can paint, with the terrain each paints. */ -export function paintableBiomes(plugin: HexmakerPlugin, parentName: string): { id: BiomeId; label: string; terrain: string; color: string }[] { +/** A biome offered on an overworld: the terrain it paints there (none for a blank biome) and its swatch colour. */ +export interface PaintableBiome { + id: BiomeId; + label: string; + /** Overworld terrain it paints; undefined for a blank biome (its hex stays blank). */ + terrain?: string; + color: string; +} + +/** The biomes this overworld's palette can paint (with the terrain each paints), and every blank biome. */ +export function paintableBiomes(plugin: HexmakerPlugin, parentName: string): PaintableBiome[] { const palette = plugin.getMapPalette(parentName); const shown = representableBiomes(palette); - const out: { id: BiomeId; label: string; terrain: string; color: string }[] = []; + const out: PaintableBiome[] = []; for (const id of allBiomeIds()) { + const label = biomeInfo(id)?.label ?? id; + if (isBlankBiome(id)) { out.push({ id, label, color: biomeNoteOf(id)?.color ?? "#a8a29e" }); continue; } if (!shown.has(id)) continue; const terrain = representativeTerrain(id, palette)!; - out.push({ id, label: biomeInfo(id)?.label ?? id, terrain, color: palette.find((t) => t.name === terrain)?.color ?? "#888" }); + out.push({ id, label, terrain, color: palette.find((t) => t.name === terrain)?.color ?? "#888" }); } return out; } +/** A biome tile's tooltip: what it paints. */ +export function biomeTileTitle(b: PaintableBiome): string { + return b.terrain ? `${b.label}: paints ${b.terrain}` : `${b.label}: a blank region, to paint by hand`; +} + export class BiomePickerModal extends HexmakerModal { constructor(private host: BiomeHost, private parentName: string, private px: number, private py: number) { super(host.app); @@ -112,7 +128,7 @@ export class BiomePickerModal extends HexmakerModal { if (lock) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); const grid = contentEl.createDiv({ cls: "duckmage-biome-grid" }); for (const b of paintableBiomes(plugin, this.parentName)) { - const btn = grid.createEl("button", { cls: "duckmage-biome-option" + (b.id === current ? " is-active" : ""), attr: { title: `Paints ${b.terrain}` } }); + const btn = grid.createEl("button", { cls: "duckmage-biome-option" + (b.id === current ? " is-active" : ""), attr: { title: biomeTileTitle(b) } }); btn.createSpan({ cls: "duckmage-biome-swatch" }).setCssProps({ "--duckmage-biome-color": b.color }); btn.createSpan({ text: b.label }); // With a region, its current biome stays clickable (a no-op); with diff --git a/src/hex-map/BiomePaletteModal.ts b/src/hex-map/BiomePaletteModal.ts new file mode 100644 index 00000000..eb6ec06b --- /dev/null +++ b/src/hex-map/BiomePaletteModal.ts @@ -0,0 +1,71 @@ +/** + * The Biome painter's palette (owner round 5): every biome the overworld can + * paint, as tiles like the terrain painter's. Picking one arms the painter; + * the hexes are then painted on the map, no modal per hex. "Custom (blank)" + * (and any biome marked blank) is offered too. + */ + +import { App } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { createIconEl, getIconUrl } from "../utils"; +import { biomeTileTitle, paintableBiomes } from "./BiomeModals"; +import { BiomeLibraryModal } from "./BiomeLibraryModal"; + +/** The palette's one line of help (God is the work mode's name). */ +const PAINT_HELP = "Click or drag over overworld hexes. A hex with no region gets this biome and its region. Changing a placed region's biome needs God, and only happens where the biome differs."; + +export class BiomePaletteModal extends HexmakerModal { + constructor( + app: App, + private plugin: HexmakerPlugin, + private overworld: string, + private current: string | null, + private onPick: (biome: string) => void, + ) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + const { contentEl } = this; + contentEl.addClass("duckmage-hex-editor"); + this.titleEl.setText("Paint biome"); + contentEl.createEl("p", { + cls: "setting-item-description", + text: PAINT_HELP, + }); + const palette = this.plugin.getMapPalette(this.overworld); + const biomes = paintableBiomes(this.plugin, this.overworld); + const grid = contentEl.createDiv({ cls: "duckmage-terrain-picker duckmage-terrain-picker-full duckmage-biome-palette" }); + if (!biomes.length) grid.createEl("p", { cls: "setting-item-description", text: "This overworld's palette has no terrain that stands for a biome." }); + for (const b of biomes) { + const tile = grid.createDiv({ + cls: `duckmage-terrain-option${b.id === this.current ? " is-selected" : ""}`, + attr: { title: biomeTileTitle(b), "data-biome": b.id, role: "button", tabindex: "0" }, + }); + const preview = tile.createDiv({ cls: "duckmage-terrain-preview" + (b.terrain ? "" : " duckmage-biome-blank-preview") }); + preview.setCssProps({ "--duckmage-bg": b.color }); + const entry = b.terrain ? palette.find((t) => t.name === b.terrain) : undefined; + if (entry?.icon) createIconEl(preview, getIconUrl(this.plugin, entry.icon), b.label, entry.iconColor, "duckmage-terrain-preview-icon"); + tile.createSpan({ text: b.label, cls: "duckmage-terrain-option-name" }); + const pick = () => { + this.close(); + this.onPick(b.id); + }; + tile.addEventListener("click", pick); + tile.addEventListener("keydown", (e: KeyboardEvent) => { + if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } + }); + } + const row = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); + row.createEl("button", { text: "Biomes…", attr: { title: "Add your own biomes, or edit these" } }).addEventListener("click", () => { + this.close(); + new BiomeLibraryModal(this.app, this.plugin, this.overworld).open(); + }); + } + + onClose(): void { + this.contentEl.empty(); + } +} diff --git a/src/hex-map/EditRegionModal.ts b/src/hex-map/EditRegionModal.ts index a0cc6a81..3c06fb35 100644 --- a/src/hex-map/EditRegionModal.ts +++ b/src/hex-map/EditRegionModal.ts @@ -26,7 +26,7 @@ import { biomeInfo, type BiomeId } from "../overworld/biomes"; import { hexBiomeAt, overworldOf, regenerateRegion, regionBiomeStatus, setBiomeAt } from "../overworld/regionsVault"; import { openBiomeGenerator } from "./BiomeLibraryModal"; import { editRegionPlan, terrainCountsText } from "../overworld/overworldInput"; -import { mayReshape, paintableBiomes, RegionGenModal, reshapeUndoable, type BiomeHost } from "./BiomeModals"; +import { biomeTileTitle, mayReshape, paintableBiomes, RegionGenModal, reshapeUndoable, type BiomeHost } from "./BiomeModals"; import { openNoteFocused } from "../openNote"; import { createIconEl, getIconUrl } from "../utils"; @@ -139,7 +139,7 @@ export class EditRegionModal extends HexmakerModal { for (const b of biomes) { const tile = grid.createDiv({ cls: `duckmage-terrain-option${b.id === current ? " is-selected" : ""}`, - attr: { title: `${b.label}: paints ${b.terrain}`, "data-biome": b.id, role: "button", tabindex: "0" }, + attr: { title: biomeTileTitle(b), "data-biome": b.id, role: "button", tabindex: "0" }, }); const preview = tile.createDiv({ cls: "duckmage-terrain-preview" }); preview.setCssProps({ "--duckmage-bg": b.color }); diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 90039b45..ce01f576 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -15,7 +15,7 @@ import { getGmIconsFromFile, readTokenPlace, } from "../frontmatter"; -import { cellPatch, currentCellEdits, sameValue, stillCurrent, UNDO_DEPTH, type UndoDirection } from "../undoBook"; +import { cellPatch, currentCellEdits, sameValue, stillCurrent, UNDO_DEPTH, type CellEdit, type UndoDirection } from "../undoBook"; import { HexEditorModal } from "./HexEditorModal"; import { TerrainPickerModal } from "./TerrainPickerModal"; import { IconPickerModal } from "./IconPickerModal"; @@ -83,9 +83,12 @@ import { hexChildMaps, regionMapAt, submapMenuPlan } from "../maps/submaps"; import { OverworldLayer } from "./overworldLayer"; import { OverworldMinimap } from "./overworldMinimap"; import { BiomePickerModal, type BiomeHost } from "./BiomeModals"; +import { BiomePaletteModal } from "./BiomePaletteModal"; +import { BiomeStroke } from "../overworld/biomePainter"; +import { biomeInfo, biomeNoteOf } from "../overworld/biomes"; import { EditRegionModal } from "./EditRegionModal"; -import { inOverworldGrid, overworldOf, regionHome, regionPalette, walkLock } from "../overworld/regionsVault"; -import { brushCells, FrameThrottle, terrainDiff, overworldLeftClick, overworldMenu, PAINT_LOCKED_HINT, PAINT_NO_REGION_HINT, paintTargets } from "../overworld/overworldInput"; +import { inOverworldGrid, overworldOf, paintBiomeHex, regionHome, regionPalette, walkLock } from "../overworld/regionsVault"; +import { brushCells, FrameThrottle, terrainDiff, overworldLeftClick, overworldMenu, PAINT_LOCKED_HINT, PAINT_NO_REGION_HINT, paintTargets, TERRAIN_IN_BIOMES_HINT } from "../overworld/overworldInput"; import { WalkRegionModal, type OverworldWalk } from "../worldgen/WalkRegionModal"; import type { Side } from "../worldgen/world"; import { withFeature } from "../advancedHints"; @@ -226,6 +229,7 @@ export class HexMapView extends ItemView { | "regionLink" | "swap" | "placeToken" + | "biome" | null = null; private isErasingMode = false; /** On-map "which tool is on" bar (fresh-eyes T3); text set in updateModeBar. */ @@ -257,6 +261,11 @@ export class HexMapView extends ItemView { private regionLinkBtnLabel: HTMLSpanElement | null = null; private paintRegionPath: string | null = null; private swapBtn: HTMLButtonElement | null = null; + /** The Biome painter (overworlds only): its button, swatch, biome, and the stroke being painted. */ + private biomeToolbarBtn: HTMLButtonElement | null = null; + private biomeBtnPreview: HTMLSpanElement | null = null; + private paintBiomeId: string | null = null; + private biomeStroke: BiomeStroke | null = null; private overlayPanel: OverlayPanel | null = null; private toolsPanel: DrawingToolPanel | null = null; private swapSource: { x: number; y: number } | null = null; @@ -775,6 +784,19 @@ export class HexMapView extends ItemView { btn?.toggle(ok); if (!ok) locked.push(action); } + // Overworlds: the Biome painter, and the terrain tool only in the Regions view (MM1). + const owView = OverworldLayer.viewOf(this.plugin, this.getActiveMap()); + const biomeOk = allows(mode, TOOL_ACTIONS.biome); + this.biomeToolbarBtn?.toggle(!!owView && biomeOk); + if (owView && !biomeOk) locked.push(TOOL_ACTIONS.biome); + if (this.terrainToolbarBtn) { + const off = owView === "biomes"; + this.terrainToolbarBtn.disabled = off; + this.terrainToolbarBtn.toggleClass("is-locked", off); + this.terrainToolbarBtn.setAttr("title", off ? TERRAIN_IN_BIOMES_HINT : ""); + if (off && this.drawingMode === "terrain") this.exitTerrainMode(); + } + if (!owView && this.drawingMode === "biome") this.exitBiomeMode(); const hint = lockedSummary(locked); if (this.toolsLockedEl) { this.toolsLockedEl.setText(hint ?? ""); @@ -1142,10 +1164,21 @@ export class HexMapView extends ItemView { hasDragged = true; return; } - // Overworld full view: the terrain tool paints the regions' own hexes. + // The Biome painter: each overworld hex crossed gets the biome (and its region). + if (this.drawingMode === "biome") { + const key = this.overworldHexKeyAt(e.target, e.clientX, e.clientY); + this.startBiomeStroke(); + if (key) this.biomeStroke?.add(key); + isTerrainPainting = true; + lastPaintedKey = key; + hasDragged = true; + beginDrag(); + return; + } + // Overworld Biomes view: biomes only (MM1), the terrain tool is off there. if (this.drawingMode === "terrain" && OverworldLayer.viewOf(this.plugin, this.getActiveMap()) === "biomes") { - // The brush paints the regions, so it works in the Regions view. - this.showOverworldRegions(); + new Notice(TERRAIN_IN_BIOMES_HINT); + this.exitTerrainMode(); hasDragged = true; return; } @@ -1238,6 +1271,14 @@ export class HexMapView extends ItemView { // window's document and drags silently die (issue #32). let dragDoc: Document | null = null; const onDragMove = (e: MouseEvent) => { + if (isTerrainPainting && this.drawingMode === "biome") { + const key = this.overworldHexKeyAt(dragDoc?.elementFromPoint(e.clientX, e.clientY) ?? null, e.clientX, e.clientY); + if (key && key !== lastPaintedKey) { + lastPaintedKey = key; + this.biomeStroke?.add(key); + } + return; + } if (isTerrainPainting && this.currentSubStroke) { const key = this.subHexKeyAt(e.clientX, e.clientY); if (key && key !== lastPaintedKey) lastPaintedKey = this.paintSubHexAt(e.clientX, e.clientY); @@ -1278,7 +1319,8 @@ export class HexMapView extends ItemView { }; const onDragUp = () => { if (isTerrainPainting) { - if (this.drawingMode === "terrain") this.commitTerrainStroke(); + if (this.drawingMode === "biome") void this.finishBiomeStroke(); + else if (this.drawingMode === "terrain") this.commitTerrainStroke(); else if (this.drawingMode === "icon") this.commitIconStroke(); else if (this.drawingMode === "factionLink") this.commitFactionStroke(); else if (this.drawingMode === "regionLink") this.commitRegionStroke(); @@ -1976,6 +2018,15 @@ export class HexMapView extends ItemView { this.handleTerrainButton(), ); + // Overworlds only (shown by applyWorkModeUi): paint biomes, regions made as you go. + this.biomeToolbarBtn = toolbar.createEl("button", { + cls: "duckmage-draw-btn duckmage-draw-btn-terrain duckmage-draw-btn-biome", + }); + this.biomeToolbarBtn.createSpan({ text: "Biome" }); + this.biomeBtnPreview = this.biomeToolbarBtn.createSpan({ cls: "duckmage-terrain-btn-preview" }); + this.biomeBtnPreview.hide(); + this.biomeToolbarBtn.addEventListener("click", () => this.handleBiomeButton()); + this.iconToolbarBtn = toolbar.createEl("button", { cls: "duckmage-draw-btn duckmage-draw-btn-terrain", }); @@ -2100,6 +2151,9 @@ export class HexMapView extends ItemView { } else if (mode === "placeToken") { onSwitch = () => this.handleTokenButton(true); switchLabel = "Switch token"; + } else if (mode === "biome") { + onSwitch = () => this.handleBiomeButton(); + switchLabel = "Switch biome"; } // swap: no picker → onSwitch stays null, menu shows only "Exit tool" @@ -2128,6 +2182,7 @@ export class HexMapView extends ItemView { else if (this.drawingMode === "regionLink") this.exitRegionLinkMode(); else if (this.drawingMode === "swap") this.exitSwapMode(); else if (this.drawingMode === "placeToken") this.exitTokenMode(); + else if (this.drawingMode === "biome") this.exitBiomeMode(); else { if (this.drawingMode === "path") this.exitPathMode(); this.drawingMode = null; @@ -2147,6 +2202,10 @@ export class HexMapView extends ItemView { private handleTerrainButton(): void { if (this.drawingMode !== "terrain" && !this.modeAllows(TOOL_ACTIONS.terrain)) return; + if (OverworldLayer.viewOf(this.plugin, this.getActiveMap()) === "biomes") { + new Notice(TERRAIN_IN_BIOMES_HINT); + return; + } // Keep the current tool while the picker is open: closing it without a // pick (Escape, clicking away, or after only changing the brush size) // must leave painting exactly as it was. It used to exit terrain mode @@ -2197,6 +2256,79 @@ export class HexMapView extends ItemView { ).open(); } + /** The Biome painter's button: pick a biome in the palette, then paint overworld hexes. */ + private handleBiomeButton(): void { + if (!OverworldLayer.viewOf(this.plugin, this.getActiveMap())) return; + if (this.drawingMode !== "biome" && !this.modeAllows(TOOL_ACTIONS.biome)) return; + new BiomePaletteModal(this.app, this.plugin, this.activeMapName, this.paintBiomeId, (biome) => { + this.leaveOtherToolFor("biome"); + this.drawingMode = "biome"; + this.isErasingMode = false; + this.paintBiomeId = biome; + this.updateToolbarButtonStates(); + }).open(); + } + + private exitBiomeMode(): void { + if (this.drawingMode !== "biome") return; + void this.finishBiomeStroke(); + this.drawingMode = null; + this.paintBiomeId = null; + this.updateToolbarButtonStates(); + } + + /** The overworld hex under a point: the brick's parent hex in the Regions view, else the hex there. */ + private overworldHexKeyAt(target: EventTarget | null, clientX: number, clientY: number): string | null { + const view = OverworldLayer.viewOf(this.plugin, this.getActiveMap()); + if (!view) return null; + if (view === "regions") { + const grid = this.viewportEl?.querySelector(".duckmage-hex-map-grid"); + const cell = grid ? this.overworldLayer.cellAt(grid, clientX, clientY) : null; + return cell?.parentHex ?? null; + } + const hexEl = this.hexElAt(target, clientX, clientY); + return hexEl ? `${hexEl.dataset.x}_${hexEl.dataset.y}` : null; + } + + /** A new painter stroke on the open overworld (the last one finishes first). */ + private startBiomeStroke(): void { + void this.finishBiomeStroke(); + const map = this.activeMapName; + const biome = this.paintBiomeId; + if (!biome) return; + this.biomeStroke = new BiomeStroke(async (key) => { + const [px, py] = key.split("_").map(Number); + const r = await paintBiomeHex(this.plugin, map, px, py, biome); + if ((r.step === "place" || r.step === "reshape") && !r.error && this.activeMapName === map) { + // Show it now: the hex's overworld terrain and the layer (labels, region bricks). + const el = this.viewportEl?.querySelector(`.duckmage-hex[data-x="${px}"][data-y="${py}"]`); + if (el) this.applyTerrainToHexEl(el, this.plugin.mapStore.get(map, key)?.terrain ?? null); + this.overworldLayer.scheduleRedraw(); + } + return r; + }); + } + + /** + * End the painter's stroke: once its hexes are done, one undo entry for + * the regions it remade (in the overworld's queue for its mode), the + * mode's hint if some hexes were locked, and a redraw. + */ + private async finishBiomeStroke(): Promise { + const stroke = this.biomeStroke; + if (!stroke) return; + this.biomeStroke = null; + const map = this.activeMapName; + const r = await stroke.finish(); + if (r.edits.length) { + this.pushUndo({ kind: "cells", edits: r.edits }, map); + this.updateUndoButton(); + } + for (const h of r.hints) new Notice(h); + if (r.errors.length) new Notice(r.errors[0]); + if ((r.changed || r.made.length) && this.activeMapName === map) this.renderGrid(); + } + private exitTerrainMode(): void { if (this.drawingMode !== "terrain") return; this.commitTerrainStroke(); @@ -2686,6 +2818,14 @@ export class HexMapView extends ItemView { ); this.swapBtn?.toggleClass("is-active", this.drawingMode === "swap"); this.tokenBtn?.toggleClass("is-active", this.drawingMode === "placeToken"); + this.biomeToolbarBtn?.toggleClass("is-active", this.drawingMode === "biome"); + if (this.biomeBtnPreview) { + const colour = this.drawingMode === "biome" && this.paintBiomeId ? biomeNoteOf(this.paintBiomeId)?.color : undefined; + if (colour) { + this.biomeBtnPreview.setCssProps({ "--duckmage-bg": colour }); + this.biomeBtnPreview.show(); + } else this.biomeBtnPreview.hide(); + } this.viewportEl?.toggleClass( "duckmage-draw-mode", this.drawingMode !== null, @@ -2825,6 +2965,7 @@ export class HexMapView extends ItemView { submapName: this.paintSubmapName, factionPath: this.paintFactionPath, regionPath: this.paintRegionPath, + biomeName: this.paintBiomeId ? biomeInfo(this.paintBiomeId)?.label ?? this.paintBiomeId : null, }); this.renderRouteControls(); const changed = this.modeBarTextEl.getText() !== (label ?? ""); @@ -4762,6 +4903,8 @@ export class HexMapView extends ItemView { await this.onHexTokenPlaceClick(x, y); return; } + // The Biome painter paints on press (and drag), not on click. + if (this.drawingMode === "biome") return; // Overworlds: the full view jumps into the region at the clicked hex; // the biomes view (or a hex with no region yet) sets the hex's biome. diff --git a/src/hex-map/OverworldModals.ts b/src/hex-map/OverworldModals.ts index 49918c59..6a1fede9 100644 --- a/src/hex-map/OverworldModals.ts +++ b/src/hex-map/OverworldModals.ts @@ -14,11 +14,12 @@ import { App, Notice, setIcon } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { hexDistance } from "../../packages/hex-wfc/src/grid"; -import { biomeInfo } from "../overworld/biomes"; +import { biomeInfo, biomeNoteOf } from "../overworld/biomes"; import { drawMiniOverworld, miniLayout, type MiniHex } from "../overworld/overworldRender"; import { formatBiomeRiver, withMeshFields } from "../overworld/regionWorld"; import { generateMissingRegions } from "../overworld/regionsVault"; -import { type Climate, type LandShape, type NorthIs, type WorldBiomesResult } from "../overworld/worldBiomes"; +import { parseUnclimated, UNCLIMATED_CHOICES, unclimatedText, type Climate, type LandShape, type NorthIs, type Unclimated, type WorldBiomesResult } from "../overworld/worldBiomes"; +import { pickBlankHexes } from "../overworld/overworldPass"; import { RECT_SIDES } from "../maps/submaps"; import { newWorldId } from "../worldgen/world"; import { isSpacePalette } from "../mapKinds"; @@ -130,6 +131,11 @@ export class NewOverworldModal extends HexmakerModal { private regionSize = 8; private blend: "narrow" | "normal" | "wide" = "normal"; private makeAll = true; + /** BC2: what the pool's biomes without a climate do. */ + private unclimated: Unclimated = "fill"; + /** "Blank hexes": how many hexes become a blank biome, and which one. */ + private blankCount = 0; + private blankBiome = ""; private result: WorldBiomesResult | null = null; private canvas!: HTMLCanvasElement; /** The pool: its note (undefined = a new, unsaved one) and its rows as edited. */ @@ -164,11 +170,15 @@ export class NewOverworldModal extends HexmakerModal { row.createSpan({ cls: "duckmage-region-gen-label", text: label }); return row; }; + // The top: name, pool and what the pool's biomes without a climate do (BC2: hard to miss). + const top = form.createDiv({ cls: "duckmage-ow-top" }); + const shapeBox = form.createDiv(); + if (regen) this.unclimated = parseUnclimated(regen.biomeGaps); if (!regen) { - const nameIn = field("Name").createEl("input", { type: "text", value: this.name, attr: { "aria-label": "Name" } }); + const nameIn = field("Name", top).createEl("input", { type: "text", value: this.name, attr: { "aria-label": "Name" } }); nameIn.addEventListener("input", () => { this.name = nameIn.value; }); - const shapeRow = field("Shape"); + const shapeRow = field("Shape", shapeBox); const shapeSel = shapeRow.createEl("select", { attr: { "aria-label": "Shape" } }); shapeSel.createEl("option", { value: "hex", text: "Hex-shaped" }); shapeSel.createEl("option", { value: "rect", text: "Rectangle" }); @@ -197,19 +207,31 @@ export class NewOverworldModal extends HexmakerModal { shapeSel.addEventListener("change", () => { this.shape = shapeSel.value as "rect" | "hex"; drawSize(); this.regen(); }); drawSize(); - const pal = field("Palette").createEl("select", { attr: { "aria-label": "Palette" } }); + const pal = field("Palette", shapeBox).createEl("select", { attr: { "aria-label": "Palette" } }); for (const p of world) pal.createEl("option", { value: p.name, text: p.name }); pal.value = this.palette; pal.addEventListener("change", () => { this.palette = pal.value; this.regen(); }); } // The pool. - const poolRow = field("Biome pool"); + const poolRow = field("Biome pool", top); const poolSel = poolRow.createEl("select", { attr: { "aria-label": "Biome pool" } }); const saveBtn = poolRow.createEl("button", { text: "Save", attr: { title: "Save the pool's biomes to its note" } }); const saveAs = poolRow.createEl("button", { text: "Save as…", attr: { title: "Save as a new pool note" } }); - this.poolBox = form.createEl("details", { cls: "duckmage-ow-pool" }); - this.poolNote = form.createEl("p", { cls: "setting-item-description" }); + // BC2: biomes without a climate. + const gapsRow = field("Biomes without a climate", top); + gapsRow.addClass("duckmage-ow-gaps"); + const gaps = gapsRow.createEl("select", { attr: { "aria-label": "Biomes without a climate" } }); + for (const c of UNCLIMATED_CHOICES) gaps.createEl("option", { value: c.value, text: c.label }); + gaps.value = this.unclimated; + const gapsNote = top.createEl("p", { cls: "setting-item-description" }); + const showGaps = () => gapsNote.setText(this.unclimated === "fill" + ? "Pool biomes with no climate fill only the hexes no other pool biome fits." + : "Pool biomes with no climate are never placed here: set them by hand with the Biome tool."); + showGaps(); + gaps.addEventListener("change", () => { this.unclimated = gaps.value as Unclimated; showGaps(); this.drawPool(); this.regen(); }); + this.poolBox = top.createEl("details", { cls: "duckmage-ow-pool" }); + this.poolNote = top.createEl("p", { cls: "setting-item-description" }); const fillPools = () => { poolSel.empty(); for (const p of this.pools) poolSel.createEl("option", { value: p.path, text: p.name }); @@ -271,6 +293,27 @@ export class NewOverworldModal extends HexmakerModal { const wv = waterRow.createSpan({ text: `${this.water}%` }); water.addEventListener("input", () => wv.setText(`${water.value}%`)); water.addEventListener("change", () => { this.water = Number(water.value); this.regen(); }); + // Blank hexes (new overworlds): blank-biome hexes, regions painted by hand. + if (!regen) { + const blanks = this.plugin.biomeStore.list().filter((b) => b.blank); + const blankRow = field("Blank hexes"); + const count = blankRow.createEl("input", { type: "number", value: String(this.blankCount), attr: { min: "0", step: "1", "aria-label": "Blank hexes", title: "Hexes left blank (a blank biome): their regions start empty, to paint by hand" } }); + this.blankBiome = blanks[0]?.id ?? ""; + if (blanks.length > 1) { + const which = blankRow.createEl("select", { attr: { "aria-label": "Blank biome" } }); + for (const b of blanks) which.createEl("option", { value: b.id, text: b.label }); + which.addEventListener("change", () => { this.blankBiome = which.value; this.regen(); }); + } + if (!blanks.length) { + count.disabled = true; + blankRow.createSpan({ cls: "setting-item-description", text: "No blank biome: tick 'Regions start blank' on one in Biomes…" }); + } + count.addEventListener("change", () => { + this.blankCount = Math.max(0, Math.round(Number(count.value) || 0)); + count.value = String(this.blankCount); + this.regen(); + }); + } const seedRow = field("Seed"); const seed = seedRow.createEl("input", { type: "number", value: String(this.seed), attr: { "aria-label": "Seed" } }); seed.addEventListener("change", () => { this.seed = Number(seed.value) >>> 0; this.regen(); }); @@ -336,9 +379,9 @@ export class NewOverworldModal extends HexmakerModal { if (b?.color) item.createSpan({ cls: "duckmage-ow-pool-swatch" }).setCssProps({ "--duckmage-swatch": b.color }); item.createSpan({ cls: "duckmage-ow-pool-name", text: b?.label ?? `${r.biome} (no such biome)` }); const tags: string[] = []; - if (b && !b.climate) tags.push("fills gaps"); + if (b && !b.climate) tags.push(this.unclimated === "fill" ? "fills gaps" : "by hand only"); if (b?.generator) tags.push("generator"); - if (tags.length) item.createSpan({ cls: "duckmage-ow-pool-tag", text: tags.join(", "), attr: { title: b && !b.climate ? "No climate: only placed where no other biome in the pool fits." : "Its regions are made by its generator, joined to their neighbours." } }); + if (tags.length) item.createSpan({ cls: "duckmage-ow-pool-tag", text: tags.join(", "), attr: { title: b && !b.climate ? (this.unclimated === "fill" ? "No climate: only placed where no other biome in the pool fits." : "No climate: never placed by the generator (see Biomes without a climate).") : "Its regions are made by its generator, joined to their neighbours." } }); const w = item.createEl("input", { type: "number", cls: "duckmage-biome-weight", attr: { min: "0", step: "0.5", placeholder: "1", "aria-label": `${b?.label ?? r.biome} weight`, title: "Weight: how often it's chosen where it fits (1 = as its note says)" } }); w.value = r.weight !== undefined ? String(r.weight) : ""; w.addEventListener("change", () => { @@ -361,7 +404,7 @@ export class NewOverworldModal extends HexmakerModal { const add = addRow.createEl("select", { attr: { "aria-label": "Add a biome" } }); add.createEl("option", { value: "", text: "Add a biome…" }); for (const b of this.plugin.biomeStore.list()) { - if (inPool.has(b.id)) continue; + if (inPool.has(b.id) || b.blank) continue; add.createEl("option", { value: b.id, text: `${b.label}${b.generator ? " (generator)" : ""}${b.climate ? "" : " (no climate)"}` }); } add.addEventListener("change", () => { @@ -400,7 +443,14 @@ export class NewOverworldModal extends HexmakerModal { const o = this.plugin.settings.hexOrientation; const s = (this.regenerate ? this.plugin.getMap(this.regenerate)?.staggerOffset : undefined) ?? this.plugin.settings.staggerOffset ?? "odd"; // River: kept as biome data (a delta at its mouth), never a path (paths come later). - this.result = layOutBiomes(this.plugin, cells, this.terrains(), { seed: this.seed, climate: this.climate, water: this.water / 100, land: this.land, north: this.north }, this.poolBiomes(), s); + this.result = layOutBiomes(this.plugin, cells, this.terrains(), { seed: this.seed, climate: this.climate, water: this.water / 100, land: this.land, north: this.north, unclimated: this.unclimated }, this.poolBiomes(), s); + // Blank hexes: a blank biome, no terrain (painted by hand later). + if (!this.regenerate && this.blankCount > 0 && this.blankBiome && this.result.biomes.size) { + for (const k of pickBlankHexes([...this.result.biomes.keys()], this.result.sea, this.blankCount, this.seed, o, s)) { + this.result.biomes.set(k, this.blankBiome); + this.result.terrain.delete(k); + } + } const ctx = this.canvas.getContext("2d"); if (!ctx) return; ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); @@ -414,7 +464,8 @@ export class NewOverworldModal extends HexmakerModal { return { x, y, color: colour.get(t ?? "") ?? "#333", label: "locked" }; } const b = this.result!.biomes.get(k); - return { x, y, color: colour.get(this.result!.terrain.get(k) ?? "") ?? "#333", label: b ? biomeInfo(b)?.label : undefined, ecotone: eco.has(k) }; + const t = this.result!.terrain.get(k); + return { x, y, color: (t ? colour.get(t) : b ? biomeNoteOf(b)?.color : undefined) ?? "#333", label: b ? biomeInfo(b)?.label : undefined, ecotone: eco.has(k) }; }); drawMiniOverworld(ctx, miniLayout(hexes, o, s, this.canvas.width, this.canvas.height), hexes, this.result.river); } @@ -431,8 +482,9 @@ export class NewOverworldModal extends HexmakerModal { map.regions = withMeshFields({ footprint: "rect", size: this.regionSize, blend: this.blend, palette: this.palette }, stagger, newWorldId); if (this.result.river.length > 1) map.biomeRiver = formatBiomeRiver(this.result.river); if (this.poolPath) map.biomePool = this.poolPath; + map.biomeGaps = unclimatedText(this.unclimated); await this.plugin.saveSettings(); - // Biomes their terrain can't say (a user's) go in the Biome column. + // Every hex's biome goes in the Biome column (BC1); blank hexes get no terrain. await writeOverworldBiomes(this.plugin, res.name, this.result); if (this.makeAll) { const t0 = performance.now(); @@ -452,7 +504,7 @@ export class NewOverworldModal extends HexmakerModal { const t0 = performance.now(); const res = await regenerateOverworld(this.plugin, name, { seed: this.seed, climate: this.climate, water: this.water / 100, land: this.land, north: this.north, - pool: this.poolBiomes(), poolPath: this.poolPath, regions: this.makeAll, + pool: this.poolBiomes(), poolPath: this.poolPath, regions: this.makeAll, unclimated: this.unclimated, }, { onProgress: (done, total) => status.setText(`Regions: ${done} of ${total}…`) }); if ("error" in res) { status.setText(res.error); return; } new Notice(`Overworld regenerated in ${((performance.now() - t0) / 1000).toFixed(1)} s: ${res.written} hexes, ${res.kept} locked kept, ${res.made} regions made, ${res.remade} remade.${res.errors.length ? ` ${res.errors.length} failed.` : ""}`); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index b35ecec9..d1bef784 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -76,6 +76,9 @@ Pick a path type in the path picker (choose **Hex by hex** or **Auto-route** fir Mark terrains impassable in the palette editor (every water-type terrain is impassable by default). Each path type chooses whether it goes around them (roads do, rivers don't) and whether it winds. Tick **Cross impassable** in the bar to let the next legs go through. If painting terrain, changing the palette, resizing the map or changing a type's routing would move an existing path, it keeps its route (points are added to hold it) and a notice offers **Reroute instead**; undoing the paint stroke undoes that too. +### Biome (overworlds only) +Opens a palette of biomes, like the terrain palette. Pick one, then click or drag over the overworld's hexes (in either view): each hex gets that biome and its region is made straight away, no window. A hex with no region yet can be painted in Build or God. Changing the biome of a hex that already has a region needs God, and only remakes the region where the biome is different: painting the same biome again does nothing. A stroke that remakes regions is one undo step (in the mode it was done in); making a region for the first time isn't undone (it makes a map). **Custom (blank)** paints a blank region to fill by hand. + ### Terrain Opens the terrain palette. Select a color/icon to enter paint mode, then left-click hexes to apply that terrain. Use **Pick** (⌖) to sample terrain from an existing hex. Use **Clear** to erase terrain from hexes. Right-click the terrain button to open the palette editor where you can reorder, rename, recolor, and add terrain types. @@ -136,7 +139,7 @@ Tokens show their name underneath. The layers panel's **Labels** group turns coo Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. -**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). Right-click a region → **Edit region…** for its name, the hex it's on, **Enter region**, **Open map note**, its biome, facts (size, palette, terrain counts, neighbouring regions, locations) and notes (kept in its map note under `## Notes`, editable in every mode). The biome can only be changed in God mode: there it's a picker with **Reroll** and **Settings…**; in Build and Play it's shown with "Switch to God to change it." The overworld has no hex editor: right-click shows only region-level items. The terrain tool always paints the regions: picking a terrain switches to the Regions view, the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. +**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). Right-click a region → **Edit region…** for its name, the hex it's on, **Enter region**, **Open map note**, its biome, facts (size, palette, terrain counts, neighbouring regions, locations) and notes (kept in its map note under `## Notes`, editable in every mode). The biome can only be changed in God mode: there it's a picker with **Reroll** and **Settings…**; in Build and Play it's shown with "Switch to God to change it." The overworld has no hex editor: right-click shows only region-level items. The **Biome** tool sets biomes (see Drawing tools). The terrain tool paints the regions and only works in the Regions view (the Biomes view shows biomes only, so the terrain tool is off there): the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (the `mode:` line in its map note) and opens in it next time; new maps are in **Build**. @@ -150,9 +153,13 @@ Notes, settings and palettes are never locked. There are no confirm boxes for th **Your own biomes.** Each biome is a note in the biomes folder (default `{world folder}/biomes`); the built-in ones are written there once, so you can edit them. A note lists terrain *types* with weights (**Mix**), **Transitions** (biomes it shouldn't touch, and what goes between), and `blend`, `land-share`, `min-islands` and an optional `generator` link. In the **Biomes** view, **Biomes…** lists them with **Add biome…**, **Edit…** (built-ins also have **Restore default**) and **Edit generator…**; the form has a live preview of one region. Needs Build or God. Inside a region, click the middle of the hex flower for **Edit region…**; right-click an overworld hex for **Create token here**. +**The Biome column.** An overworld's map note keeps each hex's biome in its **Hexes** table's **Biome** column, by name ("Temperate forest"), for every hex with a biome. Any spelling of a biome's name or id reads; a name that isn't a biome is left as you wrote it and the hex goes by its terrain. Overworlds made before this get the column filled once. + +**Blank biomes.** **Custom (blank)** (and any biome whose note says `blank: yes`, or with **Regions start blank** ticked in its form) makes an empty region to paint by hand: nothing is generated, the overworld hex has no terrain (the Biome column names it), and the regions around it don't blend into it. It's offered wherever biomes are: the Biome tool, **Set biome…**, **Edit region…** and walking into new land. **New overworld…** has **Blank hexes**: that many hexes (land first, spread out) start blank. + **Biome climates.** Optional keys in a biome note (or the form's folded **Climate** section) say where generated overworlds put it: `temperature` (cold, cool, mild, warm, hot, or `0.2–0.5`), `moisture` (dry, moderate, wet), `elevation` (low, mid, high, sea, mouth), `coastal: yes`, `chance` (like `50%`) and `rare: yes`. Set, World biomes can choose it like a built-in; blank, it's only placed by hand. -**Generate overworld.** **New overworld…** lays out a **biome pool** (a note in `{world folder}/biome-pools` listing biomes, with an optional weight each; **All biomes** ships). Add or remove biomes, save the pool, watch the preview, then **Create**: the map and every region are made. A pool biome without a climate only fills hexes nothing else fits. It's a first pass; edit any region afterwards. Map menu → **Regions** → **Generate overworld…** redoes the whole map (God only): locked hexes and their regions stay, other regions are remade in place. +**Generate overworld.** **New overworld…** lays out a **biome pool** (a note in `{world folder}/biome-pools` listing biomes, with an optional weight each; **All biomes** ships). Add or remove biomes, save the pool, watch the preview, then **Create**: the map and every region are made. At the top of the form, **Biomes without a climate** says what the pool's biomes with no climate do: **Fill gaps only** (the default: only hexes nothing else in the pool fits) or **Never place them** (set them by hand). The overworld remembers it (`no-climate-biomes:` in its map note). **Coast** has a climate (coastal lowland), so World biomes puts it on land by the sea; existing overworlds only change if you regenerate them. It's a first pass; edit any region afterwards. Map menu → **Regions** → **Generate overworld…** redoes the whole map (God only): locked hexes and their regions stay, other regions are remade in place. **Walking into new land.** In a region, the hex flower on the toolbar shows a **+** on each neighbour that has no region yet ("New region to the east"). Click it, pick the biome that lies there or **Roll** for one (the seed is shown; the same seed rolls the same biome), watch the preview of the new region blended with the regions around it, then **Create and go**. A different biome makes border country in between. Past the overworld's edge, the overworld grows by a hex to fit the new region. The hex editor's neighbour flower does the same on the hexes past the region's edge, and maps joined side by side get a **+** on the empty sides of their arrow pad. Needs Build or God: in Play the **+** says "Switch to Build to make a region." diff --git a/src/hex-map/overworldMinimap.ts b/src/hex-map/overworldMinimap.ts index 998fa78c..98a1a786 100644 --- a/src/hex-map/overworldMinimap.ts +++ b/src/hex-map/overworldMinimap.ts @@ -10,7 +10,7 @@ import { setIcon } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { MapData } from "../types"; import { regionMapAt } from "../maps/submaps"; -import { biomeInfo } from "../overworld/biomes"; +import { biomeInfo, biomeNoteOf } from "../overworld/biomes"; import { drawMiniOverworld, miniHexAt, miniLayout, type MiniHex } from "../overworld/overworldRender"; import { ecotoneHexes, overworldBiomes, parseBiomeRiver } from "../overworld/regionWorld"; import { overworldOf, overworldTerrain, placedBiomes, regionHome } from "../overworld/regionsVault"; @@ -54,8 +54,8 @@ export class OverworldMinimap { const sw = box.createDiv({ cls: "duckmage-ow-view-toggle", attr: { role: "group", "aria-label": "Overworld view" } }); sw.createSpan({ cls: "duckmage-ow-view-label", text: "View:" }); for (const [id, label, tip] of [ - ["regions", "Regions", "Every region's hexes, stitched together (blank bricks where there's none yet). Click to enter a region; the terrain tool paints its hexes."], - ["biomes", "Biomes", "One biome per hex. Click a hex to enter its region, or to set the biome of one with none yet. Right-click a region → Edit region… for its name, biome and notes."], + ["regions", "Regions", "Every region's hexes, stitched together (blank bricks where there's none yet). Click to enter a region; the terrain tool paints its hexes, the Biome tool sets biomes."], + ["biomes", "Biomes", "One biome per hex. Click a hex to enter its region, or to set the biome of one with none yet; the Biome tool paints biomes (the terrain tool is off here). Right-click a region → Edit region… for its name, biome and notes."], ] as const) { const on = view === id; const b = sw.createEl("button", { text: label, cls: on ? "is-active" : "", attr: { title: on ? `${tip} (showing now)` : tip, "aria-pressed": on ? "true" : "false" } }); @@ -95,10 +95,12 @@ export class OverworldMinimap { const biomes = overworldBiomes(terrain, palette, ow.layout.orientation, ow.layout.parentStagger, placedBiomes(this.plugin, t.overworld.name)); const eco = ecotoneHexes(biomes, ow.layout.orientation, ow.layout.parentStagger); const hexes: MiniHex[] = []; - for (const [k, terr] of terrain) { + // Painted hexes, and blank-biome hexes (a Biome cell, no terrain) in their biome's colour. + for (const k of new Set([...terrain.keys(), ...biomes.keys()])) { const [x, y] = k.split("_").map(Number); const b = biomes.get(k); - hexes.push({ x, y, color: colour.get(terr) ?? "#333", label: b ? biomeInfo(b)?.label : undefined, ecotone: eco.has(k) }); + const terr = terrain.get(k); + hexes.push({ x, y, color: (terr ? colour.get(terr) : b ? biomeNoteOf(b)?.color : undefined) ?? "#333", label: b ? biomeInfo(b)?.label : undefined, ecotone: eco.has(k) }); } if (!hexes.length) { box.remove(); this.el = null; return; } const canvas = box.createEl("canvas", { cls: "duckmage-ow-minimap-canvas" }); diff --git a/src/hex-map/toolMode.ts b/src/hex-map/toolMode.ts index b38580b2..81951dab 100644 --- a/src/hex-map/toolMode.ts +++ b/src/hex-map/toolMode.ts @@ -16,7 +16,9 @@ export type DrawingMode = | "factionLink" | "regionLink" | "swap" - | "placeToken"; + | "placeToken" + /** The Biome painter (overworlds only). */ + | "biome"; export interface ToolModeState { mode: DrawingMode | null; @@ -43,6 +45,8 @@ export interface ToolModeState { submapName?: string | null; factionPath?: string | null; regionPath?: string | null; + /** The Biome painter's biome (its label). */ + biomeName?: string | null; } /** "world/factions/Red Hand.md" → "Red Hand"; icon file → its name. */ @@ -98,5 +102,7 @@ export function toolModeLabel(s: ToolModeState): string | null { return "Swapping hexes: click two hexes"; case "placeToken": return "Placing token: click a hex"; + case "biome": + return s.biomeName ? `Painting biome: ${s.biomeName} (click or drag over hexes)` : "Painting biome"; } } diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index 54b8e32d..ed03d0e7 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -387,6 +387,8 @@ const SIMPLE_KEYS: [keyof MapSettings, string, Kind, string[]?][] = [ ["workMode", "mode", "str"], ["biomeRiver", "biome-river", "str"], ["biomePool", "biome-pool", "note"], + // BC2: "fill gaps" or "never" (worldBiomes.parseUnclimated). + ["biomeGaps", "no-climate-biomes", "str"], ["showCoords", "show-coords", "bool"], ["showTerrainIcons", "show-terrain-icons", "bool"], ["showIconOverrides", "show-icon-overrides", "bool"], diff --git a/src/overworld/biomeForm.ts b/src/overworld/biomeForm.ts index 869ba9a3..a073b318 100644 --- a/src/overworld/biomeForm.ts +++ b/src/overworld/biomeForm.ts @@ -18,6 +18,8 @@ import type { RegionLayout } from "./layout"; export type RegionRoute = | { kind: "blend" } + /** A blank biome (`blank: yes`): nothing generated, painted by hand. */ + | { kind: "blank" } /** Made by a generator note (generateBiomeRegion, src/worldgen/biomeRegion.ts). */ | { kind: "generator"; generator: string; ready: boolean }; @@ -26,9 +28,11 @@ export type RegionRoute = * with a `generator:` link has its regions made by that generator * (generateBiomeRegion, joined to the cells already painted around it; * regionsVault.planRegionWithGenerator); every other biome blends (the - * blend field mixes its type mix with its neighbours'). + * blend field mixes its type mix with its neighbours'). A blank biome's + * regions are left blank. */ -export function regionGenerator(biome: Pick | undefined): RegionRoute { +export function regionGenerator(biome: Pick | undefined): RegionRoute { + if (biome?.blank) return { kind: "blank" }; if (biome?.generator) return { kind: "generator", generator: biome.generator, ready: true }; return { kind: "blend" }; } @@ -37,8 +41,9 @@ export function regionGenerator(biome: Pick | unde export const generatorName = (target: string): string => target.slice(target.lastIndexOf("/") + 1).replace(/\.md$/, ""); /** The status line shown for a biome (undefined when it simply blends). */ -export function routeNote(biome: Pick | undefined): string | undefined { +export function routeNote(biome: Pick | undefined): string | undefined { const r = regionGenerator(biome); + if (r.kind === "blank") return "Blank: its regions start empty, to paint by hand."; if (r.kind === "generator" && !r.ready) return `Uses ${generatorName(r.generator)}: available once generator regions land. Blends until then.`; if (r.kind === "generator") return `Made by ${generatorName(r.generator)}, joined to its neighbours.`; return undefined; @@ -61,6 +66,8 @@ export interface BiomeFormState { /** Type → fewest patches (the Mix table's Min patches); kept through the form. */ minPatches: Map; shore: boolean; + /** Regions start blank (painted by hand); the mix may then be empty. */ + blank: boolean; transitions: BiomeTransition[]; /** Climate for generated overworlds, as typed (blank = not set). */ climate: ClimateFormState; @@ -125,6 +132,7 @@ export function formFromFields(fields: BiomeNoteFields | undefined, types: strin minIslands: fields?.minIslands, minPatches: new Map((fields?.mix ?? []).filter((r) => r.minPatches !== undefined).map((r) => [r.type, r.minPatches!])), shore: !!fields?.shore, + blank: !!fields?.blank, transitions: (fields?.transitions ?? []).map((t) => ({ ...t })), climate: climateFormFrom(fields?.climate), }; @@ -148,6 +156,7 @@ export function fieldsFromForm(s: BiomeFormState, id?: string): BiomeNoteFields if (s.landPercent !== undefined) f.landShare = Math.min(100, Math.max(0, s.landPercent)) / 100; if (s.minIslands !== undefined) f.minIslands = Math.max(0, Math.round(s.minIslands)); if (s.shore) f.shore = true; + if (s.blank) f.blank = true; const climate = s.climate ? climateFromForm(s.climate).climate : undefined; if (climate) f.climate = climate; return f; @@ -160,7 +169,7 @@ export function formProblem(s: BiomeFormState, others: { id: string; label: stri const k = biomeSlug(label); if (!k) return "Use some letters or numbers in the name."; if (others.some((o) => o.id === k || biomeSlug(o.label) === k)) return `There's already a biome called ${label}.`; - if (![...s.mix.values()].some((w) => w > 0)) return "Give at least one terrain type a weight."; + if (!s.blank && ![...s.mix.values()].some((w) => w > 0)) return "Give at least one terrain type a weight."; const climate = s.climate ? climateFromForm(s.climate).problems : []; if (climate.length) return `Climate: ${climate[0]}.`; return undefined; diff --git a/src/overworld/biomeNote.ts b/src/overworld/biomeNote.ts index 411429b1..065ee673 100644 --- a/src/overworld/biomeNote.ts +++ b/src/overworld/biomeNote.ts @@ -40,6 +40,9 @@ * are for watery biomes. All optional. * - `generator`: a generator note this biome's regions come from (once * generator regions land); without one it mixes with the blend field. + * - `blank: yes`: its regions start blank (nothing generated) and are + * painted by hand (the shipped "Custom (blank)" biome). Never placed by + * World biomes; its Mix may be empty. * * Reading is forgiving: columns by header name in any order, `colour` or * `color`, weights like `40` or `40%`. Rows that can't be read are reported @@ -105,6 +108,8 @@ export interface BiomeNoteFields { generator?: string; /** Where World biomes may place it (biomeClimate.ts); unset = only by hand. */ climate?: BiomeClimate; + /** `blank: yes`: its regions start blank, to paint by hand (no generation, never placed by World biomes). */ + blank?: boolean; } export interface BiomeNoteProblem { @@ -132,7 +137,7 @@ export function biomeFileName(label: string): string { export const BIOME_HELP = [ "> [!info] Biome", - "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale; an optional *Min patches* column asks for at least that many separate patches of the type). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `shore: yes` puts a region's land on the side of its land neighbours and its water on the other; `generator` links a generator note. For generated overworlds (optional): `temperature` (cold, cool, mild, warm, hot, or 0.2–0.5), `moisture` (dry, moderate, wet), `elevation` (sea, low, mid, high, mouth), `coastal: yes`, `chance` (like 50%) and `rare: yes`; without them the biome is only placed by hand. Delete a row to drop it.", + "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale; an optional *Min patches* column asks for at least that many separate patches of the type). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `shore: yes` puts a region's land on the side of its land neighbours and its water on the other; `blank: yes` makes its regions start blank, to paint by hand; `generator` links a generator note. For generated overworlds (optional): `temperature` (cold, cool, mild, warm, hot, or 0.2–0.5), `moisture` (dry, moderate, wet), `elevation` (sea, low, mid, high, mouth), `coastal: yes`, `chance` (like 50%) and `rare: yes`; without them the biome is only placed by hand. Delete a row to drop it.", ]; // ── reading ────────────────────────────────────────────────────────────── @@ -279,6 +284,12 @@ export function parseBiomeNote(content: string, basename: string): ParsedBiomeNo if (v === true) fields.shore = true; else if (v === undefined) problems.push({ where: "settings", text: `shore should be yes or no, not "${shore}"` }); } + const blank = fm.get("blank"); + if (blank) { + const v = readYesNo(blank); + if (v === true) fields.blank = true; + else if (v === undefined) problems.push({ where: "settings", text: `blank should be yes or no, not "${blank}"` }); + } const climate = readClimate(fm); if (climate.climate) fields.climate = climate.climate; for (const p of climate.problems) problems.push({ where: "settings", text: p.text }); @@ -361,6 +372,7 @@ function ownKeys(f: BiomeNoteFields): [string, string | undefined][] { ["land-share", f.landShare !== undefined ? shareText(f.landShare) : undefined], ["min-islands", f.minIslands !== undefined ? String(f.minIslands) : undefined], ["shore", f.shore ? "yes" : undefined], + ["blank", f.blank ? "yes" : undefined], ["generator", f.generator ? `"[[${f.generator}]]"` : undefined], ...climateKeyValues(f.climate), ]; @@ -431,7 +443,7 @@ function sameValue(key: string, cur: string, want: string): boolean { if (key === "colour") return readColour(cur) === readColour(w); if (key === "generator") return linkTarget(cur) === linkTarget(w); if (key === "id") return biomeSlug(cur) === biomeSlug(w); - if (key === "shore") return readYesNo(cur) === readYesNo(w); + if (key === "shore" || key === "blank") return readYesNo(cur) === readYesNo(w); if (CLIMATE_KEY_SET.has(key)) return sameClimateValue(key, cur, w); return cur.trim() === w.trim(); } diff --git a/src/overworld/biomePainter.ts b/src/overworld/biomePainter.ts new file mode 100644 index 00000000..5b910238 --- /dev/null +++ b/src/overworld/biomePainter.ts @@ -0,0 +1,93 @@ +/** + * The Biome painter (owner round 5, BC1 + MM1): a drawing tool on + * overworlds. Pick a biome in a compact palette, then click or drag over + * overworld hexes: each hex gets the biome and its region is made (or + * remade) automatically, no modal. + * + * - A hex with no region yet: placing is a first placement (Build, God). + * - A hex whose region exists: changing its biome needs God, and only + * happens when the hex's biome DIFFERS from the painter's. Re-clicking a + * hex that already has the painter's biome does nothing (no regeneration). + * - Play: nothing changes; the stroke says how to unlock it, once. + * + * Strokes run one hex at a time, in order (each region pins the ones made + * before it), and each changed region is recorded for undo in the + * overworld's queue for its mode (the view pushes one entry per stroke). + * + * Pure: no Obsidian imports. + */ + +import { canAdd, canReshape, PLACE_LOCKED_HINT, RESHAPE_LOCKED_HINT } from "../workMode"; +import type { BiomeId } from "./biomes"; + +export type BiomePaintStep = + /** Nothing to do: the hex already has this biome and its region. */ + | { kind: "skip" } + /** First placement: set the biome, make the region (Build, God). */ + | { kind: "place" } + /** A different biome on a placed region: set it, remake the region (God). */ + | { kind: "reshape" } + /** The map's mode doesn't allow it. */ + | { kind: "locked"; hint: string }; + +/** What painting `painter` onto a hex does, in this map's mode. */ +export function biomePaintStep(map: { workMode?: string } | undefined, hasRegion: boolean, current: BiomeId | undefined, painter: BiomeId): BiomePaintStep { + if (hasRegion) { + if (current === painter) return { kind: "skip" }; + return canReshape(map) ? { kind: "reshape" } : { kind: "locked", hint: RESHAPE_LOCKED_HINT }; + } + return canAdd(map) ? { kind: "place" } : { kind: "locked", hint: PLACE_LOCKED_HINT }; +} + +/** What painting one hex came to. */ +export interface BiomePaintResult { + step: BiomePaintStep["kind"]; + /** Undo edits of a reshape (the overworld hex and the region's cells). */ + edits?: E[]; + /** A region that was made. */ + made?: string; + hint?: string; + error?: string; +} + +/** + * One drag of the painter: hexes are painted one at a time, in the order + * the pointer crossed them, each at most once per stroke. `finish()` + * resolves once every queued hex is done, with what the stroke did. + */ +export class BiomeStroke { + private seen = new Set(); + private chain: Promise = Promise.resolve(); + private edits: E[] = []; + private made: string[] = []; + private changed = 0; + private hints = new Set(); + private errors: string[] = []; + + constructor(private paintOne: (key: string) => Promise>) {} + + /** Queue a hex (false when this stroke already did it). */ + add(key: string): boolean { + if (this.seen.has(key)) return false; + this.seen.add(key); + this.chain = this.chain.then(async () => { + try { + const r = await this.paintOne(key); + if (r.edits?.length) this.edits.push(...r.edits); + if (r.made) this.made.push(r.made); + if (r.step === "place" || r.step === "reshape") this.changed++; + if (r.hint) this.hints.add(r.hint); + if (r.error) this.errors.push(r.error); + } catch (e) { + this.errors.push(e instanceof Error ? e.message : String(e)); + } + }); + return true; + } + + /** Wait for the queue; what the stroke did. */ + async finish(): Promise<{ edits: E[]; made: string[]; changed: number; hints: string[]; errors: string[] }> { + await this.chain; + return { edits: [...this.edits], made: [...this.made], changed: this.changed, hints: [...this.hints], errors: [...this.errors] }; + } +} diff --git a/src/overworld/biomePool.ts b/src/overworld/biomePool.ts index 47eb71d4..a37b11d4 100644 --- a/src/overworld/biomePool.ts +++ b/src/overworld/biomePool.ts @@ -183,9 +183,9 @@ export function updateBiomePool(content: string, rows: BiomePoolRow[]): string { const key = (r: BiomePoolRow) => [r.biome.toLowerCase(), r.weight ?? 1, r.notes ?? ""]; -/** The shipped pool: every built-in biome, linked by its note's name. */ +/** The shipped pool: every built-in biome, linked by its note's name (blank biomes left out: they're placed by hand). */ export function allBiomesPool(presets: readonly BiomeNoteFields[]): BiomePoolRow[] { - return presets.map((p) => ({ biome: biomeFileName(p.label) })); + return presets.filter((p) => !p.blank).map((p) => ({ biome: biomeFileName(p.label) })); } /** diff --git a/src/overworld/biomePresets.ts b/src/overworld/biomePresets.ts index 42174247..0980c32b 100644 --- a/src/overworld/biomePresets.ts +++ b/src/overworld/biomePresets.ts @@ -13,8 +13,12 @@ * Min patches: the types smoothing washed out of most regions of the biome * (measured with dev/measure-patches.ts: 200 seeds of an 8×8 region, on * Expanded) that give it its character, e.g. alpine peaks, a volcano. - * Coast is the one note-only preset (no row in the BIOMES table): a - * `shore` biome whose land faces its land neighbours. + * Coast is a note-only preset (no row in the BIOMES table): a `shore` + * biome whose land faces its land neighbours. Its climate (coastal + * lowland, BC3, 2026-10-11) lets World biomes place it on sea↔land borders. + * "Custom (blank)" is the other note-only preset: `blank`, so its regions + * start empty for painting by hand (BC1); it has no mix and no climate and + * is never placed by World biomes. * * Pure: no Obsidian imports. */ @@ -39,8 +43,9 @@ export const BIOME_PRESETS: readonly BiomeNoteFields[] = [ { id: "volcanic", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15, minPatches: 1 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1, minPatches: 1 }], transitions: [], climate: { elevation: "high", chance: 0.12, rare: true } }, { id: "coastal-fjord", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16, minPatches: 1 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10, minPatches: 1 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [], climate: { temperature: { lo: 0, hi: 0.3 }, elevation: "low", coastal: true, chance: 0.5 } }, { id: "archipelago", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [], landShare: 0.3, minIslands: 2, climate: { elevation: "sea", coastal: true, chance: 0.3 } }, - { id: "coast", label: "Coast", color: "#d9c98f", mix: [{ type: "coast", weight: 30 }, { type: "water", weight: 28 }, { type: "shallows", weight: 18 }, { type: "grassland", weight: 14 }, { type: "hills", weight: 6 }, { type: "wetland", weight: 4 }], transitions: [{ next: "Alpine", between: "Coastal fjord" }], shore: true }, + { id: "coast", label: "Coast", color: "#d9c98f", mix: [{ type: "coast", weight: 30 }, { type: "water", weight: 28 }, { type: "shallows", weight: 18 }, { type: "grassland", weight: 14 }, { type: "hills", weight: 6 }, { type: "wetland", weight: 4 }], transitions: [{ next: "Alpine", between: "Coastal fjord" }], shore: true, climate: { elevation: "low", coastal: true, chance: 0.35 } }, { id: "open-sea", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20, minPatches: 1 }], transitions: [], climate: { elevation: "sea" } }, + { id: "custom", label: "Custom (blank)", color: "#a8a29e", mix: [], transitions: [], blank: true }, ]; /** A copy of a preset's fields (callers may change it). */ diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index 5282b1ae..914ee815 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -431,6 +431,21 @@ export function biomeByRef(ref: string | undefined): BiomeId | undefined { return ref && source ? source.names.get(biomeSlug(ref)) : undefined; } +/** + * What the overworld's Biome column says for a biome: its label (readable), + * or its id when the label wouldn't read back as this biome (two biomes + * sharing a label, or no notes loaded). + */ +export function biomeRef(id: BiomeId): string { + const label = source?.biomes.get(id)?.label; + return label && biomeByRef(label) === id ? label : id; +} + +/** A blank biome (`blank: yes`): its regions start empty, painted by hand. */ +export function isBlankBiome(id: BiomeId | undefined): boolean { + return !!id && !!source?.biomes.get(id)?.blank; +} + function noteBiomeInfo(id: BiomeId): BiomeInfo | undefined { return source?.infos.get(id); } diff --git a/src/overworld/overworldGen.ts b/src/overworld/overworldGen.ts index 47d4b95b..540c6c35 100644 --- a/src/overworld/overworldGen.ts +++ b/src/overworld/overworldGen.ts @@ -31,12 +31,12 @@ import { } from "./biomePool"; import { biomeFileName, type BiomeNoteFields } from "./biomeNote"; import { BIOME_PRESETS } from "./biomePresets"; -import { biomeForTerrain, biomeNoteOf, type BiomeId } from "./biomes"; +import { biomeByRef, biomeForTerrain, biomeNoteOf, biomeRef, isBlankBiome, type BiomeId } from "./biomes"; import { regionGenerator } from "./biomeForm"; -import { firstPassWrites } from "./overworldPass"; +import { biomeColumnFills, firstPassWrites } from "./overworldPass"; import { formatBiomeRiver, regionOrder } from "./regionWorld"; -import { createRegion, overworldOf, regenerateRegion } from "./regionsVault"; -import { worldBiomes, type WorldBiomesOptions, type WorldBiomesResult } from "./worldBiomes"; +import { createRegion, hexBiomeAt, overworldBiomeHexes, overworldOf, regenerateRegion } from "./regionsVault"; +import { unclimatedText, worldBiomes, type WorldBiomesOptions, type WorldBiomesResult } from "./worldBiomes"; /** Hint shown where regenerating a whole overworld is locked. */ export const REGENERATE_LOCKED_HINT = "Switch to God to regenerate the whole overworld."; @@ -144,7 +144,7 @@ export function overworldCells(plugin: HexmakerPlugin, mapName: string): [number const map = plugin.getMap(mapName); if (!map) return []; const keys = new Set(); - for (const [k, h] of plugin.mapStore.all(mapName)) if (h.terrain || h.regionMap) keys.add(k); + for (const [k, h] of plugin.mapStore.all(mapName)) if (h.terrain || h.regionMap || h.biome) keys.add(k); for (const m of plugin.settings.maps) if (m.submapKind === "region" && m.parent?.map === mapName) keys.add(m.parent.hex); if (!keys.size) { for (let y = map.gridOffset.y; y < map.gridOffset.y + map.gridSize.rows; y++) { @@ -167,11 +167,10 @@ export function layOutBiomes( return worldBiomes(cells, o, s, palette, { ...opts, biomes: pool }); } -/** Write a result into the overworld (locked hexes kept). Returns the hexes kept. */ +/** Write a result into the overworld (locked hexes kept): terrain and the Biome column. Returns the hexes kept. */ export async function writeOverworldBiomes(plugin: HexmakerPlugin, mapName: string, result: WorldBiomesResult): Promise<{ written: number; kept: string[] }> { - const palette = plugin.getMapPalette(mapName); const current = new Map([...plugin.mapStore.all(mapName)].map(([k, h]) => [k, { terrain: h.terrain, biome: h.biome, locked: h.locked }])); - const { cells, kept } = firstPassWrites(current, result, (t) => biomeForTerrain(t, palette)); + const { cells, kept } = firstPassWrites(current, result, biomeRef, isBlankBiome); for (const [k, patch] of cells) plugin.mapStore.set(mapName, k, patch); await plugin.mapStore.flush(); return { written: cells.length, kept }; @@ -214,7 +213,7 @@ export async function regionPass( out.remade.push(existing.name); name = existing.name; } - } else if (terrain) { + } else if (terrain || biome) { const res = await createRegion(plugin, mapName, px, py, { fill: "match", ...(biome ? { biome } : {}) }); if ("error" in res) out.errors.push(`${px}, ${py}: ${res.error}`); else { out.made.push(res.name); name = res.name; } @@ -225,11 +224,38 @@ export async function regionPass( } function biomeOfHex(plugin: HexmakerPlugin, mapName: string, hex: string, terrain: string | undefined): BiomeId | undefined { - const own = plugin.mapStore.get(mapName, hex)?.biome; - if (own) return plugin.biomeStore.get(own)?.id; + const own = biomeByRef(plugin.mapStore.get(mapName, hex)?.biome); + if (own) return own; return terrain ? biomeForTerrain(terrain, plugin.getMapPalette(mapName)) : undefined; } +/** + * BC1, once per vault: older overworlds wrote the Biome column only for + * biomes their terrain couldn't say. Fill it for every hex with a biome + * (its region's, else its terrain's), so every overworld reads the same. + * Hexes with a Biome cell are left as written. Returns how many were filled. + */ +export async function fillBiomeColumns(plugin: HexmakerPlugin): Promise { + if (plugin.settings.biomeColumnsFilled) return 0; + let n = 0; + for (const map of plugin.settings.maps) { + if (!overworldOf(plugin, map.name)) continue; + const fills = biomeColumnFills( + overworldBiomeHexes(plugin, map), + (k) => plugin.mapStore.get(map.name, k), + (k) => hexBiomeAt(plugin, map.name, k), + biomeRef, + ); + if (!fills.length) continue; + plugin.mapStore.setMany(map.name, fills.map(([k, ref]) => [k, { biome: ref }])); + n += fills.length; + } + if (n) await plugin.mapStore.flush(); + plugin.settings.biomeColumnsFilled = true; + await plugin.saveSettings(); + return n; +} + export interface RegenerateOptions extends Omit { /** The pool's note (recorded on the map), and its biomes. */ poolPath?: string; @@ -258,6 +284,7 @@ export async function regenerateOverworld( const { written, kept } = await writeOverworldBiomes(plugin, mapName, result); map.biomeRiver = result.river.length > 1 ? formatBiomeRiver(result.river) : undefined; if (opts.poolPath) map.biomePool = opts.poolPath; + map.biomeGaps = unclimatedText(opts.unclimated ?? "fill"); await plugin.saveSettings(); let regions = { made: [] as string[], remade: [] as string[], waiting: 0, errors: [] as string[] }; if ((opts.regions ?? true) && overworldOf(plugin, mapName) && canAdd(map)) { diff --git a/src/overworld/overworldInput.ts b/src/overworld/overworldInput.ts index 5f032356..a6312530 100644 --- a/src/overworld/overworldInput.ts +++ b/src/overworld/overworldInput.ts @@ -29,6 +29,9 @@ export const BIOME_LOCKED_HINT = "Switch to God to change it."; /** The hint when the terrain brush is used on an overworld in Play. */ export const PAINT_LOCKED_HINT = "Switch to Build to paint the regions."; +/** The terrain tool on an overworld's Biomes view (MM1: that view is biomes only). */ +export const TERRAIN_IN_BIOMES_HINT = "The Biomes view shows biomes only: use the Biome tool here, or switch to Regions to paint terrain."; + /** The hint when the brush lands where there's no region. */ export const PAINT_NO_REGION_HINT = "No region here yet; place a biome first."; diff --git a/src/overworld/overworldPass.ts b/src/overworld/overworldPass.ts index ce19d34a..20c174f0 100644 --- a/src/overworld/overworldPass.ts +++ b/src/overworld/overworldPass.ts @@ -1,12 +1,21 @@ /** * The overworld first pass (#50), pure part: what a World biomes result * writes into an overworld's hexes. Hand-painted (locked) hexes are never - * written; every other hex gets its biome's terrain, and its biome in the - * Biome column when the terrain can't say it (a user's biome). + * written; every other hex gets its biome's terrain AND its biome in the + * Biome column (BC1, owner 2026-10-11: always, not only where the terrain + * can't say it, so a user's biome is never lost). A blank biome's hex gets + * no terrain: its region is painted by hand. + * + * Also here: filling the Biome column of older overworlds once (the + * column used to be written only for biomes the terrain couldn't say), and + * turning some generated hexes into blank ones ("Blank hexes" on the New + * overworld form). * * Pure: no Obsidian imports. */ +import { hexDistance, type Orientation, type Stagger } from "../../packages/hex-wfc/src/grid"; +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; import type { BiomeId } from "./biomes"; export interface PassHex { @@ -16,32 +25,93 @@ export interface PassHex { } export interface PassWrites { - /** Hex → patch (`biome: null` clears the column). */ - cells: [string, { terrain: string; biome: string | null }][]; + /** Hex → patch (`terrain: null` clears it: a blank biome). */ + cells: [string, { terrain: string | null; biome: string }][]; /** Locked hexes left as they were. */ kept: string[]; } /** - * The writes for a result. `readsAs(terrain)` is the biome a terrain stands - * for on the overworld's palette (biomeForTerrain). Hexes whose biome has + * The writes for a result. `refOf(biome)` is what the Biome column says for + * a biome (biomes.biomeRef: its label). `isBlank(biome)`: a blank biome + * (its hex is written with no terrain). Hexes whose (non-blank) biome has * no terrain on the palette are left alone. */ export function firstPassWrites( current: ReadonlyMap, result: { biomes: ReadonlyMap; terrain: ReadonlyMap }, - readsAs: (terrain: string) => BiomeId | undefined, + refOf: (biome: BiomeId) => string, + isBlank: (biome: BiomeId) => boolean = () => false, ): PassWrites { const cells: PassWrites["cells"] = []; const kept: string[] = []; for (const [k, biome] of result.biomes) { - if (current.get(k)?.locked) { kept.push(k); continue; } - const terrain = result.terrain.get(k); - if (!terrain) continue; - const want = readsAs(terrain) === biome ? null : biome; const cur = current.get(k); - if (cur?.terrain === terrain && (cur.biome ?? null) === want) continue; - cells.push([k, { terrain, biome: want }]); + if (cur?.locked) { kept.push(k); continue; } + const terrain = isBlank(biome) ? null : result.terrain.get(k); + if (terrain === undefined) continue; + const ref = refOf(biome); + if ((cur?.terrain ?? null) === terrain && cur?.biome === ref) continue; + cells.push([k, { terrain, biome: ref }]); } return { cells, kept }; } + +/** + * BC1 migration: the Biome column for every overworld hex that has a biome + * but no (readable) Biome cell yet. `biomeOf(key)` is the hex's biome as + * the overworld reads it today (its region's, else its terrain's); + * `known(ref)` says whether a written cell names a biome (an unreadable + * one is left as the user wrote it). Returns hex → ref to write. + */ +export function biomeColumnFills( + hexes: Iterable, + current: (key: string) => PassHex | undefined, + biomeOf: (key: string) => BiomeId | undefined, + refOf: (biome: BiomeId) => string, +): [string, string][] { + const out: [string, string][] = []; + for (const k of hexes) { + if (current(k)?.biome) continue; + const b = biomeOf(k); + if (b) out.push([k, refOf(b)]); + } + return out; +} + +/** + * Pick `n` hexes of a generated overworld to turn into blank ones (the New + * overworld form's "Blank hexes"): land hexes first, spread out (each pick + * is the land hex farthest from the earlier ones, ties broken by the seed), + * then sea hexes if there isn't enough land. Deterministic for a seed. + */ +export function pickBlankHexes( + keys: readonly string[], + sea: ReadonlySet, + n: number, + seed: number, + orientation: Orientation, + stagger: Stagger, +): string[] { + const want = Math.max(0, Math.min(keys.length, Math.floor(n))); + if (!want) return []; + const rng = mulberry32((seed >>> 0) ^ 0xb1a4c); + const pos = (k: string) => k.split("_").map(Number) as [number, number]; + const picked: string[] = []; + const pickFrom = (pool: string[]) => { + const left = [...pool]; + while (picked.length < want && left.length) { + let best = -1, bestScore = -Infinity; + for (let i = 0; i < left.length; i++) { + const d = picked.length ? Math.min(...picked.map((p) => hexDistance(pos(p), pos(left[i]), orientation, stagger))) : 0; + const score = d + rng() * 0.5; + if (score > bestScore) { bestScore = score; best = i; } + } + picked.push(left.splice(best, 1)[0]); + } + }; + const sorted = [...keys].sort(); + pickFrom(sorted.filter((k) => !sea.has(k))); + pickFrom(sorted.filter((k) => sea.has(k))); + return picked; +} diff --git a/src/overworld/regionWorld.ts b/src/overworld/regionWorld.ts index 698e9721..15225f4b 100644 --- a/src/overworld/regionWorld.ts +++ b/src/overworld/regionWorld.ts @@ -153,8 +153,8 @@ export function regionNeighbourMaps, @@ -170,6 +170,7 @@ export function overworldBiomes( if (b) out.set(k, b); else unresolved.push(k); } + for (const [k, b] of placed ?? []) if (!terrain.has(k)) out.set(k, b); for (const k of unresolved) { const [x, y] = k.split("_").map(Number); const counts = new Map(); diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index 0ad9af74..a84173f5 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -20,7 +20,7 @@ import { slugify } from "../utils"; import { newWorldId } from "../worldgen/world"; import { BUILTIN_GENERATORS, builtinModel } from "../worldgen/builtinGenerators"; import { regionMapAt } from "../maps/submaps"; -import { biomeByRef, biomeForTerrain, biomeNoteOf, biomeProfiles, biomeSourceVersion, noteBiomeProfiles, representativeTerrain, type BiomeId, type BiomeProfile } from "./biomes"; +import { biomeByRef, biomeForTerrain, biomeNoteOf, biomeProfiles, biomeRef, biomeSourceVersion, isBlankBiome, noteBiomeProfiles, representativeTerrain, type BiomeId, type BiomeProfile } from "./biomes"; import { regionCells, type RegionLayout } from "./layout"; import type { BlendWidth } from "./blendField"; import { ADD_REGION_LOCKED_HINT, canAdd, canReshape, PLACE_LOCKED_HINT, RESHAPE_LOCKED_HINT } from "../workMode"; @@ -41,6 +41,8 @@ import { type RegionPlan, } from "./regionWorld"; import { hexNeighbors } from "../../packages/hex-wfc/src/grid"; +import { biomePaintStep, type BiomePaintResult } from "./biomePainter"; +import { cellEdits, type CellEdit } from "../undoBook"; export function gridRulesOf(plugin: HexmakerPlugin): GridRules { return { orientation: plugin.settings.hexOrientation, stagger: plugin.settings.staggerOffset ?? "odd" }; @@ -117,13 +119,28 @@ export function placedBiomes(plugin: HexmakerPlugin, overworldName: string): Map } /** - * Record hex `hex`'s biome in the overworld's Biome column when its - * terrain can't say it (a user's biome), else clear it. Not flushed. + * Record hex `hex`'s biome in the overworld's Biome column (BC1: always, + * by its label, so it reads in the note and survives a terrain that reads + * as another biome). Not flushed. */ -export function recordHexBiome(plugin: HexmakerPlugin, overworldName: string, hex: string, biome: BiomeId, terrain: string | undefined): void { - const reads = terrain ? biomeForTerrain(terrain, plugin.getMapPalette(overworldName)) : undefined; - const want = reads === biome ? undefined : biome; - if ((plugin.mapStore.get(overworldName, hex)?.biome ?? undefined) !== want) plugin.mapStore.set(overworldName, hex, { biome: want ?? null }); +export function recordHexBiome(plugin: HexmakerPlugin, overworldName: string, hex: string, biome: BiomeId): void { + const want = biomeRef(biome); + if (plugin.mapStore.get(overworldName, hex)?.biome !== want) plugin.mapStore.set(overworldName, hex, { biome: want }); +} + +/** + * Hexes of an overworld that have a biome: painted, or with a Biome cell + * (a blank biome's hex has no terrain), inside its grid. + */ +export function overworldBiomeHexes(plugin: HexmakerPlugin, map: MapData): string[] { + const out = new Set(overworldTerrain(plugin, map).keys()); + const { x: ox, y: oy } = map.gridOffset, { cols, rows } = map.gridSize; + for (const [k, h] of plugin.mapStore.all(map.name)) { + if (!h.biome || out.has(k)) continue; + const [x, y] = k.split("_").map(Number); + if (x >= ox && x < ox + cols && y >= oy && y < oy + rows) out.add(k); + } + return [...out]; } /** One overworld hex's biome: its placed biome, else read from its terrain. */ @@ -207,6 +224,8 @@ function regionInputs(plugin: HexmakerPlugin, parentName: string, px: number, py if (opts.biome) placed.set(`${px}_${py}`, opts.biome); const biomes = overworldBiomes(terrain, owPalette, ow.layout.orientation, ow.layout.parentStagger, placed); const ownBiome = biomes.get(`${px}_${py}`); + // A blank biome's hexes are painted by hand: they don't blend into their neighbours. + for (const [k, b] of biomes) if (isBlankBiome(b) && k !== `${px}_${py}`) biomes.delete(k); const ws = worldSeed(ow.settings.worldId ?? ow.map.name); const pinned = pinnedAround(plugin, parentName, ow.layout, px, py); const own = regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`); @@ -227,8 +246,8 @@ function regionInputs(plugin: HexmakerPlugin, parentName: string, px: number, py return { ow, palette, ownBiome, pinned, seed, plan }; } -/** A region plan, with the paths and note a generator-made region may bring. */ -export type RegionPlanOut = RegionPlan & { paths?: MapPath[]; note?: string }; +/** A region plan, with the paths and note a generator-made region may bring. `blank`: a blank biome's (nothing painted; a remake clears it). */ +export type RegionPlanOut = RegionPlan & { paths?: MapPath[]; note?: string; blank?: boolean }; /** * What the region of hex (px, py) would be, made the way its biome says @@ -242,9 +261,11 @@ export async function planRegionWithGenerator(plugin: HexmakerPlugin, parentName const inputs = regionInputs(plugin, parentName, px, py, opts); if (!inputs) return undefined; const { ow, palette, ownBiome, pinned, seed } = inputs; - const plan = inputs.plan(); const note = ownBiome ? biomeNoteOf(ownBiome) : undefined; const route = regionGenerator(note); + // A blank biome: nothing generated, painted by hand. + if (route.kind === "blank") return { cells: new Map(), mix: new Map([[ownBiome!, 1]]), biome: { generator: ownBiome! }, blank: true }; + const plan = inputs.plan(); if (route.kind !== "generator" || !route.ready) return plan; const box = regionBox(ow.layout, px, py); const name = ow.settings.palette ?? ow.map.paletteName; @@ -277,6 +298,7 @@ export async function planBiomePreview(plugin: HexmakerPlugin, overworldName: st if (!ow) return undefined; const palette = regionPalette(plugin, ow.map); const route = regionGenerator(fields); + if (route.kind === "blank") return undefined; if (route.kind !== "generator" || !route.ready) return fields.mix.length ? previewRegion(ow.layout, palette, fields, seed) : undefined; const plan: RegionPlanOut = { cells: new Map(), mix: new Map([[fields.id, 1]]) }; const box = regionBox(ow.layout, 0, 0); @@ -353,6 +375,12 @@ export async function createRegion(plugin: HexmakerPlugin, parentName: string, p if (plan?.note) new Notice(`${plugin.mapLabel(res.name)}: ${plan.note}`); await plugin.linkRegion(parentName, px, py, res.name); await fillBlankParent(plugin, parentName, px, py, res.name); + // BC1: the hex's biome in the overworld's Biome column, however the region was made. + const biome = opts.biome ?? hexBiomeAt(plugin, parentName, hex); + if (biome) { + recordHexBiome(plugin, parentName, hex, biome); + await plugin.mapStore.flush(); + } return res; } @@ -375,12 +403,12 @@ export async function fillBlankParent(plugin: HexmakerPlugin, parentName: string return top; } -/** Overworld hexes that could get a region: painted, inside the map, none yet. */ +/** Overworld hexes that could get a region: with a biome (painted, or a Biome cell), inside the map, none yet. */ export function missingRegionHexes(plugin: HexmakerPlugin, parentName: string): [number, number][] { const map = plugin.getMap(parentName); if (!map) return []; const out: [number, number][] = []; - for (const k of overworldTerrain(plugin, map).keys()) { + for (const k of overworldBiomeHexes(plugin, map)) { if (regionMapAt(plugin.settings.maps, parentName, k)) continue; const [x, y] = k.split("_").map(Number); out.push([x, y]); @@ -459,6 +487,8 @@ export async function regenerateRegion(plugin: HexmakerPlugin, regionName: strin const cur = plugin.mapStore.all(regionName); const cells: [string, { terrain: string }][] = []; for (const [k, t] of plan.cells) if (cur.get(k)?.terrain !== t) cells.push([k, { terrain: t }]); + // A blank biome: its unlocked cells are cleared ("" removes the terrain). + if (plan.blank) for (const [k, h] of cur) if (h.terrain && !h.locked) cells.push([k, { terrain: "" }]); plugin.mapStore.setMany(regionName, cells); // A generator's paths replace the ones of the same types it drew before. if (plan.paths?.length) addGeneratedPaths(plugin, regionName, plan.paths, new Set(plan.paths.map((p) => p.typeName))); @@ -486,13 +516,15 @@ export async function setBiomeAt( ): Promise<{ name: string } | { error: string }> { const parent = plugin.getMap(parentName); if (!parent) return { error: "Map not found." }; - const terrain = representativeTerrain(biome, plugin.getMapPalette(parentName)); - if (!terrain) return { error: "This map's palette has no terrain for that biome." }; + // A blank biome paints no terrain on the overworld: its hex is blank, named by the Biome column. + const blank = isBlankBiome(biome); + const terrain = blank ? undefined : representativeTerrain(biome, plugin.getMapPalette(parentName)); + if (!blank && !terrain) return { error: "This map's palette has no terrain for that biome." }; const hex = `${px}_${py}`; const lock = reshapeLock(plugin, parentName, px, py); if (lock) return { error: lock }; - if (plugin.mapStore.get(parentName, hex)?.terrain !== terrain) plugin.mapStore.set(parentName, hex, { terrain }); - recordHexBiome(plugin, parentName, hex, biome, terrain); + if (plugin.mapStore.get(parentName, hex)?.terrain !== terrain) plugin.mapStore.set(parentName, hex, { terrain: terrain ?? null }); + recordHexBiome(plugin, parentName, hex, biome); await plugin.mapStore.flush(); const existing = regionMapAt(plugin.settings.maps, parentName, hex); if (existing) { @@ -502,6 +534,30 @@ export async function setBiomeAt( return createRegion(plugin, parentName, px, py, { ...opts, biome, fill: "match" }); } +/** + * The Biome painter on one overworld hex (biomePainter.ts): set `biome` and + * make the region (first placement, Build/God), or remake it with the new + * biome (God, only when the hex's biome differs: the same biome again does + * nothing). A reshape returns its undo edits (recorded field by field: the + * overworld hex and the region's cells); a first placement makes a map and + * isn't undone (as with the biome picker). + */ +export async function paintBiomeHex(plugin: HexmakerPlugin, parentName: string, px: number, py: number, biome: BiomeId): Promise> { + const map = plugin.getMap(parentName); + if (!map || !inOverworldGrid(map, px, py)) return { step: "skip" }; + const hex = `${px}_${py}`; + const region = regionMapAt(plugin.settings.maps, parentName, hex); + const step = biomePaintStep(map, !!region, hexBiomeAt(plugin, parentName, hex), biome); + if (step.kind === "skip") return { step: "skip" }; + if (step.kind === "locked") return { step: "locked", hint: step.hint }; + if (step.kind === "place") { + const res = await setBiomeAt(plugin, parentName, px, py, biome); + return "error" in res ? { step: "place", error: res.error } : { step: "place", made: res.name }; + } + const { result, cells } = await plugin.mapStore.record(() => setBiomeAt(plugin, parentName, px, py, biome)); + return { step: "reshape", edits: cellEdits(cells), ...("error" in result ? { error: result.error } : {}) }; +} + // ── walking into new land ──────────────────────────────────────────────── /** Is overworld hex (px, py) inside the overworld's grid? */ @@ -543,7 +599,7 @@ export async function walkIntoHex( if (!overworldOf(plugin, parentName)) return { error: "This map has no rectangle region settings." }; const existing = regionMapAt(plugin.settings.maps, parentName, `${px}_${py}`); if (existing) return { error: `That hex's region is ${plugin.mapLabel(existing.name)}.` }; - if (!representativeTerrain(biome, plugin.getMapPalette(parentName))) return { error: "This map's palette has no terrain for that biome." }; + if (!isBlankBiome(biome) && !representativeTerrain(biome, plugin.getMapPalette(parentName))) return { error: "This map's palette has no terrain for that biome." }; const grow = gridToInclude(parent.gridOffset, parent.gridSize, px, py); if (grow) { parent.gridOffset = grow.offset; diff --git a/src/overworld/worldBiomes.ts b/src/overworld/worldBiomes.ts index fa1920f8..2fc5730d 100644 --- a/src/overworld/worldBiomes.ts +++ b/src/overworld/worldBiomes.ts @@ -63,8 +63,30 @@ export interface WorldBiomesOptions { * biome with a climate. */ biomes?: readonly BiomeNoteFields[]; + /** + * A pool's biomes without a climate (BC2): "fill" (default) puts them + * only in hexes no climate biome fits; "never" leaves them for hand + * placement. Biomes outside a pool without a climate are never placed. + */ + unclimated?: Unclimated; } +/** What World biomes does with a pool's biomes that have no climate (BC2). */ +export type Unclimated = "fill" | "never"; +export const UNCLIMATED_CHOICES: { value: Unclimated; label: string }[] = [ + { value: "fill", label: "Fill gaps only" }, + { value: "never", label: "Never place them" }, +]; + +/** A map note's `no-climate-biomes:` value, read forgivingly ("never", "no", "hand only" → never; anything else → fill). */ +export function parseUnclimated(raw: string | undefined): Unclimated { + const t = (raw ?? "").trim().toLowerCase(); + return /^(never|no|none|off|hand)/.test(t) ? "never" : "fill"; +} + +/** How a choice is written in the map note (readable). */ +export const unclimatedText = (u: Unclimated): string => (u === "never" ? "never" : "fill gaps"); + export interface WorldBiomesResult { /** Hex key → biome. */ biomes: Map; @@ -192,7 +214,7 @@ export function worldBiomes( // 4. Biome per hex, from the candidates' climates (biomeClimate.ts): the // hex's band (high, mid, low; sea), then the band's biomes that fit its // temperature and moisture, rarest and narrowest first, one roll. - const pool = placementPool(opts.biomes); + const pool = placementPool(opts.biomes, opts.unclimated); const { cands, byId } = pool; const isRare = (b: BiomeId) => byId.get(b)?.rare ?? !!biomeInfo(b)?.rare; const zoneOf = (b: BiomeId) => byId.get(b)?.zone ?? biomeInfo(b)?.zone; @@ -206,9 +228,11 @@ export function worldBiomes( const ok = (b: BiomeId): BiomeId | undefined => resolveBiome(b, shown) ?? (allowed.has(b) ? b : undefined); const band = (e: ClimateElevation) => pool.tryOrder.filter((c) => c.elevation === e); const bands = { high: band("high"), mid: band("mid"), low: band("low"), sea: band("sea"), mouth: band("mouth") }; + /** Biomes the palette can paint: shown, or standing in for by a similar one that is. A biome with neither isn't placed. */ + const paintable = (b: BiomeId) => resolveBiome(b, shown) !== undefined; /** The band's first biome (rarest, narrowest) that fits and takes the roll. */ const pickFrom = (list: PlacementCandidate[], t: number, m: number, coast: boolean): BiomeId | undefined => { - const fit = list.filter((c) => inClimateRange(c.temperature, t) && inClimateRange(c.moisture, m) && (!c.coastal || coast)); + const fit = list.filter((c) => inClimateRange(c.temperature, t) && inClimateRange(c.moisture, m) && (!c.coastal || coast) && paintable(c.id)); if (!fit.length) return undefined; const roll = fit.some((c) => c.chance < 1) ? rng() : 0; return fit.find((c) => roll < c.chance)?.id; @@ -231,6 +255,9 @@ export function worldBiomes( }; const biomes = new Map(); const bigLand = landKeys.length >= 8; + /** Coastal-only biomes (climate `coastal`) stay on hexes by the coast through every repair. */ + const onCoast = (k: string) => (sea.has(k) ? toLand.get(k) === 1 : toSea.get(k) === 1); + const coastalOnly = (b: BiomeId) => !!byId.get(b)?.coastal; for (const k of keys) { const t = temperature.get(k)!, m = moisture.get(k)!; let b: BiomeId | undefined; @@ -281,12 +308,12 @@ export function worldBiomes( const rareCount = () => [...biomes.values()].filter((b) => isRare(b)).length; /** A common land biome for a hex when a rare one has to go and no similar one will do. */ const commonNear = (k: string): BiomeId | undefined => nearest( - cands.filter((c) => !c.rare && c.zone !== "sea" && c.elevation !== "mouth" && shown.has(c.id)), + cands.filter((c) => !c.rare && c.zone !== "sea" && c.elevation !== "mouth" && shown.has(c.id) && (!c.coastal || onCoast(k))), temperature.get(k)!, moisture.get(k)!, ); /** Best replacement biome for a group of hexes now holding `from`. */ - const alternative = (group: string[], from: BiomeId, avoid: Set = new Set()): BiomeId | undefined => { + const alternative = (group: string[], from: BiomeId, avoid: Set = new Set(), inlandCoastal = false): BiomeId | undefined => { const [t, m] = climateOf(group); const inGroup = new Set(group); const around = new Set(); @@ -302,6 +329,9 @@ export function worldBiomes( if (c.rare && rareCount() >= rareCap) continue; if ([...around].some((a) => !compatible(a, b))) continue; const score = misfit(b, t, m) + (similar.includes(b) ? 0 : 0.35) + (around.has(b) ? 0.5 : 0) + rng() * 0.05; + // Coastal-only biomes stay by the coast (checked after the roll, so other + // picks don't change), unless nothing else fits (`inlandCoastal`). + if (c.coastal && !inlandCoastal && !group.every(onCoast)) continue; if (score < bestScore) { bestScore = score; best = b; } } return best; @@ -339,7 +369,8 @@ export function worldBiomes( }; const recolour = (group: string[], from: BiomeId, avoid?: Set): boolean => { - const alt = alternative(group, from, avoid); + // Last resort (a patch boxed in by biomes it can't touch): a coastal-only biome inland. + const alt = alternative(group, from, avoid) ?? alternative(group, from, avoid, true); if (!alt) return false; for (const k of group) biomes.set(k, alt); return true; @@ -349,7 +380,7 @@ export function worldBiomes( for (const k of landKeys) { const counts = new Map(); for (const n of nbrs.get(k)!) if (isLand(n)) counts.set(biomes.get(n)!, (counts.get(biomes.get(n)!) ?? 0) + 1); - for (const [b, c] of counts) if (c >= 4 && b !== biomes.get(k) && !isRare(b)) biomes.set(k, b); + for (const [b, c] of counts) if (c >= 4 && b !== biomes.get(k) && !isRare(b) && (!coastalOnly(b) || onCoast(k))) biomes.set(k, b); } // b. A mountain chain from the ridge when there's room and none exists: @@ -391,7 +422,9 @@ export function worldBiomes( if (!recolour(rimChunk(patch, Math.max(1, excess)), top)) break; } // e. Patches of at most MAX_PATCH hexes. - for (let guard = 0; guard < 200; guard++) { + // Generous: without a biome that may touch every other (Coastal fjord + // used to be one, inland), big maps need more splits to settle. + for (let guard = 0; guard < 2000; guard++) { const big = patches().filter((p) => p.length > MAX_PATCH).sort((a, b) => b.length - a.length)[0]; if (!big) break; if (!recolour(rimChunk(big, Math.min(4, big.length - 1)), biomes.get(big[0])!)) break; @@ -437,6 +470,7 @@ export function worldBiomes( const fitN = misfit(b, temperature.get(n)!, moisture.get(n)!); const which = fitK >= fitN ? k : n; if (biomes.get(which) === target) continue; + if (coastalOnly(target) && !onCoast(which)) continue; biomes.set(which, target); ecotones.add(which); changed = true; @@ -492,11 +526,12 @@ export interface PlacementPool { /** * The biomes World biomes may place. With `list` (a biome pool) only those, - * and the pool's biomes without a climate fill hexes no climate biome fits. + * and the pool's biomes without a climate fill hexes no climate biome fits + * (`unclimated` "fill"; "never" leaves them out). Blank biomes never. * Without one: every biome note with a climate (the shipped presets before * the notes load); biomes without a climate are never placed. */ -export function placementPool(list?: readonly BiomeNoteFields[]): PlacementPool { +export function placementPool(list?: readonly BiomeNoteFields[], unclimated: Unclimated = "fill"): PlacementPool { const notes: readonly BiomeNoteFields[] = list ?? (biomeSourceActive() ? allBiomeIds().map((id) => biomeNoteOf(id)).filter((b): b is BiomeNoteFields => !!b) : BIOME_PRESETS); const presetOrder = new Map(BIOME_PRESETS.map((p, i) => [p.id, i])); @@ -508,9 +543,11 @@ export function placementPool(list?: readonly BiomeNoteFields[]): PlacementPool for (const b of notes) { if (seen.has(b.id)) continue; seen.add(b.id); + // Blank biomes (regions painted by hand) are never placed. + if (b.blank) continue; const c = b.climate; if (!c || !isPlaceable(c)) { - if (list) fallback.push({ id: b.id, sea: biomeInfo(b.id)?.zone === "sea" || (b.landShare !== undefined && b.landShare < 0.5) }); + if (list && unclimated === "fill") fallback.push({ id: b.id, sea: biomeInfo(b.id)?.zone === "sea" || (b.landShare !== undefined && b.landShare < 0.5) }); continue; } const elevation = c.elevation ?? "low"; diff --git a/src/types.ts b/src/types.ts index d24fe6fd..a7ca5000 100644 --- a/src/types.ts +++ b/src/types.ts @@ -223,6 +223,10 @@ export interface MapData { biomeRiver?: string; /** Overworlds: the biome pool note (vault path) its biomes were placed from (`biome-pool: "[[…]]"`). */ biomePool?: string; + /** Overworlds: what generating does with the pool's biomes that have no + * climate (BC2), as written: "fill gaps" (default) or "never" + * (`no-climate-biomes: never`). Read with worldBiomes.parseUnclimated. */ + biomeGaps?: string; backgroundImage?: MapBackgroundImage; /** Optional independent transform applied to the hex grid container, * used during background-image calibration so the user can resize/shift @@ -353,6 +357,8 @@ export interface HexmakerPluginSettings { biomePoolsFolder?: string; /** True once the shipped "All biomes" pool note was written (once, so a deleted one stays deleted). */ biomePoolSeeded?: boolean; + /** True once every overworld's Biome column was filled (BC1 migration, once per vault). */ + biomeColumnsFilled?: boolean; /** Vault folder for world types notes (which worlds space generators place); blank = `/world-types`. */ worldTypesFolder?: string; /** True once the shipped "Default space" world types note was written (once, so a deleted one stays deleted). */ diff --git a/src/workMode.ts b/src/workMode.ts index 1753ec9c..e629462a 100644 --- a/src/workMode.ts +++ b/src/workMode.ts @@ -161,6 +161,8 @@ export const TOOL_ACTIONS: Record = { regionLink: "paint-region-area", swap: "swap-hexes", placeToken: "token", + // First placements; a placed region's biome is God's (checked per hex, biomePainter.ts). + biome: "place-biome", }; /** Every registered command id (addCommand in src/). */ diff --git a/src/worldgen/WalkRegionModal.ts b/src/worldgen/WalkRegionModal.ts index 4a978b5f..58d5d186 100644 --- a/src/worldgen/WalkRegionModal.ts +++ b/src/worldgen/WalkRegionModal.ts @@ -158,7 +158,8 @@ export class WalkRegionModal extends HexmakerModal { roll.addEventListener("click", () => { this.seed = randomSeed(); seedInput.value = String(this.seed); - biome = rollBiome(biomes.map((b) => b.id), this.seed, here) ?? biome; + // A roll never lands on a blank biome (pick it by hand). + biome = rollBiome(biomes.filter((b) => b.terrain).map((b) => b.id), this.seed, here) ?? biome; select.value = biome; rolled = `Rolled ${labelOf(biome)} (seed ${this.seed}).`; refresh(); diff --git a/styles.css b/styles.css index fd35656e..9c565844 100644 --- a/styles.css +++ b/styles.css @@ -8770,3 +8770,23 @@ textarea.duckmage-edit-region-notes-input { font-size: var(--font-ui-smaller); color: var(--text-muted); } + +/* Round 5 overworld tools: the Biome painter, blank biomes, the + "Biomes without a climate" row at the top of New overworld. */ +.duckmage-draw-btn-terrain:disabled { + opacity: 0.5; + cursor: not-allowed; +} +.duckmage-biome-blank-preview { + background-image: repeating-linear-gradient(45deg, transparent 0 4px, var(--background-modifier-border) 4px 6px); +} +.duckmage-ow-top { + padding: 6px 8px; + margin-bottom: 6px; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + background: var(--background-secondary); +} +.duckmage-ow-gaps .duckmage-region-gen-label { + font-weight: var(--font-semibold); +} diff --git a/tests/biomeClimate.test.ts b/tests/biomeClimate.test.ts index 846161a8..2724b068 100644 --- a/tests/biomeClimate.test.ts +++ b/tests/biomeClimate.test.ts @@ -1,6 +1,6 @@ import { describe, it, afterEach } from "node:test"; import expect from "expect"; -import { hexDistance } from "../packages/hex-wfc/src/grid"; +import { hexDistance, hexNeighbors } from "../packages/hex-wfc/src/grid"; import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; import { MOISTURE_WORDS, @@ -13,7 +13,7 @@ import { } from "../src/overworld/biomeClimate"; import { buildBiomeNote, parseBiomeNote, updateBiomeNote, type BiomeNoteFields } from "../src/overworld/biomeNote"; import { BIOME_PRESETS, biomePreset } from "../src/overworld/biomePresets"; -import { BIOMES, biomeInfo, setBiomeSource } from "../src/overworld/biomes"; +import { BIOMES, biomeInfo, representativeTerrain, setBiomeSource } from "../src/overworld/biomes"; import { placementPool, worldBiomes, type WorldBiomesOptions } from "../src/overworld/worldBiomes"; import { lowland, worldBiomes as legacyWorldBiomes } from "./fixtures/worldBiomesLegacy"; import { climatesToAdd } from "../src/overworld/BiomeStore"; @@ -95,7 +95,7 @@ describe("biome climate: reading and writing", () => { }); it("every biome the old generator placed has a climate, and its note round-trips it", () => { - // Shipped biomes it never placed (the shore biome Coast) are placed by hand only. + // Coast (never placed by the old generator) has a climate too since BC3; Custom (blank) never does. for (const b of BIOMES) expect(isPlaceable(BIOME_PRESETS.find((p) => p.id === b.id)?.climate)).toBe(true); for (const p of BIOME_PRESETS.filter((x) => x.climate)) { const back = parseBiomeNote(buildBiomeNote(p), p.label); @@ -173,6 +173,27 @@ describe("biome form: climate section", () => { describe("World biomes from climates", () => { const SEEDS = [1, 2, 3, 7, 11, 42, 99, 123, 777, 2024, 31337, 65535]; + /** + * Deliberately updated for BC3 (owner, 2026-10-11). Coast got a climate + * (coastal lowland), so the shipped presets no longer give the old + * placement: the frozen copy is compared with the old generator's biomes + * (every shipped biome except Coast). With them: + * - Limited: still exactly the old placement. + * - Expanded: the same sea, river and climate fields; the biomes differ + * only through one fix that came with BC3: the repairs (majority filter, + * patch splits, rare swaps, transitions) no longer move a coastal-only + * biome (Coastal fjord) inland. The old generator put it on ~90 inland + * hexes over these cases; now a handful (only where a patch is boxed + * in by biomes it may not touch). Everything downstream of those + * repairs can shift, so ≥ 90% of hexes keep their old biome. + * Existing overworlds only change when they're regenerated. + */ + const OLD_SET = BIOME_PRESETS.filter((p) => p.id !== "coast"); + const inlandCoastal = (r: { biomes: Map; sea: Set }) => [...r.biomes].filter(([k, b]) => { + if (!BIOME_PRESETS.find((p) => p.id === b)?.climate?.coastal || r.sea.has(k)) return false; + const [x, y] = k.split("_").map(Number); + return !hexNeighbors(x, y, "flat", "odd").some(([a, c]) => r.sea.has(`${a}_${c}`)); + }).length; const cases: { cells: [number, number][]; o: Partial }[] = [ { cells: hexWorld(2), o: {} }, { cells: hexWorld(3), o: { climate: "varied" } }, @@ -183,31 +204,50 @@ describe("World biomes from climates", () => { { cells: hexWorld(6), o: { climate: "varied", north: "warmer", water: 0.4 } }, ]; - for (const [name, palette] of [["Expanded", DEFAULT_TERRAIN_PALETTE], ["Limited", LIMITED_TERRAIN_PALETTE]] as const) { - it(`reproduces the old placement exactly with only the shipped biomes (${name})`, () => { - for (const { cells, o } of cases) { - for (const seed of SEEDS) { - const opts = { seed, ...o }; - const old = legacyWorldBiomes(cells, "flat", "odd", palette, opts); - const now = worldBiomes(cells, "flat", "odd", palette, opts); - expect(sorted(now.biomes)).toBe(sorted(old.biomes)); - expect(sorted(now.terrain)).toBe(sorted(old.terrain)); - expect(now.river).toEqual(old.river); - expect([...now.ecotones].sort()).toEqual([...old.ecotones].sort()); - } + it("reproduces the old placement exactly with the old biomes (Limited)", () => { + for (const { cells, o } of cases) { + for (const seed of SEEDS) { + const opts = { seed, ...o }; + const old = legacyWorldBiomes(cells, "flat", "odd", LIMITED_TERRAIN_PALETTE, opts); + const now = worldBiomes(cells, "flat", "odd", LIMITED_TERRAIN_PALETTE, { ...opts, biomes: OLD_SET }); + expect(sorted(now.biomes)).toBe(sorted(old.biomes)); + expect(sorted(now.terrain)).toBe(sorted(old.terrain)); + expect(now.river).toEqual(old.river); + expect([...now.ecotones].sort()).toEqual([...old.ecotones].sort()); } - }); - } + } + }); - it("reproduces it with the shipped biomes loaded from notes, in any order", () => { - setBiomeSource([...BIOME_PRESETS].reverse()); + it("matches the old placement with the old biomes (Expanded), except coastal-only biomes stay on the coast", () => { + let same = 0, total = 0, oldInland = 0, newInland = 0; + for (const { cells, o } of cases) { + for (const seed of SEEDS) { + const opts = { seed, ...o }; + const old = legacyWorldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, opts); + const now = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { ...opts, biomes: OLD_SET }); + expect([...now.sea].sort()).toEqual([...old.sea].sort()); + expect(now.river).toEqual(old.river); + expect(sorted(now.temperature as never)).toBe(sorted(old.temperature as never)); + newInland += inlandCoastal(now); + oldInland += inlandCoastal(old); + for (const [k, b] of old.biomes) { total++; if (now.biomes.get(k) === b) same++; } + // Every hex is painted with its own biome's terrain. + for (const [k, b] of now.biomes) expect(now.terrain.get(k)).toBe(representativeTerrain(b, DEFAULT_TERRAIN_PALETTE)); + } + } + expect(oldInland).toBeGreaterThan(50); + expect(newInland).toBeLessThanOrEqual(oldInland / 10); + expect(same / total).toBeGreaterThanOrEqual(0.9); + }); + + it("gives the same placement with the biomes loaded from notes, in any order", () => { for (const { cells, o } of cases.slice(0, 4)) { for (const seed of SEEDS.slice(0, 6)) { const opts = { seed, ...o }; setBiomeSource(undefined); - const old = legacyWorldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, opts); + const shipped = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { ...opts, biomes: OLD_SET }); setBiomeSource([...BIOME_PRESETS].reverse()); - expect(sorted(worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, opts).biomes)).toBe(sorted(old.biomes)); + expect(sorted(worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { ...opts, biomes: [...OLD_SET].reverse() }).biomes)).toBe(sorted(shipped.biomes)); } } }); diff --git a/tests/biomeNotes.test.ts b/tests/biomeNotes.test.ts index bb5fc443..0b89719e 100644 --- a/tests/biomeNotes.test.ts +++ b/tests/biomeNotes.test.ts @@ -133,8 +133,9 @@ describe("biome note format", () => { // ── presets ────────────────────────────────────────────────────────────── describe("shipped biome presets", () => { - it("cover every built-in biome with the same label (Coast is note-only)", () => { - expect(BIOME_PRESETS.map((b) => b.id).filter((id) => id !== "coast")).toEqual(BIOMES.map((b) => b.id)); + it("cover every built-in biome with the same label (Coast and Custom (blank) are note-only)", () => { + expect(BIOME_PRESETS.map((b) => b.id).filter((id) => id !== "coast" && id !== "custom")).toEqual(BIOMES.map((b) => b.id)); + expect(BIOME_PRESETS.find((p) => p.id === "custom")!.blank).toBe(true); for (const b of BIOMES) expect(BIOME_PRESETS.find((p) => p.id === b.id)!.label).toBe(b.label); expect(BIOME_PRESETS.find((p) => p.id === "coast")!.shore).toBe(true); }); diff --git a/tests/biomePool.test.ts b/tests/biomePool.test.ts index 6d1c14ab..48932084 100644 --- a/tests/biomePool.test.ts +++ b/tests/biomePool.test.ts @@ -15,7 +15,7 @@ import { } from "../src/overworld/biomePool"; import { biomeFileName, type BiomeNoteFields } from "../src/overworld/biomeNote"; import { BIOME_PRESETS } from "../src/overworld/biomePresets"; -import { biomeForTerrain, setBiomeSource } from "../src/overworld/biomes"; +import { biomeForTerrain, biomeRef, isBlankBiome, setBiomeSource } from "../src/overworld/biomes"; import { worldBiomes } from "../src/overworld/worldBiomes"; import { firstPassWrites } from "../src/overworld/overworldPass"; import { buildMapNote, parseMapNote, type HexData, type MapNoteData } from "../src/maps/mapNote"; @@ -65,13 +65,15 @@ describe("biome pool notes", () => { expect(parseBiomePool("no table here").problems.length).toBe(1); }); - it("ships one pool with every built-in biome", () => { + it("ships one pool with every built-in biome (blank ones are placed by hand, not pooled)", () => { const rows = allBiomesPool(BIOME_PRESETS); + const pooled = BIOME_PRESETS.filter((p) => !p.blank); + expect(pooled.length).toBe(BIOME_PRESETS.length - 1); expect(ALL_BIOMES_POOL).toBe("All biomes"); - expect(rows.map((r) => r.biome)).toEqual(BIOME_PRESETS.map((p) => biomeFileName(p.label))); + expect(rows.map((r) => r.biome)).toEqual(pooled.map((p) => biomeFileName(p.label))); const { biomes, unknown } = poolBiomes(parseBiomePool(buildBiomePool(ALL_BIOMES_POOL, rows)).rows, finder([...BIOME_PRESETS])); expect(unknown).toEqual([]); - expect(biomes.map((b) => b.id)).toEqual(BIOME_PRESETS.map((p) => p.id)); + expect(biomes.map((b) => b.id)).toEqual(pooled.map((p) => p.id)); }); it("weights scale a biome's chance; 0 leaves it out; unknown biomes are reported", () => { @@ -145,7 +147,7 @@ describe("placement from a pool", () => { describe("the first pass writes", () => { const readsAs = (t: string) => biomeForTerrain(t, DEFAULT_TERRAIN_PALETTE); - it("never touches locked hexes; records a biome its terrain can't say", () => { + it("never touches locked hexes; records every hex's biome (BC1), by label", () => { setBiomeSource([...BIOME_PRESETS, { id: "ash", label: "Ash", mix: [{ type: "badlands", weight: 1 }], transitions: [], climate: { elevation: "low" } }]); const r = worldBiomes(hexWorld(3), "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 3 }); const keys = [...r.biomes.keys()]; @@ -153,28 +155,31 @@ describe("the first pass writes", () => { [keys[0], { terrain: "my painted", locked: true }], [keys[1], { terrain: "old", biome: "old-one" }], ]); - const w = firstPassWrites(current, r, readsAs); + const w = firstPassWrites(current, r, biomeRef, isBlankBiome); expect(w.kept).toEqual([keys[0]]); expect(w.cells.some(([k]) => k === keys[0])).toBe(false); + expect(w.cells.length).toBe(r.biomes.size - 1); for (const [k, patch] of w.cells) { expect(patch.terrain).toBe(r.terrain.get(k)); - expect(patch.biome).toBe(readsAs(patch.terrain) === r.biomes.get(k) ? null : r.biomes.get(k)); + expect(patch.biome).toBe(biomeRef(r.biomes.get(k)!)); } + // Even where the terrain reads back as the biome, the column says it. + expect(w.cells.some(([k, p]) => readsAs(p.terrain!) === r.biomes.get(k))).toBe(true); // Nothing to do the second time round (beyond the locked hex). const after = new Map(current); - for (const [k, p] of w.cells) after.set(k, { terrain: p.terrain, biome: p.biome ?? undefined }); - expect(firstPassWrites(after, r, readsAs).cells).toEqual([]); + for (const [k, p] of w.cells) after.set(k, { terrain: p.terrain ?? undefined, biome: p.biome }); + expect(firstPassWrites(after, r, biomeRef, isBlankBiome).cells).toEqual([]); }); it("regenerating keeps locked hexes across seeds", () => { const cells = hexWorld(3); const first = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 1 }); const state = new Map(); - for (const [k, p] of firstPassWrites(state, first, readsAs).cells) state.set(k, { terrain: p.terrain }); + for (const [k, p] of firstPassWrites(state, first, biomeRef).cells) state.set(k, { terrain: p.terrain ?? undefined }); const lockedKey = [...state.keys()][4]; state.set(lockedKey, { terrain: "hand painted", locked: true }); const second = worldBiomes(cells, "flat", "odd", DEFAULT_TERRAIN_PALETTE, { seed: 2 }); - for (const [k, p] of firstPassWrites(state, second, readsAs).cells) state.set(k, { ...state.get(k), terrain: p.terrain }); + for (const [k, p] of firstPassWrites(state, second, biomeRef).cells) state.set(k, { ...state.get(k), terrain: p.terrain ?? undefined }); expect(state.get(lockedKey)).toEqual({ terrain: "hand painted", locked: true }); }); }); diff --git a/tests/overworldTools.test.ts b/tests/overworldTools.test.ts new file mode 100644 index 00000000..cf55fde6 --- /dev/null +++ b/tests/overworldTools.test.ts @@ -0,0 +1,404 @@ +/** + * Round-5 overworld tools (owner decisions BC1, BC2, BC3, MM1): + * - BC1: the Biome column is written for every overworld hex with a biome, + * readable (the biome's label), and older overworlds are filled once; + * the "Custom (blank)" biome makes blank regions, and new overworlds can + * get several blank hexes in one go. + * - Biome painter: first placement in Build/God, a placed region's biome is + * God's, re-painting the same biome never regenerates, reshapes are undoable. + * - BC2: what a pool's biomes without a climate do ("fill gaps" / "never"). + * - BC3: Coast has a climate and is placed on sea↔land borders. + */ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { hexDistance, hexNeighbors } from "../packages/hex-wfc/src/grid"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import { buildBiomeNote, parseBiomeNote, updateBiomeNote, type BiomeNoteFields } from "../src/overworld/biomeNote"; +import { BIOME_PRESETS, biomePreset } from "../src/overworld/biomePresets"; +import { biomeByRef, biomeRef, isBlankBiome, representativeTerrain, setBiomeSource } from "../src/overworld/biomes"; +import { allBiomesPool } from "../src/overworld/biomePool"; +import { regionGenerator, routeNote, fieldsFromForm, formFromFields, formProblem, formTypes } from "../src/overworld/biomeForm"; +import { biomeColumnFills, firstPassWrites, pickBlankHexes } from "../src/overworld/overworldPass"; +import { parseUnclimated, placementPool, unclimatedText, worldBiomes } from "../src/overworld/worldBiomes"; +import { BiomeStroke, biomePaintStep } from "../src/overworld/biomePainter"; +import { paintBiomeHex, setBiomeAt } from "../src/overworld/regionsVault"; +import { fillBiomeColumns } from "../src/overworld/overworldGen"; +import { buildMapNote, parseMapNote, type HexData, type MapNoteData } from "../src/maps/mapNote"; +import { cellPatch, type CellEdit } from "../src/undoBook"; +import { PLACE_LOCKED_HINT, RESHAPE_LOCKED_HINT, TOOL_ACTIONS } from "../src/workMode"; +import { toolModeLabel } from "../src/hex-map/toolMode"; +import type { MapData } from "../src/types"; + +afterEach(() => setBiomeSource(undefined)); + +const hexWorld = (R: number): [number, number][] => { + const out: [number, number][] = []; + for (let x = 0; x <= 2 * R; x++) for (let y = 0; y <= 2 * R; y++) if (hexDistance([x, y], [R, R], "flat", "odd") <= R) out.push([x, y]); + return out; +}; +const PAL = DEFAULT_TERRAIN_PALETTE; +const terrainOf = (id: string) => representativeTerrain(id, PAL)!; + +// ── a small overworld in memory (like walkNewRegion.test.ts) ───────────── + +type Hex = Partial; +function world(mode?: string) { + const overworld = { + name: "ow", paletteName: "Default", workMode: mode, + gridSize: { cols: 3, rows: 3 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", + regions: { footprint: "rect", size: 4, blend: "normal", worldId: "w1", stagger: "odd" }, + pathChains: [], + } as unknown as MapData; + const maps: MapData[] = [overworld]; + const store = new Map>(); + const hexes = (m: string): Map => { + let h = store.get(m); + if (!h) store.set(m, (h = new Map())); + return h; + }; + let recorder: ((m: string, k: string, before: Hex | undefined) => void) | null = null; + const write = (m: string, k: string, patch: Record) => { + recorder?.(m, k, hexes(m).get(k)); + const h: Record = { ...hexes(m).get(k) }; + for (const [f, v] of Object.entries(patch)) { + if (v === undefined || v === null || v === "" || v === false) delete h[f]; + else h[f] = v; + } + if (Object.keys(h).length) hexes(m).set(k, h as Hex); else hexes(m).delete(k); + }; + const writes: string[] = []; + const made: { name: string; cells?: Map }[] = []; + const plugin = { + settings: { maps, hexOrientation: "flat", staggerOffset: "odd" } as Record, + getMap: (n: string) => maps.find((m) => m.name === n), + getMapPalette: () => PAL, + getPaletteOrPresetTerrains: () => PAL, + getPaletteByName: () => undefined, + mapLabel: (n: string) => n, + mapStore: { + get: (m: string, k: string) => store.get(m)?.get(k), + all: (m: string) => hexes(m), + set: (m: string, k: string, patch: Record) => { writes.push(`${m}|${k}`); write(m, k, patch); return true; }, + setMany: (m: string, cells: Iterable<[string, Record]>) => { for (const [k, p] of cells) { writes.push(`${m}|${k}`); write(m, k, p); } }, + flush: async () => {}, + record: async (fn: () => T | Promise) => { + const before = new Map(); + recorder = (m, k, b) => { const id = `${m}|${k}`; if (!before.has(id)) before.set(id, { map: m, key: k, before: b ? { ...b } : undefined }); }; + try { + const result = await fn(); + return { result, cells: [...before.values()].map((c) => ({ ...c, after: hexes(c.map).get(c.key) ? { ...hexes(c.map).get(c.key) } : undefined })) }; + } finally { recorder = null; } + }, + }, + saveSettings: async () => {}, + createNewMap: async ( + name: string, cols: number, rows: number, _palette: string, x: number, y: number, stagger: string, + _progress: unknown, cells?: Map, extra?: { parent?: { map: string; hex: string } }, + ) => { + const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-"); + maps.push({ name: slug, paletteName: "Default", gridSize: { cols, rows }, gridOffset: { x, y }, staggerOffset: stagger, parent: extra?.parent, submapKind: "region", pathChains: [] } as unknown as MapData); + for (const [k, t] of cells ?? []) hexes(slug).set(k, { terrain: t }); + made.push({ name: slug, cells }); + return { name: slug }; + }, + linkRegion: async () => true, + }; + /** A region already made on hex (x, y), painted with `terrain`. */ + const addRegion = (x: number, y: number, biome: string) => { + const name = `ow-${x}-${y}`; + maps.push({ name, submapKind: "region", parent: { map: "ow", hex: `${x}_${y}` }, gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 4 * x, y: 4 * y }, biome: { generator: biome }, pathChains: [] } as unknown as MapData); + hexes("ow").set(`${x}_${y}`, { terrain: terrainOf(biome), biome: biomeRef(biome) }); + for (let i = 0; i < 4; i++) hexes(name).set(`${4 * x + i}_${4 * y}`, { terrain: terrainOf(biome) }); + return name; + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { plugin: plugin as any, store, maps, overworld, writes, made, addRegion, hexes }; +} + +// ── BC1: the Biome column ───────────────────────────────────────────────── + +describe("BC1: the Biome column, always", () => { + it("first pass writes every hex's biome, by label, even when its terrain says it", () => { + setBiomeSource(BIOME_PRESETS); + const r = worldBiomes(hexWorld(2), "flat", "odd", PAL, { seed: 5 }); + const w = firstPassWrites(new Map(), r, biomeRef, isBlankBiome); + expect(w.cells.length).toBe(r.biomes.size); + for (const [k, patch] of w.cells) { + expect(patch.biome).toBe(biomeRef(r.biomes.get(k)!)); + expect(biomeByRef(patch.biome)).toBe(r.biomes.get(k)); + expect(patch.terrain).toBe(r.terrain.get(k)); + } + // Nothing to do the second time. + const after = new Map(w.cells.map(([k, p]) => [k, { terrain: p.terrain ?? undefined, biome: p.biome }])); + expect(firstPassWrites(after, r, biomeRef, isBlankBiome).cells).toEqual([]); + }); + + it("an old id-style cell is rewritten readably once, and a locked hex is kept", () => { + setBiomeSource(BIOME_PRESETS); + const r = { biomes: new Map([["0_0", "taiga"], ["1_0", "taiga"]]), terrain: new Map([["0_0", terrainOf("taiga")], ["1_0", terrainOf("taiga")]]) }; + const cur = new Map([["0_0", { terrain: terrainOf("taiga"), biome: "taiga" }], ["1_0", { terrain: "x", locked: true }]]); + const w = firstPassWrites(cur, r, biomeRef, isBlankBiome); + expect(w.cells).toEqual([["0_0", { terrain: terrainOf("taiga"), biome: "Taiga" }]]); + expect(w.kept).toEqual(["1_0"]); + }); + + it("round-trips through the map note, and reads tolerantly", () => { + setBiomeSource(BIOME_PRESETS); + const data: MapNoteData = { settings: { paletteName: "Default" }, hexes: new Map([["0_0", { terrain: "forest", biome: "Temperate forest" }], ["1_0", { biome: "Custom (blank)" }]]), paths: [] }; + const back = parseMapNote(buildMapNote("ow", data))!; + expect(back.hexes.get("0_0")).toEqual({ terrain: "forest", biome: "Temperate forest" }); + expect(back.hexes.get("1_0")).toEqual({ biome: "Custom (blank)" }); + // Any spelling of a biome reads back (id, label, note name; case). + for (const ref of ["temperate-forest", "Temperate forest", "TEMPERATE FOREST"]) expect(biomeByRef(ref)).toBe("temperate-forest"); + expect(biomeByRef("No such biome")).toBeUndefined(); + }); + + it("the migration fills hexes with a biome and no cell, leaving written cells alone", () => { + const cur = new Map([["0_0", { terrain: "forest" }], ["1_0", { terrain: "forest", biome: "My own" }], ["2_0", {}]]); + const fills = biomeColumnFills(["0_0", "1_0", "2_0"], (k) => cur.get(k), (k) => (k === "2_0" ? undefined : "taiga"), (b) => `<${b}>`); + expect(fills).toEqual([["0_0", ""]]); + }); + + it("fillBiomeColumns runs once per vault", async () => { + setBiomeSource(BIOME_PRESETS); + const w = world("play"); // the migration is not a user action: no mode gate + w.hexes("ow").set("0_0", { terrain: terrainOf("taiga") }); + w.hexes("ow").set("1_0", { terrain: terrainOf("grassland"), biome: "ash" }); + const n = await fillBiomeColumns(w.plugin); + expect(n).toBe(1); + expect(w.hexes("ow").get("0_0")).toEqual({ terrain: terrainOf("taiga"), biome: "Taiga" }); + expect(w.hexes("ow").get("1_0")?.biome).toBe("ash"); + expect(w.plugin.settings.biomeColumnsFilled).toBe(true); + w.hexes("ow").set("2_0", { terrain: terrainOf("taiga") }); + expect(await fillBiomeColumns(w.plugin)).toBe(0); + expect(w.hexes("ow").get("2_0")?.biome).toBeUndefined(); + }); +}); + +// ── the blank biome ─────────────────────────────────────────────────────── + +describe("Custom (blank) biome", () => { + it("ships as a blank preset with no mix, outside the All biomes pool and placement", () => { + const custom = biomePreset("custom")!; + expect(custom.blank).toBe(true); + expect(custom.mix).toEqual([]); + expect(custom.climate).toBeUndefined(); + expect(allBiomesPool(BIOME_PRESETS).map((r) => r.biome)).not.toContain("Custom (blank)"); + expect(placementPool(BIOME_PRESETS).cands.map((c) => c.id)).not.toContain("custom"); + expect(placementPool(BIOME_PRESETS).fallback.map((c) => c.id)).not.toContain("custom"); + }); + + it("`blank: yes` round-trips through its note, and a hand-edited value reads", () => { + const note = buildBiomeNote(biomePreset("custom")!); + expect(note).toContain("blank: yes"); + const back = parseBiomeNote(note, "Custom (blank)"); + expect(back.problems).toEqual([]); + expect(back.fields.blank).toBe(true); + expect(parseBiomeNote(note.replace("blank: yes", "blank: TRUE"), "x").fields.blank).toBe(true); + expect(parseBiomeNote(note.replace("blank: yes", "blank: maybe"), "x").problems.map((p) => p.text)).toEqual(['blank should be yes or no, not "maybe"']); + // Turning it off removes the key; the user's spelling is kept when it reads the same. + expect(updateBiomeNote(note, { ...back.fields, blank: undefined }).split("\n---")[0]).not.toContain("blank:"); + const spelled = note.replace("blank: yes", "blank: true"); + expect(updateBiomeNote(spelled, back.fields)).toBe(spelled); + }); + + it("routes to a blank region; any biome can be made blank in the form (no mix needed)", () => { + expect(regionGenerator({ blank: true, generator: "x" })).toEqual({ kind: "blank" }); + expect(routeNote({ blank: true })).toMatch(/^Blank/); + const s = formFromFields(undefined, formTypes(PAL)); + s.label = "Unknown lands"; + expect(formProblem(s, [])).toMatch(/weight/); + s.blank = true; + expect(formProblem(s, [])).toBeUndefined(); + expect(fieldsFromForm(s).blank).toBe(true); + }); + + it("placing it leaves the overworld hex blank (the Biome column names it) and makes an empty region", async () => { + setBiomeSource(BIOME_PRESETS); + const w = world("build"); + w.hexes("ow").set("2_1", { terrain: terrainOf("taiga") }); + const r = await setBiomeAt(w.plugin, "ow", 2, 1, "custom"); + expect("name" in r).toBe(true); + expect(w.hexes("ow").get("2_1")).toEqual({ biome: "Custom (blank)" }); + expect(w.made).toHaveLength(1); + expect(w.made[0].cells?.size ?? 0).toBe(0); + expect(w.maps.find((m) => m.parent?.hex === "2_1")?.biome).toEqual({ generator: "custom" }); + }); + + it("remaking a region as blank (God) clears its painted cells but keeps locked ones", async () => { + setBiomeSource(BIOME_PRESETS); + const w = world("god"); + const name = w.addRegion(1, 1, "taiga"); + w.hexes(name).set("7_4", { terrain: "lake", locked: true }); + await setBiomeAt(w.plugin, "ow", 1, 1, "custom"); + expect([...w.hexes(name).entries()]).toEqual([["7_4", { terrain: "lake", locked: true }]]); + }); + + it("blank hexes on a new overworld: n of them, land first, spread out, the same for a seed", () => { + const cells = hexWorld(3).map(([x, y]) => `${x}_${y}`); + const sea = new Set(cells.slice(0, 20)); + const a = pickBlankHexes(cells, sea, 4, 7, "flat", "odd"); + expect(a).toHaveLength(4); + expect(new Set(a).size).toBe(4); + for (const k of a) expect(sea.has(k)).toBe(false); + expect(pickBlankHexes(cells, sea, 4, 7, "flat", "odd")).toEqual(a); + const pos = (k: string) => k.split("_").map(Number) as [number, number]; + expect(Math.min(...a.slice(1).map((k) => hexDistance(pos(k), pos(a[0]), "flat", "odd")))).toBeGreaterThan(1); + // More than the land: the sea fills the rest; never more than the map. + expect(pickBlankHexes(cells, sea, cells.length - 10, 1, "flat", "odd").filter((k) => sea.has(k))).toHaveLength(10); + expect(pickBlankHexes(cells, sea, 999, 1, "flat", "odd")).toHaveLength(cells.length); + expect(pickBlankHexes(cells, sea, 0, 1, "flat", "odd")).toEqual([]); + }); +}); + +// ── the Biome painter ───────────────────────────────────────────────────── + +describe("Biome painter", () => { + it("is a drawing tool for Build (first placements)", () => { + expect(TOOL_ACTIONS.biome).toBe("place-biome"); + expect(toolModeLabel({ mode: "biome", erasing: false, biomeName: "Taiga" })).toMatch(/^Painting biome: Taiga/); + }); + + it("gates each hex by the map's mode: place in Build/God, change a placed one in God only", () => { + expect(biomePaintStep({ workMode: "play" }, false, undefined, "taiga")).toEqual({ kind: "locked", hint: PLACE_LOCKED_HINT }); + expect(biomePaintStep({ workMode: "build" }, false, "grassland", "taiga")).toEqual({ kind: "place" }); + expect(biomePaintStep({ workMode: "god" }, false, undefined, "taiga")).toEqual({ kind: "place" }); + expect(biomePaintStep({ workMode: "build" }, true, "grassland", "taiga")).toEqual({ kind: "locked", hint: RESHAPE_LOCKED_HINT }); + expect(biomePaintStep({ workMode: "god" }, true, "grassland", "taiga")).toEqual({ kind: "reshape" }); + }); + + it("the same biome again never regenerates, in any mode", () => { + for (const mode of ["play", "build", "god"]) expect(biomePaintStep({ workMode: mode }, true, "taiga", "taiga")).toEqual({ kind: "skip" }); + }); + + it("on the map: first placement in Build makes the region, no undo entry (it makes a map)", async () => { + setBiomeSource(BIOME_PRESETS); + const w = world("build"); + const r = await paintBiomeHex(w.plugin, "ow", 0, 0, "grassland"); + expect(r.step).toBe("place"); + expect(r.made).toBeTruthy(); + expect(r.edits).toBeUndefined(); + expect(w.hexes("ow").get("0_0")).toEqual({ terrain: terrainOf("grassland"), biome: "Grassland" }); + }); + + it("on the map: re-painting the same biome on a region writes nothing", async () => { + setBiomeSource(BIOME_PRESETS); + const w = world("god"); + w.addRegion(1, 1, "taiga"); + const writes = w.writes.length; + expect(await paintBiomeHex(w.plugin, "ow", 1, 1, "taiga")).toEqual({ step: "skip" }); + expect(w.writes.length).toBe(writes); + expect(w.made).toEqual([]); + }); + + it("on the map: Build can't change a placed biome; God remakes it and undo puts it back", async () => { + setBiomeSource(BIOME_PRESETS); + const b = world("build"); + const nameB = b.addRegion(1, 1, "taiga"); + const before = [...b.hexes(nameB)]; + expect(await paintBiomeHex(b.plugin, "ow", 1, 1, "grassland")).toEqual({ step: "locked", hint: RESHAPE_LOCKED_HINT }); + expect([...b.hexes(nameB)]).toEqual(before); + + const g = world("god"); + const name = g.addRegion(1, 1, "taiga"); + const owBefore = { ...g.hexes("ow").get("1_1") }; + const r = await paintBiomeHex(g.plugin, "ow", 1, 1, "grassland"); + expect(r.step).toBe("reshape"); + expect(g.hexes("ow").get("1_1")).toEqual({ terrain: terrainOf("grassland"), biome: "Grassland" }); + const edits = r.edits as CellEdit[]; + expect(edits.some((e) => e.map === "ow" && e.key === "1_1")).toBe(true); + expect(edits.some((e) => e.map === name)).toBe(true); + // Undo: every recorded field back to its value before the stroke. + for (const e of edits) g.plugin.mapStore.set(e.map, e.key, cellPatch(e, "undo")); + expect(g.hexes("ow").get("1_1")).toEqual(owBefore); + expect(g.hexes(name).get("4_4")).toEqual({ terrain: terrainOf("taiga") }); + }); + + it("a stroke paints each hex once, in order, and gathers edits and hints", async () => { + const order: string[] = []; + const s = new BiomeStroke(async (k) => { + order.push(k); + if (k === "2_0") return { step: "locked", hint: "nope" }; + if (k === "3_0") return { step: "skip" }; + return { step: "reshape", edits: [Number(k[0])] }; + }); + for (const k of ["0_0", "1_0", "0_0", "2_0", "3_0", "1_0", "2_0"]) s.add(k); + const r = await s.finish(); + expect(order).toEqual(["0_0", "1_0", "2_0", "3_0"]); + expect(r.edits).toEqual([0, 1]); + expect(r.changed).toBe(2); + expect(r.hints).toEqual(["nope"]); + }); +}); + +// ── BC2: pool biomes without a climate ──────────────────────────────────── + +describe("BC2: biomes without a climate", () => { + const PLAIN: BiomeNoteFields = { id: "glass", label: "Glass", mix: [{ type: "desert", weight: 1 }], transitions: [] }; + const POOL = [BIOME_PRESETS.find((p) => p.id === "tundra")!, BIOME_PRESETS.find((p) => p.id === "open-sea")!, PLAIN]; + + it("fill gaps (default) puts them where nothing else fits; never leaves them out", () => { + setBiomeSource([...BIOME_PRESETS, PLAIN]); + expect(placementPool(POOL).fallback.map((f) => f.id)).toEqual(["glass"]); + expect(placementPool(POOL, "never").fallback).toEqual([]); + let filled = 0; + for (const seed of [1, 2, 3, 4, 5, 6]) { + const fill = worldBiomes(hexWorld(3), "flat", "odd", PAL, { seed, climate: "warm", biomes: POOL }); + filled += [...fill.biomes.values()].filter((b) => b === "glass").length; + const never = worldBiomes(hexWorld(3), "flat", "odd", PAL, { seed, climate: "warm", biomes: POOL, unclimated: "never" }); + expect([...never.biomes.values()]).not.toContain("glass"); + expect(never.biomes.size).toBe(hexWorld(3).length); + } + expect(filled).toBeGreaterThan(0); + }); + + it("is kept on the overworld readably and read forgivingly", () => { + expect(unclimatedText("fill")).toBe("fill gaps"); + expect(unclimatedText("never")).toBe("never"); + for (const v of ["never", "Never", "no", "hand only", "none"]) expect(parseUnclimated(v)).toBe("never"); + for (const v of [undefined, "", "fill gaps", "fill", "gaps", "whatever"]) expect(parseUnclimated(v)).toBe("fill"); + const data: MapNoteData = { settings: { paletteName: "Default", biomeGaps: "never" }, hexes: new Map(), paths: [] }; + const note = buildMapNote("ow", data); + expect(note).toContain("no-climate-biomes: never"); + expect(parseMapNote(note)!.settings.biomeGaps).toBe("never"); + }); +}); + +// ── BC3: Coast on sea↔land borders ──────────────────────────────────────── + +describe("BC3: Coast is placed on sea↔land borders", () => { + it("has a coastal lowland climate", () => { + expect(biomePreset("coast")!.climate).toMatchObject({ elevation: "low", coastal: true }); + }); + + it("only on land next to the sea (bar a rare boxed-in patch), and on most generated overworlds", () => { + setBiomeSource(BIOME_PRESETS); + let inland = 0, total = 0; + let worlds = 0, withCoast = 0; + for (const seed of [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]) { + for (const cells of [hexWorld(3), hexWorld(4)]) { + const r = worldBiomes(cells, "flat", "odd", PAL, { seed, climate: "temperate", water: 0.3 }); + worlds++; + const coast = [...r.biomes].filter(([, b]) => b === "coast").map(([k]) => k); + if (coast.length) withCoast++; + for (const k of coast) { + total++; + expect(r.sea.has(k)).toBe(false); + const [x, y] = k.split("_").map(Number); + if (!hexNeighbors(x, y, "flat", "odd").some(([a, b]) => r.sea.has(`${a}_${b}`))) inland++; + expect(r.terrain.get(k)).toBe(representativeTerrain("coast", PAL)); + } + } + } + expect(withCoast).toBeGreaterThan(worlds / 2); + expect(inland).toBeLessThanOrEqual(total / 20); + }); + + it("is not placed where the palette can't paint it (no notes loaded: no terrain stands for Coast)", () => { + for (const seed of [1, 2, 3]) { + const r = worldBiomes(hexWorld(4), "flat", "odd", PAL, { seed, climate: "temperate", water: 0.3 }); + expect([...r.biomes.values()]).not.toContain("coast"); + for (const k of r.biomes.keys()) expect(r.terrain.has(k)).toBe(true); + } + }); +}); From 84e748a8d91776e3b7ca093e97b8484ae1a1dca9 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:42:19 -0400 Subject: [PATCH 288/558] feat: missing maps + make generator from a region (SM-DEL, PR1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SM-DEL: a map whose folder and map note were deleted by hand is marked missing, never re-created empty. MapStore keeps the last note text of every map in /map-cache/; at startup a map with no note, nothing to migrate and a cache entry is missing (fresh-install placeholders and 1.5 maps still migrate). Missing maps are never written (sync, flush, reloadFromNotes); a note deleted mid-session marks the map missing (vault delete event, plugin's own Delete excluded via expectRemoval); a note put back loads again (create event). Restore re-creates the note from memory, else the cache (exact hexes, paths, settings), else settings; Remove drops the entry without touching files. The map list shows a warning icon with Restore / Remove, and the map view an empty state with the same. Palettes: an emptied list is no longer refilled with the defaults, the last palette can be deleted, and palette notes deleted while closed stay deleted (data.json's copy backed up first); Settings → Add default palettes puts them back on request. Smoke "deleted" setup now judges F8-missing / F8-no-refill / F8-restore / F8-remove, and C3 expects the missing-map state. PR1: "Make generator…" in Edit region and "Make generator from …" in the Maps right-click menu: learn a generator from the region as painted, as a new generator or over an existing one, listed most fitting first (region's biome's generator, parent biomes', learned from this region, related biomes', then the rest). Overwrite backs the old note up as plain Markdown. A new generator gets a biome inheriting the region's biome basics (climate, land share, min islands, transitions, shore, blend, colour, mix) with `parent:` and Terrain weights from the region. Biome notes gain an optional Terrain weights table (per-terrain weight within a type; unlisted terrains count 1) used by region profiles. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 + dev/smoke/lib/page.mjs | 4 + dev/smoke/run.mjs | 2 + dev/smoke/setups.mjs | 23 ++- package.json | 4 +- src/HexmakerPlugin.ts | 86 +++++++-- src/HexmakerSettingTab.ts | 27 +++ src/hex-map/EditRegionModal.ts | 13 +- src/hex-map/HexMapView.ts | 21 ++- src/hex-map/MakeGeneratorModal.ts | 145 +++++++++++++++ src/hex-map/MapModal.ts | 77 +++++--- src/hex-map/help.md | 11 ++ src/maps/MapStore.ts | 226 ++++++++++++++++++++++- src/overworld/biomeNote.ts | 51 ++++- src/overworld/biomes.ts | 43 ++++- src/palettes/PaletteStore.ts | 67 ++++++- src/worldgen/generators.ts | 6 + src/worldgen/regionGenerator.ts | 296 ++++++++++++++++++++++++++++++ styles.css | 80 ++++++++ tests/helpers/memVault.ts | 10 + tests/missingMaps.test.ts | 180 ++++++++++++++++++ tests/palettes.test.ts | 60 +++++- tests/regionGenerator.test.ts | 261 ++++++++++++++++++++++++++ 23 files changed, 1620 insertions(+), 79 deletions(-) create mode 100644 src/hex-map/MakeGeneratorModal.ts create mode 100644 src/worldgen/regionGenerator.ts create mode 100644 tests/missingMaps.test.ts create mode 100644 tests/regionGenerator.test.ts diff --git a/README.md b/README.md index 50c66362..a51c302a 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,7 @@ Organise your world into multiple named hex maps, each stored as a subfolder und - **Name** — change the name shown everywhere. Nothing moves on disk. The name is stored as `display-name:` in the map note. - **Folder name** — rename the folder itself; its hex notes and map note move with it and links to the map are updated. - **Delete** — removes the map and moves all its hex notes to the trash. +- **Missing maps** — if a map's folder and map note are deleted by hand (outside the plugin), the map is not quietly re-created empty. It shows in the list with a ⚠ and two buttons, and opening it shows the same: **Restore** writes its map note back from the last saved copy (the plugin keeps one in its folder, `map-cache/`, every time it saves a map note), so its hexes, paths and settings come back exactly; **Remove** drops it from the list (no files are deleted). A note put back by hand (or by sync) loads again on its own. - **Weather and rumours** — the tables the hex editor rolls for Weather and Hooks & Rumors on this map (stored in the map note as `weather-table` and `rumors-table`). - **Terrain theme** — assign a terrain type to a map. The swatch appears next to the map name in the switch list and sets the colour of the submap center dot when this map is linked as a submap from a parent map. - **Back** (`← Back` button) — returns to the previously active map after following a submap link. @@ -140,6 +141,10 @@ Which biome a hex is comes from its terrain's **Type**, never its name: forest-t **Your own biomes.** Every biome is a plain note in the biomes folder (default `{world folder}/biomes`, see Settings). The built-in ones are written there once when the plugin starts, so you can edit them like any other note; delete one and it stays deleted. A biome note has a name, a colour, a **Mix** table of terrain *types* with weights (never terrain names, so it works on any palette with types), a **Transitions** table (biomes it shouldn't touch and the biome put between them), and in its frontmatter `blend` (narrow, normal or wide), `land-share` and `min-islands` (for watery biomes) and an optional `generator: [[…]]` link. Rows that can't be read are reported and left as you wrote them; your own text in the note is kept. On an overworld's **Biomes** view, **Biomes…** lists them: **Add biome…** opens a form (pick **Blend (built-in mixing)** or one of your generators, name, colour, type weights, blend, land share, fewest islands, transitions) with a live preview of one region, and **Save** writes the note. **Edit…** opens the same form for an existing biome (built-in ones also have **Restore default**, which backs up the old note first). **Edit generator…** (also in **Edit region…**) opens the biome's generator, or its note for now. Biomes linked to a generator say "available once generator regions land" and blend until then. Your biomes appear in the biome picker and make regions with the blend field straight away. Adding and editing biomes needs Build or God. A region keeps its biome when you rename the biome's note; if you delete the note, the region keeps its terrain and **Edit region…** shows "Unknown biome". Inside a region, click the middle of the hex flower to open **Edit region…** for it; the overworld's right-click menu has **Create token here** to mark the party. +**Terrain weights.** A biome's Mix is by terrain type; an optional **Terrain weights** table (`| Terrain | Weight |`) says how one type's share is split between its terrains, so different forests can go together in different ratios: `Pine forest | 3` and `Oak forest | 1` make three pine hexes for every oak. Terrains not listed count 1, and 0 leaves one out. Names are matched ignoring case; rows that can't be read are reported. + +**Make a generator from a region.** Edit a region by hand, then **Edit region… → Make generator…** (or right-click the map in **Maps** → **Make generator from …**). It learns how the region's terrain fits together and asks: **New generator** (a name) or **Overwrite existing**, from a list with the most fitting first: the generator of the region's own biome, then its parent biomes', then generators learned from this region, then related biomes' (neighbours it was blended with, similar biomes), then the rest. Overwriting saves the old generator as a plain note in the plugin folder's `backups/` first, and biomes that use it keep using it. A new generator gets its own biome that starts as a copy of the region's biome: climate, land share, fewest islands, transitions, shore, blend, colour and mix, with `parent:` naming the biome it came from and Terrain weights taken from the region. Edit it like any biome note. + **Biome climates.** A biome note can say where generated overworlds put it, with optional plain keys: `temperature` (cold, cool, mild, warm, hot, a range like `cold–mild`, or numbers like `0.2–0.5`), `moisture` (dry, moderate, wet, or numbers), `elevation` (`low`, `mid` for hills, `high` for peaks, `sea`, or `mouth` for the river's mouth), `coastal: yes` (only next to the coast), `chance` (like `50%`: the share of fitting hexes it takes) and `rare: yes` (at most one hex in about 20). With any of them set, World biomes can choose the biome like a built-in one; left blank, the biome is only placed by hand. The built-in biomes carry their climates in their notes too (older built-in notes get them added once), so you can see and change why tundra goes north. Where several biomes fit a hex, the rarer and then the narrower one is tried first. The biome form has the same fields in a folded **Climate (optional, for generated overworlds)** section. Values the plugin can't read are reported and ignored. **Generate overworld (first pass).** **New overworld…** lays out the biomes of a **biome pool**: a plain note in the biome pools folder (default `{world folder}/biome-pools`) with a `Biome | Weight | Notes` table linking biome notes. **All biomes** (every built-in) is written there once. In the form, pick a pool and add or remove biomes (built-in, your own, or ones made by a generator), set a weight (1 as its note says, 0.5 half as often, 2 twice, 0 never), and **Save** or **Save as…** a new pool; the preview updates as you go. Climate, land, which way is colder, water and seed are the World biomes settings. A biome in the pool without a climate is only placed where no other biome in the pool fits. **Create** makes the map (it remembers its pool as `biome-pool: "[[…]]"`) and every region with its biome; a biome whose terrain doesn't tell it apart (one of yours) is kept in the overworld's optional **Biome** column. It's only a first pass: edit, reroll or swap any region afterwards. To redo the whole map, open the map menu → **Regions** → **Generate overworld…** (God only): locked hexes keep their terrain and their regions are left alone, every other region is remade in place (its name, notes and locked hexes stay), and missing regions are made. @@ -346,6 +351,7 @@ Open **Settings → Hexmap World Creator** to configure: | **Biome pools folder** | Folder holding the biome pool notes used by Generate overworld (default `{world folder}/biome-pools`). | | **World types folder** | Folder holding the world types tables used by the space generators (default `{world folder}/world-types`). | | **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | +| **Add default palettes** | Shown when Expanded or Limited isn't in the list: puts them back. Palettes you delete (in settings or by deleting their notes) stay deleted; an empty palette list stays empty until you add one. | | **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | diff --git a/dev/smoke/lib/page.mjs b/dev/smoke/lib/page.mjs index b491dfad..1729af42 100644 --- a/dev/smoke/lib/page.mjs +++ b/dev/smoke/lib/page.mjs @@ -76,6 +76,7 @@ export function state(id) { paths: p.mapStore.paths(m.name)?.length ?? 0, hexes: p.mapStore.all(m.name).size, broken: !!p.mapStore.broken?.has?.(m.name), + missing: !!p.mapStore.isMissing?.(m.name), noteExists: !!app.vault.getAbstractFileByPath(p.mapStore.notePath(m.name)), notePath: p.mapStore.notePath(m.name), space: !!p.isSpaceMap?.(m.name), @@ -144,6 +145,8 @@ export async function openMap(id, name, timeoutMs) { const root = v?.containerEl; hexes = root ? root.querySelectorAll(".duckmage-hex[data-x]").length : 0; const canvas = root ? root.querySelectorAll("canvas").length : 0; + // A missing map (SM-DEL) shows its empty state instead of a grid. + if (v?.activeMapName === name && root?.querySelector(".duckmage-map-missing-state")) break; if (v?.activeMapName === name && (hexes > 0 || canvas > 0)) { if (hexes === last) stable++; else stable = 0; if (stable >= 3) break; @@ -160,6 +163,7 @@ export async function openMap(id, name, timeoutMs) { expected: m ? m.gridSize.cols * m.gridSize.rows : null, canvas: v?.containerEl?.querySelectorAll("canvas").length ?? 0, workModeBtn: !!v?.containerEl?.querySelector(".duckmage-work-mode-btn"), + missingState: !!v?.containerEl?.querySelector(".duckmage-map-missing-state"), }; } diff --git a/dev/smoke/run.mjs b/dev/smoke/run.mjs index 879a3c7d..d8e91d70 100644 --- a/dev/smoke/run.mjs +++ b/dev/smoke/run.mjs @@ -218,6 +218,8 @@ async function runSetup(setup) { firstOpen ??= r; opens.push({ map: m.name, ...r }); if (r.active !== m.name) probs.push(`${m.name}: view shows ${r.active}`); + // Deleted by hand (SM-DEL): the view shows the missing empty state. + else if (m.missing) { if (!r.missingState) probs.push(`${m.name}: missing, but no missing-map state shown`); } else if (m.broken) probs.push(`${m.name}: map note unreadable`); else if (r.hexes === 0 && r.canvas === 0) probs.push(`${m.name}: nothing rendered`); else if (!m.overworld && r.hexes !== r.expected) probs.push(`${m.name}: ${r.hexes} hexes, expected ${r.expected}`); diff --git a/dev/smoke/setups.mjs b/dev/smoke/setups.mjs index 6e56f24f..3f16cdae 100644 --- a/dev/smoke/setups.mjs +++ b/dev/smoke/setups.mjs @@ -392,11 +392,28 @@ async function deletedExtra(ctx) { const errLoop = ctx.log.length; await new Promise((r) => setTimeout(r, 8000)); const grew = ctx.log.length - errLoop; - return [ - // Recorded, not judged (owner call, see open-work): what the plugin does with maps whose folder and note are gone. - { check: "F8-loads", ok: true, detail: `maps: ${st.maps.map((m) => `${m.name} (${!m.noteExists ? "no note" : ctx.snap0[m.notePath] ? "note kept" : "note re-created, " + m.hexes + " hexes"})`).join(", ")}; palettes: ${st.palettes.join(", ") || "(none)"}; path types: ${st.pathTypes}` }, + const gone = st.maps.filter((m) => m.name.startsWith("gone-")); + // Owner call SM-DEL: maps whose folder and note are gone are marked missing, never re-created; + // an emptied palette list stays empty (no automatic defaults). + const out = [ + { check: "F8-missing", ok: gone.length === 2 && gone.every((m) => m.missing && !m.noteExists), detail: `maps: ${st.maps.map((m) => `${m.name} (${m.missing ? "missing" : !m.noteExists ? "no note" : ctx.snap0[m.notePath] ? "note kept" : "note re-created, " + m.hexes + " hexes"})`).join(", ")}` }, + { check: "F8-no-refill", ok: st.palettes.length === 0, detail: `palettes: ${st.palettes.join(", ") || "(none)"}; path types: ${st.pathTypes}` }, { check: "F8-no-loop", ok: grew === 0, detail: `console errors/warnings added in 8 s idle: ${grew}; notices: ${notices.join(" | ") || "(none)"}` }, ]; + // Restore one from its cached note: hexes and the path come back exactly; Remove the other. + const r = await ctx.ev((id) => (async () => { + const p = window.app.plugins.plugins[id]; + const ok = await p.restoreMissingMap("gone-one"); + await p.mapStore.flush(); + const hexes = [...p.mapStore.all("gone-one")].map(([k, h]) => `${k}=${h.terrain}`).sort(); + const paths = p.mapStore.paths("gone-one").map((x) => `${x.name}:${x.branches[0]?.anchors.join(">")}`); + const note = !!window.app.vault.getAbstractFileByPath(p.mapStore.notePath("gone-one")); + await p.removeMapEntry("gone-two"); + return { ok, hexes, paths, note, missing: p.mapStore.isMissing("gone-one"), maps: p.settings.maps.map((m) => m.name) }; + })(), ctx.pluginId); + out.push({ check: "F8-restore", ok: r.ok && r.note && !r.missing && r.hexes.length === 3 && r.paths.length === 1 && r.paths[0].startsWith("Old road:0_1>4_3"), detail: `restored gone-one: note ${r.note}, hexes ${r.hexes.join(" ")}, paths ${r.paths.join(" ")}` }); + out.push({ check: "F8-remove", ok: !r.maps.includes("gone-two"), detail: `maps now: ${r.maps.join(", ")}` }); + return out; } async function manyMapsExtra(ctx) { diff --git a/package.json b/package.json index c1768281..6689d5f4 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index a03f4c08..23c477a4 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -35,7 +35,7 @@ import { SetupWizardView } from "./SetupWizardView"; import { BiomeStore } from "./overworld/BiomeStore"; import { WorldTypeStore } from "./space/WorldTypeStore"; import { WorldTypesModal } from "./space/WorldTypesModal"; -import { PaletteStore } from "./palettes/PaletteStore"; +import { PaletteStore, fillPalettePathTypes, clonePalette, missingDefaults, palettesOnLoad } from "./palettes/PaletteStore"; import { PathsService } from "./paths/PathsService"; import { RoutePins } from "./paths/routePins"; import { setPathEditMapLookup } from "./paths/editGate"; @@ -207,11 +207,13 @@ export default class HexmakerPlugin extends Plugin { this.paletteStore.onModify(f); this.biomeStore.onModify(f); this.worldTypeStore.onModify(f); + this.mapStore.onCreate(f); }), ); this.registerEvent( this.app.vault.on("delete", (f) => { if (isIconFile(f.path)) this.loadAvailableIcons(); + this.mapStore.onDelete(f); this.paletteStore.onDelete(f); this.biomeStore.onDelete(f); this.worldTypeStore.onDelete(f); @@ -773,18 +775,10 @@ export default class HexmakerPlugin extends Plugin { // of maps whose note does, so the fresh map objects take the store's at // once. Missing paths mean "not loaded", never "no paths". this.mapStore.adoptAll(); - // Ensure terrainPalettes is valid - if ( - !Array.isArray(this.settings.terrainPalettes) || - this.settings.terrainPalettes.length === 0 - ) { - this.settings.terrainPalettes = DEFAULT_SETTINGS.terrainPalettes.map( - (p) => ({ - name: p.name, - terrains: p.terrains.map((t) => ({ ...t })), - }), - ); - } + // Ensure terrainPalettes is valid. An empty list is the user's (every + // palette deleted, SM-DEL): it stays empty; "Add default palettes" in + // settings puts the defaults back on request. + this.settings.terrainPalettes = palettesOnLoad(this.settings.terrainPalettes, DEFAULT_SETTINGS.terrainPalettes); // PA5: path types saved before every behaviour was an explicit option get // them filled in from the old name rules (once), so no map changes look. // Notes are migrated by PaletteStore on attach. @@ -2168,6 +2162,49 @@ export default class HexmakerPlugin extends Plugin { * Create hex notes for every (x, y) in the cartesian product of xs × ys, * skipping any that already exist on disk. Returns the number of notes created. */ + /** + * Restore a missing map (SM-DEL): its note is written back from the last + * saved copy (see MapStore.restoreMissing). Says what it did. + */ + async restoreMissingMap(name: string): Promise { + const r = await this.mapStore.restoreMissing(name); + if ("error" in r) { + new Notice(r.error); + return false; + } + const how = r.source === "settings" ? " from its settings (no saved copy of its hexes was found)" : r.source === "note" ? " (its note was back)" : ""; + new Notice(`Restored map "${this.mapLabel(name)}"${how}.`); + this.refreshHexMap(); + return true; + } + + /** + * Remove a map from the map list without touching files (a missing map's + * folder is already gone). Links to it in other maps are dropped and its + * regions and locations become top-level maps, as when deleting a map. + */ + async removeMapEntry(name: string): Promise { + this.settings.maps = this.settings.maps.filter((m) => m.name !== name); + if (this.settings.defaultMap === name) this.settings.defaultMap = this.settings.maps[0]?.name ?? ""; + this.mapStore.forgetMap(name); + this.undoBook.forgetMap(name); + for (const m of this.settings.maps) { + for (const [key, h] of [...this.mapStore.all(m.name)]) { + const patch = removeMapPatch(h, name); + if (Object.keys(patch).length) this.mapStore.set(m.name, key, patch); + } + if (m.parent?.map === name) { + delete m.parent; + delete m.submapKind; + } + } + for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_HEX_MAP)) { + if (leaf.view instanceof HexMapView && leaf.view.activeMapName === name) leaf.view.activeMapName = this.settings.maps[0]?.name ?? ""; + } + await this.saveSettings(); + this.refreshHexMap(); + } + async createNewMap( rawName: string, cols: number, @@ -2587,6 +2624,29 @@ export default class HexmakerPlugin extends Plugin { await this.saveSettings(); } + /** The built-in default palettes (a fresh install's) that aren't in the palette list. */ + missingDefaultPalettes(): string[] { + return missingDefaults(this.settings.terrainPalettes, DEFAULT_SETTINGS.terrainPalettes).map((p) => p.name); + } + + /** + * Put back the default palettes that aren't there (only ever on request: + * palettes the user deleted stay deleted). Returns the names added. + */ + async addDefaultPalettes(): Promise { + const add = this.missingDefaultPalettes(); + for (const p of missingDefaults(this.settings.terrainPalettes, DEFAULT_SETTINGS.terrainPalettes)) { + this.settings.terrainPalettes.push(clonePalette(p)); + } + if (!add.length) return add; + // Same as a fresh install's: path types from the shipped list. + fillPalettePathTypes(this.settings.terrainPalettes, this.settings.pathTypes); + await this.saveSettings(); + await this.ensureTablesForNewTerrains(); + new Notice(`Added ${add.join(" and ")}.`); + return add; + } + /** Install `name` from the presets if no palette by that name exists yet. */ async ensurePaletteInstalled(name: string): Promise { if (this.getPaletteByName(name) || !getPreset(name)) return; diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index b8f7320b..dbe78d67 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -110,6 +110,9 @@ type LocalSettingDefinitionItem = const TEMPLATES_FOLDER_DESC = "Vault-relative folder for the plugin's note templates: the hex template (unless Template path points elsewhere) and the town template. Edit them there; new notes use them. Blank = \"templates\" in the world folder. Workflow templates stay with their workflows."; +/** "Add default palettes" (both settings paths): deleted palettes stay deleted until asked. */ +const ADD_DEFAULTS_DESC = "Put the built-in palettes back. Palettes you delete stay deleted; they only come back from here."; + /** The "Palette for new maps" setting's description (both settings paths). */ const DEFAULT_PALETTE_DESC = "The palette a new map starts on. First palette = the first one listed below (overland before space)."; @@ -724,6 +727,18 @@ export class HexmakerSettingTab extends PluginSettingTab { defaultValue: "", }, }, + { + name: "Add default palettes", + desc: ADD_DEFAULTS_DESC, + visible: () => this.plugin.missingDefaultPalettes().length > 0, + render: (setting: Setting) => { + setting.addButton((b) => + b.setButtonText(`Add ${this.plugin.missingDefaultPalettes().join(" and ")}`).onClick(() => { + void this.plugin.addDefaultPalettes().then(() => this.requestDeclarativeRerender()); + }), + ); + }, + }, ], }, { @@ -1658,6 +1673,18 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); + const missingDefaults = this.plugin.missingDefaultPalettes(); + if (missingDefaults.length) { + new Setting(containerEl) + .setName("Add default palettes") + .setDesc(ADD_DEFAULTS_DESC) + .addButton((b) => + b.setButtonText(`Add ${missingDefaults.join(" and ")}`).onClick(() => { + void this.plugin.addDefaultPalettes().then(() => this.display()); + }), + ); + } + const palettes = this.plugin.settings.terrainPalettes; const renderPaletteList = () => { diff --git a/src/hex-map/EditRegionModal.ts b/src/hex-map/EditRegionModal.ts index a0cc6a81..ef991220 100644 --- a/src/hex-map/EditRegionModal.ts +++ b/src/hex-map/EditRegionModal.ts @@ -25,6 +25,7 @@ import { flowerPetals } from "../maps/mapNav"; import { biomeInfo, type BiomeId } from "../overworld/biomes"; import { hexBiomeAt, overworldOf, regenerateRegion, regionBiomeStatus, setBiomeAt } from "../overworld/regionsVault"; import { openBiomeGenerator } from "./BiomeLibraryModal"; +import { openMakeGenerator } from "./MakeGeneratorModal"; import { editRegionPlan, terrainCountsText } from "../overworld/overworldInput"; import { mayReshape, paintableBiomes, RegionGenModal, reshapeUndoable, type BiomeHost } from "./BiomeModals"; import { openNoteFocused } from "../openNote"; @@ -127,10 +128,16 @@ export class EditRegionModal extends HexmakerModal { biomeSec.createEl("p", { cls: "duckmage-locked-hint", text: `Unknown biome: ${status.unknown} (its note is gone). The region keeps its terrain.` }); } const editGenerator = (row: HTMLElement) => { - if (!current) return; - row.createEl("button", { text: "Edit generator…", attr: { title: "Tune how this biome's regions are made" } }).addEventListener("click", () => { + if (current) { + row.createEl("button", { text: "Edit generator…", attr: { title: "Tune how this biome's regions are made" } }).addEventListener("click", () => { + this.close(); + void openBiomeGenerator(plugin, current); + }); + } + // PR1: learn a generator from this region as painted (new, or over an existing one). + row.createEl("button", { text: "Make generator…", attr: { title: "Learn a generator from this region's terrain; its biome starts as a copy of this one" } }).addEventListener("click", () => { this.close(); - void openBiomeGenerator(plugin, current); + openMakeGenerator(plugin.app, plugin, name); }); }; const biomes = paintableBiomes(plugin, this.overworld); diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 90039b45..ae9c2809 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -28,7 +28,7 @@ import { VIEW_TYPE_HEX_TABLE, VIEW_TYPE_RANDOM_TABLES, } from "../constants"; -import { MapModal } from "./MapModal"; +import { MapModal, renderMissingActions } from "./MapModal"; import { mapAncestors } from "./submapNav"; import { ancestorNeighbourCrumbs, neighbourCrumbs } from "../maps/mapTree"; import { toolModeLabel } from "./toolMode"; @@ -394,6 +394,22 @@ export class HexMapView extends ItemView { return `Hex map — ${this.plugin.mapLabel(this.activeMapName)}`; } + private missingEl: HTMLElement | null = null; + + /** Show (true) or clear (false) the missing-map empty state for the open map. */ + private renderMissingState(): boolean { + this.missingEl?.remove(); + this.missingEl = null; + const name = this.activeMapName; + if (!this.plugin.mapStore.isMissing(name) || !this.controlsEl) return false; + const box = this.controlsEl.createDiv({ cls: "duckmage-map-missing-state" }); + this.missingEl = box; + box.createEl("h3", { text: `${this.plugin.mapLabel(name)} is missing` }); + box.createEl("p", { text: `Its folder and map note (${this.plugin.mapStore.notePath(name)}) were deleted. Restore writes the note back from the last saved copy; Remove drops the map from the list. No file is deleted.` }); + renderMissingActions(box, this.plugin, name, () => this.renderGrid()); + return true; + } + private getActiveMap(): MapData { return this.plugin.getOrCreateMap(this.activeMapName); } @@ -4029,6 +4045,9 @@ export class HexMapView extends ItemView { if (!this.viewportEl) return; this.factionTooltipEl?.hide(); this.viewportEl.empty(); + // A map whose note was deleted by hand (SM-DEL): a clear empty state + // with Restore / Remove instead of an empty grid. + if (this.renderMissingState()) return; const gap = this.plugin.settings.hexGap?.trim() || "0.15"; this.viewportEl.style.setProperty( diff --git a/src/hex-map/MakeGeneratorModal.ts b/src/hex-map/MakeGeneratorModal.ts new file mode 100644 index 00000000..538c2a20 --- /dev/null +++ b/src/hex-map/MakeGeneratorModal.ts @@ -0,0 +1,145 @@ +/** + * "Make generator from this region…" (PR1): new generator (a name) or + * overwrite an existing one, picked from a list with the most fitting + * first (the region's own biome's generator, its parent biomes', ones + * learned from this region, related biomes'). Opened from Edit region and + * from a map's right-click menu in the Maps window. See + * src/worldgen/regionGenerator.ts. + */ + +import { App, Notice } from "obsidian"; +import { HexmakerModal } from "../HexmakerModal"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { makeRegionGenerator, overwriteTargets, type OverwriteCandidate } from "../worldgen/regionGenerator"; +import { hasFeature } from "../featureLevel"; +import { withFeature } from "../advancedHints"; +import { slugify } from "../utils"; + +/** Open the dialog (an Advanced feature: in Simple, offers to turn Generators on first). */ +export function openMakeGenerator(app: App, plugin: HexmakerPlugin, mapName: string): void { + if (!hasFeature(plugin.settings, "generators")) { + withFeature(plugin, "generators", () => openMakeGenerator(app, plugin, mapName)); + return; + } + new MakeGeneratorModal(app, plugin, mapName).open(); +} + +export class MakeGeneratorModal extends HexmakerModal { + private mode: "new" | "overwrite" = "new"; + private name = ""; + private picked: string | null = null; + + constructor(app: App, private plugin: HexmakerPlugin, private mapName: string) { + super(app); + } + + onOpen(): void { + this.makeDraggable(); + this.modalEl.addClass("duckmage-make-generator-modal"); + this.titleEl.setText(`Make generator from ${this.plugin.mapLabel(this.mapName)}`); + this.name = this.plugin.mapLabel(this.mapName); + void this.render(); + } + + private async render(): Promise { + const { contentEl, plugin } = this; + contentEl.empty(); + const { candidates, biome } = await overwriteTargets(plugin, this.mapName); + contentEl.createEl("p", { + cls: "setting-item-description", + text: `Learns how this map's terrain fits together.` + + (biome ? ` A new generator gets its own biome that starts as a copy of ${biome.label} (climate, islands, transitions, shore, mix).` : ""), + }); + + const choice = contentEl.createDiv({ cls: "duckmage-make-generator-choice" }); + const radio = (value: "new" | "overwrite", label: string): HTMLInputElement => { + const row = choice.createEl("label", { cls: "duckmage-make-generator-option" }); + const input = row.createEl("input", { type: "radio", attr: { name: "duckmage-make-generator", value } }); + input.checked = this.mode === value; + row.createSpan({ text: label }); + input.addEventListener("change", () => { + if (!input.checked) return; + this.mode = value; + void this.render(); + }); + return input; + }; + + radio("new", "New generator"); + if (this.mode === "new") { + const nameInput = choice.createEl("input", { + type: "text", + cls: "duckmage-make-generator-name", + value: this.name, + attr: { "aria-label": "Generator name", placeholder: "Name" }, + }); + nameInput.addEventListener("input", () => { this.name = nameInput.value; }); + window.setTimeout(() => nameInput.focus(), 0); + } + + const over = radio("overwrite", "Overwrite existing"); + over.disabled = !candidates.length; + if (!candidates.length) choice.createEl("p", { cls: "setting-item-description", text: "No generators yet." }); + if (this.mode === "overwrite" && candidates.length) { + if (!this.picked || !candidates.some((c) => c.path === this.picked)) this.picked = candidates[0].path; + this.renderList(choice, candidates); + choice.createEl("p", { cls: "setting-item-description", text: "The old generator is backed up first. Biomes that use it keep using it." }); + } + + const buttons = contentEl.createDiv({ cls: "duckmage-token-modal-buttons" }); + const go = buttons.createEl("button", { text: this.mode === "new" ? "Make generator" : "Overwrite", cls: this.mode === "new" ? "mod-cta" : "mod-warning" }); + go.addEventListener("click", () => void this.make(go)); + buttons.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); + } + + private renderList(el: HTMLElement, candidates: OverwriteCandidate[]): void { + const list = el.createDiv({ cls: "duckmage-make-generator-list", attr: { role: "listbox", "aria-label": "Generator to overwrite" } }); + for (const c of candidates) { + const row = list.createDiv({ + cls: "duckmage-make-generator-row" + (c.path === this.picked ? " is-selected" : "") + (c.reason !== "other" ? " is-suggested" : ""), + attr: { role: "option", tabindex: "0", "aria-selected": String(c.path === this.picked), title: c.path }, + }); + row.createSpan({ cls: "duckmage-make-generator-row-name", text: c.name }); + if (c.why) row.createSpan({ cls: "duckmage-make-generator-row-why", text: c.why }); + const pick = () => { + this.picked = c.path; + for (const r of Array.from(list.children)) { + r.removeClass("is-selected"); + r.setAttr("aria-selected", "false"); + } + row.addClass("is-selected"); + row.setAttr("aria-selected", "true"); + }; + row.addEventListener("click", pick); + row.addEventListener("keydown", (e: KeyboardEvent) => { + if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } + }); + } + } + + private async make(btn: HTMLButtonElement): Promise { + const { plugin } = this; + if (this.mode === "new" && !slugify(this.name)) { + new Notice("Enter a generator name."); + return; + } + if (this.mode === "overwrite" && !this.picked) return; + btn.disabled = true; + const res = await makeRegionGenerator(plugin, this.mapName, this.mode === "new" ? { kind: "new", name: this.name } : { kind: "overwrite", path: this.picked! }); + if ("error" in res) { + new Notice(res.error); + btn.disabled = false; + return; + } + const parts = [`${this.mode === "new" ? "Made" : "Overwrote"} generator "${res.file.basename}" from ${plugin.mapLabel(this.mapName)}`]; + if (res.backup) parts.push(`the old one is in ${res.backup}`); + if (res.biome) parts.push(`new biome "${res.biome}" uses it`); + new Notice(parts.join("; ") + ".", 8000); + this.close(); + await plugin.openTerrainGenerator({ mapName: this.mapName, generatorPath: res.file.path, paletteName: plugin.getMap(this.mapName)?.paletteName }); + } + + onClose(): void { + this.contentEl.empty(); + } +} diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 12900170..5e2ed0f5 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -8,7 +8,6 @@ import { renderMapExportForm } from "../export/MapExportModal"; import { FileLinkSuggestModal } from "./FileLinkSuggestModal"; import { listGenerators, - saveGeneratorFromMap, generatorsForRegion, type GeneratorFile, } from "../worldgen/generators"; @@ -23,6 +22,7 @@ import { hasFeature } from "../featureLevel"; import { renderAdvancedHint, withFeature } from "../advancedHints"; import { regionsOf, removeMapPatch } from "../maps/submaps"; import { RegionSettingsModal } from "./newChildMap"; +import { openMakeGenerator } from "./MakeGeneratorModal"; import { GenerateRegionsModal, NewOverworldModal } from "./OverworldModals"; import { REGENERATE_LOCKED_HINT } from "../overworld/overworldGen"; import { canReshape, lockedHint } from "../workMode"; @@ -36,6 +36,37 @@ import { ROLLED_SECTION_TABLES, mapSectionTable, starterTablePath } from "../reg type ModalTab = "Maps" | "Properties" | "Regions" | "Export"; +/** + * Restore / Remove for a missing map (SM-DEL), in the map list and on the + * map view's empty state. Remove asks once more (a second click) before it + * drops the map from the list; no file is touched either way. + */ +export function renderMissingActions(el: HTMLElement, plugin: HexmakerPlugin, name: string, done: () => void): void { + const box = el.createSpan({ cls: "duckmage-map-missing-actions" }); + const restore = box.createEl("button", { text: "Restore", cls: "mod-cta", attr: { title: "Write its map note back from the last saved copy" } }); + restore.addEventListener("click", (e) => { + e.stopPropagation(); + restore.disabled = true; + void plugin.restoreMissingMap(name).then(done); + }); + const remove = box.createEl("button", { text: "Remove", attr: { title: "Drop it from the map list (no files are deleted)" } }); + let armed = false; + remove.addEventListener("click", (e) => { + e.stopPropagation(); + if (!armed) { + armed = true; + remove.setText("Remove from list?"); + remove.addClass("mod-warning"); + return; + } + remove.disabled = true; + void plugin.removeMapEntry(name).then(() => { + new Notice(`Removed "${plugin.mapLabel(name)}" from the map list.`); + done(); + }); + }); +} + export class MapModal extends HexmakerModal { private confirmingDelete: string | null = null; private stopKeepInViewport?: () => void; @@ -328,11 +359,15 @@ export class MapModal extends HexmakerModal { .onClick(() => void this.openGenerator(map.name, existing)), ); } + // New, or over an existing one (the region's biome's and its parents' first), PR1. menu.addItem((item) => item - .setTitle(existing ? `Learn a new generator from ${this.plugin.mapLabel(map.name)}` : `Create generator from ${this.plugin.mapLabel(map.name)}`) + .setTitle(`Make generator from ${this.plugin.mapLabel(map.name)}…`) .setIcon(existing ? "plus" : "wand-sparkles") - .onClick(() => void this.createGeneratorFrom(map.name)), + .onClick(() => { + this.close(); + openMakeGenerator(this.app, this.plugin, map.name); + }), ); menu.showAtPosition(at); }); @@ -347,6 +382,12 @@ export class MapModal extends HexmakerModal { swatch.addClass("duckmage-map-terrain-swatch--set"); } + const missing = this.plugin.mapStore.isMissing(map.name); + if (missing) { + row.addClass("is-missing"); + const warn = row.createSpan({ cls: "duckmage-map-missing-icon", attr: { "aria-label": "Missing: its folder and map note were deleted", title: "Missing: its folder and map note were deleted" } }); + setIcon(warn, "alert-triangle"); + } const nameSpan = row.createSpan({ text: node.label, cls: "duckmage-map-list-name" }); // The slug is the folder; worth seeing when it differs from the name. if (node.label !== map.name) nameSpan.setAttr("title", `Folder: ${map.name}`); @@ -354,6 +395,13 @@ export class MapModal extends HexmakerModal { this.view.switchMapFromModal(map.name); this.close(); }); + if (missing) { + renderMissingActions(row, this.plugin, map.name, () => { + this.onChanged(); + this.render(); + }); + return; + } // "palette: Expanded" in muted text; a bare "Expanded" read like a fold state (round 6 U10). row.createSpan({ cls: "duckmage-region-palette-badge", text: `palette: ${map.paletteName}`, attr: { title: "Terrain palette" } }); } @@ -745,27 +793,6 @@ export class MapModal extends HexmakerModal { // ── Generator ───────────────────────────────────────────────────────────── - /** Learn a generator from a region and open it in the terrain generator. */ - private async createGeneratorFrom(mapName: string): Promise { - // An Advanced feature: in Simple, offer to turn it on first. - if (!hasFeature(this.plugin.settings, "generators")) { - withFeature(this.plugin, "generators", () => void this.createGeneratorFrom(mapName)); - return; - } - const result = await saveGeneratorFromMap(this.plugin, mapName, mapName); - if ("error" in result) { - new Notice(result.error); - return; - } - new Notice(`Created generator "${result.model.name}" from ${this.plugin.mapLabel(mapName)}.`); - this.close(); - await this.plugin.openTerrainGenerator({ - mapName, - generatorPath: result.file.path, - paletteName: result.model.meta.palette, - }); - } - /** Open a region's existing generator in the terrain generator. */ private async openGenerator(mapName: string, g: GeneratorFile): Promise { this.close(); @@ -784,6 +811,8 @@ export class MapModal extends HexmakerModal { const folderPath = hexFolder ? `${hexFolder}/${name}` : name; const folder = this.app.vault.getAbstractFileByPath(folderPath); if (folder instanceof TFolder) { + // Our own delete: the note going doesn't make the map "missing". + this.plugin.mapStore.expectRemoval(name); try { await this.app.fileManager.trashFile(folder); } catch (e) { diff --git a/src/hex-map/help.md b/src/hex-map/help.md index b35ecec9..c450a410 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -174,8 +174,19 @@ Every new terrain (from the terrain tool, the palette editor, a new palette or a **Templates**: the plugin keeps its note templates in one folder (**Settings → Templates folder**, `templates` in the world folder by default): `hex.md` for hex notes and `town.md` for new towns made from the hex editor. Edit them there and new notes follow. +## Missing maps + +If a map's folder and map note were deleted outside the plugin, the map isn't re-created empty. It shows with a ⚠ in the map list, and opening it shows **Restore** (puts its map note back from the last saved copy: hexes, paths and settings) and **Remove** (drops it from the list; no files are deleted). + +## Make a generator from a region + +**Edit region… → Make generator…** (or right-click a map in **Maps**) learns a generator from the region as you painted it. Choose **New generator** or **Overwrite existing**; the list puts the region's own biome's generator and its parent biomes' first. Overwriting keeps a backup. A new generator gets a biome that copies the region's biome (climate, islands, transitions, shore, mix). + ## Palettes +Deleted palettes stay deleted, the last one too. **Settings → Add default palettes** puts the built-in ones back. + + **Expanded** is the default fantasy palette on new installs (if you used the plugin before, new maps keep starting on your first palette): more terrains (coasts, wetlands, forest and mountain kinds) and it matches the generators. **Limited** has fewer, simpler terrains and is quicker to paint. Pick any palette as the start for new maps in **Settings → Palette for new maps**. Expanded now has **savanna** and **river delta** too (World biomes paints those biomes with them); an Expanded palette you already have gets them once, after a backup, unless it already has terrains of those names. Delete them and they stay deleted. No palette or terrain is special because of its name. What a terrain does comes from its **Type**: water types are impassable to auto-routes, generators place terrain by type, Orbits puts the *moon*-type terrain beside planets and the *jump point* past the last orbit. Rename anything, or build a palette from scratch, and it works the same once its terrains have types. A terrain with no type gets no defaults and generators skip it; **Guess types from names** in the palette editor fills the Type column for you to check. diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index 2f9e41d4..f1839930 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -134,6 +134,17 @@ export class MapStore { private clearedHexes = new Set(); /** While `record` runs: hears each hex's value before its first change. */ private recorder: ((map: string, key: string, before: HexData | undefined) => void) | null = null; + /** + * Maps whose note (and usually folder) was deleted by hand (SM-DEL): never + * re-created behind the user's back. Shown with Restore / Remove. + */ + private missing = new Set(); + /** Maps the plugin itself is deleting: their note going away isn't "missing". */ + private removing = new Set(); + /** Per map: the note text last saved to the map cache (skip same-text writes). */ + private cached = new Map(); + private deleteTimer: number | undefined; + private deleted = new Set(); constructor(private plugin: HexmakerPlugin) {} @@ -149,7 +160,188 @@ export class MapStore { if (map === undefined) return true; const ps = (this.plugin as { paletteStore?: { isReady?: () => boolean } }).paletteStore; if (ps?.isReady && !ps.isReady()) return false; - return !!this.plugin.getMap(map) && !this.broken.has(map) && !this.migrating.has(map); + return !!this.plugin.getMap(map) && !this.broken.has(map) && !this.migrating.has(map) && !this.missing.has(map); + } + + // ── missing maps (SM-DEL) ──────────────────────────────────────────── + + /** The map's note was deleted by hand: it's listed with Restore / Remove and never re-created on its own. */ + isMissing(map: string): boolean { + return this.missing.has(map); + } + + /** Every missing map, in settings order. */ + missingMaps(): string[] { + return this.uniqueMaps().map((m) => m.name).filter((n) => this.missing.has(n)); + } + + /** The plugin is about to delete this map's folder (MapModal's Delete): not "missing". */ + expectRemoval(map: string): void { + this.removing.add(map); + } + + private markMissing(map: string): void { + if (this.missing.has(map)) return; + this.missing.add(map); + this.dirty.delete(map); + console.warn(`Hexmap World Creator: the map note of "${map}" is gone; the map is marked missing (Restore or Remove it in the map list).`); + } + + /** Where the last known copy of each map note is kept (plugin folder, outside the vault's notes). */ + private cacheDir(): string { + return `${this.plugin.manifest.dir}/map-cache`; + } + + cachePath(map: string): string { + return `${this.cacheDir()}/${map.replace(/[\\/:*?"<>|]/g, "_")}.md`; + } + + /** + * Keep a copy of a map note's text (the last one read or written) so a + * note deleted by hand can be restored exactly. Never throws. + */ + private async cacheNote(map: string, text: string): Promise { + if (this.cached.get(map) === text) return; + const adapter = this.plugin.app.vault.adapter as { exists(p: string): Promise; mkdir(p: string): Promise; write(p: string, d: string): Promise; read?(p: string): Promise }; + try { + const path = this.cachePath(map); + if (!this.cached.has(map) && adapter.read && (await adapter.exists(path)) && (await adapter.read(path)) === text) { + this.cached.set(map, text); + return; + } + if (!(await adapter.exists(this.cacheDir()))) await adapter.mkdir(this.cacheDir()); + await adapter.write(path, text); + this.cached.set(map, text); + } catch (e) { + console.error(`Hexmap World Creator: couldn't save the map cache for ${map}`, e); + } + } + + /** The cached copy of a map's note, or null. */ + async readCache(map: string): Promise { + const adapter = this.plugin.app.vault.adapter as { exists(p: string): Promise; read?(p: string): Promise }; + try { + const path = this.cachePath(map); + if (!adapter.read || !(await adapter.exists(path))) return null; + return await adapter.read(path); + } catch { + return null; + } + } + + /** + * No note, and nothing in its folder to migrate, but the map had a note + * before (its cache exists): deleted by hand. A map that never had a note + * (a fresh install's placeholder, a 1.5 map) is migrated as before. + */ + private async wasDeleted(map: MapData): Promise { + const adapter = this.plugin.app.vault.adapter as { exists(p: string): Promise }; + try { + if (!(await adapter.exists(this.cachePath(map.name)))) return false; + } catch { + return false; + } + for (const file of this.hexFiles(map.name)) { + const fm = await this.frontmatterOf(file); + if (fm && HEX_DATA_KEYS.some((k) => k in fm)) return false; + } + return true; + } + + /** + * Re-create a missing map's note from the best copy there is: the data in + * memory (deleted this session), else the cached note text (exact: hexes, + * paths, settings), else its settings alone. Returns where it came from. + */ + restoreMissing(name: string): Promise<{ source: "memory" | "cache" | "settings" | "note" } | { error: string }> { + let out: { source: "memory" | "cache" | "settings" | "note" } | { error: string } = { error: `No map called ${name}.` }; + return this.enqueue(async () => { + const map = this.plugin.getMap(name); + if (!map) return; + const { vault } = this.plugin.app; + const path = this.notePath(name); + if (vault.getAbstractFileByPath(path) instanceof TFile) { + // Put back by hand meanwhile: just load it. + this.missing.delete(name); + const r = await this.loadMap(map); + out = typeof r === "object" ? { error: `The map note ${path} is back but can't be read: ${r.unreadable}` } : { source: "note" }; + return; + } + await this.ensureFolders(this.mapFolder(name)); + if (this.lastKey.has(name)) { + this.missing.delete(name); + await this.writeNote(map); + out = { source: "memory" }; + } else { + const cached = await this.readCache(name); + const r = cached ? readMapNote(cached, this.readOpts(path)) : null; + this.missing.delete(name); + if (cached && r && r.ok) { + this.lastContent.set(path, cached); + await vault.create(path, cached); + await this.loadMap(map); + out = { source: "cache" }; + } else { + await this.writeNote(map); + out = { source: "settings" }; + } + } + this.emit(name); + await this.plugin.saveData(this.plugin.settings); + this.plugin.refreshHexMap(); + }).then(() => out); + } + + private async ensureFolders(folder: string): Promise { + const { vault } = this.plugin.app; + const parts = folder.split("/"); + for (let i = 1; i <= parts.length; i++) { + const p = parts.slice(0, i).join("/"); + if (!vault.getAbstractFileByPath(p)) { + try { await vault.createFolder(p); } catch { /* made meanwhile */ } + } + } + } + + /** A note or folder was deleted: maps whose note went with it are marked missing (after a moment, so the plugin's own deletes settle first). */ + onDelete(file: TAbstractFile): void { + if (!this.ready) return; + const p = file.path; + for (const m of this.uniqueMaps()) { + const note = this.notePath(m.name); + if (note === p || note.startsWith(p + "/")) this.deleted.add(m.name); + } + if (!this.deleted.size) return; + window.clearTimeout(this.deleteTimer); + this.deleteTimer = window.setTimeout(() => void this.enqueue(async () => { + const names = [...this.deleted]; + this.deleted.clear(); + let any = false; + for (const name of names) { + if (this.removing.delete(name)) continue; + if (!this.plugin.getMap(name) || this.plugin.app.vault.getAbstractFileByPath(this.notePath(name)) instanceof TFile) continue; + this.markMissing(name); + any = true; + this.emit(name); + } + if (any) this.plugin.refreshHexMap(); + }), 250); + } + + /** A note appeared: a missing map's note put back (undo in the file explorer, sync) loads. */ + onCreate(file: TAbstractFile): void { + if (!this.ready || !(file instanceof TFile)) return; + const name = this.missingMaps().find((n) => this.notePath(n) === file.path); + if (!name) return; + void this.enqueue(async () => { + const map = this.plugin.getMap(name); + if (!map || !this.missing.has(name)) return; + const r = await this.loadMap(map); + if (r !== "loaded") return; + this.missing.delete(name); + this.emit(name); + this.plugin.refreshHexMap(); + }); } // ── paths ──────────────────────────────────────────────────────────── @@ -573,6 +765,10 @@ export class MapStore { if (this.broken.has(map.name)) continue; const r = await this.loadMap(map); if (typeof r === "object") this.markBroken(map.name, this.notePath(map.name), r.unreadable, r.newer); + // No note (deleted, or not synced in yet): never written from the + // bare data.json copy; it loads when the note arrives (onCreate). + else if (r === "missing") this.markMissing(map.name); + else this.missing.delete(map.name); } this.plugin.refreshHexMap(); }); @@ -582,6 +778,7 @@ export class MapStore { sync(): Promise { if (!this.ready) return this.queue; for (const m of this.uniqueMaps()) { + if (this.missing.has(m.name)) continue; if (this.lastKey.get(m.name) !== mapNoteKey(this.dataFor(m))) this.dirty.add(m.name); // A palette change can change the derived Summary (a terrain no longer // "not in the palette"): rewrite; the write is skipped if the text is the same. @@ -616,7 +813,7 @@ export class MapStore { } private async writeNote(map: MapData): Promise { - if (this.broken.has(map.name)) return; + if (this.broken.has(map.name) || this.missing.has(map.name)) return; const { vault } = this.plugin.app; const path = this.notePath(map.name); const file = vault.getAbstractFileByPath(path); @@ -652,6 +849,7 @@ export class MapStore { this.reported.set(map.name, problemSignature(r.data.problems)); this.lastContent.set(path, next); if (next !== current) await vault.modify(file, next); + await this.cacheNote(map.name, next); this.lastKey.set(map.name, mapNoteKey(data)); this.clearedPaths.delete(map.name); this.clearedHexes.delete(map.name); @@ -666,6 +864,7 @@ export class MapStore { this.lastDerived.set(map.name, JSON.stringify(ctx)); this.lastContent.set(path, content); await vault.create(path, content); + await this.cacheNote(map.name, content); this.lastKey.set(map.name, mapNoteKey(data)); } } @@ -805,6 +1004,7 @@ export class MapStore { this.lastContent.set(file.path, content); if (!r || !r.ok) return { unreadable: r ? r.reason : NO_FRONTMATTER, newer: r && !r.ok ? r.newer : undefined }; this.apply(map, r.data); + await this.cacheNote(map.name, content); if ((r.data.format ?? 1) < MAP_NOTE_FORMAT) this.dirty.add(map.name); else if (r.data.problems?.length) this.toReview.add(map.name); return "loaded"; @@ -851,6 +1051,7 @@ export class MapStore { return; } this.markReadable(map.name); + await this.cacheNote(map.name, content); const data = r.data; const before = new Map(this.hexes.get(map.name) ?? []); this.apply(map, data); @@ -930,6 +1131,8 @@ export class MapStore { const t = this.hexes.get(oldName); if (t) { this.hexes.delete(oldName); this.hexes.set(newName, t); } if (this.broken.delete(oldName)) this.broken.add(newName); + if (this.missing.delete(oldName)) this.missing.add(newName); + this.cached.delete(oldName); for (const m of [this.views, this.routeCaches, this.known] as Map[]) { if (m.has(oldName)) { m.set(newName, m.get(oldName)); m.delete(oldName); } } @@ -950,7 +1153,7 @@ export class MapStore { repairRegionMirrors(skip: string[] = []): number { const maps = this.uniqueMaps(); const fixes = regionMirrorFixes(maps, (m, k) => this.get(m, k), (m) => this.all(m)) - .filter((f) => !skip.includes(f.map) && !this.broken.has(f.map)); + .filter((f) => !skip.includes(f.map) && !this.broken.has(f.map) && !this.missing.has(f.map)); for (const f of fixes) { console.warn(`Hexmap World Creator: fixed a region link: ${f.map} hex ${f.hex}: ${f.reason}.`); this.set(f.map, f.hex, f.patch); @@ -968,6 +1171,9 @@ export class MapStore { this.lastKey.delete(name); this.lastDerived.delete(name); this.dirty.delete(name); + this.missing.delete(name); + this.removing.delete(name); + this.cached.delete(name); } // ── startup + migration ────────────────────────────────────────────── @@ -984,9 +1190,12 @@ export class MapStore { const maps = this.uniqueMaps(); const toMigrate: MapData[] = []; const unreadable: MapData[] = []; + const gone: MapData[] = []; for (const map of maps) { const r = await this.loadMap(map); - if (r === "missing") toMigrate.push(map); + // Deleted by hand (SM-DEL): marked missing, never re-created empty. + if (r === "missing" && (await this.wasDeleted(map))) gone.push(map); + else if (r === "missing") toMigrate.push(map); else if (r !== "loaded") { // A map note that exists but doesn't parse (hand-broken // frontmatter or table) must never be "migrated" over: its hex @@ -997,13 +1206,14 @@ export class MapStore { } } for (const m of toMigrate) this.migrating.add(m.name); + for (const m of gone) this.markMissing(m.name); this.ready = true; if (toMigrate.length) await this.migrate(toMigrate); // Hex notes still carrying map data after a load (an interrupted // cleanup, or notes synced in from an older device) get cleaned now. - await this.cleanHexNotes(maps.filter((m) => !toMigrate.includes(m) && !unreadable.includes(m)), false); + await this.cleanHexNotes(maps.filter((m) => !toMigrate.includes(m) && !unreadable.includes(m) && !gone.includes(m)), false); // Region map cells follow the region maps' own records. - this.repairRegionMirrors(unreadable.map((m) => m.name)); + this.repairRegionMirrors([...unreadable, ...gone].map((m) => m.name)); // Notes in the older format (JSON values) are converted once, after a // backup; unreadable rows in the others are reported. for (const name of [...this.dirty]) { @@ -1013,6 +1223,10 @@ export class MapStore { } await this.review(); this.reportConversions(); + if (gone.length) { + const names = gone.map((m) => (this.plugin as { mapLabel?: (n: string) => string }).mapLabel?.call(this.plugin, m.name) ?? m.name); + new Notice(`Hexmap World Creator: the map note${gone.length === 1 ? " of" : "s of"} ${names.join(", ")} ${gone.length === 1 ? "is" : "are"} gone. ${gone.length === 1 ? "It's" : "They're"} marked missing in the map list: Restore puts the last saved copy back, Remove drops the map.`, 15000); + } this.plugin.refreshHexMap(); }); } diff --git a/src/overworld/biomeNote.ts b/src/overworld/biomeNote.ts index 411429b1..6dff8f9e 100644 --- a/src/overworld/biomeNote.ts +++ b/src/overworld/biomeNote.ts @@ -33,6 +33,12 @@ * - *Mix* is by terrain TYPE (the palette's Type column), never by terrain * name: a region of this biome gets each type in proportion to its weight * (any scale), spread over the palette's terrains of that type. + * - *Terrain weights* (optional, PR1): how one type's share is split among + * the palette's terrains of that type, by name (`| Terrain | Weight |`, + * "Pine forest 3, Oak forest 1"). Terrains not listed count 1; 0 leaves + * one out. Without the table a type's share is split evenly. + * - `parent`: the biome this one was made from ("Make generator from + * this region"); used to list related generators first. * - *Transitions*: biomes this one shouldn't touch on an overworld, and the * biome put between them. Biomes are named by label, id or note name. * - `blend`: narrow, normal or wide (how far the biome mixes into its @@ -72,6 +78,14 @@ export interface BiomeMixRow { minPatches?: number; } +/** One row of the optional Terrain weights table: a palette terrain's weight within its type. */ +export interface BiomeTerrainWeight { + /** Palette terrain name, as written (matched ignoring case). */ + terrain: string; + /** Relative weight within its type, >= 0 (0 = never). */ + weight: number; +} + export interface BiomeTransition { /** The biome this one shouldn't touch (as written: label, id or note name). */ next: string; @@ -105,6 +119,10 @@ export interface BiomeNoteFields { generator?: string; /** Where World biomes may place it (biomeClimate.ts); unset = only by hand. */ climate?: BiomeClimate; + /** Per-terrain weights within a type (the optional Terrain weights table). */ + terrainWeights?: BiomeTerrainWeight[]; + /** The biome this one was made from (label, id or note name). */ + parent?: string; } export interface BiomeNoteProblem { @@ -132,7 +150,7 @@ export function biomeFileName(label: string): string { export const BIOME_HELP = [ "> [!info] Biome", - "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale; an optional *Min patches* column asks for at least that many separate patches of the type). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `shore: yes` puts a region's land on the side of its land neighbours and its water on the other; `generator` links a generator note. For generated overworlds (optional): `temperature` (cold, cool, mild, warm, hot, or 0.2–0.5), `moisture` (dry, moderate, wet), `elevation` (sea, low, mid, high, mouth), `coastal: yes`, `chance` (like 50%) and `rare: yes`; without them the biome is only placed by hand. Delete a row to drop it.", + "> A biome for overworld regions. **Mix**: how much of each terrain *type* its regions get (weights, any scale; an optional *Min patches* column asks for at least that many separate patches of the type). **Terrain weights** (optional): how a type's share is split between its terrains, like Pine forest 3 and Oak forest 1 (terrains not listed count 1). **Transitions**: biomes it shouldn't touch, and the biome put between. In the frontmatter, `blend` is narrow, normal or wide; `land-share` (like `60%`) and `min-islands` are for watery biomes; `shore: yes` puts a region's land on the side of its land neighbours and its water on the other; `generator` links a generator note. For generated overworlds (optional): `temperature` (cold, cool, mild, warm, hot, or 0.2–0.5), `moisture` (dry, moderate, wet), `elevation` (sea, low, mid, high, mouth), `coastal: yes`, `chance` (like 50%) and `rare: yes`; without them the biome is only placed by hand. Delete a row to drop it.", ]; // ── reading ────────────────────────────────────────────────────────────── @@ -172,6 +190,7 @@ function findTable(lines: string[], want: (headers: string[]) => boolean): Span } const isMix = (h: string[]) => h.includes("type") && (h.includes("weight") || h.includes("share")); +const isTerrainWeights = (h: string[]) => h.includes("terrain") && !h.includes("type") && (h.includes("weight") || h.includes("share")); const isTransitions = (h: string[]) => (h.includes("next to") || h.includes("biome")) && (h.includes("put between") || h.includes("between") || h.includes("transition")); /** The frontmatter span (line indices: the opening and closing `---`), or null. */ @@ -273,6 +292,8 @@ export function parseBiomeNote(content: string, basename: string): ParsedBiomeNo } const gen = fm.get("generator"); if (gen && linkTarget(gen)) fields.generator = linkTarget(gen); + const parent = fm.get("parent"); + if (parent && linkTarget(parent)) fields.parent = linkTarget(parent); const shore = fm.get("shore"); if (shore) { const v = readYesNo(shore); @@ -311,6 +332,24 @@ export function parseBiomeNote(content: string, basename: string): ParsedBiomeNo } else fields.mix.push(minPatches !== undefined ? { type, weight: w, minPatches } : { type, weight: w }); } } + const tw = findTable(lines, isTerrainWeights); + if (tw) { + const ni = tw.headers.indexOf("terrain"); + const wi = tw.headers.includes("weight") ? tw.headers.indexOf("weight") : tw.headers.indexOf("share"); + const rows: BiomeTerrainWeight[] = []; + for (let i = tw.start + 2; i < tw.end; i++) { + const cells = splitRow(lines[i]); + if (cells.every((c) => c === "")) continue; + const terrain = linkTarget(cells[ni] ?? ""); + const w = num(cells[wi] ?? ""); + if (!terrain) { problems.push({ where: "Terrain weights", text: `row ${i + 1}: no terrain` }); continue; } + if (!Number.isFinite(w) || w < 0) { problems.push({ where: "Terrain weights", text: `row ${i + 1}: weight "${cells[wi] ?? ""}" isn't a number` }); continue; } + const hit = rows.find((r) => r.terrain.toLowerCase() === terrain.toLowerCase()); + if (hit) hit.weight += w; + else rows.push({ terrain, weight: w }); + } + if (rows.length) fields.terrainWeights = rows; + } const tr = findTable(lines, isTransitions); if (tr) { const ni = tr.headers.includes("next to") ? tr.headers.indexOf("next to") : tr.headers.indexOf("biome"); @@ -346,6 +385,10 @@ function mixTable(rows: BiomeMixRow[]): string[] { ]; } +function terrainWeightsTable(rows: BiomeTerrainWeight[]): string[] { + return ["| Terrain | Weight |", "| --- | ---: |", ...rows.map((r) => `| ${esc(r.terrain)} | ${fmt(r.weight)} |`)]; +} + function transitionsTable(rows: BiomeTransition[]): string[] { return ["| Next to | Put between |", "| --- | --- |", ...rows.map((r) => `| ${esc(r.next)} | ${esc(r.between)} |`)]; } @@ -362,6 +405,7 @@ function ownKeys(f: BiomeNoteFields): [string, string | undefined][] { ["min-islands", f.minIslands !== undefined ? String(f.minIslands) : undefined], ["shore", f.shore ? "yes" : undefined], ["generator", f.generator ? `"[[${f.generator}]]"` : undefined], + ["parent", f.parent ? quote(f.parent) : undefined], ...climateKeyValues(f.climate), ]; } @@ -377,6 +421,7 @@ export function buildBiomeNote(f: BiomeNoteFields): string { ...BIOME_HELP, "", "## Mix", "", ...mixTable(f.mix), "", + ...(f.terrainWeights?.length ? ["## Terrain weights", "", ...terrainWeightsTable(f.terrainWeights), ""] : []), "## Transitions", "", ...transitionsTable(f.transitions), "", ].join("\n"); @@ -418,6 +463,8 @@ export function updateBiomeNote(content: string, f: BiomeNoteFields): string { lines.splice(fm.open + 1, fm.close - fm.open - 1, ...nextBody); // Tables. lines = putTable(lines, isMix, mixTable(f.mix), "## Mix"); + // Only written when there are weights, or the note already has the table. + if (f.terrainWeights?.length || findTable(lines, isTerrainWeights)) lines = putTable(lines, isTerrainWeights, terrainWeightsTable(f.terrainWeights ?? []), "## Terrain weights"); lines = putTable(lines, isTransitions, transitionsTable(f.transitions), "## Transitions"); const out = lines.join(eol); return out === content.replace(/\r\n?/g, "\n").split("\n").join(eol) ? content : out; @@ -429,7 +476,7 @@ function sameValue(key: string, cur: string, want: string): boolean { const w = unquote(want); if (key === "land-share") return parseShare(cur) === parseShare(w); if (key === "colour") return readColour(cur) === readColour(w); - if (key === "generator") return linkTarget(cur) === linkTarget(w); + if (key === "generator" || key === "parent") return linkTarget(cur) === linkTarget(w); if (key === "id") return biomeSlug(cur) === biomeSlug(w); if (key === "shore") return readYesNo(cur) === readYesNo(w); if (CLIMATE_KEY_SET.has(key)) return sameClimateValue(key, cur, w); diff --git a/src/overworld/biomes.ts b/src/overworld/biomes.ts index 5282b1ae..b0363bad 100644 --- a/src/overworld/biomes.ts +++ b/src/overworld/biomes.ts @@ -13,7 +13,7 @@ import type { HexWfcModel, TerrainEntry } from "../../packages/hex-wfc/src/model"; import { mapTerrainsByType, TYPE_FALLBACKS } from "../worldgen/builtinGenerators"; -import { biomeSlug, mixShares, type BiomeMixRow, type BiomeNoteFields } from "./biomeNote"; +import { biomeSlug, mixShares, type BiomeMixRow, type BiomeNoteFields, type BiomeTerrainWeight } from "./biomeNote"; import type { TerrainColor } from "../types"; import { typesInGroup } from "../terrainTypes"; import { climateCentre, isPlaceable, type BiomeClimate, type ClimateElevation, type ClimateRange } from "./biomeClimate"; @@ -441,25 +441,48 @@ function typesToTry(mix: BiomeMixRow[]): string[] { return [...own, ...own.flatMap((t) => TYPE_FALLBACKS[t] ?? [])]; } -/** The palette terrain painted for a note-only biome: the first terrain of its heaviest type the palette has. */ +/** + * The palette terrain painted for a note-only biome: of its heaviest type + * the palette has, the terrain with the most weight in its Terrain weights + * (palette order on a tie; the first one without the table). + */ function noteBiomeTerrain(biome: BiomeId, palette: TerrainColor[]): string | undefined { const n = source?.biomes.get(biome); if (!n) return undefined; for (const ty of typesToTry(n.mix)) { if (ty === "settlement") continue; - const hit = palette.find((t) => typeOf(t) === ty); - if (hit) return hit.name; + const of = palette.filter((t) => typeOf(t) === ty).map((t) => t.name); + if (!of.length) continue; + const w = withinTypeWeights(of, n.terrainWeights); + let best = of[0]; + for (const name of of) if ((w.get(name) ?? 0) > (w.get(best) ?? 0)) best = name; + return best; } return undefined; } /** - * Profile from a type mix (a biome note's): each type's share, spread - * evenly over the palette's terrains of that type. A type the palette + * How one type's share splits over its palette terrains (`names`), as + * fractions summing to 1: a terrain listed in `weights` (any case) gets its + * weight, the others 1; weight 0 leaves a terrain out. All left out (or no + * weights): an even split, so a type in the mix is never lost. + */ +export function withinTypeWeights(names: readonly string[], weights: readonly BiomeTerrainWeight[] | undefined): Map { + const byName = new Map((weights ?? []).map((w) => [w.terrain.trim().toLowerCase(), w.weight])); + const raw = names.map((n) => [n, Math.max(0, byName.get(n.toLowerCase()) ?? 1)] as const); + const total = raw.reduce((s, [, v]) => s + v, 0); + if (total <= 0) return new Map(names.map((n) => [n, 1 / names.length])); + return new Map(raw.filter(([, v]) => v > 0).map(([n, v]) => [n, v / total])); +} + +/** + * Profile from a type mix (a biome note's): each type's share, split over + * the palette's terrains of that type by `terrainWeights` (the note's + * Terrain weights; evenly without them, see withinTypeWeights). A type the palette * doesn't have goes to its first fallback type it does (TYPE_FALLBACKS), * else is dropped. Settlements never count. */ -export function profileFromMix(id: BiomeId, mix: BiomeMixRow[], palette: TerrainColor[]): BiomeProfile { +export function profileFromMix(id: BiomeId, mix: BiomeMixRow[], palette: TerrainColor[], terrainWeights?: readonly BiomeTerrainWeight[]): BiomeProfile { const byType = new Map(); for (const t of palette) { const ty = typeOf(t); @@ -475,8 +498,8 @@ export function profileFromMix(id: BiomeId, mix: BiomeMixRow[], palette: Terrain const names = new Map>(); for (const [ty, v] of types) { types.set(ty, v / total); - const list = byType.get(ty)!; - names.set(ty, new Map(list.map((n) => [n, 1 / list.length]))); + // Within the type: the Terrain weights table, else an even split. + names.set(ty, withinTypeWeights(byType.get(ty)!, terrainWeights)); } const profile: BiomeProfile = { id, types, names }; // Min patches follow their type to the one the palette has (the same fallback as the mix). @@ -492,7 +515,7 @@ export function profileFromMix(id: BiomeId, mix: BiomeMixRow[], palette: Terrain /** A biome note's profile on a palette: its mix, islands and shore settings. */ export function profileFromFields(b: BiomeNoteFields, palette: TerrainColor[]): BiomeProfile { - const p = profileFromMix(b.id, b.mix, palette); + const p = profileFromMix(b.id, b.mix, palette, b.terrainWeights); if (b.landShare !== undefined) p.landShare = b.landShare; if (b.minIslands !== undefined) p.minIslands = b.minIslands; if (b.shore) p.shore = true; diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index 5252e27b..cfa5dbae 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -146,6 +146,26 @@ function newNote(pal: TerrainPalette): string { * palettes every map could draw every type, so copying them all keeps every * map's paths drawable. Returns how many palettes were filled. */ +/** A palette's own copy (never alias a shared constant). */ +export function clonePalette(p: TerrainPalette): TerrainPalette { + return { name: p.name, terrains: p.terrains.map((t) => ({ ...t })) }; +} + +/** + * The palette list as loaded from data.json: missing or not a list (a fresh + * install, a broken file) → the defaults; any list, empty too, is kept as + * the user left it (SM-DEL: deleted palettes stay deleted). + */ +export function palettesOnLoad(saved: unknown, defaults: readonly TerrainPalette[]): TerrainPalette[] { + return Array.isArray(saved) ? (saved as TerrainPalette[]) : defaults.map(clonePalette); +} + +/** The default palettes not in `list` (by name, any case), in their own order. */ +export function missingDefaults(list: readonly { name: string }[], defaults: readonly TerrainPalette[]): TerrainPalette[] { + const have = new Set(list.map((p) => p.name.toLowerCase())); + return defaults.filter((p) => !have.has(p.name.toLowerCase())); +} + export function fillPalettePathTypes(palettes: TerrainPalette[], legacy: PathType[] | undefined): number { const source = legacy && legacy.length ? legacy : DEFAULT_PATH_TYPES; let n = 0; @@ -279,11 +299,16 @@ export class PaletteStore { * settings-only palettes to notes the first time, then loads every note. */ init(): Promise { - return this.enqueue(() => this.attach()); + return this.enqueue(() => this.attach(true)); } - /** Bind to the current folder: migrate if needed, then load from notes. */ - private async attach(): Promise { + /** + * Bind to the current folder: migrate if needed, then load from notes. + * `startup`: the folder is the one the palettes were saved in, so no + * notes there means they were deleted (they stay deleted, SM-DEL); on a + * folder change (not startup) every palette is written into the new one. + */ + private async attach(startup = false): Promise { this.boundPath = new WeakMap(); this.knownPaths.clear(); this.lastContent.clear(); @@ -302,7 +327,11 @@ export class PaletteStore { for (const f of this.paletteFiles()) { if (parsePaletteNote(await this.plugin.app.vault.cachedRead(f))) existing.push(f); } - if (!settings.palettesMigrated || existing.length === 0) { + // (Only when the folder holds no notes at all: a note that doesn't read is never taken as deleted.) + if (startup && settings.palettesMigrated && this.paletteFiles().length === 0 && settings.terrainPalettes.length) { + await this.dropDeletedPalettes(); + dirty = true; + } else if (!settings.palettesMigrated || existing.length === 0) { const paletteNames = new Set(existing.map((f) => f.basename.toLowerCase())); for (const pal of settings.terrainPalettes) { const safe = paletteFileName(pal.name); @@ -400,6 +429,31 @@ export class PaletteStore { if (dirty) await this.persist(); } + /** + * Every palette note was deleted while Obsidian was closed (SM-DEL): + * the palettes go too, never re-created from data.json's copy. That copy + * is backed up first, and a notice says how to get the defaults back. + * Maps keep their palette name, so a palette note put back reattaches. + */ + private async dropDeletedPalettes(): Promise { + const settings = this.plugin.settings; + const names = settings.terrainPalettes.map((p) => p.name); + let where = ""; + try { + const dir = `${this.plugin.manifest.dir}/backups/palettes-${new Date().toISOString().slice(0, 10)}`; + where = await writeJsonBackup(this.plugin.app.vault.adapter, dir, "deleted-palettes", JSON.stringify({ savedAt: new Date().toISOString(), palettes: settings.terrainPalettes })); + } catch (e) { + console.error("Hexmap World Creator: couldn't back up the deleted palettes", e); + } + settings.terrainPalettes = []; + new Notice( + `Hexmap World Creator: no palette notes in "${this.folder()}", so there are no terrain palettes now (${names.join(", ")} were deleted).` + + (where ? ` A copy is in ${where}.` : "") + + " Add palettes, or the defaults, in Settings → Terrain palettes.", + 15000, + ); + } + /** * Save the full text of every palette note (gzipped JSON in the plugin's * backups folder) when any of them still has colours that aren't inline @@ -731,7 +785,8 @@ export class PaletteStore { this.lastContent.delete(file.path); const pal = this.paletteBoundTo(file.path); const list = this.plugin.settings.terrainPalettes; - if (!pal || list.length <= 1) return; // keep at least one palette + // Deleted palettes stay deleted, the last one too (SM-DEL). + if (!pal) return; // Maps keep their paletteName so they reattach if the note comes back // (e.g. restored from trash, or delivered late by sync). list.splice(list.indexOf(pal), 1); @@ -756,7 +811,7 @@ export class PaletteStore { if (!isPalette) { // Moved out of the palettes folder: same as a delete. const list = this.plugin.settings.terrainPalettes; - if (list.length > 1) list.splice(list.indexOf(pal), 1); + list.splice(list.indexOf(pal), 1); await this.persist(); return; } diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index fb19f107..d0787f0d 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -393,6 +393,12 @@ export async function saveGeneratorFromMaps( return { file, model }; } +/** Learn a generator from one map's painted hexes, in memory (not saved). */ +export function learnGeneratorFromMap(plugin: HexmakerPlugin, mapName: string, rawName: string): { model: HexWfcModel } | { error: string } { + const name = slugify(rawName) || slugify(mapName); + return learnFromMaps(plugin, [mapName], name, sourceMeta(plugin, [mapName])); +} + /** Learn a generator from one map (see saveGeneratorFromMaps). */ export function saveGeneratorFromMap( plugin: HexmakerPlugin, diff --git a/src/worldgen/regionGenerator.ts b/src/worldgen/regionGenerator.ts new file mode 100644 index 00000000..d7da42cb --- /dev/null +++ b/src/worldgen/regionGenerator.ts @@ -0,0 +1,296 @@ +/** + * "Make generator from this region…" (PR1, owner round 5): learn a + * generator from a region's hand-edited terrain, as a new generator or + * over an existing one, and give it a biome that inherits the region's + * biome basics (climate, islands, transitions, shore, blend, colour, mix). + * + * - rankOverwriteTargets (pure): the generators to offer for "Overwrite + * existing", the most fitting first: the region's own biome's generator, + * then its parent biomes', then ones learned from this region, then + * related biomes' (neighbours it was blended with, similar biomes, its + * children and siblings), then the rest by name. + * - inheritedBiome (pure): the new biome's note fields. + * - makeRegionGenerator: the glue (learn, back up, write, create the biome). + */ + +import { TFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { TerrainColor } from "../types"; +import { biomeSlug, type BiomeMixRow, type BiomeNoteFields, type BiomeTerrainWeight } from "../overworld/biomeNote"; +import { copyClimate } from "../overworld/biomeClimate"; +import { SIMILAR } from "../overworld/biomes"; +import { hexBiomeAt, regionBiomeStatus } from "../overworld/regionsVault"; +import { learnGeneratorFromMap, listGenerators, saveGeneratorFromMap, sourceMapsOf, type GeneratorFile } from "./generators"; +import { modelToMarkdown } from "../../packages/hex-wfc/src"; + +export type OverwriteReason = "own" | "parent" | "learned" | "related" | "other"; + +export interface OverwriteCandidate { + /** The generator note's vault path. */ + path: string; + name: string; + reason: OverwriteReason; + /** Short words for the list ("this region's biome: Coast"). */ + why: string; +} + +/** A generator as the ranking sees it. */ +export interface RankedGenerator { + path: string; + name: string; + sourceMaps: string[]; +} + +export interface RankContext { + region: string; + /** The region's biome (its note), if it has one. */ + biome?: BiomeNoteFields; + /** Every biome note. */ + biomes: readonly BiomeNoteFields[]; + /** Biomes the region was blended with (MapData.biome.from), as written. */ + blendedWith?: readonly string[]; + /** A biome's `generator` link → the generator note's path (undefined if it doesn't resolve). */ + resolveGenerator: (link: string) => string | undefined; +} + +/** A biome by id, label or note name (as biome references are written). */ +function findBiome(biomes: readonly BiomeNoteFields[], ref: string | undefined): BiomeNoteFields | undefined { + if (!ref) return undefined; + const k = biomeSlug(ref); + return biomes.find((b) => b.id === k) ?? biomes.find((b) => biomeSlug(b.label) === k); +} + +/** The biome's parents, nearest first (cycle-safe). */ +export function biomeAncestors(biome: BiomeNoteFields | undefined, biomes: readonly BiomeNoteFields[]): BiomeNoteFields[] { + const out: BiomeNoteFields[] = []; + const seen = new Set(biome ? [biome.id] : []); + let cur = findBiome(biomes, biome?.parent); + while (cur && !seen.has(cur.id)) { + seen.add(cur.id); + out.push(cur); + cur = findBiome(biomes, cur.parent); + } + return out; +} + +/** Biomes related to `biome` but not its parents: blended neighbours, similar biomes, children, siblings. */ +export function relatedBiomes(biome: BiomeNoteFields | undefined, biomes: readonly BiomeNoteFields[], blendedWith: readonly string[] = []): BiomeNoteFields[] { + if (!biome) return blendedWith.map((r) => findBiome(biomes, r)).filter((b): b is BiomeNoteFields => !!b); + const parent = findBiome(biomes, biome.parent); + const refs: (BiomeNoteFields | undefined)[] = [ + ...blendedWith.map((r) => findBiome(biomes, r)), + ...(SIMILAR[biome.id] ?? []).map((id) => findBiome(biomes, id)), + ...biomes.filter((b) => findBiome(biomes, b.parent)?.id === biome.id), + ...(parent ? biomes.filter((b) => b.id !== biome.id && findBiome(biomes, b.parent)?.id === parent.id) : []), + ]; + const out: BiomeNoteFields[] = []; + for (const b of refs) if (b && b.id !== biome.id && !out.includes(b)) out.push(b); + return out; +} + +/** + * The generators "Overwrite existing" offers, most fitting first (see the + * file comment). Each generator once, under its best reason. + */ +export function rankOverwriteTargets(gens: readonly RankedGenerator[], ctx: RankContext): OverwriteCandidate[] { + const byPath = new Map(gens.map((g) => [g.path, g])); + const out: OverwriteCandidate[] = []; + const add = (path: string | undefined, reason: OverwriteReason, why: string) => { + const g = path ? byPath.get(path) : undefined; + if (!g || out.some((c) => c.path === g.path)) return; + out.push({ path: g.path, name: g.name, reason, why }); + }; + const genOf = (b: BiomeNoteFields) => (b.generator ? ctx.resolveGenerator(b.generator) : undefined); + if (ctx.biome) add(genOf(ctx.biome), "own", `this region's biome: ${ctx.biome.label}`); + for (const b of biomeAncestors(ctx.biome, ctx.biomes)) add(genOf(b), "parent", `parent biome: ${b.label}`); + // Learned from this region: alone first, then combined ones. + const learned = gens.filter((g) => g.sourceMaps.includes(ctx.region)).sort((a, b) => a.sourceMaps.length - b.sourceMaps.length || a.name.localeCompare(b.name)); + for (const g of learned) add(g.path, "learned", "learned from this region"); + for (const b of relatedBiomes(ctx.biome, ctx.biomes, ctx.blendedWith)) add(genOf(b), "related", `related biome: ${b.label}`); + for (const g of [...gens].sort((a, b) => a.name.localeCompare(b.name))) add(g.path, "other", ""); + return out; +} + +/** Hex counts by terrain → a type mix (settlements and untyped terrains left out). */ +export function mixFromTerrain(counts: ReadonlyMap, palette: readonly TerrainColor[]): BiomeMixRow[] { + const typeOf = new Map(palette.map((t) => [t.name, t.type])); + const out: BiomeMixRow[] = []; + for (const [terrain, n] of counts) { + const type = typeOf.get(terrain); + if (!type || type === "settlement" || n <= 0) continue; + const hit = out.find((r) => r.type === type); + if (hit) hit.weight += n; + else out.push({ type, weight: n }); + } + return out.sort((a, b) => b.weight - a.weight); +} + +/** + * Terrain weights from the region's hex counts, for the types where the + * region uses more than one terrain (where the split matters: "different + * forests go together in different ratios"), limited to `types`. + */ +export function terrainWeightsFromTerrain(counts: ReadonlyMap, palette: readonly TerrainColor[], types: readonly string[]): BiomeTerrainWeight[] { + const typeOf = new Map(palette.map((t) => [t.name, t.type])); + const byType = new Map(); + for (const [terrain, n] of counts) { + const type = typeOf.get(terrain); + if (!type || !types.includes(type) || n <= 0) continue; + byType.set(type, [...(byType.get(type) ?? []), [terrain, n]]); + } + const out: BiomeTerrainWeight[] = []; + for (const type of types) { + const rows = byType.get(type); + if (!rows || rows.length < 2) continue; + for (const [terrain, weight] of rows.sort((a, b) => b[1] - a[1])) out.push({ terrain, weight }); + } + return out; +} + +/** + * The note fields of a biome for a generator made from a region: the + * source biome's basics (climate, land share, min islands, transitions, + * shore, blend, colour) and its mix as a starting point; without one, the + * mix the region's terrain shows. Terrain weights come from the region. + */ +export function inheritedBiome(source: BiomeNoteFields | undefined, opts: { label: string; generator: string; counts: ReadonlyMap; palette: readonly TerrainColor[] }): Omit { + const mix = source?.mix.length ? source.mix.map((r) => ({ ...r })) : mixFromTerrain(opts.counts, opts.palette); + const f: Omit = { + label: opts.label, + mix, + transitions: (source?.transitions ?? []).map((t) => ({ ...t })), + generator: opts.generator, + }; + if (source) { + f.parent = source.label; + if (source.color) f.color = source.color; + if (source.blend) f.blend = source.blend; + if (source.landShare !== undefined) f.landShare = source.landShare; + if (source.minIslands !== undefined) f.minIslands = source.minIslands; + if (source.shore) f.shore = true; + const climate = copyClimate(source.climate); + if (climate) f.climate = climate; + } + const weights = terrainWeightsFromTerrain(opts.counts, opts.palette, mix.map((r) => r.type)); + if (weights.length) f.terrainWeights = weights; + return f; +} + +// ── glue ───────────────────────────────────────────────────────────────── + +/** The biome a region was made from (its own record, else its overworld hex's), as a note. */ +export function regionSourceBiome(plugin: HexmakerPlugin, mapName: string): BiomeNoteFields | undefined { + const status = regionBiomeStatus(plugin, mapName); + if (status && "id" in status) { + const b = plugin.biomeStore.get(status.id); + if (b) return b; + } + const map = plugin.getMap(mapName); + if (map?.submapKind === "region" && map.parent) { + const id = hexBiomeAt(plugin, map.parent.map, map.parent.hex); + if (id) return plugin.biomeStore.get(id); + } + return undefined; +} + +/** A generator link (biome `generator:`) → the note's path. */ +export function resolveGeneratorLink(plugin: HexmakerPlugin, link: string): string | undefined { + const v = plugin.app.vault; + const hit = v.getAbstractFileByPath(link) ?? v.getAbstractFileByPath(`${link}.md`) ?? plugin.app.metadataCache.getFirstLinkpathDest?.(link, ""); + return hit instanceof TFile ? hit.path : undefined; +} + +/** The overwrite list for a region, ranked (see rankOverwriteTargets). */ +export async function overwriteTargets(plugin: HexmakerPlugin, mapName: string): Promise<{ candidates: OverwriteCandidate[]; generators: GeneratorFile[]; biome?: BiomeNoteFields }> { + const generators = await listGenerators(plugin); + const biome = regionSourceBiome(plugin, mapName); + const candidates = rankOverwriteTargets( + generators.map((g) => ({ path: g.file.path, name: g.model.name, sourceMaps: sourceMapsOf(g.model) })), + { + region: mapName, + biome, + biomes: plugin.biomeStore.list(), + blendedWith: plugin.getMap(mapName)?.biome?.from, + resolveGenerator: (link) => resolveGeneratorLink(plugin, link), + }, + ); + return { candidates, generators, biome }; +} + +/** Hexes per terrain on a map (from the map note's data). */ +function terrainCountsOf(plugin: HexmakerPlugin, mapName: string): Map { + const out = new Map(); + for (const h of plugin.mapStore.all(mapName).values()) if (h.terrain) out.set(h.terrain, (out.get(h.terrain) ?? 0) + 1); + return out; +} + +/** Save `text` under the plugin's backups folder as plain Markdown, never over an earlier one. Returns the path. */ +async function backupText(plugin: HexmakerPlugin, base: string, text: string): Promise { + const adapter = plugin.app.vault.adapter; + const dir = `${plugin.manifest.dir}/backups/generators-${new Date().toISOString().slice(0, 10)}`; + if (!(await adapter.exists(dir))) await adapter.mkdir(dir); + let path = `${dir}/${base}.md`; + for (let n = 2; await adapter.exists(path); n++) path = `${dir}/${base}-${n}.md`; + await adapter.write(path, text); + return path; +} + +export type MakeTarget = { kind: "new"; name: string } | { kind: "overwrite"; path: string }; + +export interface MakeResult { + file: TFile; + /** Where the overwritten generator was backed up. */ + backup?: string; + /** The biome made for the generator (label), if one was. */ + biome?: string; +} + +/** + * Learn a generator from `mapName` into `target`. A new generator gets a + * biome inheriting the region's biome (when the region has one). An + * overwrite backs the old note up first and keeps the biomes that use it; + * if none does, it gets an inheriting biome too. + */ +export async function makeRegionGenerator(plugin: HexmakerPlugin, mapName: string, target: MakeTarget): Promise { + let file: TFile; + let backup: string | undefined; + if (target.kind === "new") { + const r = await saveGeneratorFromMap(plugin, mapName, target.name); + if ("error" in r) return r; + file = r.file; + } else { + const f = plugin.app.vault.getAbstractFileByPath(target.path); + if (!(f instanceof TFile)) return { error: `The generator ${target.path} is gone.` }; + const name = f.basename; + const learned = learnGeneratorFromMap(plugin, mapName, name); + if ("error" in learned) return learned; + const old = await plugin.app.vault.read(f); + try { + backup = await backupText(plugin, name, old); + } catch (e) { + console.error("Hexmap World Creator: couldn't back up the generator before overwriting it", e); + return { error: `Couldn't back up ${f.path}, so it wasn't overwritten.` }; + } + await plugin.app.vault.modify(f, modelToMarkdown(learned.model)); + file = f; + } + const link = file.path.replace(/\.md$/i, ""); + const usedBy = plugin.biomeStore.list().some((b) => b.generator && resolveGeneratorLink(plugin, b.generator) === file.path); + const source = regionSourceBiome(plugin, mapName); + let biome: string | undefined; + if (source && !usedBy && plugin.biomeStore.isReady()) { + const label = uniqueBiomeLabel(plugin, target.kind === "new" ? target.name.trim() || file.basename : file.basename); + const fields = inheritedBiome(source, { label, generator: link, counts: terrainCountsOf(plugin, mapName), palette: plugin.getMapPalette(mapName) }); + const res = await plugin.biomeStore.create(fields); + if (!("error" in res)) biome = label; + } + return { file, backup, biome }; +} + +/** A biome label not taken yet ("Coast", "Coast 2", …). */ +function uniqueBiomeLabel(plugin: HexmakerPlugin, want: string): string { + const taken = new Set(plugin.biomeStore.list().flatMap((b) => [b.id, biomeSlug(b.label)])); + let label = want; + for (let n = 2; taken.has(biomeSlug(label)); n++) label = `${want} ${n}`; + return label; +} diff --git a/styles.css b/styles.css index fd35656e..6216483d 100644 --- a/styles.css +++ b/styles.css @@ -8770,3 +8770,83 @@ textarea.duckmage-edit-region-notes-input { font-size: var(--font-ui-smaller); color: var(--text-muted); } +/* Missing maps (SM-DEL): folder and map note deleted by hand */ +.duckmage-map-missing-icon { + display: inline-flex; + color: var(--text-warning); + margin-right: 4px; +} +.duckmage-map-missing-icon svg { + width: 14px; + height: 14px; +} +.duckmage-map-list-item.is-missing .duckmage-map-list-name { + color: var(--text-muted); +} +.duckmage-map-missing-actions { + display: inline-flex; + gap: 4px; + margin-left: auto; +} +.duckmage-map-missing-actions button { + padding: 2px 8px; + font-size: var(--font-ui-smaller); +} +.duckmage-map-missing-state { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + max-width: 420px; + padding: 16px 20px; + border: 1px solid var(--background-modifier-border); + border-radius: 8px; + background: var(--background-primary); + text-align: center; +} +.duckmage-map-missing-state .duckmage-map-missing-actions { + margin-left: 0; +} +/* Make generator from this region (PR1) */ +.duckmage-make-generator-choice { + display: flex; + flex-direction: column; + gap: 6px; +} +.duckmage-make-generator-option { + display: flex; + align-items: center; + gap: 6px; + font-weight: var(--font-semibold); +} +.duckmage-make-generator-name { + margin-left: 22px; + max-width: 320px; +} +.duckmage-make-generator-list { + margin-left: 22px; + max-height: 240px; + overflow-y: auto; + border: 1px solid var(--background-modifier-border); + border-radius: 6px; +} +.duckmage-make-generator-row { + display: flex; + justify-content: space-between; + gap: 12px; + padding: 4px 8px; + cursor: pointer; +} +.duckmage-make-generator-row:hover { + background: var(--background-modifier-hover); +} +.duckmage-make-generator-row.is-selected { + background: var(--background-modifier-active-hover); +} +.duckmage-make-generator-row-why { + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} +.duckmage-make-generator-row.is-suggested .duckmage-make-generator-row-name { + font-weight: var(--font-semibold); +} diff --git a/tests/helpers/memVault.ts b/tests/helpers/memVault.ts index f4a5e834..f2ea1f2d 100644 --- a/tests/helpers/memVault.ts +++ b/tests/helpers/memVault.ts @@ -80,6 +80,12 @@ export class MemVault { return m ? parseMiniYaml(m[1]) : undefined; } + /** Delete a file, or a folder and everything in it (as a user would by hand). */ + remove(path: string): void { + for (const p of [...this.files.keys()]) if (p === path || p.startsWith(path + "/")) this.files.delete(p); + for (const p of [...this.folders]) if (p === path || p.startsWith(path + "/")) this.folders.delete(p); + } + body(path: string): string { return (this.files.get(path) ?? "").replace(FM, ""); } @@ -110,6 +116,10 @@ export class MemVault { exists: async (p: string) => v.files.has(p) || v.folders.has(p) || v.binaries.has(p), mkdir: async (p: string) => { v.ensureFolder(p); }, write: async (p: string, c: string) => { v.put(p, c); }, + read: async (p: string) => { + if (!v.files.has(p)) throw new Error("no file " + p); + return v.files.get(p)!; + }, writeBinary: async (p: string, data: ArrayBuffer) => { if (v.failBinary) throw new Error("disk full"); v.binaries.set(p, new Uint8Array(data)); diff --git a/tests/missingMaps.test.ts b/tests/missingMaps.test.ts new file mode 100644 index 00000000..f3720827 --- /dev/null +++ b/tests/missingMaps.test.ts @@ -0,0 +1,180 @@ +/** + * SM-DEL (owner, round 5): a map whose folder and map note were deleted by + * hand is marked missing (Restore / Remove), never silently re-created as + * an empty note. Restore puts back exactly what the note held (hexes, + * paths, settings) from the map cache. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { TFile, TFolder } from "obsidian"; +import { MapStore } from "../src/maps/MapStore"; +import { parseMapNote } from "../src/maps/mapNote"; +import { MemVault } from "./helpers/memVault"; +import type { MapData } from "../src/types"; + +(globalThis as Record).window ??= globalThis; + +const NOTE = "world/hexes/isle/_isle.md"; +const CACHE = ".obsidian/plugins/hexmaker/map-cache/isle.md"; + +function plugin(vault: MemVault, maps: MapData[]) { + return { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", maps }, + getMap: (n: string) => maps.find((m) => m.name === n), + saveData: async () => {}, + refreshHexMap: () => {}, + }; +} + +const isle = (): MapData => ({ name: "isle", paletteName: "Expanded", gridSize: { cols: 6, rows: 5 }, gridOffset: { x: 0, y: 0 }, pathChains: [] }) as MapData; + +/** data.json's copy of a map: settings without paths (the note holds them). */ +function fromDataJson(m: MapData): MapData { + const { paths: _p, pathChains: _c, ...rest } = JSON.parse(JSON.stringify(m)) as MapData; + return rest as MapData; +} + +async function boot(vault: MemVault, maps: MapData[]) { + const p = plugin(vault, maps); + const store = new MapStore(p as never); + await store.init(); + return { p, store }; +} + +/** A painted map with a path, its note written and cached. */ +async function painted(vault: MemVault) { + const map = isle(); + const { store } = await boot(vault, [map]); + store.setMany("isle", [["1_1", { terrain: "forest" }], ["2_2", { terrain: "hills" }], ["3_3", { terrain: "ocean", name: "Bay" }]]); + store.setPaths("isle", [{ name: "Old road", typeName: "Road", branches: [{ anchors: ["0_1", "4_3"] }] }]); + map.baseTerrain = "ocean"; + await store.sync(); + await store.flush(); + return map; +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +describe("missing maps (SM-DEL)", () => { + it("every note write is cached outside the vault's notes", async () => { + const vault = new MemVault(); + await painted(vault); + expect(vault.files.get(CACHE)).toBe(vault.files.get(NOTE)); + }); + + it("folder and note deleted while closed: marked missing, nothing re-created", async () => { + const vault = new MemVault(); + const map = await painted(vault); + vault.remove("world/hexes/isle"); + const { store } = await boot(vault, [fromDataJson(map)]); + expect(store.isMissing("isle")).toBe(true); + expect(store.missingMaps()).toEqual(["isle"]); + expect(store.isReady("isle")).toBe(false); + await store.sync(); + await store.flush(); + expect(vault.files.has(NOTE)).toBe(false); + expect([...vault.folders].some((f) => f === "world/hexes/isle")).toBe(false); + }); + + it("Restore brings back hexes, paths and settings exactly, from the cache", async () => { + const vault = new MemVault(); + const map = await painted(vault); + const before = vault.files.get(NOTE)!; + vault.remove("world/hexes/isle"); + const copy = fromDataJson(map); + delete copy.baseTerrain; // a setting only the note still had + const { store } = await boot(vault, [copy]); + const r = await store.restoreMissing("isle"); + expect(r).toEqual({ source: "cache" }); + expect(store.isMissing("isle")).toBe(false); + expect(vault.files.get(NOTE)).toBe(before); + expect(store.get("isle", "3_3")).toEqual({ terrain: "ocean", name: "Bay" }); + expect(store.all("isle").size).toBe(3); + expect(store.paths("isle").map((p) => [p.name, p.branches[0].anchors])).toEqual([["Old road", ["0_1", "4_3"]]]); + expect(copy.baseTerrain).toBe("ocean"); + const note = parseMapNote(vault.files.get(NOTE)!)!; + expect(note.hexes.size).toBe(3); + }); + + it("a fresh install's placeholder (never had a note) is created, not missing", async () => { + const vault = new MemVault(); + const { store } = await boot(vault, [isle()]); + expect(store.isMissing("isle")).toBe(false); + expect(vault.files.has(NOTE)).toBe(true); + }); + + it("a cached map whose folder still has hex notes with map data migrates instead", async () => { + const vault = new MemVault(); + const map = await painted(vault); + vault.files.delete(NOTE); + vault.files.set("world/hexes/isle/1_1.md", "---\nterrain: desert\n---\n# Hex\n"); + const { store } = await boot(vault, [fromDataJson(map)]); + expect(store.isMissing("isle")).toBe(false); + expect(store.get("isle", "1_1")?.terrain).toBe("desert"); + }); + + it("deleted mid-session: marked missing after a moment; Restore uses what's in memory", async () => { + const vault = new MemVault(); + const map = isle(); + const { store } = await boot(vault, [map]); + store.setMany("isle", [["4_4", { terrain: "forest" }]]); + await store.flush(); + vault.remove("world/hexes/isle"); + const folder = new TFolder(); + folder.path = "world/hexes/isle"; + store.onDelete(folder); + await sleep(400); + await store.flush(); + expect(store.isMissing("isle")).toBe(true); + expect(vault.files.has(NOTE)).toBe(false); + // Edits while missing stay in memory and are never written… + store.setMany("isle", [["5_4", { terrain: "hills" }]]); + await store.flush(); + expect(vault.files.has(NOTE)).toBe(false); + // …until Restore. + expect(await store.restoreMissing("isle")).toEqual({ source: "memory" }); + const note = parseMapNote(vault.files.get(NOTE)!)!; + expect([...note.hexes.keys()].sort()).toEqual(["4_4", "5_4"]); + }); + + it("the plugin's own Delete (expectRemoval) doesn't mark the map missing", async () => { + const vault = new MemVault(); + const { store } = await boot(vault, [isle()]); + store.expectRemoval("isle"); + vault.remove("world/hexes/isle"); + const note = new TFile(); + note.path = NOTE; + store.onDelete(note); + await sleep(400); + await store.flush(); + expect(store.isMissing("isle")).toBe(false); + }); + + it("a missing map's note put back by hand loads again (onCreate)", async () => { + const vault = new MemVault(); + const map = await painted(vault); + const text = vault.files.get(NOTE)!; + vault.remove("world/hexes/isle"); + const { store } = await boot(vault, [fromDataJson(map)]); + vault.files.set(NOTE, text); + const f = new TFile(); + f.path = NOTE; + store.onCreate(f); + await store.flush(); + expect(store.isMissing("isle")).toBe(false); + expect(store.all("isle").size).toBe(3); + }); + + it("data.json replaced from outside: a map without a note is missing, not written", async () => { + const vault = new MemVault(); + const maps = [isle()]; + const { store } = await boot(vault, maps); + maps.push({ name: "far", paletteName: "Expanded", gridSize: { cols: 3, rows: 3 }, gridOffset: { x: 0, y: 0 } } as MapData); + await store.reloadFromNotes(); + await store.sync(); + expect(store.isMissing("far")).toBe(true); + expect(vault.files.has("world/hexes/far/_far.md")).toBe(false); + }); +}); diff --git a/tests/palettes.test.ts b/tests/palettes.test.ts index 2f272c56..471cd19b 100644 --- a/tests/palettes.test.ts +++ b/tests/palettes.test.ts @@ -19,7 +19,7 @@ import { uniquePaletteName, } from "../src/palettes/presets"; import { parsePathTypes, setPathTypes } from "../src/palettes/pathTypeTable"; -import { PaletteStore } from "../src/palettes/PaletteStore"; +import { PaletteStore, missingDefaults, palettesOnLoad } from "../src/palettes/PaletteStore"; import { DEFAULT_SETTINGS } from "../src/constants"; import { iconLabel, iconPack } from "../src/utils"; import type { HexmakerPluginSettings, PathType, TerrainColor } from "../src/types"; @@ -428,27 +428,48 @@ describe("PaletteStore", () => { expect(h.vault.files.has("world/palettes/Expanded.md")).toBe(false); }); - it("never deletes the last palette", async () => { + it("a deleted last palette stays deleted (SM-DEL: never re-written by sync)", async () => { h.settings.terrainPalettes.splice(1); await h.store.init(); const f = h.file("world/palettes/Limited.md"); h.vault.files.delete(f.path); h.store.onDelete(f); await h.store.sync(); - expect(h.settings.terrainPalettes.map((x) => x.name)).toEqual(["Limited"]); - expect(h.vault.files.has("world/palettes/Limited.md")).toBe(true); // re-written by sync + expect(h.settings.terrainPalettes.map((x) => x.name)).toEqual([]); + expect(h.vault.files.has("world/palettes/Limited.md")).toBe(false); }); - it("rewrites notes when the folder is emptied (safety net)", async () => { + it("palette notes deleted while closed stay deleted: dropped (backed up), not re-written", async () => { await h.store.init(); h.vault.files.clear(); const fresh = makeHarness({ palettesMigrated: true }); fresh.settings.terrainPalettes = h.settings.terrainPalettes; await fresh.store.init(); - expect([...fresh.vault.files.keys()].sort()).toEqual([ - "world/palettes/Expanded.md", - "world/palettes/Limited.md", - ]); + expect([...fresh.vault.files.keys()]).toEqual([]); + expect(fresh.settings.terrainPalettes).toEqual([]); + // data.json's copy is kept in a backup before it's dropped. + expect([...fresh.vault.raw.keys()].some((p) => p.includes("/backups/palettes-") && p.includes("/deleted-palettes"))).toBe(true); + }); + + it("an emptied palette list stays empty on load (no notes written)", async () => { + const fresh = makeHarness({ palettesMigrated: true }); + fresh.settings.terrainPalettes = []; + await fresh.store.init(); + await fresh.store.sync(); + expect(fresh.settings.terrainPalettes).toEqual([]); + expect([...fresh.vault.files.keys()]).toEqual([]); + }); + + it("a palette note that doesn't read is never taken as deleted", async () => { + await h.store.init(); + h.vault.files.clear(); + h.vault.files.set("world/palettes/Limited.md", "no table here"); + const fresh = makeHarness({ palettesMigrated: true }); + for (const [p, c] of h.vault.files) fresh.vault.files.set(p, c); + fresh.settings.terrainPalettes = h.settings.terrainPalettes; + await fresh.store.init(); + expect(fresh.settings.terrainPalettes.length).toBe(2); + expect(fresh.vault.files.get("world/palettes/Limited.md")).toBe("no table here"); }); it("round-trips child-palette between notes and palettes", async () => { @@ -811,3 +832,24 @@ describe("PaletteStore colour conversion", () => { expect(h.vault.raw.size).toBe(0); }); }); + +describe("palette list on load (SM-DEL: no automatic refill)", () => { + const defaults = DEFAULT_SETTINGS.terrainPalettes; + it("an emptied list stays empty", () => { + expect(palettesOnLoad([], defaults)).toEqual([]); + }); + it("no list at all (fresh install, broken data) gets the defaults, as copies", () => { + const got = palettesOnLoad(undefined, defaults); + expect(got.map((p) => p.name)).toEqual(defaults.map((p) => p.name)); + expect(got[0].terrains).not.toBe(defaults[0].terrains); + expect(palettesOnLoad("nonsense", defaults).length).toBe(defaults.length); + }); + it("a saved list is kept as it is", () => { + const mine = [{ name: "Moorland", terrains: [] }]; + expect(palettesOnLoad(mine, defaults)).toBe(mine); + }); + it("Add default palettes offers only the ones not there (any case)", () => { + expect(missingDefaults([], defaults).map((p) => p.name)).toEqual(defaults.map((p) => p.name)); + expect(missingDefaults([{ name: defaults[0].name.toUpperCase() }], defaults).map((p) => p.name)).toEqual(defaults.slice(1).map((p) => p.name)); + }); +}); diff --git a/tests/regionGenerator.test.ts b/tests/regionGenerator.test.ts new file mode 100644 index 00000000..2bc761e5 --- /dev/null +++ b/tests/regionGenerator.test.ts @@ -0,0 +1,261 @@ +/** + * PR1 (owner, round 5): "Make generator from this region" — the new + * generator's biome inherits the region's biome basics; "Overwrite + * existing" lists the most fitting generators first (the region's biome's, + * its parents'); an overwrite keeps a backup. Plus the biome note's + * optional Terrain weights ("different forests go together in different + * ratios"). + */ +import { describe, it, afterEach } from "node:test"; +import expect from "expect"; +import { biomeAncestors, inheritedBiome, makeRegionGenerator, mixFromTerrain, rankOverwriteTargets, relatedBiomes, terrainWeightsFromTerrain, type RankedGenerator } from "../src/worldgen/regionGenerator"; +import { buildBiomeNote, parseBiomeNote, updateBiomeNote, type BiomeNoteFields } from "../src/overworld/biomeNote"; +import { profileFromFields, profileFromMix, setBiomeSource, withinTypeWeights } from "../src/overworld/biomes"; +import { setHexDataSource } from "../src/frontmatter"; +import { biomeSlug } from "../src/overworld/biomeNote"; +import { MemVault } from "./helpers/memVault"; +import type { HexData } from "../src/maps/mapNote"; +import type { MapData, TerrainColor } from "../src/types"; + +const biome = (id: string, extra: Partial = {}): BiomeNoteFields => ({ id, label: id[0].toUpperCase() + id.slice(1).replace(/-/g, " "), mix: [{ type: "forest", weight: 1 }], transitions: [], ...extra }); + +describe("Overwrite existing: the most fitting generators first", () => { + const biomes = [ + biome("coast", { generator: "gen/coast", parent: "Shoreline" }), + biome("shoreline", { generator: "gen/shore", parent: "Sea edge" }), + biome("sea-edge", { generator: "gen/sea" }), + biome("coastal-fjord", { generator: "gen/fjord" }), + biome("cove", { generator: "gen/cove", parent: "Coast" }), + ]; + const gens: RankedGenerator[] = [ + { path: "gen/aaa.md", name: "aaa", sourceMaps: [] }, + { path: "gen/coast.md", name: "coast", sourceMaps: ["bay"] }, + { path: "gen/cove.md", name: "cove", sourceMaps: [] }, + { path: "gen/fjord.md", name: "fjord", sourceMaps: [] }, + { path: "gen/mixed.md", name: "mixed", sourceMaps: ["bay", "north"] }, + { path: "gen/sea.md", name: "sea", sourceMaps: [] }, + { path: "gen/shore.md", name: "shore", sourceMaps: [] }, + { path: "gen/solo.md", name: "solo", sourceMaps: ["bay"] }, + { path: "gen/zzz.md", name: "zzz", sourceMaps: [] }, + ]; + const resolveGenerator = (l: string) => `${l}.md`; + + it("own biome, parents (nearest first), learned from the region, related, then the rest by name", () => { + const out = rankOverwriteTargets(gens, { region: "bay", biome: biomes[0], biomes, resolveGenerator }); + expect(out.map((c) => [c.name, c.reason])).toEqual([ + ["coast", "own"], + ["shore", "parent"], + ["sea", "parent"], + ["solo", "learned"], + ["mixed", "learned"], + ["cove", "related"], + ["aaa", "other"], + ["fjord", "other"], + ["zzz", "other"], + ]); + expect(out[0].why).toBe("this region's biome: Coast"); + }); + + it("every generator is listed once", () => { + const out = rankOverwriteTargets(gens, { region: "bay", biome: biomes[0], biomes, resolveGenerator }); + expect(new Set(out.map((c) => c.path)).size).toBe(gens.length); + }); + + it("a region with no biome: learned ones first, then by name", () => { + const out = rankOverwriteTargets(gens, { region: "bay", biomes, resolveGenerator }); + expect(out.slice(0, 3).map((c) => c.name)).toEqual(["coast", "solo", "mixed"]); + expect(out[3].reason).toBe("other"); + }); + + it("parents are cycle-safe", () => { + const loop = [biome("a", { parent: "b" }), biome("b", { parent: "a" })]; + expect(biomeAncestors(loop[0], loop).map((b) => b.id)).toEqual(["b"]); + }); + + it("related: blended neighbours, similar biomes, children and siblings, never itself or duplicates", () => { + const all = [biome("taiga"), biome("tundra"), biome("temperate-forest"), biome("pine", { parent: "taiga" }), biome("larch", { parent: "pine" }), biome("fir", { parent: "taiga" })]; + const rel = relatedBiomes(all[3], all, ["tundra"]).map((b) => b.id); + expect(rel).toEqual(["tundra", "larch", "fir"]); + }); +}); + +const PALETTE: TerrainColor[] = [ + { name: "Pine", color: "#204020", type: "forest" }, + { name: "Oak", color: "#306030", type: "forest" }, + { name: "Birch", color: "#507050", type: "forest" }, + { name: "Sea", color: "#2050a0", type: "water" }, + { name: "Hamlet", color: "#aa8844", type: "settlement" }, +]; + +describe("the new generator's biome inherits the region's biome basics", () => { + const source: BiomeNoteFields = { + id: "coast", label: "Coast", color: "#88aacc", blend: "wide", + mix: [{ type: "water", weight: 3 }, { type: "forest", weight: 1, minPatches: 2 }], + transitions: [{ next: "Alpine", between: "Valley" }], + landShare: 0.4, minIslands: 2, shore: true, + climate: { temperature: { lo: 0.4, hi: 0.6 }, moisture: { lo: 0.6, hi: 0.8 }, coastal: true, chance: 0.5 }, + generator: "gen/coast", + }; + const counts = new Map([["Pine", 12], ["Oak", 4], ["Sea", 30], ["Hamlet", 1]]); + + it("copies climate, islands, transitions, shore, blend, colour and the mix; parent is the source", () => { + const f = inheritedBiome(source, { label: "Rocky coast", generator: "gen/rocky", counts, palette: PALETTE }); + expect(f).toMatchObject({ + label: "Rocky coast", generator: "gen/rocky", parent: "Coast", color: "#88aacc", blend: "wide", + landShare: 0.4, minIslands: 2, shore: true, + mix: source.mix, transitions: source.transitions, climate: source.climate, + }); + // Copies, not the source's own objects. + expect(f.mix).not.toBe(source.mix); + expect(f.climate).not.toBe(source.climate); + expect(f.climate!.temperature).not.toBe(source.climate!.temperature); + }); + + it("takes the split within a type from the region (only types it uses more than one terrain of)", () => { + const f = inheritedBiome(source, { label: "x", generator: "g", counts, palette: PALETTE }); + expect(f.terrainWeights).toEqual([{ terrain: "Pine", weight: 12 }, { terrain: "Oak", weight: 4 }]); + }); + + it("without a source biome: the mix is what the region shows (no settlements), no parent", () => { + const f = inheritedBiome(undefined, { label: "x", generator: "g", counts, palette: PALETTE }); + expect(f.mix).toEqual([{ type: "water", weight: 30 }, { type: "forest", weight: 16 }]); + expect(f.parent).toBeUndefined(); + expect(f.climate).toBeUndefined(); + expect(mixFromTerrain(new Map([["Hamlet", 3]]), PALETTE)).toEqual([]); + expect(terrainWeightsFromTerrain(counts, PALETTE, ["water"])).toEqual([]); + }); +}); + +describe("biome Terrain weights: different forests in different ratios", () => { + it("splits a type's share by the weights; unlisted terrains count 1; 0 leaves one out", () => { + const p = profileFromMix("f", [{ type: "forest", weight: 1 }], PALETTE, [{ terrain: "pine", weight: 3 }, { terrain: "Birch", weight: 0 }]); + const forest = p.names.get("forest")!; + expect(forest.get("Pine")).toBeCloseTo(0.75); + expect(forest.get("Oak")).toBeCloseTo(0.25); + expect(forest.has("Birch")).toBe(false); + expect(p.types.get("forest")).toBe(1); + }); + + it("no weights: an even split, as before; all zero: even too (the type isn't lost)", () => { + expect([...withinTypeWeights(["A", "B"], undefined).values()]).toEqual([0.5, 0.5]); + expect([...withinTypeWeights(["A", "B"], [{ terrain: "a", weight: 0 }, { terrain: "b", weight: 0 }]).values()]).toEqual([0.5, 0.5]); + }); + + it("profileFromFields uses the note's weights", () => { + const p = profileFromFields({ ...biome("woods"), terrainWeights: [{ terrain: "Oak", weight: 2 }] }, PALETTE); + expect(p.names.get("forest")!.get("Oak")).toBeCloseTo(0.5); + }); + + it("reads and writes the table and `parent`, forgivingly", () => { + const text = [ + "---", "hexmaker-biome: 1", "id: woods", "label: Woods", "parent: \"[[Taiga]]\"", "---", "", + "## Mix", "", "| Type | Weight |", "| --- | ---: |", "| forest | 10 |", "", + "## Terrain weights", "", "| Terrain | Weight |", "| --- | --- |", "| [[Pine]] | 60% |", "| Oak | 40 |", "| oak | 5 |", "| Birch | lots |", "", + ].join("\n"); + const { fields, problems } = parseBiomeNote(text, "Woods"); + expect(fields.parent).toBe("Taiga"); + expect(fields.terrainWeights).toEqual([{ terrain: "Pine", weight: 60 }, { terrain: "Oak", weight: 45 }]); + expect(problems).toEqual([{ where: "Terrain weights", text: "row 21: weight \"lots\" isn't a number" }]); + // Rewriting with the same fields leaves the note alone; a change rewrites the table. + expect(updateBiomeNote(buildBiomeNote(fields), fields)).toBe(buildBiomeNote(fields)); + const next = updateBiomeNote(text, { ...fields, terrainWeights: [{ terrain: "Pine", weight: 1 }] }); + expect(parseBiomeNote(next, "Woods").fields.terrainWeights).toEqual([{ terrain: "Pine", weight: 1 }]); + expect(next).toContain("parent: \"[[Taiga]]\""); + }); + + it("a note without weights gets no table", () => { + const f = biome("plain"); + expect(buildBiomeNote(f)).not.toContain("## Terrain weights"); + const note = buildBiomeNote(f); + expect(updateBiomeNote(note, { ...f, blend: "wide" })).not.toContain("## Terrain weights"); + }); +}); + +// ── glue: new / overwrite through makeRegionGenerator ───────────────────── + +function world() { + const vault = new MemVault({ + "world/generators/old-coast.md": "---\npalette: Woods\n---\n# old-coast\n\nHand notes that the backup must keep.\n", + }); + const region: MapData = { name: "bay", paletteName: "Woods", gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 0, y: 0 }, submapKind: "region", parent: { map: "ow", hex: "2_2" }, biome: { generator: "coast" } } as MapData; + const maps = [region]; + const hexes = new Map(); + for (let x = 0; x < 4; x++) for (let y = 0; y < 4; y++) hexes.set(`${x}_${y}`, { terrain: (x + y) % 3 === 0 ? "Sea" : x < 2 ? "Pine" : "Oak" }); + const biomes: BiomeNoteFields[] = [ + { id: "coast", label: "Coast", mix: [{ type: "water", weight: 2 }, { type: "forest", weight: 1 }], transitions: [], climate: { temperature: { lo: 0.2, hi: 0.4 } }, landShare: 0.5 }, + ]; + setBiomeSource(biomes); + setHexDataSource({ + isReady: () => true, + resolve: (p: string) => { + const m = /^world\/hexes\/([^/]+)\/(-?\d+_-?\d+)\.md$/.exec(p); + return m ? { map: m[1], key: m[2] } : null; + }, + get: (m: string, k: string) => (m === "bay" ? hexes.get(k) : undefined), + set: () => true, + } as never); + const plugin = { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker", version: "9.9.9" }, + settings: { worldFolder: "world", hexFolder: "world/hexes", hexOrientation: "flat", maps }, + getMap: (n: string) => maps.find((m) => m.name === n), + hexPath: (x: number, y: number, m: string) => `world/hexes/${m}/${x}_${y}.md`, + paths: { resolvedPathChains: () => [] }, + mapStore: { all: (m: string) => (m === "bay" ? hexes : new Map()), get: () => undefined }, + getMapPalette: () => PALETTE, + biomeStore: { + isReady: () => true, + list: () => biomes, + get: (n: string) => biomes.find((b) => b.id === biomeSlug(n) || biomeSlug(b.label) === biomeSlug(n)), + create: async (f: Omit) => { + const id = biomeSlug(f.label); + biomes.push({ ...f, id }); + return { id }; + }, + }, + }; + return { vault, plugin, biomes }; +} + +describe("makeRegionGenerator", () => { + afterEach(() => { + setHexDataSource(null); + setBiomeSource(undefined); + }); + + it("new: writes the generator and a biome that inherits the region's biome and uses it", async () => { + const { vault, plugin, biomes } = world(); + const r = await makeRegionGenerator(plugin as never, "bay", { kind: "new", name: "Rocky bay" }); + if ("error" in r) throw new Error(r.error); + expect(r.file.path).toBe("world/generators/rocky-bay.md"); + expect(vault.files.get(r.file.path)).toContain("source-map: bay"); + const made = biomes.find((b) => b.label === "Rocky bay")!; + expect(made).toMatchObject({ parent: "Coast", generator: "world/generators/rocky-bay", landShare: 0.5, climate: { temperature: { lo: 0.2, hi: 0.4 } } }); + expect(made.terrainWeights?.map((w) => w.terrain).sort()).toEqual(["Oak", "Pine"]); + expect(r.biome).toBe("Rocky bay"); + }); + + it("overwrite: backs the old note up word for word, then writes the learned generator over it", async () => { + const { vault, plugin } = world(); + const old = vault.files.get("world/generators/old-coast.md")!; + const r = await makeRegionGenerator(plugin as never, "bay", { kind: "overwrite", path: "world/generators/old-coast.md" }); + if ("error" in r) throw new Error(r.error); + expect(r.backup).toMatch(/^\.obsidian\/plugins\/hexmaker\/backups\/generators-\d{4}-\d{2}-\d{2}\/old-coast\.md$/); + expect(vault.files.get(r.backup!)).toBe(old); + expect(vault.files.get("world/generators/old-coast.md")).toContain("source-map: bay"); + // A second overwrite never writes over the first backup. + const r2 = await makeRegionGenerator(plugin as never, "bay", { kind: "overwrite", path: "world/generators/old-coast.md" }); + if ("error" in r2) throw new Error(r2.error); + expect(r2.backup).toMatch(/old-coast-2\.md$/); + }); + + it("overwrite of a generator a biome already uses keeps that biome (no new one)", async () => { + const { plugin, biomes } = world(); + biomes.push({ id: "old", label: "Old coast", mix: [{ type: "water", weight: 1 }], transitions: [], generator: "world/generators/old-coast" }); + const before = biomes.length; + const r = await makeRegionGenerator(plugin as never, "bay", { kind: "overwrite", path: "world/generators/old-coast.md" }); + if ("error" in r) throw new Error(r.error); + expect(r.biome).toBeUndefined(); + expect(biomes.length).toBe(before); + }); +}); From 9ec5b3267937b44582f1af9f6e3a467aca7d7f4b Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:45:05 -0400 Subject: [PATCH 289/558] test(callout): syncHexMapData split into src/maps/calloutSync.ts and tested end to end Applied, Play-locked, newer-map, stale-copy and not-in-palette cases on a small host with the real work-mode gate. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 64 ++---------------------- src/maps/calloutSync.ts | 85 +++++++++++++++++++++++++++++++ tests/calloutSync.test.ts | 102 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 194 insertions(+), 61 deletions(-) create mode 100644 src/maps/calloutSync.ts create mode 100644 tests/calloutSync.test.ts diff --git a/package.json b/package.json index 6d2e8fbe..beb5b7a2 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 7bf25a55..d02c2fa0 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -71,7 +71,7 @@ import { MapStore, withoutNotePaths } from "./maps/MapStore"; import { setModeMapLookup } from "./modeGate"; import { cellEdits, UndoBook } from "./undoBook"; import type { UndoItem } from "./hex-map/undoItems"; -import { lockedHint, workModeOf } from "./workMode"; +import { workModeOf } from "./workMode"; import { withMapLink } from "./maps/mapNote"; import { addLocationPatch, @@ -84,11 +84,11 @@ import { setRegionPatch, } from "./maps/submaps"; import type { RegionSettings } from "./types"; -import { mapDataLines, mapDataSyncMessage, planCalloutImport, setMapData, shownValues, type HexMapDataView } from "./hexMapData"; +import { mapDataLines, mapDataSyncMessage, setMapData, shownValues, type HexMapDataView } from "./hexMapData"; import { CalloutMemory } from "./maps/calloutMemory"; +import { syncHexMapData as syncHexMapDataWith, type CalloutSyncResult } from "./maps/calloutSync"; import { hexBiomeAt, overworldOf } from "./overworld/regionsVault"; import { BIOMES, biomeNoteOf } from "./overworld/biomes"; -import { sameName } from "./hexBodyFields"; import { hasRegionMapData, regionUse, renameRegionInStore, renamedTokenMap, setRegionMapData, type RegionMapDataView } from "./regionMapData"; import { ConfirmModal } from "./worldgen/ConfirmModal"; import { displayNameFor, mapLabel } from "./maps/mapTree"; @@ -1976,62 +1976,8 @@ export default class HexmakerPlugin extends Plugin { */ async syncHexMapData( mapName: string, x: number, y: number, opts: { insert?: boolean; quiet?: boolean } = {}, - ): Promise<{ wrote: boolean; applied: string[]; notApplied: string[]; unreadable: string[] }> { - const out = { wrote: false, applied: [] as string[], notApplied: [] as string[], unreadable: [] as string[] }; - const path = this.hexPath(x, y, mapName); - const file = this.app.vault.getAbstractFileByPath(path); - if (!(file instanceof TFile)) return out; - await this.calloutMemory.ready(); - // Read first: most notes need nothing, and a no-op process() still writes. - const current = await this.app.vault.read(file); - const now = () => shownValues(mapDataLines(this.hexMapDataView(mapName, x, y))); - const plan = planCalloutImport(current, this.calloutMemory.get(path), now()); - // No callout and none to add: nothing to do. - if (!plan && !opts.insert) return out; - if (plan) { - out.notApplied.push(...plan.notApplied); - out.unreadable.push(...plan.unreadable); - const edits = Object.entries(plan.apply) as [keyof typeof plan.apply, string | null][]; - if (edits.length) { - await this.undoableEdit(mapName, async () => { - const key = `${x}_${y}`; - for (const [field, value] of edits) { - const shown = `${field[0].toUpperCase()}${field.slice(1)}: ${value ?? "—"}`; - if (field === "name") { - await this.setHexName(mapName, x, y, value ?? ""); - out.applied.push(shown); - } else if (field === "terrain") { - // A terrain must be one the map's palette has (matched ignoring case). - const terrain = value === null ? null : this.getMapPalette(mapName).find((t) => sameName(t.name, value))?.name; - if (terrain === undefined) { out.notApplied.push(`${shown} (not in this map's palette)`); continue; } - if (!this.mapStore.set(mapName, key, { terrain }, "paint-terrain")) { out.notApplied.push(`${shown} (${lockedHint("paint-terrain")})`); continue; } - await this.syncHexEncounterTableLink(path, terrain); - out.applied.push(shown); - } else { - if (!this.mapStore.set(mapName, key, { region: value }, "paint-region-area")) { out.notApplied.push(`${shown} (${lockedHint("paint-region-area")})`); continue; } - out.applied.push(shown); - } - } - }); - } - } - const view = this.hexMapDataView(mapName, x, y); - const notes = [...out.notApplied.map((s) => `Not applied: ${s}`), ...out.unreadable.map((s) => `Not read: ${s}`)]; - const latest = await this.app.vault.read(file); - if (setMapData(latest, view, opts.insert, notes) !== latest) { - await this.app.vault.process(file, (content) => { - const next = setMapData(content, view, opts.insert, notes); - out.wrote = next !== content; - return next; - }); - } - // Remember what the callout shows now, so the next edit is told from a stale copy. - if (plan || opts.insert) this.calloutMemory.set(path, now()); - if (!opts.quiet) { - const msg = mapDataSyncMessage(`${this.mapLabel(mapName)} ${x}, ${y}`, out); - if (msg) new Notice(msg, 8000); - } - return out; + ): Promise { + return syncHexMapDataWith(this, mapName, x, y, opts); } /** Add (or update) the Map data callout in every hex note of a map. Returns how many notes changed. */ diff --git a/src/maps/calloutSync.ts b/src/maps/calloutSync.ts new file mode 100644 index 00000000..848cbdd1 --- /dev/null +++ b/src/maps/calloutSync.ts @@ -0,0 +1,85 @@ +/** + * Phase 2 of the hex-note Map data callout (src/hexMapData.ts): hand edits + * to Terrain, Region or Name go to the map, then the callout is rewritten. + * Split from HexmakerPlugin so it can be tested on a small host. + */ +import { Notice, TFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { mapDataLines, mapDataSyncMessage, planCalloutImport, setMapData, shownValues } from "../hexMapData"; +import { lockedHint } from "../workMode"; +import { sameName } from "../hexBodyFields"; + +/** What syncHexMapData needs from the plugin. */ +export type CalloutSyncHost = Pick; + +export interface CalloutSyncResult { + wrote: boolean; + /** Edits put on the map ("Terrain: swamp"). */ + applied: string[]; + /** Edits that weren't, each with why. */ + notApplied: string[]; + /** Callout lines that couldn't be read. */ + unreadable: string[]; +} + +/** See HexmakerPlugin.syncHexMapData. */ +export async function syncHexMapData( + host: CalloutSyncHost, mapName: string, x: number, y: number, opts: { insert?: boolean; quiet?: boolean } = {}, +): Promise { + const out = { wrote: false, applied: [] as string[], notApplied: [] as string[], unreadable: [] as string[] }; + const path = host.hexPath(x, y, mapName); + const file = host.app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) return out; + await host.calloutMemory.ready(); + // Read first: most notes need nothing, and a no-op process() still writes. + const current = await host.app.vault.read(file); + const now = () => shownValues(mapDataLines(host.hexMapDataView(mapName, x, y))); + const plan = planCalloutImport(current, host.calloutMemory.get(path), now()); + // No callout and none to add: nothing to do. + if (!plan && !opts.insert) return out; + if (plan) { + out.notApplied.push(...plan.notApplied); + out.unreadable.push(...plan.unreadable); + const edits = Object.entries(plan.apply) as [keyof typeof plan.apply, string | null][]; + if (edits.length) { + await host.undoableEdit(mapName, async () => { + const key = `${x}_${y}`; + for (const [field, value] of edits) { + const shown = `${field[0].toUpperCase()}${field.slice(1)}: ${value ?? "—"}`; + if (field === "name") { + await host.setHexName(mapName, x, y, value ?? ""); + out.applied.push(shown); + } else if (field === "terrain") { + // A terrain must be one the map's palette has (matched ignoring case). + const terrain = value === null ? null : host.getMapPalette(mapName).find((t) => sameName(t.name, value))?.name; + if (terrain === undefined) { out.notApplied.push(`${shown} (not in this map's palette)`); continue; } + if (!host.mapStore.set(mapName, key, { terrain }, "paint-terrain")) { out.notApplied.push(`${shown} (${lockedHint("paint-terrain")})`); continue; } + await host.syncHexEncounterTableLink(path, terrain); + out.applied.push(shown); + } else { + if (!host.mapStore.set(mapName, key, { region: value }, "paint-region-area")) { out.notApplied.push(`${shown} (${lockedHint("paint-region-area")})`); continue; } + out.applied.push(shown); + } + } + }); + } + } + const view = host.hexMapDataView(mapName, x, y); + const notes = [...out.notApplied.map((s) => `Not applied: ${s}`), ...out.unreadable.map((s) => `Not read: ${s}`)]; + const latest = await host.app.vault.read(file); + if (setMapData(latest, view, opts.insert, notes) !== latest) { + await host.app.vault.process(file, (content) => { + const next = setMapData(content, view, opts.insert, notes); + out.wrote = next !== content; + return next; + }); + } + // Remember what the callout shows now, so the next edit is told from a stale copy. + if (plan || opts.insert) host.calloutMemory.set(path, now()); + if (!opts.quiet) { + const msg = mapDataSyncMessage(`${host.mapLabel(mapName)} ${x}, ${y}`, out); + if (msg) new Notice(msg, 8000); + } + return out; +} diff --git a/tests/calloutSync.test.ts b/tests/calloutSync.test.ts new file mode 100644 index 00000000..7647c94e --- /dev/null +++ b/tests/calloutSync.test.ts @@ -0,0 +1,102 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { TFile } from "obsidian"; +import { syncHexMapData } from "../src/maps/calloutSync"; +import { mapDataLines, shownValues, type HexMapDataView } from "../src/hexMapData"; +import { canDo, setModeMapLookup } from "../src/modeGate"; +import type { ModeAction } from "../src/workMode"; +import type { HexData } from "../src/maps/mapNote"; + +/** + * syncHexMapData end to end on a fake plugin: the real method, a vault of + * one hex note, a map store of plain maps, and the work-mode gate. + */ +function setup(opts: { mode?: string; hex?: HexData; note: (lines: string[]) => string; shown?: HexData }) { + const path = "hexes/coast/3_4.md"; + const file = Object.assign(Object.create(TFile.prototype) as TFile, { path, name: "3_4.md", basename: "3_4", extension: "md" }); + const hexes = new Map([["3_4", { ...(opts.hex ?? {}) }]]); + const memory = new Map>(); + const view = (h: HexData): HexMapDataView => ({ map: "coast", mapLabel: "Coast", x: 3, y: 4, terrain: h.terrain, region: h.region, name: h.name }); + if (opts.shown) memory.set(path, shownValues(mapDataLines(view(opts.shown)))); + let content = opts.note(mapDataLines(view(opts.shown ?? opts.hex ?? {}))); + const map = { name: "coast", workMode: opts.mode ?? "build" }; + setModeMapLookup((n) => (n === "coast" ? map : undefined)); + const encounterSyncs: (string | null)[] = []; + const fake = { + app: { + vault: { + getAbstractFileByPath: (p: string) => (p === path ? file : null), + read: async () => content, + process: async (_f: TFile, fn: (c: string) => string) => { content = fn(content); return content; }, + }, + }, + hexPath: () => path, + mapLabel: () => "Coast", + calloutMemory: { ready: async () => {}, get: (p: string) => memory.get(p), set: (p: string, v: Record) => memory.set(p, v) }, + hexMapDataView: (_m: string, _x: number, _y: number) => view(hexes.get("3_4") ?? {}), + getMapPalette: () => [{ name: "forest", color: "#228833" }, { name: "Swamp", color: "#556633" }], + undoableEdit: async (_m: string, fn: () => unknown) => fn(), + setHexName: async (_m: string, _x: number, _y: number, name: string) => { hexes.set("3_4", { ...hexes.get("3_4"), name: name || undefined }); }, + syncHexEncounterTableLink: async (_p: string, t: string | null) => { encounterSyncs.push(t); }, + mapStore: { + set: (m: string, key: string, patch: Partial, action?: string) => { + if (action && !canDo(m, action as ModeAction)) return false; // the real work-mode gate + const h = { ...(hexes.get(key) ?? {}) } as Record; + for (const [k, v] of Object.entries(patch)) if (v === null || v === undefined) delete h[k]; else h[k] = v; + hexes.set(key, h as HexData); + return true; + }, + }, + }; + const sync = () => syncHexMapData(fake as never, "coast", 3, 4, { quiet: true }); + return { sync, hexes, memory, content: () => content, encounterSyncs }; +} + +const note = (lines: string[]) => `# Hex 3, 4\n\n${lines.join("\n")}\n\nText.\n`; + +describe("Map data callout phase 2, end to end (syncHexMapData)", () => { + it("puts a hand-edited terrain on the map (palette case), then shows it", async () => { + const s = setup({ hex: { terrain: "forest" }, shown: { terrain: "forest" }, note: (l) => note(l).replace("> Terrain: forest", "> Terrain: swamp") }); + const r = await s.sync(); + expect(r.applied).toEqual(["Terrain: swamp"]); + expect(s.hexes.get("3_4")?.terrain).toBe("Swamp"); + expect(s.encounterSyncs).toEqual(["Swamp"]); + expect(s.content()).toContain("> Terrain: Swamp"); + expect(s.memory.get("hexes/coast/3_4.md")?.terrain).toBe("Swamp"); + // A second pass finds nothing to do. + expect(await s.sync()).toMatchObject({ wrote: false, applied: [], notApplied: [] }); + }); + + it("in Play, a locked field is reported and kept as typed; a name still goes through", async () => { + const s = setup({ mode: "play", hex: { terrain: "forest", name: "Oak" }, shown: { terrain: "forest", name: "Oak" }, + note: (l) => note(l).replace("> Terrain: forest", "> Terrain: swamp").replace("> Name: Oak", "> Name: Great Oak") }); + const r = await s.sync(); + expect(s.hexes.get("3_4")).toEqual({ terrain: "forest", name: "Great Oak" }); + expect(r.notApplied).toEqual(["Terrain: swamp (Switch to Build to paint terrain.)"]); + expect(s.content()).toContain("> Terrain: forest"); + expect(s.content()).toContain("> Not applied: Terrain: swamp (Switch to Build to paint terrain.)"); + }); + + it("never writes over a newer map value", async () => { + const s = setup({ hex: { terrain: "hills" }, shown: { terrain: "forest" }, note: (l) => note(l).replace("> Terrain: forest", "> Terrain: swamp") }); + const r = await s.sync(); + expect(s.hexes.get("3_4")?.terrain).toBe("hills"); + expect(r.notApplied).toEqual(["Terrain: swamp (the map has changed it to hills since)"]); + expect(s.content()).toContain("> Terrain: hills"); + }); + + it("refreshes a stale copy without touching the map", async () => { + const s = setup({ hex: { terrain: "hills" }, shown: { terrain: "forest" }, note }); + const r = await s.sync(); + expect(r).toMatchObject({ wrote: true, applied: [], notApplied: [] }); + expect(s.hexes.get("3_4")?.terrain).toBe("hills"); + expect(s.content()).toContain("> Terrain: hills"); + }); + + it("reports a terrain the palette doesn't have", async () => { + const s = setup({ hex: { terrain: "forest" }, shown: { terrain: "forest" }, note: (l) => note(l).replace("> Terrain: forest", "> Terrain: lava") }); + const r = await s.sync(); + expect(s.hexes.get("3_4")?.terrain).toBe("forest"); + expect(r.notApplied).toEqual(["Terrain: lava (not in this map's palette)"]); + }); +}); From 83b9edb77b0cf4fa8220ab1e6066940da8d5115a Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:56:13 -0400 Subject: [PATCH 290/558] fix(palettes): treat a missing palette note as deleted only on a positive record Coordinator guard on SM-DEL: an empty palettes folder at startup no longer drops the palettes. settings.paletteNotes records the folder and each palette's note path whenever notes are bound, written or trashed. At startup a palette is dropped only when it is recorded, the record is for the current folder, and that note is gone; data.json's copy is backed up first (nothing dropped if the backup fails). Dropped palettes are stashed, so a note that arrives later (sync) puts the same palette back in its place. No record (upgrade from data.json-only palettes), a different folder, or a runtime folder change: notes are written from data.json as before. Tests: upgrade, late sync, moved folder, runtime folder change, deliberate deletion with backup, unreadable note. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/palettes/PaletteStore.ts | 96 +++++++++++++++++++++++------- src/types.ts | 7 +++ tests/palettes.test.ts | 111 ++++++++++++++++++++++++++++++----- 4 files changed, 180 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index a51c302a..93918d88 100644 --- a/README.md +++ b/README.md @@ -351,7 +351,7 @@ Open **Settings → Hexmap World Creator** to configure: | **Biome pools folder** | Folder holding the biome pool notes used by Generate overworld (default `{world folder}/biome-pools`). | | **World types folder** | Folder holding the world types tables used by the space generators (default `{world folder}/world-types`). | | **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | -| **Add default palettes** | Shown when Expanded or Limited isn't in the list: puts them back. Palettes you delete (in settings or by deleting their notes) stay deleted; an empty palette list stays empty until you add one. | +| **Add default palettes** | Shown when Expanded or Limited isn't in the list: puts them back. Palettes you delete (in settings, or by deleting a palette note the plugin wrote) stay deleted, with a copy in the plugin folder's `backups/`; an empty palette list stays empty until you add one. A palette whose note isn't there yet for another reason (an upgrade, a new palettes folder, a note sync hasn't delivered) is kept: its note is written, or the palette comes back when the note arrives. | | **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index cfa5dbae..261e88b0 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -203,6 +203,8 @@ export class PaletteStore { private lastContent = new Map(); private ready = false; private attachedFolder = ""; + /** Palettes dropped at startup as deleted, by lower-cased name and note path: a note that turns up later (sync) brings its palette back. */ + private stash = new Map(); private reattachTimer: number | undefined; private queue: Promise = Promise.resolve(); /** Palette notes whose terrain table doesn't parse: never rewritten until @@ -327,11 +329,22 @@ export class PaletteStore { for (const f of this.paletteFiles()) { if (parsePaletteNote(await this.plugin.app.vault.cachedRead(f))) existing.push(f); } - // (Only when the folder holds no notes at all: a note that doesn't read is never taken as deleted.) - if (startup && settings.palettesMigrated && this.paletteFiles().length === 0 && settings.terrainPalettes.length) { - await this.dropDeletedPalettes(); - dirty = true; - } else if (!settings.palettesMigrated || existing.length === 0) { + // Deleted palettes stay deleted (SM-DEL), but only on a positive record: + // a palette whose note this plugin wrote or read in this same folder, + // and that note is gone now. Anything without a record (an upgrade from + // data.json-only palettes, a new or moved folder) is written as before. + const rec = settings.paletteNotes; + if (startup && rec && rec.folder === this.folder()) { + const gone = settings.terrainPalettes.filter((p) => { + const path = rec.notes[p.name]; + return !!path && !this.plugin.app.vault.getAbstractFileByPath(path); + }); + if (gone.length) { + await this.dropDeletedPalettes(gone); + dirty = true; + } + } + if (!settings.palettesMigrated || existing.length === 0) { const paletteNames = new Set(existing.map((f) => f.basename.toLowerCase())); for (const pal of settings.terrainPalettes) { const safe = paletteFileName(pal.name); @@ -426,30 +439,55 @@ export class PaletteStore { settings.pathTypesExplicit = true; dirty = true; } + if (this.recordNotes()) dirty = true; if (dirty) await this.persist(); } /** - * Every palette note was deleted while Obsidian was closed (SM-DEL): - * the palettes go too, never re-created from data.json's copy. That copy - * is backed up first, and a notice says how to get the defaults back. - * Maps keep their palette name, so a palette note put back reattaches. + * Bring settings.paletteNotes up to date with the notes bound now (the + * positive record deletion detection needs). True when it changed. + */ + private recordNotes(): boolean { + const notes: Record = {}; + for (const pal of this.plugin.settings.terrainPalettes) { + const path = this.boundPath.get(pal); + if (path && this.knownPaths.has(path)) notes[pal.name] = path; + } + const next = { folder: this.attachedFolder, notes }; + if (JSON.stringify(next) === JSON.stringify(this.plugin.settings.paletteNotes)) return false; + this.plugin.settings.paletteNotes = next; + return true; + } + + /** + * Palettes whose notes (recorded in settings.paletteNotes) were deleted + * while Obsidian was closed (SM-DEL): they go too, never re-created from + * data.json's copy. That copy is backed up first (if the backup fails, + * nothing is dropped). A note that turns up later at the same path or + * name (sync delivering it late) brings its palette back (onModify). + * Maps keep their palette name, so they reattach. */ - private async dropDeletedPalettes(): Promise { + private async dropDeletedPalettes(gone: TerrainPalette[]): Promise { const settings = this.plugin.settings; - const names = settings.terrainPalettes.map((p) => p.name); let where = ""; try { const dir = `${this.plugin.manifest.dir}/backups/palettes-${new Date().toISOString().slice(0, 10)}`; - where = await writeJsonBackup(this.plugin.app.vault.adapter, dir, "deleted-palettes", JSON.stringify({ savedAt: new Date().toISOString(), palettes: settings.terrainPalettes })); + where = await writeJsonBackup(this.plugin.app.vault.adapter, dir, "deleted-palettes", JSON.stringify({ savedAt: new Date().toISOString(), palettes: gone })); } catch (e) { - console.error("Hexmap World Creator: couldn't back up the deleted palettes", e); + console.error("Hexmap World Creator: couldn't back up the deleted palettes; they were kept", e); + return; + } + const rec = settings.paletteNotes; + for (const pal of gone) { + const index = settings.terrainPalettes.indexOf(pal); + this.stash.set(pal.name.toLowerCase(), { pal, index }); + const path = rec?.notes[pal.name]; + if (path) this.stash.set(path, { pal, index }); } - settings.terrainPalettes = []; + settings.terrainPalettes = settings.terrainPalettes.filter((p) => !gone.includes(p)); new Notice( - `Hexmap World Creator: no palette notes in "${this.folder()}", so there are no terrain palettes now (${names.join(", ")} were deleted).` + - (where ? ` A copy is in ${where}.` : "") + - " Add palettes, or the defaults, in Settings → Terrain palettes.", + `Hexmap World Creator: the palette note${gone.length === 1 ? "" : "s"} of ${gone.map((p) => p.name).join(", ")} ${gone.length === 1 ? "was" : "were"} deleted, so ${gone.length === 1 ? "that palette is" : "those palettes are"} gone too. A copy is in ${where}.` + + (settings.terrainPalettes.length ? "" : " Add palettes, or the defaults, in Settings → Terrain palettes."), 15000, ); } @@ -669,7 +707,12 @@ export class PaletteStore { if (file instanceof TFile) await fileManager.trashFile(file); } - if (renamedInMemory) await this.persist(); + if (renamedInMemory) { + this.recordNotes(); + await this.persist(); + } + // Notes written or trashed: keep the record deletion detection relies on. + else if (this.recordNotes()) await this.plugin.saveData(this.plugin.settings); } } @@ -760,13 +803,25 @@ export class PaletteStore { changed = true; } } else { - pal = { name: file.basename, terrains }; - this.plugin.settings.terrainPalettes.push(pal); + // A palette dropped at startup whose note arrived late (sync): back in its old place. + const back = this.stash.get(file.path) ?? this.stash.get(file.basename.toLowerCase()); + const list = this.plugin.settings.terrainPalettes; + if (back) { + for (const [k, v] of [...this.stash]) if (v.pal === back.pal) this.stash.delete(k); + pal = back.pal; + if (pal.name !== file.basename) pal.name = file.basename; + pal.terrains.splice(0, pal.terrains.length, ...terrains); + list.splice(Math.min(back.index, list.length), 0, pal); + } else { + pal = { name: file.basename, terrains }; + list.push(pal); + } changed = true; } if (applyNoteMeta(pal, content)) changed = true; if (fillPalettePathTypes([pal], this.plugin.settings.pathTypes)) changed = true; this.bind(pal, file.path, content); + if (this.recordNotes()) changed = true; if (changed) await this.persist(); // The hand edit may have changed what the derived cells should say // (a new type, a terrain added without a type): refresh them now, or @@ -790,6 +845,7 @@ export class PaletteStore { // Maps keep their paletteName so they reattach if the note comes back // (e.g. restored from trash, or delivered late by sync). list.splice(list.indexOf(pal), 1); + this.recordNotes(); await this.persist(); }); } diff --git a/src/types.ts b/src/types.ts index d24fe6fd..5078a356 100644 --- a/src/types.ts +++ b/src/types.ts @@ -359,6 +359,13 @@ export interface HexmakerPluginSettings { worldTypesSeeded?: boolean; /** True once settings-only palettes were written out as notes. */ palettesMigrated: boolean; + /** + * The palette notes the plugin has written or read (SM-DEL): the folder, + * and each palette's note path by palette name. A palette counts as + * deleted at startup only when it's recorded here, in the same folder, + * and its note is gone; without a record its note is written again. + */ + paletteNotes?: { folder: string; notes: Record }; /** * True once every path type's behaviour (avoid impassable, auto-route, * routing) was written out explicitly (PA5). Before that, blank cells in diff --git a/tests/palettes.test.ts b/tests/palettes.test.ts index 471cd19b..df1a19b3 100644 --- a/tests/palettes.test.ts +++ b/tests/palettes.test.ts @@ -439,18 +439,6 @@ describe("PaletteStore", () => { expect(h.vault.files.has("world/palettes/Limited.md")).toBe(false); }); - it("palette notes deleted while closed stay deleted: dropped (backed up), not re-written", async () => { - await h.store.init(); - h.vault.files.clear(); - const fresh = makeHarness({ palettesMigrated: true }); - fresh.settings.terrainPalettes = h.settings.terrainPalettes; - await fresh.store.init(); - expect([...fresh.vault.files.keys()]).toEqual([]); - expect(fresh.settings.terrainPalettes).toEqual([]); - // data.json's copy is kept in a backup before it's dropped. - expect([...fresh.vault.raw.keys()].some((p) => p.includes("/backups/palettes-") && p.includes("/deleted-palettes"))).toBe(true); - }); - it("an emptied palette list stays empty on load (no notes written)", async () => { const fresh = makeHarness({ palettesMigrated: true }); fresh.settings.terrainPalettes = []; @@ -462,16 +450,109 @@ describe("PaletteStore", () => { it("a palette note that doesn't read is never taken as deleted", async () => { await h.store.init(); - h.vault.files.clear(); h.vault.files.set("world/palettes/Limited.md", "no table here"); - const fresh = makeHarness({ palettesMigrated: true }); + const fresh = makeHarness({ palettesMigrated: true, paletteNotes: h.settings.paletteNotes }); for (const [p, c] of h.vault.files) fresh.vault.files.set(p, c); fresh.settings.terrainPalettes = h.settings.terrainPalettes; await fresh.store.init(); - expect(fresh.settings.terrainPalettes.length).toBe(2); + // Not a deletion: no backup, nothing dropped as deleted, the note left as written. + expect([...fresh.vault.raw.keys()].some((p) => p.includes("/deleted-palettes"))).toBe(false); expect(fresh.vault.files.get("world/palettes/Limited.md")).toBe("no table here"); }); + // SM-DEL guard: absence is deletion only with a record that the plugin wrote the note. + describe("deleted palette notes: only on a positive record", () => { + const backups = (hh: ReturnType) => [...hh.vault.raw.keys()].filter((p) => p.includes("/backups/palettes-") && p.includes("/deleted-palettes")); + + it("records each palette's note path (and the folder) once the notes are written", async () => { + await h.store.init(); + expect(h.settings.paletteNotes).toEqual({ folder: "world/palettes", notes: { Limited: "world/palettes/Limited.md", Expanded: "world/palettes/Expanded.md" } }); + }); + + it("upgrade from data.json-only palettes (no record, no notes): keeps them and writes the notes", async () => { + for (const migrated of [false, true]) { + const fresh = makeHarness({ palettesMigrated: migrated }); + await fresh.store.init(); + expect(fresh.settings.terrainPalettes.map((p) => p.name).sort()).toEqual(["Expanded", "Limited"]); + expect([...fresh.vault.files.keys()].sort()).toEqual(["world/palettes/Expanded.md", "world/palettes/Limited.md"]); + expect(backups(fresh)).toEqual([]); + } + }); + + it("a deliberate deletion after the plugin wrote the notes removes them, with a backup", async () => { + await h.store.init(); + const limited = h.vault.files.get("world/palettes/Limited.md")!; + h.vault.files.delete("world/palettes/Limited.md"); // deleted while Obsidian was closed + const fresh = makeHarness({ palettesMigrated: true, paletteNotes: h.settings.paletteNotes }); + for (const [p, c] of h.vault.files) fresh.vault.files.set(p, c); + fresh.vault.folders.add("world").add("world/palettes"); + fresh.settings.terrainPalettes = h.settings.terrainPalettes; + await fresh.store.init(); + await fresh.store.sync(); + expect(fresh.settings.terrainPalettes.map((p) => p.name)).toEqual(["Expanded"]); + expect(fresh.vault.files.has("world/palettes/Limited.md")).toBe(false); + expect(backups(fresh)).toHaveLength(1); + expect(fresh.settings.paletteNotes!.notes).toEqual({ Expanded: "world/palettes/Expanded.md" }); + expect(limited).toContain("|"); + }); + + it("every recorded note deleted: the list ends up empty, nothing re-written", async () => { + await h.store.init(); + h.vault.files.clear(); + const fresh = makeHarness({ palettesMigrated: true, paletteNotes: h.settings.paletteNotes }); + fresh.settings.terrainPalettes = h.settings.terrainPalettes; + await fresh.store.init(); + await fresh.store.sync(); + expect(fresh.settings.terrainPalettes).toEqual([]); + expect([...fresh.vault.files.keys()]).toEqual([]); + expect(backups(fresh)).toHaveLength(1); + }); + + it("synced vault, notes arriving late: each palette comes back in its place when its note is created", async () => { + await h.store.init(); + const notes = new Map(h.vault.files); + const fresh = makeHarness({ palettesMigrated: true, paletteNotes: h.settings.paletteNotes }); + fresh.settings.terrainPalettes = h.settings.terrainPalettes; + const before = fresh.settings.terrainPalettes.map((p) => p.name); + const objects = [...fresh.settings.terrainPalettes]; + await fresh.store.init(); // data.json arrived, the notes haven't yet + for (const [p, c] of notes) { + fresh.vault.files.set(p, c); + fresh.store.onModify(fresh.file(p)); // vault "create" event + } + await fresh.store.sync(); + expect(fresh.settings.terrainPalettes.map((p) => p.name)).toEqual(before); + expect(fresh.settings.terrainPalettes[0]).toBe(objects[0]); // same objects, open views keep them + // Nothing was written over the arriving notes. + for (const [p, c] of notes) expect(fresh.vault.files.get(p)).toBe(c); + }); + + it("a palettes folder that doesn't match the record (moved, renamed setting): palettes kept and written there", async () => { + await h.store.init(); + const fresh = makeHarness({ palettesMigrated: true, paletteNotes: h.settings.paletteNotes, palettesFolder: "elsewhere/pals" }); + fresh.settings.terrainPalettes = h.settings.terrainPalettes; + await fresh.store.init(); + expect(fresh.settings.terrainPalettes.map((p) => p.name).sort()).toEqual(["Expanded", "Limited"]); + expect([...fresh.vault.files.keys()].sort()).toEqual(["elsewhere/pals/Expanded.md", "elsewhere/pals/Limited.md"]); + expect(backups(fresh)).toEqual([]); + expect(fresh.settings.paletteNotes!.folder).toBe("elsewhere/pals"); + }); + + it("changing the folder setting to a new empty folder while running: palettes kept and written there", async () => { + (globalThis as Record).window ??= globalThis; // the re-attach timer + await h.store.init(); + h.settings.palettesFolder = "new/pals"; + await h.store.sync(); // schedules the re-attach once typing stops + await new Promise((r) => setTimeout(r, 1700)); + await h.store.sync(); + expect(h.settings.terrainPalettes.map((p) => p.name).sort()).toEqual(["Expanded", "Limited"]); + expect(h.vault.files.has("new/pals/Expanded.md")).toBe(true); + expect(h.vault.files.has("new/pals/Limited.md")).toBe(true); + expect(h.settings.paletteNotes!.folder).toBe("new/pals"); + expect(backups(h)).toEqual([]); + }); + }); + it("round-trips child-palette between notes and palettes", async () => { h.settings.terrainPalettes[0].childPalette = "Expanded"; await h.store.init(); From d552c494f0b1a94355779f852213fe086fe4e7db Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 08:59:28 -0400 Subject: [PATCH 291/558] feat(path-tool): forks stay attached to their main line Owner decision 2026-10-11. New pure module src/paths/forks.ts: - keepForksAttached: after a branch is re-routed, forks (and joins) that were on its old route follow it - onto the dragged point's new hex when they left from it, else the nearest hex of the new route. - splitOffOrphans: when a branch goes, forks hanging off it (with their own forks) become paths of their own; if the main line went and nothing else is left, the first keeps the path's name and notes. Wired into the path tool's drag preview, anchor delete and Delete fork/main line; each stays one commit (one undo step). Notice names forks that split off. tests/pathForks.test.ts (10 tests). Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- package.json | 4 +- src/hex-map/help.md | 2 +- src/hex-map/pathTool.ts | 75 +++++++++++++++--- src/paths/forks.ts | 172 ++++++++++++++++++++++++++++++++++++++++ tests/pathForks.test.ts | 123 ++++++++++++++++++++++++++++ 6 files changed, 363 insertions(+), 15 deletions(-) create mode 100644 src/paths/forks.ts create mode 100644 tests/pathForks.test.ts diff --git a/README.md b/README.md index b024fc94..152c061c 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,7 @@ Click the **pencil** icon on the right edge of the map to open the drawing tools - **Meander** — gentle curve through the midpoints between hex centres (good for rivers). - **Edge** — traces strictly along the hex polygon boundary lines between hexes. -**Editing paths:** there is no separate edit mode. While the path tool is on a type, every path of that type shows its points as handles: drag a point to move it, drag the line to add a point there and move it, right-click a point to delete it (a branch or path left with one point goes too, with a notice; undo brings it back), click an end to carry on from it, and click empty ground to start a new path. Click a line to select that path, and click it again to start a fork. Right-click a line (or Shift+right-click a point) for the path menu: Split here, Delete this fork, Delete path, Rename…, Change type…, Reverse. Paths of other types are left alone while you work: a click on one is a click on the ground, and hovering it names the type to switch to (right-click it for **Switch to** that type). Each drag or delete is one undo step, and editing paths needs Build or God mode. The bar at the top of the map lists these actions. +**Editing paths:** there is no separate edit mode. While the path tool is on a type, every path of that type shows its points as handles: drag a point to move it, drag the line to add a point there and move it, right-click a point to delete it (a branch or path left with one point goes too, with a notice; undo brings it back), click an end to carry on from it, and click empty ground to start a new path. Click a line to select that path, and click it again to start a fork. Forks stay attached: moving the point a fork leaves from takes the fork along, deleting it moves the fork to the nearest point left on the line, and if the main line goes its forks become paths of their own (still one undo step). Right-click a line (or Shift+right-click a point) for the path menu: Split here, Delete this fork, Delete path, Rename…, Change type…, Reverse. Paths of other types are left alone while you work: a click on one is a click on the ground, and hovering it names the type to switch to (right-click it for **Switch to** that type). Each drag or delete is one undo step, and editing paths needs Build or God mode. The bar at the top of the map lists these actions. **Auto-route:** the picker (and the bar at the top of the map while drawing) switches between **Hex by hex** and **Auto-route**: in the picker, choose how to draw (step 1), then the path type (step 2). With Auto-route, click a start hex and then an end hex: the path takes the shortest way inside the map, around impassable terrain, keeping close to the straight line between the two, and then carries on from that end, so you can route leg by leg. Path types whose **Auto-route** option is *winding* (River, by default) wind gently instead of running straight; *direct* ones keep to the line. It's an option on each type, never a matter of its name. A route continues an existing path only when its start is that path's end; starting anywhere else (such as the first hex of another road) makes a new path, and existing paths are never changed. The result is an ordinary path: drag its points to reshape it, right-click a point to remove it, or click an end to extend it. diff --git a/package.json b/package.json index c1768281..dfb7edd8 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/pathForks.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/pathForks.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/hex-map/help.md b/src/hex-map/help.md index fe5d8624..464975a3 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -73,7 +73,7 @@ There's no separate edit mode. While the tool is on a type (say Road), every Roa - **Reshape the line:** drag the line itself: a new point is added where you grabbed it, and moves with the pointer. - **Delete a point:** right-click it, or hover it and press **Backspace**. A branch left with one point goes, and so does a path; the map says so and undo brings it back. Backspace while drawing removes the last point. - **Continue:** click an end to carry on from it. -- **Select and fork:** click a path's line to select it (it's highlighted and its name shows in the bar; click the name to rename it). Click the selected path's line again to start a fork there. A path and its forks are one path in the map note. +- **Select and fork:** click a path's line to select it (it's highlighted and its name shows in the bar; click the name to rename it). Click the selected path's line again to start a fork there. A path and its forks are one path in the map note. Forks stay attached: drag the point a fork leaves from and the fork comes along; delete it and the fork joins the nearest point that is left. If a main line goes, its forks become paths of their own (one undo step). - **New path:** click empty ground. **Alt-click**, or **New path** in the bar, starts a new path even on top of a path of the same type (a crossroads of two roads). - **Path menu:** right-click a path's line, or **Shift**+right-click a point: its own items come first (**Split here**, **Delete this fork**, **Delete path**, **Rename…**, **Change type…**, **Reverse**), then the tool's. In erase mode (the picker's ✕), click a path of the tool's type to split it there. - **Esc** steps out one level: finish the branch, then deselect, then leave the tool. **Ctrl/Cmd+Z** undoes each change. diff --git a/src/hex-map/pathTool.ts b/src/hex-map/pathTool.ts index 659471ab..56ea2f38 100644 --- a/src/hex-map/pathTool.ts +++ b/src/hex-map/pathTool.ts @@ -24,14 +24,12 @@ import { Notice } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { HexKey, MapPath } from "../types"; import { latticeCenter, type LatticeGrid, type PathStroke, type Pt } from "../paths/pathGeometry"; -import type { ResolvedBranch } from "../paths/resolve"; import type { RouteCache } from "../paths/routeCache"; import { appendAnchor, clonePath, clonePaths, deleteAnchor, - deleteBranch, forkAt, insertAnchorAt, moveAnchor, @@ -41,6 +39,8 @@ import { splitBranchAt, } from "../paths/edit"; import { anchorsFor, routeFnFor } from "../paths/fromHexes"; +import { keepForksAttached, splitOffOrphans } from "../paths/forks"; +import { routeBranch, type ResolvedBranch } from "../paths/resolve"; import { canEditPaths, PATH_EDIT_LOCKED_HINT, type PathEditAction } from "../paths/editGate"; import { pathRouteText } from "../maps/mapNote"; import { pathRouteStats } from "../maps/MapStore"; @@ -909,7 +909,7 @@ export class PathTool { deleteBranch(path: string, branch: number): void { const p = this.pathNamed(path); if (!p) return; - this.afterPathEdit(p.name, deleteBranch(p, branch)); + this.removeBranch(p, branch, () => { this.active = null; }); } deletePath(path: string): void { @@ -917,16 +917,67 @@ export class PathTool { this.afterPathEdit(path, null); } + /** The routes of a path's branches as they are now (its anchors where not resolved). */ + private routesOf(p: MapPath): HexKey[][] { + return p.branches.map((b, i) => this.branchRoute(p.name, i)?.hexes ?? [...b.anchors]); + } + + /** A branch's route for `anchors` (the type's routing), or null before the map is ready. */ + private routeOf(typeName: string, anchors: readonly HexKey[]): HexKey[] | null { + const router = this.plugin.paths.router(this.map); + if (!router) return null; + return routeBranch(anchors, this.plugin.paths.styleOf(this.map, typeName), router).hexes; + } + + /** + * After branch `branch` of `p` was re-routed (from `oldRoute`): forks and + * joins that were on it follow it (keepForksAttached), so they stay attached. + */ + private attachForks(p: MapPath, branch: number, oldRoute: readonly HexKey[], moved?: { from: HexKey; to: HexKey }): MapPath { + const grid = this.grid(); + const anchors = p.branches[branch]?.anchors; + if (!grid || !anchors || p.branches.length < 2) return p; + const route = this.routeOf(p.typeName, anchors); + return route ? keepForksAttached(p, branch, oldRoute, route, grid, moved) : p; + } + + /** + * Remove a branch; forks that hung off it become paths of their own + * (splitOffOrphans), all in one undo step, with a notice naming them. + */ + private removeBranch(p: MapPath, branch: number, adjust?: (next: MapPath | null) => void): void { + const taken = this.paths().map((q) => q.name); + const { path: rest, split } = splitOffOrphans(p, branch, this.routesOf(p), taken); + this.afterPathEdit(p.name, rest, (q) => { + adjust?.(q); + if (split.length) { + const names = split.map((s) => s.name).join(", "); + new Notice(split.length === 1 ? `Its fork is now a path of its own: ${names}.` : `Its forks are now paths of their own: ${names}.`); + } + }, split); + } + deleteAnchor(path: string, branch: number, anchor: number): void { const p = this.pathNamed(path); if (!p) return; const next = deleteAnchor(p, branch, anchor); - // The active end steps back with its anchor; a branch that went takes it along. - this.afterPathEdit(p.name, next, (q) => { - if (!q || q.branches.length < p.branches.length) this.active = null; - // A branch (or the path) with one point left goes too: say so. + // A branch (or the path) with one point left goes too: say so. + const say = (q: MapPath | null) => { const note = anchorDeleteNotice(p, q, branch); if (note) new Notice(note); + }; + if (!next || next.branches.length < p.branches.length) { + // The branch went: the active end goes with it; its forks split off. + this.removeBranch(p, branch, (q) => { + this.active = null; + say(q); + }); + return; + } + // Forks that left the deleted point re-attach to the nearest point of the new route. + const fixed = this.attachForks(next, branch, this.routesOf(p)[branch]); + this.afterPathEdit(p.name, fixed, (q) => { + if (!q || q.branches.length < p.branches.length) this.active = null; }); } @@ -962,9 +1013,9 @@ export class PathTool { }).open(); } - /** Commit one path's replacement (null removes it), keeping the tool state valid. */ - private afterPathEdit(name: string, next: MapPath | null, adjust?: (next: MapPath | null) => void): void { - if (!this.commit(this.replacePath(name, next))) return; + /** Commit one path's replacement (null removes it; extra: paths split off it), keeping the tool state valid. */ + private afterPathEdit(name: string, next: MapPath | null, adjust?: (next: MapPath | null) => void, extra: MapPath[] = []): void { + if (!this.commit([...this.replacePath(name, next), ...extra])) return; adjust?.(next); if (!next && this.selected === name) { this.selected = null; @@ -1322,7 +1373,9 @@ export class PathTool { p = ins.path; anchor = ins.anchor; } - const moved = moveAnchor(p, d.branch, anchor, d.lastHex); + const from = p.branches[d.branch].anchors[anchor]; + // Forks leaving the dragged point move with it; others on the old route stay on the new one. + const moved = this.attachForks(moveAnchor(p, d.branch, anchor, d.lastHex), d.branch, d.route.hexes, { from, to: d.lastHex }); d.preview = d.before.map((q) => (q.name === d.path ? moved : q)); this.plugin.paths.setPreview(this.map, d.preview); this.strokeMemo = null; diff --git a/src/paths/forks.ts b/src/paths/forks.ts new file mode 100644 index 00000000..494f2039 --- /dev/null +++ b/src/paths/forks.ts @@ -0,0 +1,172 @@ +/** + * Keeping forks attached to the branch they leave (owner decision + * 2026-10-11). A fork is a branch whose first anchor lies on another + * branch's route (a join: whose last anchor does); nothing else ties them. + * So when an edit changes one branch's route, the branches attached to it + * have to follow, or they're left hanging beside it: + * + * - keepForksAttached: a branch's route changed (an anchor moved, added or + * deleted). Forks and joins that were on its old route and aren't on the + * new one move: onto the moved anchor's new hex when they sat on that + * anchor, else onto the nearest hex of the new route. + * - splitOffOrphans: a branch was removed. Forks that hung off it (and + * their own forks) become paths of their own; when the main line went + * and nothing else is left, the first of them keeps the path's name. + * + * Pure, no Obsidian imports. The caller commits the result as one step. + */ + +import type { HexKey, MapPath, PathBranch } from "../types"; +import { latticeCenter, type LatticeGrid } from "./pathGeometry"; +import { uniquePathName } from "./names"; + +function cloneBranch(b: PathBranch): PathBranch { + const out: PathBranch = { anchors: [...b.anchors] }; + if (b.label !== undefined) out.label = b.label; + if (b.extra) out.extra = { ...b.extra }; + return out; +} + +/** The hex of `route` nearest `hex` (first on ties). */ +export function nearestOnRoute(hex: HexKey, route: readonly HexKey[], grid: LatticeGrid): HexKey | null { + const p = latticeCenter(hex, grid); + let best: HexKey | null = null; + let bestD = Infinity; + for (const k of route) { + const c = latticeCenter(k, grid); + const d = Math.hypot(p.cx - c.cx, p.cy - c.cy); + if (d < bestD - 1e-9) { + bestD = d; + best = k; + } + } + return best; +} + +/** + * Branch `branch` of `p` was re-routed from `oldRoute` to `newRoute` (p is + * the path after the edit; branch indices unchanged). Every other branch + * whose first anchor (fork) or last anchor (join) was on the old route but + * isn't on the new one is moved back onto it: to `moved.to` when it sat on + * `moved.from` (the dragged anchor), else to the nearest hex of the new + * route. An end that lands on its neighbour anchor merges with it; a branch + * left with fewer than two anchors is dropped. Returns `p` itself when + * nothing had to move. + */ +export function keepForksAttached( + p: MapPath, + branch: number, + oldRoute: readonly HexKey[], + newRoute: readonly HexKey[], + grid: LatticeGrid, + moved?: { from: HexKey; to: HexKey }, +): MapPath { + if (!newRoute.length) return p; + const was = new Set(oldRoute); + const now = new Set(newRoute); + const target = (hex: HexKey): HexKey | null => { + if (moved && hex === moved.from) return moved.to; + if (!was.has(hex) || now.has(hex)) return null; + return nearestOnRoute(hex, newRoute, grid); + }; + let changed = false; + const branches: PathBranch[] = []; + p.branches.forEach((b, i) => { + if (i === branch || b.anchors.length < 2) { + branches.push(b); + return; + } + const a = [...b.anchors]; + const head = target(a[0]); + const tail = target(a[a.length - 1]); + if (head === null && tail === null) { + branches.push(b); + return; + } + changed = true; + if (head !== null) { + a[0] = head; + if (a[1] === head) a.splice(1, 1); + } + if (tail !== null) { + a[a.length - 1] = tail; + if (a.length > 1 && a[a.length - 2] === tail) a.splice(a.length - 2, 1); + } + if (a.length < 2) return; // nothing left of it + branches.push({ ...cloneBranch(b), anchors: a }); + }); + if (!changed) return p; + const out: MapPath = { name: p.name, typeName: p.typeName, branches }; + if (p.notes !== undefined) out.notes = p.notes; + if (p.extra) out.extra = { ...p.extra }; + return out; +} + +/** + * Branch `removed` of `before` is being deleted (`routes[i]` = branch i's + * route before the edit). The branches that hung off it, and anything + * hanging off those, can't stay in the path detached: each such group + * becomes a path of its own (new names from `taken`), its root first so + * it's the new main line. When nothing but such groups is left, the first + * group keeps the path (its name, notes and extra columns). Returns the + * path that's left (null when none) and the new paths. + */ +export function splitOffOrphans( + before: MapPath, + removed: number, + routes: readonly (readonly HexKey[])[], + taken: Iterable, +): { path: MapPath | null; split: MapPath[] } { + const n = before.branches.length; + const onRoute = (hex: HexKey, j: number) => (routes[j] ?? before.branches[j].anchors).includes(hex); + // Each branch's parent: the first other surviving branch its start is on. + // Branches whose start was only on the removed branch are orphan roots. + const parent: (number | null)[] = []; + const root: boolean[] = []; + for (let i = 0; i < n; i++) { + parent.push(null); + root.push(false); + if (i === removed || i === 0) continue; + const start = before.branches[i].anchors[0]; + let p: number | null = null; + for (let j = 0; j < n && p === null; j++) if (j !== i && j !== removed && onRoute(start, j)) p = j; + parent[i] = p; + root[i] = p === null && onRoute(start, removed); + } + // Groups: each root and its descendants (by parent chain, in index order). + const groupOf = (i: number): number | null => { + const seen = new Set(); + let k: number | null = i; + while (k !== null && !seen.has(k)) { + if (root[k]) return k; + seen.add(k); + k = parent[k]; + } + return null; + }; + const groups = new Map(); + const stay: number[] = []; + for (let i = 0; i < n; i++) { + if (i === removed) continue; + const g = groupOf(i); + if (g === null) stay.push(i); + else groups.set(g, [...(groups.get(g) ?? []), i]); + } + // Roots first within their group (index order otherwise). + const ordered = [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([g, members]) => [g, ...members.filter((m) => m !== g)]); + const branchesOf = (idx: number[]) => idx.map((i) => cloneBranch(before.branches[i])); + const names = [...taken]; + const fresh = (idx: number[]): MapPath => { + const name = uniquePathName(before.typeName, names); + names.push(name); + return { name, typeName: before.typeName, branches: branchesOf(idx) }; + }; + let path: MapPath | null = null; + if (stay.length) path = { name: before.name, typeName: before.typeName, branches: branchesOf(stay) }; + else if (ordered.length) path = { name: before.name, typeName: before.typeName, branches: branchesOf(ordered.shift()!) }; + if (path) { + if (before.notes !== undefined) path.notes = before.notes; + if (before.extra) path.extra = { ...before.extra }; + } + return { path, split: ordered.map(fresh) }; +} diff --git a/tests/pathForks.test.ts b/tests/pathForks.test.ts new file mode 100644 index 00000000..682894c2 --- /dev/null +++ b/tests/pathForks.test.ts @@ -0,0 +1,123 @@ +/** + * Forks stay attached to their main line (owner decision 2026-10-11): + * dragging the junction point carries the fork's start with it; deleting + * it re-attaches the fork to the nearest point of the new route; when the + * main line itself goes, its forks become paths of their own. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import type { MapPath } from "../src/types"; +import { keepForksAttached, nearestOnRoute, splitOffOrphans } from "../src/paths/forks"; +import { deleteAnchor, moveAnchor } from "../src/paths/edit"; +import { resolvePaths } from "../src/paths/resolve"; +import type { RouteContext } from "../src/paths/router"; +import type { LatticeGrid } from "../src/paths/pathGeometry"; + +const grid: LatticeGrid = { orientation: "flat", stagger: "odd" }; +const ctx: RouteContext = { orientation: "flat", stagger: "odd", bounds: { minX: 0, minY: 0, maxX: 19, maxY: 15 }, blocked: new Set() }; +const routes = (p: MapPath) => { + const r = resolvePaths([p], ctx); + return p.branches.map((_, i) => r.find((x) => x.branch === i)?.hexes ?? []); +}; +const forkOf = (p: MapPath, branch: number) => resolvePaths([p], ctx).find((x) => x.branch === branch)!; + +describe("dragging the junction point carries the fork with it", () => { + const P: MapPath = { name: "King's Road", typeName: "Road", branches: [{ anchors: ["1_5", "5_5", "9_5"] }, { anchors: ["5_5", "5_10"], label: "south" }] }; + + it("the fork's first anchor moves to where the point was dropped, and it still forks there", () => { + expect(forkOf(P, 1).forkFrom).toEqual({ branch: 0, hexIdx: expect.any(Number) }); + const moved = moveAnchor(P, 0, 1, "5_2"); + const out = keepForksAttached(moved, 0, routes(P)[0], routes(moved)[0], grid, { from: "5_5", to: "5_2" }); + expect(out.branches[1]).toEqual({ anchors: ["5_2", "5_10"], label: "south" }); + expect(out.branches[0].anchors).toEqual(["1_5", "5_2", "9_5"]); + expect(forkOf(out, 1).forkFrom?.branch).toBe(0); + // Without the rule the fork would be left hanging at 5_5. + expect(forkOf(moved, 1).forkFrom).toBeUndefined(); + }); + + it("a fork that left the route between anchors snaps to the nearest hex of the new route", () => { + const Q: MapPath = { name: "R", typeName: "Road", branches: [{ anchors: ["1_5", "9_5"] }, { anchors: ["5_5", "5_10"] }] }; + const moved = moveAnchor(Q, 0, 1, "9_1"); + const now = routes(moved)[0]; + expect(now).not.toContain("5_5"); + const out = keepForksAttached(moved, 0, routes(Q)[0], now, grid, { from: "9_5", to: "9_1" }); + expect(out.branches[1].anchors[0]).toBe(nearestOnRoute("5_5", now, grid)); + expect(now).toContain(out.branches[1].anchors[0]); + expect(out.branches[1].anchors[1]).toBe("5_10"); + }); + + it("forks still on the new route, and other paths' branches, are left as they are (same object when nothing moves)", () => { + const moved = moveAnchor(P, 0, 2, "9_6"); + const out = keepForksAttached(moved, 0, routes(P)[0], routes(moved)[0], grid, { from: "9_5", to: "9_6" }); + expect(out).toBe(moved); + }); + + it("a join (a branch ending on the moved point) follows too", () => { + const J: MapPath = { name: "Loop", typeName: "Road", branches: [{ anchors: ["1_5", "5_5", "9_5"] }, { anchors: ["3_10", "5_5"] }] }; + const moved = moveAnchor(J, 0, 1, "5_3"); + const out = keepForksAttached(moved, 0, routes(J)[0], routes(moved)[0], grid, { from: "5_5", to: "5_3" }); + expect(out.branches[1].anchors).toEqual(["3_10", "5_3"]); + }); + + it("a fork whose start lands on its own next anchor merges with it; one left with a single anchor goes", () => { + const M: MapPath = { name: "M", typeName: "Road", branches: [{ anchors: ["1_5", "5_5", "9_5"] }, { anchors: ["5_5", "5_8", "5_10"] }] }; + const moved = moveAnchor(M, 0, 1, "5_8"); + const out = keepForksAttached(moved, 0, routes(M)[0], routes(moved)[0], grid, { from: "5_5", to: "5_8" }); + expect(out.branches[1].anchors).toEqual(["5_8", "5_10"]); + const S: MapPath = { name: "S", typeName: "Road", branches: [{ anchors: ["1_5", "5_5", "9_5"] }, { anchors: ["5_5", "5_8"] }] }; + const gone = keepForksAttached(moveAnchor(S, 0, 1, "5_8"), 0, routes(S)[0], routes(moveAnchor(S, 0, 1, "5_8"))[0], grid, { from: "5_5", to: "5_8" }); + expect(gone.branches).toHaveLength(1); + }); +}); + +describe("deleting the junction point re-attaches the fork to the nearest remaining point", () => { + it("the fork's start moves onto the new route; its other anchors stay", () => { + const P: MapPath = { name: "K", typeName: "Road", branches: [{ anchors: ["1_5", "5_1", "9_5"] }, { anchors: ["5_1", "4_0"] }] }; + const next = deleteAnchor(P, 0, 1)!; + const now = routes(next)[0]; + expect(now).not.toContain("5_1"); + const out = keepForksAttached(next, 0, routes(P)[0], now, grid); + expect(now).toContain(out.branches[1].anchors[0]); + expect(out.branches[1].anchors[0]).toBe(nearestOnRoute("5_1", now, grid)); + expect(out.branches[1].anchors.slice(1)).toEqual(["4_0"]); + expect(forkOf(out, 1).forkFrom?.branch).toBe(0); + }); +}); + +describe("when the main line goes, its forks become paths of their own", () => { + const main = { anchors: ["1_5", "9_5"] }; + + it("one fork: it keeps the path (name, notes) as its main line", () => { + const P: MapPath = { name: "King's Road", typeName: "Road", notes: "old", branches: [main, { anchors: ["5_5", "5_10"] }] }; + const r = splitOffOrphans(P, 0, routes(P), ["King's Road"]); + expect(r.path).toEqual({ name: "King's Road", typeName: "Road", notes: "old", branches: [{ anchors: ["5_5", "5_10"] }] }); + expect(r.split).toEqual([]); + }); + + it("two forks: the first keeps the path, the second becomes a new path; a fork of a fork goes with its parent", () => { + const P: MapPath = { + name: "King's Road", + typeName: "Road", + branches: [main, { anchors: ["3_5", "3_10"] }, { anchors: ["7_5", "7_12"] }, { anchors: ["7_9", "11_9"] }], + }; + const before = routes(P); + expect(before[2]).toContain("7_9"); + const r = splitOffOrphans(P, 0, before, ["King's Road", "Road"]); + expect(r.path?.branches).toEqual([{ anchors: ["3_5", "3_10"] }]); + expect(r.split).toEqual([{ name: "Road 2", typeName: "Road", branches: [{ anchors: ["7_5", "7_12"] }, { anchors: ["7_9", "11_9"] }] }]); + }); + + it("removing a fork splits off only what hung off that fork; the main line stays", () => { + const P: MapPath = { name: "K", typeName: "Road", branches: [main, { anchors: ["7_5", "7_12"] }, { anchors: ["7_9", "11_9"] }, { anchors: ["3_5", "3_1"] }] }; + const r = splitOffOrphans(P, 1, routes(P), ["K"]); + expect(r.path?.branches).toEqual([main, { anchors: ["3_5", "3_1"] }]); + expect(r.split.map((s) => s.branches)).toEqual([[{ anchors: ["7_9", "11_9"] }]]); + }); + + it("a path with one branch is simply gone; a fork with nothing hanging off it just goes", () => { + const one: MapPath = { name: "Lane", typeName: "Road", branches: [main] }; + expect(splitOffOrphans(one, 0, routes(one), ["Lane"])).toEqual({ path: null, split: [] }); + const P: MapPath = { name: "K", typeName: "Road", branches: [main, { anchors: ["5_5", "5_10"] }] }; + expect(splitOffOrphans(P, 1, routes(P), ["K"])).toEqual({ path: { name: "K", typeName: "Road", branches: [main] }, split: [] }); + }); +}); From a7c18858582ff60d35afafcb915414770c605efd Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 09:21:32 -0400 Subject: [PATCH 292/558] feat(export): draw moon tethers in the PNG export when it includes paths moonTethers()/MOON_TETHER_STYLE in moonLinks.ts give the map view and the PNG renderer the same lattice segments and style (colour/opacity mirrored in styles.css, kept equal by a test). Only ties with both hexes in the exported range are drawn. Co-Authored-By: Claude Opus 5.5 --- src/export/mapPngRenderer.ts | 14 ++++++++++++ src/hex-map/HexMapView.ts | 12 +++++----- src/hex-map/moonLinks.ts | 30 +++++++++++++++++++++++++ tests/moonLinks.test.ts | 43 +++++++++++++++++++++++++++++++++++- 4 files changed, 93 insertions(+), 6 deletions(-) diff --git a/src/export/mapPngRenderer.ts b/src/export/mapPngRenderer.ts index d567d486..3bc453a2 100644 --- a/src/export/mapPngRenderer.ts +++ b/src/export/mapPngRenderer.ts @@ -42,6 +42,7 @@ import { } from "./handoutLabels"; import { BADGE_INFO, BADGE_SECTIONS, badgeSize, hiddenBadges as hiddenBadgeKinds, linkSectionsFromCache, type BadgeSection } from "../hex-map/linkBadges"; import { usedTerrainEntries } from "../hex-map/terrainLegend"; +import { MOON_TETHER_STYLE, moonTethers } from "../hex-map/moonLinks"; import { hexNameTone } from "../hex-map/hexNameLayer"; import { MIN_NAME_SCREEN_PX, nameFontShorthand, resolveNameFont } from "../hex-map/hexNameFont"; import { DEFAULT_TOKEN_FILL, groupSize, tokenGroupOffsets, tokenNamePlacement } from "../hex-map/tokenDefaults"; @@ -508,6 +509,19 @@ export async function renderMapToPngBlob( // only bolder when asked (decision 4 of the path-anchors design). const strokes = plugin.paths.strokes(map.name, { laneScale: boldPaths ? PNG_PATH_BOLD : 1 }); const affine = { sx: R, sy: R, tx: padding - minX, ty: padding - minY }; + // Moons tied to their planet (S11), under the paths as on screen. Only + // ties whose two hexes are both in the exported range. + const terrainAt = new Map(); + for (const [k, h] of plugin.mapStore.all(map.name)) if (h.terrain) terrainAt.set(k, h.terrain); + const lattice = plugin.paths.lattice(map.name); + if (lattice) { + ctx.save(); + ctx.globalAlpha = MOON_TETHER_STYLE.opacity; + for (const seg of moonTethers(terrainAt, plugin.getMapPalette(map.name), lattice, (k) => centerMap.has(k))) { + drawPath(ctx, applyAffine(seg, affine), MOON_TETHER_STYLE.color, MOON_TETHER_STYLE.width * R, MOON_TETHER_STYLE.dash.map((d) => d * R), false); + } + ctx.restore(); + } for (const st of strokes) { const width = boldPaths ? pngPathWidth(st.width * SCREEN_HEX_RADIUS, R) : st.width * R; const k = width / (st.width * R || 1); diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 5bb157cf..6618c295 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -67,7 +67,7 @@ import { type LatticeAffine, type LatticeGrid, } from "../paths/pathGeometry"; -import { moonPlanetLinks, tether } from "./moonLinks"; +import { MOON_TETHER_STYLE, moonTethers } from "./moonLinks"; import { GotoHexModal } from "./GotoHexModal"; import { HexHelpModal } from "./HexHelpModal"; import { FolderTreePickerModal } from "./FolderTreePickerModal"; @@ -6425,10 +6425,12 @@ export class HexMapView extends ItemView { if (calib) { const terrain = new Map(); for (const [k, h] of this.plugin.mapStore.all(region.name)) if (h.terrain) terrain.set(k, h.terrain); - const links = moonPlanetLinks(terrain, this.plugin.getMapPalette(region.name), calib.lattice.orientation, calib.lattice.stagger); - for (const [moon, planet] of links) { - const [a, b] = em(tether(latticeCenter(moon, calib.lattice), latticeCenter(planet, calib.lattice))); - moonLines.push({ d: `M${fmt(a.cx)} ${fmt(a.cy)}L${fmt(b.cx)} ${fmt(b.cy)}`, width: fmt(0.07 * scale), dash: `${fmt(0.1 * scale)} ${fmt(0.08 * scale)}` }); + // The same segments the PNG export draws (moonTethers). + const width = fmt(MOON_TETHER_STYLE.width * scale); + const dash = MOON_TETHER_STYLE.dash.map((d) => fmt(d * scale)).join(" "); + for (const seg of moonTethers(terrain, this.plugin.getMapPalette(region.name), calib.lattice)) { + const [a, b] = em(seg); + moonLines.push({ d: `M${fmt(a.cx)} ${fmt(a.cy)}L${fmt(b.cx)} ${fmt(b.cy)}`, width, dash }); } } // The path tool: the selected path highlighted, its anchor handles diff --git a/src/hex-map/moonLinks.ts b/src/hex-map/moonLinks.ts index 084d5c9f..34014d74 100644 --- a/src/hex-map/moonLinks.ts +++ b/src/hex-map/moonLinks.ts @@ -9,6 +9,7 @@ import type { TerrainColor } from "../types"; import { effectiveTerrainType } from "../terrainTypes"; import { hexNeighbors, type Orientation, type Stagger } from "../../packages/hex-wfc/src/grid"; +import { latticeCenter, type LatticeGrid, type Pt } from "../paths/pathGeometry"; export const MOON_TYPES: readonly string[] = ["moon"]; export const PLANET_TYPES: readonly string[] = ["world", "gas-giant"]; @@ -42,3 +43,32 @@ export function tether(a: { cx: number; cy: number }, b: { cx: number; cy: numbe const at = (f: number) => ({ cx: a.cx + (b.cx - a.cx) * f, cy: a.cy + (b.cy - a.cy) * f }); return [at(t), at(1 - t)]; } + +/** + * How a tether looks, in lattice units (× the hex radius when drawn). The + * map view sets width and dash from here; its colour and opacity live in + * styles.css (`.duckmage-moon-link`, kept equal by tests/moonLinks.test.ts). + * The PNG export draws all four from here, so it matches the screen. + */ +export const MOON_TETHER_STYLE = { + color: "#d7deff", + opacity: 0.55, + width: 0.07, + dash: [0.1, 0.08] as readonly number[], +} as const; + +/** + * Every moon tether on a map, in lattice units: the segment the map view and + * the PNG export both draw. `include` drops ties whose ends are not both + * drawn (an export of part of the map). + */ +export function moonTethers( + terrainAt: ReadonlyMap, + palette: readonly TerrainColor[], + grid: LatticeGrid, + include: (hexKey: string) => boolean = () => true, +): [Pt, Pt][] { + return moonPlanetLinks(terrainAt, palette, grid.orientation, grid.stagger) + .filter(([moon, planet]) => include(moon) && include(planet)) + .map(([moon, planet]) => tether(latticeCenter(moon, grid), latticeCenter(planet, grid))); +} diff --git a/tests/moonLinks.test.ts b/tests/moonLinks.test.ts index 4608258e..d056cfe3 100644 --- a/tests/moonLinks.test.ts +++ b/tests/moonLinks.test.ts @@ -1,6 +1,9 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { moonPlanetLinks, tether } from "../src/hex-map/moonLinks"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { MOON_TETHER_STYLE, moonPlanetLinks, moonTethers, tether } from "../src/hex-map/moonLinks"; +import { latticeCenter } from "../src/paths/pathGeometry"; import type { TerrainColor } from "../src/types"; const palette: TerrainColor[] = [ @@ -33,3 +36,41 @@ describe("moons tied to their planet (S11)", () => { expect(tether({ cx: 0, cy: 0 }, { cx: 10, cy: 0 })).toEqual([{ cx: 3, cy: 0 }, { cx: 7, cy: 0 }]); }); }); + +describe("moon tethers: the same segments on screen and in the PNG export", () => { + it("gives each tie's segment in lattice units", () => { + const t = new Map([["2_2", "Luna"], ["2_1", "Terra"]]); + const grid = { orientation: "flat", stagger: "odd" } as const; + const segs = moonTethers(t, palette, grid); + expect(segs).toEqual([tether(latticeCenter("2_2", grid), latticeCenter("2_1", grid))]); + }); + + it("drops ties with an end outside the drawn range", () => { + const t = new Map([["2_2", "Luna"], ["2_1", "Terra"], ["5_5", "Luna"], ["5_6", "Jove"]]); + const grid = { orientation: "flat", stagger: "odd" } as const; + expect(moonTethers(t, palette, grid, (k) => k !== "5_6")).toHaveLength(1); + expect(moonTethers(t, palette, grid, () => false)).toEqual([]); + }); + + it("the map view and the PNG export both draw moonTethers with MOON_TETHER_STYLE", () => { + const view = readFileSync(path.join(process.cwd(), "src", "hex-map", "HexMapView.ts"), "utf8"); + const png = readFileSync(path.join(process.cwd(), "src", "export", "mapPngRenderer.ts"), "utf8"); + for (const src of [view, png]) { + expect(src).toMatch(/moonTethers\(/); + expect(src).toMatch(/MOON_TETHER_STYLE\.width \* /); + } + // The export draws them only with the paths. + const showPaths = png.indexOf("if (showPaths) {"); + expect(showPaths).toBeGreaterThan(-1); + expect(png.indexOf("moonTethers(", showPaths)).toBeGreaterThan(showPaths); + expect(png).toMatch(/MOON_TETHER_STYLE\.color/); + expect(png).toMatch(/globalAlpha = MOON_TETHER_STYLE\.opacity/); + }); + + it("styles.css paints the on-screen tether in the export's colour and opacity", () => { + const css = readFileSync(path.join(process.cwd(), "styles.css"), "utf8").replace(/\r\n/g, "\n"); + const rule = /\.duckmage-moon-link \{([^}]*)\}/.exec(css)![1]; + expect(rule).toMatch(new RegExp(`stroke: ${MOON_TETHER_STYLE.color};`)); + expect(rule).toMatch(new RegExp(`opacity: ${MOON_TETHER_STYLE.opacity};`)); + }); +}); From 4a3d3a3dd795044fbdfb602d4fb2ec50b520896c Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 09:21:32 -0400 Subject: [PATCH 293/558] feat(palettes): one-time River 'Carves: water' for palettes from before carving planPresetPathFields (presetUpdates.ts) offers fields the shipped path types (DEFAULT_PATH_TYPES) gained since, once each (settings.presetPathFieldsAdded): only to a palette whose path types are still a copy of the shipped list, whose type is still the shipped record (routing/auto-route/avoid unchanged), and whose note never had the column (pathTableHasColumn). A user-set or cleared value is never touched. Palette notes are backed up first. Co-Authored-By: Claude Opus 5.5 --- src/constants.ts | 7 +++ src/palettes/PaletteStore.ts | 55 +++++++++++++++++++++-- src/palettes/pathTypeTable.ts | 10 +++++ src/palettes/presetUpdates.ts | 82 ++++++++++++++++++++++++++++++++++- src/types.ts | 2 + tests/palettes.test.ts | 67 ++++++++++++++++++++++++++++ tests/presetTerrains.test.ts | 77 ++++++++++++++++++++++++++++++-- 7 files changed, 292 insertions(+), 8 deletions(-) diff --git a/src/constants.ts b/src/constants.ts index f2b51a87..956a1acd 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -340,6 +340,12 @@ export const DEFAULT_PATH_TYPES: PathType[] = [ { name: "River", color: "#3b82f6", width: 3, lineStyle: "solid", routing: "meander", avoidImpassable: false, autoRoute: "winding", carves: "water" }, ]; +/** Fields added to the shipped path types after palettes copied them: + * set once where the palette never set them (src/palettes/presetUpdates.ts). */ +export const ADDED_PRESET_PATH_FIELDS: { pathType: string; field: "carves" | "carveWidth" }[] = [ + { pathType: "River", field: "carves" }, +]; + /** How a path is drawn when its type isn't in the map's palette (renamed or * deleted there): plain grey, so it stays visible and can be fixed. */ export const UNKNOWN_PATH_TYPE: PathType = { name: "", color: "#9ca3af", width: 3, lineStyle: "dashed", routing: "through", avoidImpassable: true, autoRoute: "direct" }; @@ -415,4 +421,5 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { dismissedHints: [], terrainTypesSeeded: false, presetTerrainsAdded: [], + presetPathFieldsAdded: [], }; diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index 261e88b0..55e49337 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -17,11 +17,11 @@ import { wrapPaletteColors, } from "./paletteNote"; import { PALETTE_PRESETS, cloneSubmapDefaults, getPreset, uniquePaletteName } from "./presets"; -import { clonePathTypes, parsePathTypes, pathTypesKey, setPathTypes, wrapPathTypeColors } from "./pathTypeTable"; +import { clonePathTypes, parsePathTypes, pathTableHasColumn, pathTypesKey, setPathTypes, wrapPathTypeColors } from "./pathTypeTable"; import { writeJsonBackup } from "../backup"; import { fillLegacyPathTypes } from "./pathTypeLegacy"; -import { ADDED_PRESET_TERRAINS, DEFAULT_PATH_TYPES } from "../constants"; -import { applyPresetTerrains, planPresetTerrains } from "./presetUpdates"; +import { ADDED_PRESET_PATH_FIELDS, ADDED_PRESET_TERRAINS, DEFAULT_PATH_TYPES } from "../constants"; +import { applyPresetPathFields, applyPresetTerrains, planPresetPathFields, planPresetTerrains } from "./presetUpdates"; import { inferTerrainType, refinedSpaceType } from "../terrainTypes"; import { repointPaletteName } from "./paletteOptions"; @@ -403,6 +403,11 @@ export class PaletteStore { // them gets the full old list, and the notes get their table below. const filled = fillPalettePathTypes(settings.terrainPalettes, settings.pathTypes) > 0; if (filled && !blocked) dirty = true; + // Fields the shipped path types gained since (River's "Carves: water"): + // once each, where the palette never set them (own backup; skipped + // entirely while notes can't change). + const pathFields = blocked ? false : await this.addNewPresetPathFields(); + if (pathFields) dirty = true; // One-time: give existing palettes terrain types (from same-named // preset terrains, else inferred from the name). Later blanks are the // user's choice and stay blank. @@ -430,7 +435,7 @@ export class PaletteStore { // Write seeded types into the notes now, in the same queued step. Queued // separately, an unload in between left notes untyped while settings // said seeding was done — and notes win on the next load. - if (!blocked && (seeded || filled || upgraded || added)) await this.syncNow(); + if (!blocked && (seeded || filled || upgraded || added || pathFields)) await this.syncNow(); // Notes from older builds (or edited by hand since) get their derived // cells shown (the Impassable column, inferred types in parentheses) // and their colours written as inline code. @@ -606,6 +611,48 @@ export class PaletteStore { return true; } + /** + * Give palettes' copies of the shipped path types the fields added to them + * since (River's "Carves: water"), once each, after backing up the palette + * notes. Only where the palette note never had the field (no column for + * it): a value the user set or cleared is left alone. Returns true when + * anything changed (settings or palettes). + */ + private async addNewPresetPathFields(): Promise { + const settings = this.plugin.settings; + const done = new Set(settings.presetPathFieldsAdded ?? []); + const noteOf = (pal: TerrainPalette): string | undefined => { + const path = this.boundPath.get(pal); + return path === undefined ? undefined : this.lastContent.get(path); + }; + const plan = planPresetPathFields(settings.terrainPalettes, ADDED_PRESET_PATH_FIELDS, done, DEFAULT_PATH_TYPES, (pal, field) => { + const content = noteOf(pal); + return content !== undefined && !pathTableHasColumn(content, field); + }); + if (!plan.done.length) return false; + if (plan.set.length) { + try { + const notes: Record = {}; + for (const { palette } of plan.set) { + const path = this.boundPath.get(palette); + if (path) notes[path] = this.lastContent.get(path) ?? ""; + } + const dir = `${this.plugin.manifest.dir}/backups/palettes-${new Date().toISOString().slice(0, 10)}`; + await writeJsonBackup(this.plugin.app.vault.adapter, dir, "palettes-before-path-fields", JSON.stringify({ savedAt: new Date().toISOString(), notes })); + } catch (e) { + // No backup, no change: try again next start. + console.error("Hexmap World Creator: couldn't back up palette notes; path types not updated", e); + return false; + } + applyPresetPathFields(plan); + const pals = [...new Set(plan.set.map((s) => s.palette.name))].map((n) => `"${n}"`).join(", "); + const what = [...new Set(plan.set.map((s) => `${s.pathType.name} ${s.field === "carves" ? "carves" : "carve width"}: ${s.value}`))].join("; "); + new Notice(`Hexmap World Creator: path types updated in ${pals} (${what}).`); + } + settings.presetPathFieldsAdded = [...done, ...plan.done]; + return true; + } + private async persist(): Promise { await this.plugin.saveData(this.plugin.settings); // A terrain added in a palette note gets its tables (HG5). diff --git a/src/palettes/pathTypeTable.ts b/src/palettes/pathTypeTable.ts index 72ad651b..fcf4d2c2 100644 --- a/src/palettes/pathTypeTable.ts +++ b/src/palettes/pathTypeTable.ts @@ -316,3 +316,13 @@ export function wrapPathTypeColors(content: string): string { } export const clonePathTypes = (types: readonly PathType[]): PathType[] => types.map((t) => ({ ...t })); + +/** + * Whether a palette note's path-types table has a column for `field`. A note + * without that column never had the field set (the column is written once + * any type has it, and kept from then on, even when cleared to "none"). + */ +export function pathTableHasColumn(content: string, field: "carves" | "carveWidth"): boolean { + const span = findPathTypesTable(content.replace(/\r\n?/g, "\n").split("\n")); + return !!span && span.columns.includes(field); +} diff --git a/src/palettes/presetUpdates.ts b/src/palettes/presetUpdates.ts index e20ec341..182755d4 100644 --- a/src/palettes/presetUpdates.ts +++ b/src/palettes/presetUpdates.ts @@ -15,7 +15,7 @@ * applying the result. */ -import type { TerrainColor, TerrainPalette } from "../types"; +import type { PathType, TerrainColor, TerrainPalette } from "../types"; export interface AddedPresetTerrain { /** Preset (palette) name. */ @@ -75,3 +75,83 @@ export function planPresetTerrains( export function applyPresetTerrains(plan: PresetTerrainPlan): void { for (const { palette, terrains } of plan.add) palette.terrains.push(...terrains.map((t) => ({ ...t }))); } + +// ── Path-type fields added to the shipped path types ───────────────────────── +// +// The same idea for path types: a field the shipped path types gained after +// palettes copied them (River's "Carves: water"). The shipped entry +// (DEFAULT_PATH_TYPES) is the source of the value. A palette's path type gets +// it ONCE, and only when the palette's path types are still a copy of the +// shipped list and that field was never set there (the caller checks the +// palette note: no column for it). A value the user set, or cleared to +// "none", is never touched. The path type must still be the shipped record: +// same name and the same behaviour the plugin wrote (routing, auto-route, +// avoid impassable), so a type the user built or reshaped is left alone. + +export type PresetPathField = "carves" | "carveWidth"; + +export interface AddedPresetPathField { + /** Path type name in the shipped list. */ + pathType: string; + field: PresetPathField; +} + +/** The once-only key for an entry (stored in settings.presetPathFieldsAdded). */ +export const pathFieldKey = (a: AddedPresetPathField): string => `${a.pathType}/${a.field}`.toLowerCase(); + +export interface PresetPathFieldPlan { + /** Fields to set, per palette path type (the objects themselves). */ + set: { palette: TerrainPalette; pathType: PathType; field: PresetPathField; value: string | number }[]; + /** Keys to remember as done (offered, whether set anywhere or not). */ + done: string[]; +} + +/** Still the shipped path type: the behaviour fields the plugin wrote are unchanged. */ +const sameShippedRecord = (pt: PathType, shipped: PathType): boolean => + pt.routing === shipped.routing && pt.autoRoute === shipped.autoRoute && pt.avoidImpassable === shipped.avoidImpassable; + +const isSet = (v: unknown): boolean => (typeof v === "string" ? v.trim() !== "" : v !== undefined && v !== null); + +/** + * Which palettes' path types get which shipped field values. `neverSet` says + * whether a palette never had `field` set (its note has no column for it). + * Nothing is changed here. + */ +export function planPresetPathFields( + palettes: TerrainPalette[], + entries: AddedPresetPathField[], + alreadyDone: ReadonlySet, + shipped: readonly PathType[], + neverSet: (palette: TerrainPalette, field: PresetPathField) => boolean, +): PresetPathFieldPlan { + const set: PresetPathFieldPlan["set"] = []; + const done: string[] = []; + const shippedNames = shipped.map((t) => t.name.toLowerCase()); + for (const e of entries) { + const key = pathFieldKey(e); + if (alreadyDone.has(key)) continue; + const source = shipped.find((t) => t.name.toLowerCase() === e.pathType.toLowerCase()); + const value = source?.[e.field]; + if (!source || !isSet(value)) continue; // not shipped (yet): try again next time + done.push(key); + for (const pal of palettes) { + const types = pal.pathTypes ?? []; + // A copy of the shipped list: still has most of its types. + const names = new Set(types.map((t) => t.name.toLowerCase())); + const kept = shippedNames.filter((n) => names.has(n)).length; + if (!shippedNames.length || kept / shippedNames.length < COPY_OVERLAP) continue; + const pt = types.find((t) => t.name.toLowerCase() === source.name.toLowerCase()); + if (!pt || !sameShippedRecord(pt, source) || isSet(pt[e.field]) || !neverSet(pal, e.field)) continue; + set.push({ palette: pal, pathType: pt, field: e.field, value: value as string | number }); + } + } + return { set, done }; +} + +/** Apply a plan: set each field. */ +export function applyPresetPathFields(plan: PresetPathFieldPlan): void { + for (const { pathType, field, value } of plan.set) { + if (field === "carves") pathType.carves = String(value); + else pathType.carveWidth = Number(value); + } +} diff --git a/src/types.ts b/src/types.ts index 7b203c75..edef20c8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -415,6 +415,8 @@ export interface HexmakerPluginSettings { hexNameStyle?: string; /** Bundled-palette terrains already offered to installed copies ("expanded/savanna"); see presetUpdates.ts. */ presetTerrainsAdded?: string[]; + /** Shipped path-type fields already offered to palettes ("river/carves"); see presetUpdates.ts. */ + presetPathFieldsAdded?: string[]; /** Terrain legend on the map and generator previews. Unset = shown. */ showTerrainLegend?: boolean; /** The map export form's last choices, per map name (round 6 S9). */ diff --git a/tests/palettes.test.ts b/tests/palettes.test.ts index df1a19b3..d6fcf627 100644 --- a/tests/palettes.test.ts +++ b/tests/palettes.test.ts @@ -934,3 +934,70 @@ describe("palette list on load (SM-DEL: no automatic refill)", () => { expect(missingDefaults([{ name: defaults[0].name.toUpperCase() }], defaults).map((p) => p.name)).toEqual(defaults.slice(1).map((p) => p.name)); }); }); + +// River's "Carves: water" for palettes from before carving shipped: once, +// only where the note never had a Carves column, backup first. +describe("PaletteStore: shipped path-type fields added since (River carves water)", () => { + const note = (pathTable: string[]) => + ["---", "hexmaker-palette: 1", "---", "", "| Terrain | Color |", "| --- | --- |", "| sea | `#0000ff` |", "", "## Path types", "", ...pathTable, ""].join("\n"); + const OLD = note([ + "| Path | Color | Width | Style | Routing | Avoid impassable | Auto-route |", + "| --- | --- | --- | --- | --- | --- | --- |", + "| Road | `#a16207` | 4 | solid | through | yes | direct |", + "| River | `#3b82f6` | 3 | solid | meander | no | winding |", + ]); + const CLEARED = note([ + "| Path | Color | Width | Style | Routing | Avoid impassable | Auto-route | Carves | Carve width |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |", + "| Road | `#a16207` | 4 | solid | through | yes | direct | none | 0 |", + "| River | `#3b82f6` | 3 | solid | meander | no | winding | none | 0 |", + ]); + const L = "world/palettes/Limited.md"; + const E = "world/palettes/Expanded.md"; + const river = (h: ReturnType, name: string) => + h.settings.terrainPalettes.find((p) => p.name === name)!.pathTypes!.find((t) => t.name === "River")!; + + it("sets it once where never set, keeps a cleared one, backs up first and records it", async () => { + const h = makeHarness({ palettesMigrated: true, terrainTypesSeeded: true, pathTypesExplicit: true, paletteColorsCode: true, paletteDataUpgraded: true }); + await h.vault.createFolder("world/palettes"); + h.vault.files.set(L, OLD); + h.vault.files.set(E, CLEARED); + await h.store.init(); + + expect(river(h, "Limited").carves).toBe("water"); + expect(h.vault.files.get(L)).toContain("| River | `#3b82f6` | 3 | solid | meander | no | winding | water | 0 |"); + // The user cleared it in Expanded: left alone. + expect(river(h, "Expanded").carves).toBeUndefined(); + expect(h.vault.files.get(E)).toContain("| River | `#3b82f6` | 3 | solid | meander | no | winding | none | 0 |"); + expect(h.settings.presetPathFieldsAdded).toEqual(["river/carves"]); + const backups = [...h.vault.raw.keys()].filter((k) => k.includes("palettes-before-path-fields")); + expect(backups).toHaveLength(1); + + // Never again: clearing it now sticks across loads. + river(h, "Limited").carves = undefined; + await h.store.sync(); + expect(h.vault.files.get(L)!).toContain("| River | `#3b82f6` | 3 | solid | meander | no | winding | none | 0 |"); + await h.store.init(); + expect(river(h, "Limited").carves).toBeUndefined(); + expect(h.vault.files.get(L)).toContain("| River | `#3b82f6` | 3 | solid | meander | no | winding | none | 0 |"); + expect([...h.vault.raw.keys()].filter((k) => k.includes("palettes-before-path-fields"))).toHaveLength(1); + }); + + it("changes nothing when the backup can't be saved, and tries again next load", async () => { + const h = makeHarness({ palettesMigrated: true, terrainTypesSeeded: true, pathTypesExplicit: true, paletteColorsCode: true, paletteDataUpgraded: true }); + await h.vault.createFolder("world/palettes"); + h.vault.files.set(L, OLD); + h.vault.files.set(E, CLEARED); + h.vault.failBackups = true; + await h.store.init(); + expect(river(h, "Limited").carves).toBeUndefined(); + expect(h.vault.files.get(L)).toContain("| River | `#3b82f6` | 3 | solid | meander | no | winding |"); + expect(h.vault.files.get(L)).not.toContain("Carves"); + expect(h.settings.presetPathFieldsAdded ?? []).toEqual([]); + + h.vault.failBackups = false; + await h.store.init(); + expect(river(h, "Limited").carves).toBe("water"); + expect(h.settings.presetPathFieldsAdded).toEqual(["river/carves"]); + }); +}); diff --git a/tests/presetTerrains.test.ts b/tests/presetTerrains.test.ts index c9fed5b5..51cb3d13 100644 --- a/tests/presetTerrains.test.ts +++ b/tests/presetTerrains.test.ts @@ -1,9 +1,10 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { ADDED_PRESET_TERRAINS, DEFAULT_TERRAIN_PALETTE, EXPANDED_PALETTE_NAME, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { ADDED_PRESET_PATH_FIELDS, ADDED_PRESET_TERRAINS, DEFAULT_PATH_TYPES, DEFAULT_TERRAIN_PALETTE, EXPANDED_PALETTE_NAME, LIMITED_TERRAIN_PALETTE } from "../src/constants"; import { PALETTE_PRESETS } from "../src/palettes/presets"; -import { addedKey, applyPresetTerrains, planPresetTerrains } from "../src/palettes/presetUpdates"; -import type { TerrainPalette } from "../src/types"; +import { addedKey, applyPresetPathFields, applyPresetTerrains, pathFieldKey, planPresetPathFields, planPresetTerrains } from "../src/palettes/presetUpdates"; +import { pathTableHasColumn } from "../src/palettes/pathTypeTable"; +import type { PathType, TerrainPalette } from "../src/types"; const presetTerrains = (n: string) => PALETTE_PRESETS.find((p) => p.name === n)?.terrains; const NEW = new Set(ADDED_PRESET_TERRAINS.map((a) => a.terrain)); @@ -64,3 +65,73 @@ describe("terrains added to a bundled palette (OW8)", () => { expect(plan.add).toHaveLength(0); }); }); + +describe("fields added to the shipped path types (River: Carves water)", () => { + const shipped = DEFAULT_PATH_TYPES; + /** Path types as copied into a palette before carving shipped. */ + const oldTypes = (): PathType[] => shipped.map(({ carves: _c, carveWidth: _w, ...t }) => ({ ...t })); + const pal = (name: string, pathTypes: PathType[]): TerrainPalette => ({ name, terrains: [], pathTypes }); + const always = () => true; + + it("ships River carving water (the value the upgrade copies)", () => { + expect(shipped.find((t) => t.name === "River")?.carves).toBe("water"); + expect(ADDED_PRESET_PATH_FIELDS).toEqual([{ pathType: "River", field: "carves" }]); + }); + + it("sets it once on a copy of the shipped types that never set it, and records it as done", () => { + const p = pal("Mine", oldTypes()); + const plan = planPresetPathFields([p], ADDED_PRESET_PATH_FIELDS, new Set(), shipped, always); + expect(plan.done).toEqual(["river/carves"]); + expect(plan.done).toEqual(ADDED_PRESET_PATH_FIELDS.map(pathFieldKey)); + applyPresetPathFields(plan); + expect(p.pathTypes!.find((t) => t.name === "River")?.carves).toBe("water"); + expect(p.pathTypes!.find((t) => t.name === "Road")?.carves).toBeUndefined(); + // Once: a later run (even with the field cleared again) does nothing. + p.pathTypes!.find((t) => t.name === "River")!.carves = undefined; + const again = planPresetPathFields([p], ADDED_PRESET_PATH_FIELDS, new Set(plan.done), shipped, always); + expect(again).toEqual({ set: [], done: [] }); + }); + + it("never overrides a value the user set, or a field they cleared", () => { + const own = oldTypes(); + own.find((t) => t.name === "River")!.carves = "swamp"; + const ownPal = pal("Own", own); + const cleared = pal("Cleared", oldTypes()); + // Cleared to none: the note has the Carves column, so it was set. + const plan = planPresetPathFields([ownPal, cleared], ADDED_PRESET_PATH_FIELDS, new Set(), shipped, (p) => p !== cleared); + expect(plan.set).toEqual([]); + expect(plan.done).toEqual(["river/carves"]); + applyPresetPathFields(plan); + expect(own.find((t) => t.name === "River")!.carves).toBe("swamp"); + expect(cleared.pathTypes!.find((t) => t.name === "River")!.carves).toBeUndefined(); + }); + + it("is a no-op on a palette without the shipped entry (or one reshaped by the user)", () => { + const noRiver = pal("Roads only", oldTypes().filter((t) => t.name !== "River")); + const custom = pal("Custom", [ + { name: "Canal", color: "#00f", width: 2, lineStyle: "solid", routing: "edge", avoidImpassable: true, autoRoute: "direct" }, + { name: "Lane", color: "#a50", width: 2, lineStyle: "dashed", routing: "through", avoidImpassable: true, autoRoute: "direct" }, + { name: "Track", color: "#555", width: 1, lineStyle: "dotted", routing: "through", avoidImpassable: true, autoRoute: "direct" }, + ]); + // A "River" the user reshaped (straight along the edges) is theirs now. + const reshaped = oldTypes(); + reshaped.find((t) => t.name === "River")!.routing = "edge"; + const plan = planPresetPathFields([noRiver, custom, pal("Reshaped", reshaped), pal("Empty", [])], ADDED_PRESET_PATH_FIELDS, new Set(), shipped, always); + expect(plan.set).toEqual([]); + expect(plan.done).toEqual(["river/carves"]); + }); + + it("waits while the shipped entry has no value (nothing recorded)", () => { + const plan = planPresetPathFields([pal("Mine", oldTypes())], ADDED_PRESET_PATH_FIELDS, new Set(), oldTypes(), always); + expect(plan).toEqual({ set: [], done: [] }); + }); + + it("reads 'never set' from the palette note: no Carves column", () => { + const old = "## Path types\n\n| Path | Color | Width | Style | Routing |\n| --- | --- | --- | --- | --- |\n| River | `#3b82f6` | 3 | solid | meander |\n"; + const cleared = "## Path types\n\n| Path | Color | Width | Style | Routing | Carves | Carve width |\n| --- | --- | --- | --- | --- | --- | --- |\n| River | `#3b82f6` | 3 | solid | meander | none | 0 |\n"; + expect(pathTableHasColumn(old, "carves")).toBe(false); + expect(pathTableHasColumn("no table here", "carves")).toBe(false); + expect(pathTableHasColumn(cleared, "carves")).toBe(true); + expect(pathTableHasColumn(cleared.replace(/\n/g, "\r\n"), "carveWidth")).toBe(true); + }); +}); From 8a131b65b433e2e01ddb9570e77ef6b64afdadb9 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 09:21:32 -0400 Subject: [PATCH 294/558] fix(smoke): count only the suite's own processes; adaptive jobs; longer stops - Safety only checks this suite's sandbox processes are gone; other Obsidian processes are reported, never compared (other sessions start/stop). - pickJobs (lib/concurrency.mjs): jobs from free memory, cores and CPU load; --jobs N overrides. - stopSandbox retries while a run's processes linger (~30 s more), 180 s per sandbox.mjs call. Co-Authored-By: Claude Opus 5.5 --- dev/smoke/lib/concurrency.mjs | 83 +++++++++++++++++++++++++++++++++++ dev/smoke/lib/obsidian.mjs | 9 +++- dev/smoke/run.mjs | 36 +++++++++------ tests/smokeSuite.test.ts | 54 +++++++++++++++++++++++ 4 files changed, 167 insertions(+), 15 deletions(-) create mode 100644 dev/smoke/lib/concurrency.mjs diff --git a/dev/smoke/lib/concurrency.mjs b/dev/smoke/lib/concurrency.mjs new file mode 100644 index 00000000..520b400e --- /dev/null +++ b/dev/smoke/lib/concurrency.mjs @@ -0,0 +1,83 @@ +/** + * How many sandboxes the smoke suite runs at once, and how it stops them. + * + * Each sandbox is a whole Obsidian (Electron) with its own profile: about + * 1.5 GB and a busy core while it loads. On a machine that is already busy + * (another smoke run, other Obsidian windows, a build) four at once time + * out, so the suite picks fewer. `--jobs N` overrides the pick. + * + * pickJobs and stopUntilGone are pure (tested in tests/smokeSuite.test.ts); + * machineLoad reads the machine. + */ +import os from "node:os"; + +export const MAX_JOBS = 4; +/** Memory one sandbox needs, bytes. */ +export const JOB_MEM_BYTES = 1.5 * 2 ** 30; +/** Memory left alone for everything else, bytes. */ +export const RESERVE_MEM_BYTES = 2 * 2 ** 30; + +/** + * Jobs to run at once. + * @param {{ requested?: number | null, freeMem: number, cpuBusy?: number | null, cpuCount?: number, max?: number }} m + * requested: --jobs (wins, within 1..max); freeMem: free bytes; cpuBusy: + * 0..1 share of CPU in use (null = unknown); cpuCount: logical cores. + * @returns {{ jobs: number, reason: string }} + */ +export function pickJobs({ requested = null, freeMem, cpuBusy = null, cpuCount = os.cpus().length, max = MAX_JOBS }) { + const clamp = (n) => Math.max(1, Math.min(max, Math.floor(n))); + if (requested !== null && requested !== undefined && Number.isFinite(Number(requested)) && Number(requested) > 0) { + return { jobs: clamp(Number(requested)), reason: "--jobs" }; + } + const byMem = Math.floor((freeMem - RESERVE_MEM_BYTES) / JOB_MEM_BYTES); + // About two cores per sandbox while it loads. + const byCores = Math.floor(cpuCount / 2); + let byCpu = max; + if (cpuBusy !== null && cpuBusy !== undefined) { + if (cpuBusy >= 0.85) byCpu = 1; + else if (cpuBusy >= 0.6) byCpu = Math.ceil(max / 2); + } + const jobs = clamp(Math.min(byMem, byCores, byCpu)); + const gb = (b) => (b / 2 ** 30).toFixed(1); + const why = [`${gb(freeMem)} GB free`, `${cpuCount} cores`]; + if (cpuBusy !== null && cpuBusy !== undefined) why.push(`CPU ${Math.round(cpuBusy * 100)}% busy`); + return { jobs, reason: why.join(", ") }; +} + +/** Free memory and how busy the CPU is over `sampleMs` (os.loadavg is always 0 on Windows). */ +export async function machineLoad(sampleMs = 1000) { + const times = () => os.cpus().map((c) => c.times); + const a = times(); + await new Promise((r) => setTimeout(r, sampleMs)); + const b = times(); + let busy = 0, total = 0; + b.forEach((t, i) => { + const d = (k) => t[k] - (a[i]?.[k] ?? 0); + const all = d("user") + d("nice") + d("sys") + d("idle") + d("irq"); + busy += all - d("idle"); + total += all; + }); + return { freeMem: os.freemem(), cpuBusy: total > 0 ? busy / total : null, cpuCount: b.length }; +} + +/** + * Stop a run, and keep at it while its processes are still there: a busy + * machine can take well over sandbox.mjs's own few seconds to let an + * Electron go. Stop is idempotent (it only kills that run's profile). + * @param {() => Promise<{ ok?: boolean }>} stop + * @param {{ attempts?: number, waitMs?: number, sleep?: (ms: number) => Promise }} [o] + * @returns {Promise<{ ok?: boolean, attempts: number }>} the last result + */ +export async function stopUntilGone(stop, { attempts = 6, waitMs = 5000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) { + let last = { ok: false }; + for (let i = 1; i <= attempts; i++) { + try { + last = await stop(); + } catch (e) { + last = { ok: false, error: String(e?.message ?? e) }; + } + if (last.ok) return { ...last, attempts: i }; + if (i < attempts) await sleep(waitMs); + } + return { ...last, attempts }; +} diff --git a/dev/smoke/lib/obsidian.mjs b/dev/smoke/lib/obsidian.mjs index 92949b54..4321d848 100644 --- a/dev/smoke/lib/obsidian.mjs +++ b/dev/smoke/lib/obsidian.mjs @@ -11,6 +11,7 @@ import fs from "node:fs"; import path from "node:path"; import { execFile, execFileSync } from "node:child_process"; import { pathToFileURL } from "node:url"; +import { stopUntilGone } from "./concurrency.mjs"; export const TOOLS_DIR = process.env.UX_TOOLS_DIR ?? process.env.UX_SANDBOX_DIR @@ -45,7 +46,13 @@ export async function createSandbox({ pluginDir, seed, pluginData, name }) { } export const launchSandbox = (runDir) => sandbox(["launch", "--run", runDir, "--width", "1400", "--height", "900"], { timeout: 240_000 }); -export const stopSandbox = (runDir) => sandbox(["stop", "--run", runDir], { timeout: 60_000 }); +/** One stop (sandbox.mjs waits ~5 s for the processes to go). */ +export const stopSandboxOnce = (runDir) => sandbox(["stop", "--run", runDir], { timeout: 180_000 }); +/** + * Stop a run and keep at it (up to ~30 s more) while its processes are + * still there: on a busy machine an Electron can take a while to exit. + */ +export const stopSandbox = (runDir) => stopUntilGone(() => stopSandboxOnce(runDir), { attempts: 7, waitMs: 5000 }); /** * Every Obsidian.exe process: { pid, main, cmd }. `main` = the browser diff --git a/dev/smoke/run.mjs b/dev/smoke/run.mjs index d8e91d70..1c9ac201 100644 --- a/dev/smoke/run.mjs +++ b/dev/smoke/run.mjs @@ -4,7 +4,7 @@ * LOCALLY before merging into feat/region-notes and before any live-vault * deploy; CI keeps the Obsidian-free tests). * - * node dev/smoke/run.mjs [--jobs 4] [--only fresh,v155] [--build

] [--no-build] [--keep] [--list] + * node dev/smoke/run.mjs [--jobs N] [--only fresh,v155] [--build ] [--no-build] [--keep] [--list] * * Windows node (Obsidian is a Windows app). From WSL use `npm run smoke`, * which hands over to node.exe (dev/smoke/cli.mjs). @@ -16,9 +16,13 @@ * 2. Per vault setup (setups.mjs): builds the fixture, `sandbox.mjs create` * (own vault + Electron profile), optionally a prep launch that builds * maps through the plugin API, then a check launch running C1–C8, then a - * restart launch for C5. At most --jobs sandboxes at once (max 4). - * 3. Stops every sandbox it started and checks no other Obsidian was - * touched (main-process count and pids before == after). + * restart launch for C5. At most --jobs sandboxes at once (max 4); + * without --jobs, as many as free memory and CPU allow + * (lib/concurrency.mjs: fewer when the machine is busy). + * 3. Stops every sandbox it started (retrying while its processes linger) + * and checks none of ITS processes are left. Other Obsidian processes + * (the owner's, other sessions' runs) may start or stop meanwhile; they + * are only reported, never counted against the run. * 4. Writes dev/smoke/last-run.json, and dev/smoke/last-pass.json when * every setup passed: { commit, dirty, buildHash, setups, results }. * @@ -34,6 +38,7 @@ import { fileURLToPath } from "node:url"; import { common, createSandbox, launchSandbox, stopSandbox, connectPage, obsidianProcesses, pluginErrors, shot, sleep, } from "./lib/obsidian.mjs"; +import { machineLoad, pickJobs } from "./lib/concurrency.mjs"; import { snapshot, diff, legacyTruth, verifyMigration, verifyBackups, noteTextHashes, verifyPaletteUpgrade } from "./lib/disk.mjs"; import * as P from "./lib/page.mjs"; import { canon, jsonDiff, oneTimeOnly } from "./lib/compare.mjs"; @@ -48,7 +53,8 @@ const argv = process.argv.slice(2); const flag = (k) => argv.includes(`--${k}`); const val = (k, d) => { const i = argv.indexOf(`--${k}`); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : d; }; if (flag("help") || flag("h")) { - console.log("usage: node dev/smoke/run.mjs [--jobs 4] [--only a,b] [--build ] [--no-build] [--keep] [--list]"); + console.log("usage: node dev/smoke/run.mjs [--jobs N] [--only a,b] [--build ] [--no-build] [--keep] [--list]"); + console.log(" --jobs N sandboxes at once (1-4); default: picked from free memory and CPU load"); process.exit(0); } if (flag("list")) { @@ -59,7 +65,8 @@ if (process.platform !== "win32") { console.error("dev/smoke/run.mjs drives Windows Obsidian: run it with Windows node, or `npm run smoke` from WSL."); process.exit(2); } -const jobs = Math.max(1, Math.min(4, Number(val("jobs", "4")) || 4)); +const jobsPick = pickJobs({ requested: val("jobs", null), ...(await machineLoad()) }); +const jobs = jobsPick.jobs; const only = val("only", null)?.split(",").map((s) => s.trim()).filter(Boolean) ?? null; if (only) { const unknown = only.filter((o) => !SETUPS.some((s) => s.id === o)); @@ -390,7 +397,7 @@ async function pool(items, n, fn) { } const t0 = Date.now(); -log(`${selected.length} setups, ${jobs} at a time: ${selected.map((s) => s.id).join(", ")}`); +log(`${selected.length} setups, ${jobs} at a time (${jobsPick.reason}): ${selected.map((s) => s.id).join(", ")}`); let results; const onSignal = async () => { log("interrupted: stopping sandboxes"); @@ -407,7 +414,10 @@ try { if (latestBefore !== null) fs.writeFileSync(latestFile, latestBefore); -// ── 3. other Obsidian processes untouched ──────────────────────────────── +// ── 3. none of this suite's Obsidian processes left ────────────────────── +// Only processes of runs this suite created count. Other Obsidian processes +// (the owner's, another session's smoke run) can start or stop at any time +// while the suite runs; they are reported, never compared. await sleep(1000); const procsAfter = obsidianProcesses(); const mineProfiles = started.map((s) => s.profile.toLowerCase()); @@ -415,15 +425,12 @@ const isMine = (p) => mineProfiles.some((m) => p.cmd.toLowerCase().includes(m)); const otherBefore = procsBefore.filter((p) => p.main && !isMine(p)); const otherAfter = procsAfter.filter((p) => p.main && !isMine(p)); const leftMine = procsAfter.filter(isMine); -const vanished = otherBefore.filter((p) => !procsAfter.some((q) => q.pid === p.pid)); const safety = { + // Information only (see above). otherObsidianBefore: otherBefore.length, otherObsidianAfter: otherAfter.length, - otherPidsBefore: otherBefore.map((p) => p.pid), - otherPidsAfter: otherAfter.map((p) => p.pid), - vanished: vanished.map((p) => p.pid), sandboxProcessesLeft: leftMine.length, - ok: otherBefore.length === otherAfter.length && vanished.length === 0 && leftMine.length === 0, + ok: leftMine.length === 0, }; // ── 4. record ──────────────────────────────────────────────────────────── @@ -439,6 +446,7 @@ const record = { version: manifest.version, seconds: Math.round((Date.now() - t0) / 1000), jobs, + jobsReason: jobsPick.reason, setups: results.map((r) => r.id), safety, results: Object.fromEntries(results.map((r) => [r.id, { ok: r.ok, ...(r.skipped ? { skipped: r.skipped } : {}), title: r.title, seconds: r.seconds, runDir: r.ok && !keep ? null : r.runDir, checks: r.checks }])), @@ -460,7 +468,7 @@ for (const r of results) { console.log(`${r.ok ? "PASS" : "FAIL"} ${r.id.padEnd(15)} ${String(r.seconds).padStart(4)} s ${r.checks.length} checks${gaps.length ? `, ${gaps.length} known gap(s)` : ""}`); for (const f of fails) console.log(` ✗ ${f.check}: ${f.detail.split("\n")[0].slice(0, 400)}`); } -console.log(`other Obsidian: ${safety.otherObsidianBefore} before, ${safety.otherObsidianAfter} after${safety.vanished.length ? `; VANISHED ${safety.vanished}` : ""}; sandbox processes left: ${safety.sandboxProcessesLeft}`); +console.log(`sandbox processes left: ${safety.sandboxProcessesLeft} (other Obsidian, not counted: ${safety.otherObsidianBefore} before, ${safety.otherObsidianAfter} after)`); const skipped = results.filter((r) => r.skipped).length; console.log(`${allOk ? "SMOKE PASSED" : "SMOKE FAILED"}${skipped ? ` (${skipped} setup(s) SKIPPED)` : ""} (${record.seconds} s, build ${buildHash}, commit ${record.commit?.slice(0, 7)}${record.dirty ? " +dirty" : ""}) → ${path.join(HERE, allOk ? "last-pass.json" : "last-run.json")}`); process.exit(allOk ? 0 : 1); diff --git a/tests/smokeSuite.test.ts b/tests/smokeSuite.test.ts index 11e25b38..c6d56dc2 100644 --- a/tests/smokeSuite.test.ts +++ b/tests/smokeSuite.test.ts @@ -5,6 +5,7 @@ import * as path from "node:path"; // The smoke suite's pure helpers (dev/smoke; the suite itself needs Windows Obsidian). import { canon, jsonDiff, oneTimeOnly } from "../dev/smoke/lib/compare.mjs"; import { diff, hexDataFromFm, paletteTerrains, verifyPaletteUpgrade } from "../dev/smoke/lib/disk.mjs"; +import { JOB_MEM_BYTES, pickJobs, stopUntilGone } from "../dev/smoke/lib/concurrency.mjs"; const read = (...p: string[]) => readFileSync(path.join(process.cwd(), ...p), "utf8").replace(/\r\n/g, "\n"); @@ -92,3 +93,56 @@ describe("smoke suite findings stay fixed", () => { expect(src).toMatch(/void storesReady\.then\(\(\) => this\.saveSettings\(\)\);/); }); }); + +describe("smoke suite: concurrency and stopping", () => { + const GB = 2 ** 30; + + it("--jobs wins, within 1..4", () => { + expect(pickJobs({ requested: "2", freeMem: 0.5 * GB, cpuBusy: 0.99, cpuCount: 2 })).toEqual({ jobs: 2, reason: "--jobs" }); + expect(pickJobs({ requested: 9, freeMem: 64 * GB, cpuCount: 32 }).jobs).toBe(4); + expect(pickJobs({ requested: "abc", freeMem: 64 * GB, cpuCount: 32 }).reason).not.toBe("--jobs"); + }); + + it("runs 4 on an idle machine with room", () => { + expect(pickJobs({ freeMem: 16 * GB, cpuBusy: 0.1, cpuCount: 16 }).jobs).toBe(4); + expect(pickJobs({ freeMem: 16 * GB, cpuCount: 16 }).jobs).toBe(4); + }); + + it("runs fewer when free memory is low", () => { + expect(pickJobs({ freeMem: 2 * GB + 3 * JOB_MEM_BYTES, cpuBusy: 0, cpuCount: 16 }).jobs).toBe(3); + expect(pickJobs({ freeMem: 4 * GB, cpuBusy: 0, cpuCount: 16 }).jobs).toBe(1); + // Never 0: one at a time still runs. + expect(pickJobs({ freeMem: 0.5 * GB, cpuBusy: 0, cpuCount: 16 }).jobs).toBe(1); + }); + + it("runs fewer when the CPU is busy or there are few cores", () => { + expect(pickJobs({ freeMem: 32 * GB, cpuBusy: 0.7, cpuCount: 16 }).jobs).toBe(2); + expect(pickJobs({ freeMem: 32 * GB, cpuBusy: 0.9, cpuCount: 16 }).jobs).toBe(1); + expect(pickJobs({ freeMem: 32 * GB, cpuBusy: 0, cpuCount: 4 }).jobs).toBe(2); + expect(pickJobs({ freeMem: 32 * GB, cpuBusy: 0.7, cpuCount: 16 }).reason).toMatch(/70% busy/); + }); + + it("stopUntilGone retries while the run's processes linger, then reports the last result", async () => { + const waits: number[] = []; + const sleep = async (ms: number) => { waits.push(ms); }; + const results = [{ ok: false, remainingSandbox: 2 }, { ok: false, remainingSandbox: 1 }, { ok: true, remainingSandbox: 0 }]; + let calls = 0; + const r = await stopUntilGone(async () => results[calls++], { attempts: 5, waitMs: 100, sleep }); + expect(r).toMatchObject({ ok: true, attempts: 3 }); + expect(waits).toEqual([100, 100]); + + let n = 0; + const never = await stopUntilGone(async () => { n++; throw new Error("busy"); }, { attempts: 3, waitMs: 1, sleep }); + expect(never).toMatchObject({ ok: false, attempts: 3, error: "busy" }); + expect(n).toBe(3); + }); + + it("only counts the suite's own processes (other Obsidian sessions may come and go)", () => { + const run = read("dev", "smoke", "run.mjs"); + expect(run).toMatch(/ok: leftMine\.length === 0,/); + expect(run).not.toMatch(/otherBefore\.length === otherAfter\.length/); + expect(run).toMatch(/pickJobs\(\{ requested: val\("jobs", null\)/); + const lib = read("dev", "smoke", "lib", "obsidian.mjs"); + expect(lib).toMatch(/stopUntilGone\(/); + }); +}); From 3ff3041877ff71c0f87e42d2afb3c924ee7deacc Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 09:21:32 -0400 Subject: [PATCH 295/558] docs: moon tethers in PNG export, River carve upgrade, smoke concurrency Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++---- src/hex-map/help.md | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index fda84bdb..f69a4151 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **World biomes** (Advanced) — an overworld: one biome per hex, laid out by temperature, moisture and height, with transition biomes (taiga between tundra and forest, savanna between jungle and badlands) where two shouldn't touch. Its hexes open into regions that blend with each other. - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it; a land neighbour always shows as at least a small strip or corner patch on its side (a swamp to the south-west, say). -- **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one; the map draws a faint dashed tether from each moon to the world or gas giant beside it, hidden with the paths), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). +- **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one; the map draws a faint dashed tether from each moon to the world or gas giant beside it, hidden with the paths; the PNG export draws it too when it includes paths), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). - **World types** (Advanced: Terrain generators) — which worlds the space generators place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types` (**Default space** ships, with the odds Star scatter and Orbits have always used; **Restore default** puts them back). Each row is a world (a terrain of your palette) with a **Weight** and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature**. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows, and a preview rolls the table for a map, orbit, star and temperature and shows how often each world comes up next to its odds. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. @@ -244,7 +244,7 @@ Click the **pencil** icon on the right edge of the map to open the drawing tools **Auto-route:** the picker (and the bar at the top of the map while drawing) switches between **Hex by hex** and **Auto-route**: in the picker, choose how to draw (step 1), then the path type (step 2). With Auto-route, click a start hex and then an end hex: the path takes the shortest way inside the map, around impassable terrain, keeping close to the straight line between the two, and then carries on from that end, so you can route leg by leg. Path types whose **Auto-route** option is *winding* (River, by default) wind gently instead of running straight; *direct* ones keep to the line. It's an option on each type, never a matter of its name. A route continues an existing path only when its start is that path's end; starting anywhere else (such as the first hex of another road) makes a new path, and existing paths are never changed. The result is an ordinary path: drag its points to reshape it, right-click a point to remove it, or click an end to extend it. - **Impassable terrain** — set per terrain in the palette editor (Impassable column) or the terrain editor. Defaults go by terrain *type*, never by name, so they work in any palette, custom ones included: every terrain of a water type (deep water, water, shallows) is impassable unless you untick it. A terrain with no type has no default (an untyped "Black Lake" is passable); give it a type, or use **Guess types from names** in the palette editor. A palette with no impassable terrain says so in the bar. Learned generators' **Connected land** uses the same impassable terrains until you save your own list. -- **Carves terrain** — a path type can also say what an overworld path of that type turns the hexes it crosses into when you confirm it into its regions (**Carves**: a terrain's name, or a terrain type such as `water` for the palette's first water terrain; **Carve width** 0 for the path's own hexes, 1 to take the hexes beside them too). New palettes' River carves `water`; Road carves nothing. It's an option of the type, never of its name: palettes you already have keep carving off until you set it. The columns appear in the palette note's Path types table once a type uses them. +- **Carves terrain** — a path type can also say what an overworld path of that type turns the hexes it crosses into when you confirm it into its regions (**Carves**: a terrain's name, or a terrain type such as `water` for the palette's first water terrain; **Carve width** 0 for the path's own hexes, 1 to take the hexes beside them too). New palettes' River carves `water`; Road carves nothing. It's an option of the type, never of its name. Palettes made before carving existed get it once, on the next load: their River (still the one the plugin wrote, same routing and auto-route) is set to carve `water` if it never had a Carves value. The palette notes are backed up first (`backups/` in the plugin folder), and a value you set or cleared to `none` is never changed. The columns appear in the palette note's Path types table once a type uses them. - **Per path type** — each path type has **Avoid impassable terrain** and **Auto-route** (direct or winding) in its editor and in the palette note's Path types table. The built-in Road avoids impassable terrain and routes direct; River does neither. Any type can be set either way, whatever it's called. Path types saved by older versions get these filled in once, from how those versions treated them, so no map changes look. - **Cross impassable** — tick it in the bar to let one route go through anyway. If no route exists the map tells you, and suggests this or changing which terrains are impassable. @@ -303,7 +303,7 @@ Export a map for printing or for your players. - **Where:** the command **Hexmap World Creator: Export current map…** (any map; it starts on the one open in the hex map view), or the map-name button in the hex map toolbar → **Export** tab. Both show the same form. - **Formats:** **Export PNG** (an image of the map), **Export PDF with reference table** (the map, then a table per section listing each hex's linked notes and the start of its Description), and **Export hexcrawl manual (PDF)** (a printable gazetteer with legend, encounter tables and keyed hexes). -- **Options:** file name; **On the map**: coordinates, icons, paths, hex names, tokens (with their names), link badges, legend (the terrains used and the badge kinds, beside the map), faction overlay, region overlay; output size. The ticks start from what the map view shows (the overlays start off), and the form remembers your last file name, ticks and size for each map. Labels near the edge are kept inside the image. Roads and rivers are drawn bolder than on screen, scaled to the output size, and badges use the map's badge size. **PDF table columns** picks which columns the reference table prints (name, terrain, towns, dungeons, features, quests, factions, encounters, description), so you can cut a handout down to what players should see. **Hexcrawl manual** holds the player-version switch and lets you leave out the legend, encounter tables, factions and regions, or index. The form lists the exact file names it will write; files go to the export folder and open in a tab. Exporting again under the same name replaces the file (the notice says "Replaced …") and refreshes the tab already showing it. +- **Options:** file name; **On the map**: coordinates, icons, paths, hex names, tokens (with their names), link badges, legend (the terrains used and the badge kinds, beside the map), faction overlay, region overlay; output size. The ticks start from what the map view shows (the overlays start off), and the form remembers your last file name, ticks and size for each map. Labels near the edge are kept inside the image. Roads and rivers are drawn bolder than on screen, scaled to the output size (with paths ticked, moon tethers are drawn too, as on screen), and badges use the map's badge size. **PDF table columns** picks which columns the reference table prints (name, terrain, towns, dungeons, features, quests, factions, encounters, description), so you can cut a handout down to what players should see. **Hexcrawl manual** holds the player-version switch and lets you leave out the legend, encounter tables, factions and regions, or index. The form lists the exact file names it will write; files go to the export folder and open in a tab. Exporting again under the same name replaces the file (the notice says "Replaced …") and refreshes the tab already showing it. - **What players see:** the PNG never includes GM-layer icons, hidden tokens or any note text (Description, Landmark, Hidden, Secret), so it is safe as a handout. The faction and region overlays show their names when ticked; leave them off if those are secret. The PDF's table has no Hidden or Secret text. The hexcrawl manual is the full GM book unless you tick **player version**, which leaves out Hidden and Secret. - A single note or hex can also be exported: **Hexmap World Creator: Export current note to PDF**, **… to Markdown**, **Export current hex (structured PDF / Markdown)**, or the **Export** link in the hex editor. @@ -428,7 +428,7 @@ npm run smoke # smoke vault matrix in sandboxed Obsidian (Windows; see belo npm run premerge # build + lint + tests + integration + smoke: run before merging or deploying ``` -**Before merging into the integration branch or deploying a build into a real vault, run `npm run premerge`** and wait for `PREMERGE PASSED`. The smoke matrix (`dev/smoke/run.mjs`) starts a throwaway, separately profiled Obsidian per vault setup (fresh install, an old 1.5.5 vault, space only, an overworld with regions, neighbour maps, a custom palette, a vault with its folders deleted, 80 maps, Simple level…), up to 4 at once, and checks the plugin loads without errors, every map opens, untouched notes stay byte-identical, a restart rewrites nothing, paint and undo round-trip, and Play mode refuses edits. It needs Windows Obsidian and the fresh-eyes tester's `sandbox.mjs` (set `UX_TOOLS_DIR` if it isn't in the default place); `npm run smoke -- --list` shows the setups and `--only ` runs some of them. Results go to `dev/smoke/last-run.json` (and `last-pass.json` on a full pass). +**Before merging into the integration branch or deploying a build into a real vault, run `npm run premerge`** and wait for `PREMERGE PASSED`. The smoke matrix (`dev/smoke/run.mjs`) starts a throwaway, separately profiled Obsidian per vault setup (fresh install, an old 1.5.5 vault, space only, an overworld with regions, neighbour maps, a custom palette, a vault with its folders deleted, 80 maps, Simple level…), up to 4 at once (fewer when free memory is low or the CPU is busy; `--jobs N` sets it), and checks the plugin loads without errors, every map opens, untouched notes stay byte-identical, a restart rewrites nothing, paint and undo round-trip, and Play mode refuses edits. It needs Windows Obsidian and the fresh-eyes tester's `sandbox.mjs` (set `UX_TOOLS_DIR` if it isn't in the default place); `npm run smoke -- --list` shows the setups and `--only ` runs some of them. Results go to `dev/smoke/last-run.json` (and `last-pass.json` on a full pass). It only counts and stops its own sandboxes' processes, so your Obsidian or another smoke run can start or stop while it runs; a sandbox slow to exit gets about 30 seconds more before the stop counts as failed. The built output is `main.js` in the repo root. Obsidian loads this file directly from the plugin folder. diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 9e1f83ed..c1be9098 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -169,7 +169,7 @@ Notes, settings and palettes are never locked. There are no confirm boxes for th **Walking into new land.** In a region, the hex flower on the toolbar shows a **+** on each neighbour that has no region yet ("New region to the east"). Click it, pick the biome that lies there or **Roll** for one (the seed is shown; the same seed rolls the same biome), watch the preview of the new region blended with the regions around it, then **Create and go**. A different biome makes border country in between. Past the overworld's edge, the overworld grows by a hex to fit the new region. The hex editor's neighbour flower does the same on the hexes past the region's edge, and maps joined side by side get a **+** on the empty sides of their arrow pad. Needs Build or God: in Play the **+** says "Switch to Build to make a region." -**Roads and rivers on an overworld** are drafts (drawn faded) until you confirm them: select one with the path tool and click **Confirm into regions** (top bar, the path's right-click menu, or **Edit region…**). It's routed through every region it crosses, through each region's own terrain, and the neighbouring regions agree where it crosses each seam, so it joins up. If its path type **carves** terrain (River carves water by default; set it in the path type's editor), those hexes change too, except locked ones. Paths you drew in a region are never touched. Reshaping the overworld path makes it a draft again; **Update regions** redoes it, **Remove from regions** takes it out. New and rerolled regions pick up confirmed paths. Build or God; one undo step. +**Roads and rivers on an overworld** are drafts (drawn faded) until you confirm them: select one with the path tool and click **Confirm into regions** (top bar, the path's right-click menu, or **Edit region…**). It's routed through every region it crosses, through each region's own terrain, and the neighbouring regions agree where it crosses each seam, so it joins up. If its path type **carves** terrain (River carves water by default; set it in the path type's editor), those hexes change too, except locked ones. Palettes from before carving get River's `water` once, only where it was never set; a value you set or cleared stays. Paths you drew in a region are never touched. Reshaping the overworld path makes it a draft again; **Update regions** redoes it, **Remove from regions** takes it out. New and rerolled regions pick up confirmed paths. Build or God; one undo step. Neighbouring regions share one set of hex numbers: a new region carries on from the map it was placed next to, so each hex number names one place in the world. Maps you join later keep their own numbers. @@ -204,7 +204,7 @@ Deleted palettes stay deleted, the last one too. **Settings → Add default pale **Expanded** is the default fantasy palette on new installs (if you used the plugin before, new maps keep starting on your first palette): more terrains (coasts, wetlands, forest and mountain kinds) and it matches the generators. **Limited** has fewer, simpler terrains and is quicker to paint. Pick any palette as the start for new maps in **Settings → Palette for new maps**. Expanded now has **savanna** and **river delta** too (World biomes paints those biomes with them); an Expanded palette you already have gets them once, after a backup, unless it already has terrains of those names. Delete them and they stay deleted. -No palette or terrain is special because of its name. What a terrain does comes from its **Type**: water types are impassable to auto-routes, generators place terrain by type, Orbits puts the *moon*-type terrain beside planets and the *jump point* past the last orbit. Rename anything, or build a palette from scratch, and it works the same once its terrains have types. On space maps a faint dashed tether joins each moon to the planet beside it (hidden with the paths). +No palette or terrain is special because of its name. What a terrain does comes from its **Type**: water types are impassable to auto-routes, generators place terrain by type, Orbits puts the *moon*-type terrain beside planets and the *jump point* past the last orbit. Rename anything, or build a palette from scratch, and it works the same once its terrains have types. On space maps a faint dashed tether joins each moon to the planet beside it (hidden with the paths; the PNG export draws it when paths are included). Palette menus (setup, New map, new submap) show the picked palette's terrains as colour swatches; hover one for its name. A terrain with no type gets no defaults and generators skip it; **Guess types from names** in the palette editor fills the Type column for you to check. From 9116011b32a4a4f8e6edbaf0a18e451e74273b12 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 09:24:10 -0400 Subject: [PATCH 296/558] fix(maps): never write an empty pathChains to data.json Loading fills an absent pathChains in with [] (compat.migrateMapData), and a save before the map store was ready, or for a map marked missing, wrote that [] back. A restart then rewrote data.json (smoke F8 C5-restart, after missing maps stopped being re-created). Empty chains carry nothing, so they're left out; non-empty ones are written as before. Co-Authored-By: Claude Opus 5.5 --- src/HexmakerPlugin.ts | 3 ++- src/maps/MapStore.ts | 11 +++++++++-- tests/mapStore.test.ts | 13 +++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index de61a7b4..a1841150 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -850,7 +850,8 @@ export default class HexmakerPlugin extends Plugin { * note, which a person can read and edit. Maps not yet in a note keep them. */ async saveData(data: unknown): Promise { - const out = data !== this.settings || !this.mapStore?.isReady() ? data : withoutNotePaths(this.settings, (name) => this.mapStore.holdsPaths(name)); + const ready = !!this.mapStore?.isReady(); + const out = data !== this.settings ? data : withoutNotePaths(this.settings, (name) => ready && this.mapStore.holdsPaths(name)); this.rememberWrite(out); return super.saveData(out); } diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index f1839930..12ad0a6e 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -1393,11 +1393,18 @@ export function droppedWhat(paths: number, hexes: number): string { /** * Settings as written to data.json: maps whose note holds their paths - * (`holds`) go without `pathChains`. Everything else is shared, not copied. + * (`holds`) go without `pathChains`. An empty `pathChains` isn't written + * either: loading fills it in (compat.migrateMapData), so writing it would + * make a restart rewrite data.json (a missing map, or a save before the + * store is ready). Everything else is shared, not copied. */ export function withoutNotePaths(settings: S, holds: (name: string) => boolean): S { const maps = settings.maps.map((m) => { - if (!holds(m.name)) return m; + if (!holds(m.name)) { + if (!Array.isArray(m.pathChains) || m.pathChains.length) return m; + const { pathChains: _chains, ...rest } = m; + return rest as MapData; + } const { pathChains: _chains, paths: _paths, ...rest } = m; return rest as MapData; }); diff --git a/tests/mapStore.test.ts b/tests/mapStore.test.ts index b64755ff..f0a36458 100644 --- a/tests/mapStore.test.ts +++ b/tests/mapStore.test.ts @@ -2,6 +2,7 @@ import { describe, it, beforeEach } from "node:test"; import expect from "expect"; import { MapStore, HEX_DATA_KEYS, droppedWhat, withoutNotePaths } from "../src/maps/MapStore"; import { parseMapNote } from "../src/maps/mapNote"; +import { migrateMapData } from "../src/compat"; import { MemVault } from "./helpers/memVault"; import { Notice } from "obsidian"; import type { MapData } from "../src/types"; @@ -523,6 +524,18 @@ describe("map store: paths live only in the map note", () => { expect(store.holdsPaths("coast-3-4")).toBe(true); }); + it("an empty pathChains (filled in on load) is never written, so a restart rewrites nothing", () => { + const settings = { maps: [ + { name: "empty", pathChains: [] }, + { name: "with-paths", pathChains: [{ typeName: "Road", hexes: ["1_1", "2_1"] }] }, + ] as unknown as MapData[] }; + const disk = withoutNotePaths(settings, () => false); + expect("pathChains" in disk.maps[0]).toBe(false); + expect(disk.maps[1].pathChains).toHaveLength(1); + // Loading it back gives the same map in memory. + expect(migrateMapData(disk.maps[0]).pathChains).toEqual([]); + }); + it("a data.json synced in from another device doesn't overwrite the notes' paths", async () => { const v = new MemVault(); const m = maps(); From 091bc6dd47be691cc4313bfbbfa452f53eeeec95 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 09:32:42 -0400 Subject: [PATCH 297/558] fix(settings): don't write data.json when nothing changed saveData now compares with what data.json holds (last loaded or written this session; an echo of our own write moves it too) and skips identical writes. Startup saves that change nothing no longer rewrite the file (smoke F8 C5-restart: "rewritten same bytes"). Integration test: a restart, with a save before the stores load, writes data.json zero times; a real change is still written. Co-Authored-By: Claude Opus 5.5 --- src/HexmakerPlugin.ts | 18 +++++++++-- .../integration/pathLossReload.integration.ts | 31 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index a1841150..5380f050 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -763,6 +763,7 @@ export default class HexmakerPlugin extends Plugin { // 2026-10-10). rawData is an untouched copy for the "fresh install?" checks. const loaded = (await this.loadData()) as Record | null; const rawData = loaded ? (JSON.parse(JSON.stringify(loaded)) as Record) : null; + this.onDisk = loaded ? JSON.stringify(loaded) : null; const data = loaded ?? {}; if (data["regions"] !== undefined && data["maps"] === undefined) { data["maps"] = data["regions"]; @@ -852,10 +853,19 @@ export default class HexmakerPlugin extends Plugin { async saveData(data: unknown): Promise { const ready = !!this.mapStore?.isReady(); const out = data !== this.settings ? data : withoutNotePaths(this.settings, (name) => ready && this.mapStore.holdsPaths(name)); + // Same as what data.json holds (last loaded or written): don't touch the + // file. Startup saves that change nothing then leave it alone (smoke C5). + let text: string | null = null; + try { text = JSON.stringify(out); } catch { /* not JSON-able: write it */ } + if (text !== null && text === this.onDisk) return; this.rememberWrite(out); - return super.saveData(out); + await super.saveData(out); + this.onDisk = text; } + /** data.json's content as last loaded or written by this session (compact JSON). */ + private onDisk: string | null = null; + /** What we wrote to data.json lately (compact JSON), to tell our own writes from outside changes. */ private recentWrites: string[] = []; @@ -900,7 +910,11 @@ export default class HexmakerPlugin extends Plugin { // together (its watcher sees a write it hasn't recorded yet). Reloading // our own data would at best do nothing and at worst roll back changes // made since that save, so ignore anything we wrote ourselves. - if (this.isOwnWrite(await this.loadData())) return; + const disk = await this.loadData(); + if (this.isOwnWrite(disk)) { + this.onDisk = JSON.stringify(disk); + return; + } await this.loadSettings(); // Map notes hold paths and map settings; the new data.json doesn't win. // Queued before any sync, so nothing writes the bare copy over a note. diff --git a/tests/integration/pathLossReload.integration.ts b/tests/integration/pathLossReload.integration.ts index 202151d4..9fc8c158 100644 --- a/tests/integration/pathLossReload.integration.ts +++ b/tests/integration/pathLossReload.integration.ts @@ -32,6 +32,9 @@ const DATA = ".obsidian/plugins/hexmaker/data.json"; const COAST = "world/hexes/coast/_coast.md"; const NORTH = "world/hexes/north/_north.md"; +/** data.json writes so far (Plugin.saveData calls that reached the file). */ +let dataWrites = 0; + /** Obsidian's Plugin.loadData / saveData, against data.json in the in-memory vault. */ function wireDataJson(v: MemVault): void { const proto = (mock.Plugin as { prototype: Record }).prototype; @@ -40,6 +43,7 @@ function wireDataJson(v: MemVault): void { return text === undefined ? null : JSON.parse(text); }; proto.saveData = async function (data: unknown) { + dataWrites++; v.files.set(DATA, JSON.stringify(data, null, 2)); }; } @@ -209,4 +213,31 @@ describe("#47: a data.json reload mid-save-burst keeps every map's paths (real p expect([JSON.stringify(again.getMap("coast")!.paths), JSON.stringify(again.getMap("north")!.paths)]).toEqual(expected); expect(again.getMap("coast")!.world).toEqual({ id: "w3", cx: 0, cy: 0 }); }); + + it("a restart that changes nothing leaves data.json alone, even with saves before the store is ready", async () => { + const b = await boot(); + const { v, plugin } = b; + await settle(b); + const text = v.files.get(DATA); + const { default: HexmakerPlugin } = await import("../../src/HexmakerPlugin"); + const again = new HexmakerPlugin(plugin.app as never, plugin.manifest as never) as unknown as Booted["plugin"] & Record; + again.app = (plugin as unknown as Record).app; + again.manifest = (plugin as unknown as Record).manifest; + again.refreshHexMap = () => {}; + again.loadAvailableIcons = () => {}; + again.ensureTablesForNewTerrains = async () => {}; + dataWrites = 0; + await again.loadSettings(); + await again.saveSettings(); // before the stores load: maps still carry the empty pathChains filled in on load + await again.paletteStore.init(); + await again.mapStore.init(); + await again.saveSettings(); + await settle({ v, plugin: again }); + expect(dataWrites).toBe(0); + expect(v.files.get(DATA)).toBe(text); + // A real change is still written. + again.settings.dismissedHints = ["changed"]; + await again.saveSettings(); + expect(dataWrites).toBe(1); + }); }); From 5d997feda4dde50df3fc9e0ed0f2c2985645372c Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 09:34:21 -0400 Subject: [PATCH 298/558] fix(settings): type the echo-check read Co-Authored-By: Claude Opus 5.5 --- src/HexmakerPlugin.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 5380f050..4abff905 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -910,7 +910,7 @@ export default class HexmakerPlugin extends Plugin { // together (its watcher sees a write it hasn't recorded yet). Reloading // our own data would at best do nothing and at worst roll back changes // made since that save, so ignore anything we wrote ourselves. - const disk = await this.loadData(); + const disk = (await this.loadData()) as unknown; if (this.isOwnWrite(disk)) { this.onDisk = JSON.stringify(disk); return; From 665f7443cd75dc31819a695679da8f68ecf66ff6 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 10:29:02 -0400 Subject: [PATCH 299/558] fix(space): fresh-eyes pass 8 (solo space) F8-F16, C11; verify C3 - F8: a token's right-click menu ends with its hex's items under "This hex: ...", so the hex under a token is reachable (hex/overworld menu items are now built by addHexMenuItems / addOverworldMenuItems). - C11: a hex's region and locations come first in its menu; "New map from this hex..." reads "Add another map..." once it has one, and the New map dialog lists the existing maps with Open buttons first. - F10: on space maps (palette or ancestor palette has space terrain types) the Region / Location cards say a star system or planet is a Location. - F11: a submap's breadcrumb ends with "from: ", read from the parent's map data (parentHexTerrain). - F12: a palette installed by a new map and generated paths with no matching path type are quiet (console only); Add palette still notifies. - F13: map legend shows full names; only names over 18 chars are cut, keeping their start (no more "g. world"). - F14: default submap names are the hex's name, else " x, y", never chained coordinates, and made unique among map names. - F15: token form note suggestions drop down out of flow; the icon grid no longer moves when the list opens or closes. - F16: palette editor tab and header follow the palette shown. - F9: World types: Add row scrolls to and focuses the new row; a delete keeps scroll and list height until the pointer leaves, and focuses the list; the row list is no longer squeezed by the preview. - C3: verified in a sandbox that Play enters existing submaps (menu and token menu); test pins the policy. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 +- package.json | 4 +- src/HexmakerPlugin.ts | 8 +- src/hex-map/HexEditorModal.ts | 3 +- src/hex-map/HexMapView.ts | 93 +++++++++++------- src/hex-map/SubmapPickerModal.ts | 9 +- src/hex-map/TokenModal.ts | 11 ++- src/hex-map/help.md | 10 +- src/hex-map/modeMenu.ts | 5 + src/hex-map/newChildMap.ts | 31 +++++- src/hex-map/submapNav.ts | 21 +++- src/hex-map/terrainLegend.ts | 52 ++++------ src/maps/submaps.ts | 38 +++++++- src/palettes/PaletteEditorView.ts | 12 +++ src/space/WorldTypesModal.ts | 47 +++++++-- src/worldgen/NewMapSetupModal.ts | 10 +- styles.css | 49 +++++++++- tests/mapMarkers.test.ts | 26 ++--- tests/spaceSoloFixes.test.ts | 154 ++++++++++++++++++++++++++++++ tests/toolMode.test.ts | 13 ++- 20 files changed, 491 insertions(+), 115 deletions(-) create mode 100644 tests/spaceSoloFixes.test.ts diff --git a/README.md b/README.md index f69a4151..c6b28263 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ You're ready to start mapping. An interactive hex grid rendered as an Obsidian panel. - **Left-click** a hex to open the hex editor. -- **Right-click** a hex for its menu: centre on it, open its note, enter its region or open its locations, **New map from this hex…**, link an existing map, link a table, swap hexes, create a token here, clear terrain. +- **Right-click** a hex for its menu: its region and locations first (**Enter region: …**, **Open: …**), then centre on it, open its note, **New map from this hex…** (**Add another map…** once the hex has one), link an existing map, link a table, swap hexes, create a token here, clear terrain. Right-clicking a token that covers a hex gives the token's items and then the hex's, under **This hex: …**. - **Pan** by clicking and dragging with the left or middle mouse button. - **Zoom** with the scroll wheel. - **Expand** the grid with the `+`/`−` buttons at the map edges. @@ -108,7 +108,7 @@ Organise your world into multiple named hex maps, each stored as a subfolder und - **Back** (`← Back` button) — returns to the previously active map after following a submap link. ### Generators -Maps can be generated instead of painted hex by hex. When you create a map (**Maps → New map…**, or the setup wizard's first map) or a submap (right-click a hex → **New map from this hex…**), pick a generator and preview it before creating. A new map starts on Overland (Star scatter for space-only setups); pick Blank to paint it all yourself. **More** under the form sets the starting coordinates, stagger and a background image (picked from the vault or dropped from your computer), and the **folder name** (made from the name; you can change it later in Map properties). A new submap is named after its hex, or the parent map's name and the hex's coordinates ("Gloomwood 3, 4") if the hex has no name; click the name once to select it all and type your own. +Maps can be generated instead of painted hex by hex. When you create a map (**Maps → New map…**, or the setup wizard's first map) or a submap (right-click a hex → **New map from this hex…**), pick a generator and preview it before creating. A new map starts on Overland (Star scatter for space-only setups); pick Blank to paint it all yourself. **More** under the form sets the starting coordinates, stagger and a background image (picked from the vault or dropped from your computer), and the **folder name** (made from the name; you can change it later in Map properties). A new submap is named after its hex, or its terrain and coordinates ("Barren world 12, 5") if the hex has no name, with " (2)" added if another map already has that name; click the name once to select it all and type your own. A palette a new map installs, and generated paths with no matching path type on the new map's palette (an orbit crossing a planet), are handled quietly, with no notice. - **World biomes** (Advanced) — an overworld: one biome per hex, laid out by temperature, moisture and height, with transition biomes (taiga between tundra and forest, savanna between jungle and badlands) where two shouldn't touch. Its hexes open into regions that blend with each other. - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. @@ -118,7 +118,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. -**Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which. The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. +**Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which (on space maps: a star system, planet or station is a Location). If the hex already has maps, the dialog lists them first with an **Open** button each, and the menu item reads **Add another map…**. Inside a submap, the breadcrumb ends with what its hex was on the parent map ("from: barren world"). The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. **Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and a small hex flower on the toolbar shows all six neighbours in their directions (hover a petal for its name, click to go there). An empty petal shows **+** ("New region to the north-east"): click it to walk into new land. Pick the biome that lies there, or **Roll** for one (the seed is shown, so a roll can be repeated; **Re-roll terrain** keeps the biome and tries a new seed), check the live preview of the new region blended with every region around it, and **Create and go**. A biome different from yours makes border country between the two. If that hex is past the overworld's edge, the overworld grows by a hex to fit it. The hex editor's neighbour flower offers the same walk on the hexes past a region's edge. Making a region needs Build or God; in Play the **+** is greyed out and says "Switch to Build to make a region." A new region is made from a short form: biome (the hex's terrain is its biome), blend, how wiggly the borders are, and a seed, with a live preview of the region against its neighbours. It blends with the overworld around it, and the hexes along its edges are pinned to the regions already made, so seams line up whatever order you make them in. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. @@ -260,7 +260,7 @@ Toggled from the **layers** panel on the right edge of the map. - **Labels** group: **Coordinates**, **Hex names** and **Token names** (all on by default). With token names off, a token's name still shows while you hover it. Hex names are always readable: never smaller than about 11px on screen, at any zoom. A long name shrinks and wraps at spaces onto up to three lines to fit inside its hex, clear of its badges and coordinates; when it still doesn't fit at a readable size (zoomed out, or a long name), it spills past the hex instead of being cut (words are never split, nothing is cut off). Their colour follows the terrain (dark text on light terrain such as snow, light text on dark terrain). **Aa** beside the Labels heading sets the hex-name font for this map: Theme / Serif / Sans / Handwritten (common system fonts, nothing bundled), size **S / M / L / XL**, **B**old and **I**talic, and ↺ back to the default. The default for every map is in **Settings → Hex name font**. Saved in the map note (`name-font`, `name-size`, `name-style`); the PNG export uses the same font. - **Show link badges** (on by default) — a coloured icon badge at a hex's right side for each kind of link in its note: towns, dungeons, features, quests, factions. **S / M / L** beside the toggle sets their size (S by default; S is small and stays inside the hex, M and L sit on the hex's right edge so they stand out). Badges sit above hex names and coordinates, and names make room for them. The legend lists the badge kinds shown on the map. Hovering the hex names the linked notes ("Gullmouth · beach · hex 6, 6 · Town: Gullmouth"). Your hex icon stays as it is. The ▸ next to the toggle picks which kinds show. Saved per map. - Opening or closing the layers panel (or the drawing tools) never moves the map; the panel may cover a few hexes at the right edge. -- **Show legend** (on by default) — a small terrain legend pinned to the bottom-left of the map view, listing only the terrains used on this map (long names are cut short; hover a row for the full name). **S / M / L** sets its size; **–** folds it to a small **Legend** button (click to open it again); **×** hides it. The new-map and generator previews show the same legend. Size and visibility are remembered. +- **Show legend** (on by default) — a small terrain legend pinned to the bottom-left of the map view, listing only the terrains used on this map by their full names (only names longer than 18 characters are cut, keeping their start; hover a row for the full name). **S / M / L** sets its size; **–** folds it to a small **Legend** button (click to open it again); **×** hides it. The new-map and generator previews show the same legend. Size and visibility are remembered. ### GM layer Toggle from the overlay panel. When active: @@ -281,7 +281,7 @@ Place movable tokens on the map — useful for tracking party position, NPCs, or **Interacting with tokens:** - **Click** a token to open the hex it stands on, just like clicking the hex. - **Drag** a token to a different hex to move it. The target hex is highlighted as you drag. -- **Right-click** a token for its menu: **Token info** (the linked note title and hex position, with "Jump to hex" and "Open note"), edit its properties (icon, shape, colours), or remove it from the map. +- **Right-click** a token for its menu: **Token info** (the linked note title and hex position, with "Jump to hex" and "Open note"), edit its properties (icon, shape, colours), or remove it from the map. Below those, under **This hex: …**, are the items of the hex it sits on (open its maps, **Open hex note**, create a token here…), so you don't have to aim past the token. Token state is stored in the linked note's frontmatter (`token`, `token-hex`, `token-map`, `token-icon`, `token-shape`, `token-color`, `token-border`, `token-visible`). Tokens follow the map they were placed on and persist with the note. diff --git a/package.json b/package.json index 4bc55786..bb3f367f 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 4abff905..cd57e651 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -2521,7 +2521,7 @@ export default class HexmakerPlugin extends Plugin { * the palette note is written by the sync that follows. Returns the new * palette's name. */ - async installPalettePreset(presetName: string, asName?: string): Promise { + async installPalettePreset(presetName: string, asName?: string, opts: { quiet?: boolean } = {}): Promise { const preset = getPreset(presetName); if (!preset) return undefined; const name = uniquePaletteName( @@ -2536,7 +2536,8 @@ export default class HexmakerPlugin extends Plugin { // table like the parent's (round 7: a system map installed "Space - // System" and its "ice planet" hex showed Encounters Table "None"). await this.ensureTablesForNewTerrains(); - new Notice(`Added palette "${name}".`); + // Installed on first use by a new map: expected, so no notice (F12). + if (!opts.quiet) new Notice(`Added palette "${name}".`); return name; } @@ -2731,7 +2732,8 @@ export default class HexmakerPlugin extends Plugin { /** Install `name` from the presets if no palette by that name exists yet. */ async ensurePaletteInstalled(name: string): Promise { if (this.getPaletteByName(name) || !getPreset(name)) return; - await this.installPalettePreset(name); + // A new map installing its palette is expected: no notice (F12). + await this.installPalettePreset(name, undefined, { quiet: true }); } getMapPalette(mapName: string): TerrainColor[] { diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 336d57ff..967734ea 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -1,6 +1,7 @@ import { App, Notice, TFile } from "obsidian"; import { canDo } from "../modeGate"; import { lockedHint, workModeOf, type ModeAction } from "../workMode"; +import { newMapItemTitle } from "../maps/submaps"; import { ModeMenu } from "./modeMenu"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; @@ -710,7 +711,7 @@ export class HexEditorModal extends HexmakerModal { add.addEventListener("click", (e) => { const { x, y } = this; const menu = new ModeMenu(workModeOf(this.plugin.getMap(this.mapName))); - menu.add("editor.new-map", "New map from this hex…", "plus", () => { this.close(); this.options.onNewChildMap?.(x, y); }); + menu.add("editor.new-map", newMapItemTitle({ regionMap, locations: locs }), "plus", () => { this.close(); this.options.onNewChildMap?.(x, y); }); if (this.options.onLinkExistingMap) { menu.add("editor.link-map", "Link existing map…", "link", () => { this.close(); this.options.onLinkExistingMap?.(x, y); }); } diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 6618c295..100204b3 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -80,7 +80,7 @@ import { TokenModal } from "./TokenModal"; import { SubmapPickerModal } from "./SubmapPickerModal"; import { LocationsModal } from "./LocationsModal"; import { startNewChildMap, startNewLocation, type NewChildMapHost } from "./newChildMap"; -import { hexChildMaps, regionMapAt, submapMenuPlan } from "../maps/submaps"; +import { hexChildMaps, newMapItemTitle, parentHexTerrain, regionMapAt, submapMenuPlan } from "../maps/submaps"; import { OverworldLayer } from "./overworldLayer"; import { OverworldMinimap } from "./overworldMinimap"; import { BiomePickerModal, type BiomeHost } from "./BiomeModals"; @@ -695,6 +695,17 @@ export class HexMapView extends ItemView { crumb.addEventListener("click", () => this.navigateToMap(name)); crumbs.createSpan({ cls: "duckmage-map-crumb-sep", text: "›" }); } + // What the hex this map was made from is ("from: barren world"), read + // from the parent's map data (F11: a sector's world type was nowhere + // in the system map made from it). + const from = parentHexTerrain(this.plugin, this.activeMapName); + if (from) { + crumbs.createSpan({ + cls: "duckmage-map-crumb-from", + text: `from: ${from.terrain}`, + attr: { title: `Made from ${from.label}, a ${from.terrain} hex` }, + }); + } crumbs.toggle(ancestors.length > 0); } @@ -4750,13 +4761,21 @@ export class HexMapView extends ItemView { // only fires when drawingMode === null. if (this.drawingMode !== null) return; + // Items the map's work mode locks are left out, with one hint line. + const menu = new ModeMenu(this.currentWorkMode()); // Overworlds are the big-picture view (#49): region-level items only, // no hex editor. - if (OverworldLayer.viewOf(this.plugin, this.getActiveMap())) { - this.showOverworldMenu(evt, x, y); - return; - } + if (OverworldLayer.viewOf(this.plugin, this.getActiveMap())) this.addOverworldMenuItems(menu, evt, x, y); + else this.addHexMenuItems(menu, x, y); + menu.showAtMouseEvent(evt); + } + /** + * A hex's right-click items (also under a token's own items, F8: the + * token covers the hex centre). `inTokenMenu` names the hex's note so it + * isn't taken for the token's. + */ + private addHexMenuItems(menu: ModeMenu, x: number, y: number, inTokenMenu = false): void { const hexPath = this.plugin.hexPath(x, y, this.activeMapName); // Terrain, icon and submap live in the map note, and a hex can have them // before its hex note exists (a generated map, a submap made from this @@ -4764,17 +4783,34 @@ export class HexMapView extends ItemView { // terrain" on such hexes (fresh-eyes N3). const terrain = getTerrainFromFile(this.app, hexPath); const iconOverride = getIconOverrideFromFile(this.app, hexPath); - const childPlan = submapMenuPlan(this.plugin.mapStore.get(this.activeMapName, `${x}_${y}`) - ?? { locations: getHexMapsFromFile(this.app, hexPath).locations }); + const hexMaps = this.plugin.mapStore.get(this.activeMapName, `${x}_${y}`) + ?? { locations: getHexMapsFromFile(this.app, hexPath).locations }; + const childPlan = submapMenuPlan(hexMaps); - // Items the map's work mode locks are left out, with one hint line. - const menu = new ModeMenu(this.currentWorkMode()); + // Maps from this hex (K7) come first, so entering what's there is the + // obvious pick (C11): its region, then up to two locations by name, or + // one "Locations (n)…" item that opens the list. + const region = childPlan.region; + const hasRegion = !!region && !!this.plugin.getMap(region); + if (region && hasRegion) { + menu.add("hex.enter-region", `Enter region: ${this.plugin.mapLabel(region)}`, "log-in", () => this.navigateToMap(region)); + } + for (const loc of childPlan.open) { + menu.add("hex.open-location", `Open: ${this.plugin.mapLabel(loc)}`, "map-pin", () => { + if (this.plugin.getMap(loc)) this.navigateToMap(loc); + else this.openLocationsList(x, y); + }); + } + if (childPlan.listCount) { + menu.add("hex.locations", `Locations (${childPlan.listCount})…`, "list", () => this.openLocationsList(x, y)); + } + if (hasRegion || childPlan.open.length || childPlan.listCount) menu.addSeparator(); menu.add("hex.center", "Center on this hex", "crosshair", () => this.centerOnHex(x, y)); menu.addSeparator(); - menu.add("hex.open-note", "Open note", "file-text", () => { + menu.add("hex.open-note", inTokenMenu ? "Open hex note" : "Open note", "file-text", () => { void (async () => { const existing = this.app.vault.getAbstractFileByPath(hexPath); const file = @@ -4785,22 +4821,9 @@ export class HexMapView extends ItemView { })(); }); - // Maps from this hex (K7): its region, then up to two locations by - // name, or one "Locations (n)…" item that opens the list. - const region = childPlan.region; - if (region && this.plugin.getMap(region)) { - menu.add("hex.enter-region", `Enter region: ${this.plugin.mapLabel(region)}`, "log-in", () => this.navigateToMap(region)); - } - for (const loc of childPlan.open) { - menu.add("hex.open-location", `Open: ${this.plugin.mapLabel(loc)}`, "map-pin", () => { - if (this.plugin.getMap(loc)) this.navigateToMap(loc); - else this.openLocationsList(x, y); - }); - } - if (childPlan.listCount) { - menu.add("hex.locations", `Locations (${childPlan.listCount})…`, "list", () => this.openLocationsList(x, y)); - } - menu.add("hex.new-map", "New map from this hex…", "plus", () => this.openNewSubmapSetup(x, y)); + // "Add another map…" once the hex has one (C11): a hex can hold several + // locations, but the menu doesn't invite re-making the same map. + menu.add("hex.new-map", newMapItemTitle(hexMaps), "plus", () => this.openNewSubmapSetup(x, y)); menu.add("hex.link-map", "Link existing map…", "link", () => this.openLinkExistingMap(x, y)); if (childPlan.open.length) { // Unlinking and reordering live in the list. @@ -4846,16 +4869,14 @@ export class HexMapView extends ItemView { }); } } - - menu.showAtMouseEvent(evt); } /** - * An overworld hex's right-click menu (overworldMenu): Enter region and + * An overworld hex's right-click items (overworldMenu): Enter region and * Edit region… on a region, Set biome… on an empty hex, Center, and the * hex's Locations. In the Regions view the brick under the pointer counts. */ - private showOverworldMenu(evt: MouseEvent, x: number, y: number): void { + private addOverworldMenuItems(menu: ModeMenu, evt: MouseEvent, x: number, y: number): void { const grid = this.viewportEl?.querySelector(".duckmage-hex-map-grid"); const cell = OverworldLayer.viewOf(this.plugin, this.getActiveMap()) === "regions" && grid ? this.overworldLayer.cellAt(grid, evt.clientX, evt.clientY) : null; @@ -4863,7 +4884,6 @@ export class HexMapView extends ItemView { const key = `${px}_${py}`; const region = regionMapAt(this.plugin.settings.maps, this.activeMapName, key)?.name; const locations = this.plugin.mapStore.get(this.activeMapName, key)?.locations?.length ?? 0; - const menu = new ModeMenu(this.currentWorkMode()); const icons: Record = { "enter-region": "log-in", "edit-region": "settings-2", "set-biome": "trees", center: "crosshair", locations: "list" }; for (const it of overworldMenu(this.getActiveMap(), !!region, locations)) { const id = `ow.${it.id}` as const; @@ -4880,7 +4900,6 @@ export class HexMapView extends ItemView { } // Mark the party (or anything) on the overworld: tokens sit on its hexes. menu.add("ow.create-token", "Create token here", "circle-user", () => this.createTokenAtHex(px, py)); - menu.showAtMouseEvent(evt); } /** "Edit region…" for the region on hex (px, py) of `overworld` (default the open map; from inside a region, its overworld). */ @@ -8015,6 +8034,16 @@ export class HexMapView extends ItemView { }); menu.addSeparator(); menu.add("token.remove", "Remove token", "trash", () => this.removeToken(token)); + // The token covers its hex's centre, so the hex's own items follow + // (F8: right-clicking "where the ship is" only gave the token's menu). + const [hx, hy] = token.hex.split("_").map(Number); + if (token.map === this.activeMapName && Number.isFinite(hx) && Number.isFinite(hy)) { + menu.addSeparator(); + const hexName = this.plugin.mapStore.get(this.activeMapName, `${hx}_${hy}`)?.name?.trim(); + menu.addLabel(hexName ? `This hex: ${hexName}` : `This hex: ${hx}, ${hy}`); + if (OverworldLayer.viewOf(this.plugin, this.getActiveMap())) this.addOverworldMenuItems(menu, evt, hx, hy); + else this.addHexMenuItems(menu, hx, hy, true); + } menu.showAtMouseEvent(evt); } } diff --git a/src/hex-map/SubmapPickerModal.ts b/src/hex-map/SubmapPickerModal.ts index a882308b..cff18bf2 100644 --- a/src/hex-map/SubmapPickerModal.ts +++ b/src/hex-map/SubmapPickerModal.ts @@ -138,9 +138,14 @@ export class SubmapPickerModal extends HexmakerModal { cls: "duckmage-submap-create-name", }); if (this.origin) { - // A readable default (NAV2): the hex's name, else " x, y". + // A short readable default (NAV2, F14): the hex's name, else its + // terrain and coordinates, unique among the maps. const { map, x, y } = this.origin; - nameInput.value = defaultSubmapLabel(this.plugin.mapStore.get(map, `${x}_${y}`)?.name, this.plugin.mapLabel(map), x, y); + const hex = this.plugin.mapStore.get(map, `${x}_${y}`); + nameInput.value = defaultSubmapLabel(hex?.name, this.plugin.mapLabel(map), x, y, { + terrain: hex?.terrain ?? this.plugin.getMap(map)?.baseTerrain, + taken: this.plugin.settings.maps.map((m) => this.plugin.mapLabel(m.name)), + }); selectAllOnFocus(nameInput); } diff --git a/src/hex-map/TokenModal.ts b/src/hex-map/TokenModal.ts index 919fab3d..5f03a05d 100644 --- a/src/hex-map/TokenModal.ts +++ b/src/hex-map/TokenModal.ts @@ -113,6 +113,11 @@ export class TokenModal extends HexmakerModal { // exactly-named note, or create a new one. A tester's half-typed // "Hermit" silently became a new note instead of "Hermit's hut". const noteStatusEl = contentEl.createDiv({ cls: "duckmage-token-note-status" }); + // The suggestions drop down over what's below (anchored under the + // status line, which keeps showing) instead of pushing it: opening or + // closing the list used to move the icon grid ~150px, so the next icon + // click hit another icon (fresh-eyes F15). + const resultsAnchor = contentEl.createDiv({ cls: "duckmage-note-picker-anchor" }); const refreshNoteStatus = () => { const title = this.pendingNoteTitle; const target = this.pendingNoteFile ?? (title ? this.findCandidateByName(title) : undefined); @@ -125,9 +130,9 @@ export class TokenModal extends HexmakerModal { } }; - // Inline results list — rendered in flow below the setting so it stays - // within the modal's scroll container (never clips outside). - const resultsEl = contentEl.createDiv({ cls: "duckmage-note-picker-results" }); + // Results list: inside the modal's scroll container (never clips + // outside), but out of flow so it never shifts the form. + const resultsEl = resultsAnchor.createDiv({ cls: "duckmage-note-picker-results is-dropdown" }); resultsEl.hide(); const onPicked = () => { resultsEl.hide(); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index c1be9098..d4b8f11c 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -5,7 +5,7 @@ | **Middle-mouse drag** (or click + drag on empty space) | Pan the map | | **Scroll wheel** | Zoom in / out | | **Left-click** a hex | Open the hex editor (terrain, notes, links) | -| **Right-click** a hex | Context menu: center on hex, open note, enter its region or locations, new map from this hex, link a map, link table, swap hex, create token here, clear terrain | +| **Right-click** a hex | Context menu: its region and locations first, then center on hex, open note, new map from this hex (**Add another map…** once it has one), link a map, link table, swap hex, create token here, clear terrain. On a token: the token's items, then the hex's | | **Double-right-click** anywhere | Exit the active tool and return to normal mode | --- @@ -21,7 +21,7 @@ Hexes with locations show a small ring at the top, with a count once there are t | Action | Result | |--------|--------| -| **Right-click → New map from this hex…** | Pick **Region** or **Location**, then set the map up and go straight into it. A location is named after the hex, or the map name and the hex's coordinates; click the name to type your own | +| **Right-click → New map from this hex…** | Pick **Region** or **Location** (on space maps, a star system or planet is a Location), then set the map up and go straight into it. Maps the hex already has are listed first. A location is named after the hex, or its terrain and coordinates ("Barren world 12, 5"); click the name to type your own | | **Right-click → Enter region / Open: …** | Go into the hex's region, or one of its (up to two) locations | | **Right-click → Locations (3)…** | From three locations on: a list to search, open, unlink and drag into order. Also **Manage locations…** | | **Right-click → Link existing map…** | Add a map you already have as one of the hex's locations | @@ -31,7 +31,7 @@ Hexes with locations show a small ring at the top, with a count once there are t | **←** / **Alt+←** | Back to the map you were on before | | **↑** / **Alt+↑** | Up to the parent map; the hex you came from flashes | | **→** / **Alt+→** | Forward again after going back | -| Breadcrumb (top left) | Jump to any map above this one | +| Breadcrumb (top left) | Jump to any map above this one; it ends with what this map's hex is on the parent ("from: barren world") | | Small hex flower after the arrows (a region of an overworld) | The six regions around this one, each in its direction. Hover a petal for its name, click to go there. An empty petal's **+** makes the region there (pick or roll its biome) | | **◀ ▲ ▼ ▶** after the arrows (neighbouring maps) | Go to the map on that side; hover for its name. **+** on an empty side makes new land there. Inside a submap they go to its parent's neighbours | @@ -110,7 +110,7 @@ Swap the contents of two hex positions by renaming their files. Selecting the source hex again cancels the selection. Selecting a different hex while a destination is already highlighted changes the destination. ### Token -Create a note-backed token (icon, shape, size, colors, description) and place it on the map. The **Token** button opens the token editor, then left-click a hex to place it. Alternatively, **right-click a hex → "Create token here"** creates the token directly on that hex with no placement step. Right-click a placed token to edit, open its note, or remove it. +Create a note-backed token (icon, shape, size, colors, description) and place it on the map. The **Token** button opens the token editor, then left-click a hex to place it. Alternatively, **right-click a hex → "Create token here"** creates the token directly on that hex with no placement step. Right-click a placed token to edit, open its note, or remove it; the hex it sits on has its items below the token's. --- @@ -127,7 +127,7 @@ Create a note-backed token (icon, shape, size, colors, description) and place it The layers button (top right) turns these on and off. - **Link badges**: a coloured icon badge at a hex's right side for each kind of link in its note (towns, dungeons, features, quests, factions). **S / M / L** beside the toggle sets their size for this map. Hover the hex to see what it links. Click ▸ to pick which kinds show. -- **Legend**: the terrains used on this map and the badge kinds shown, at the bottom left (hover a cut-short name for the full one). **S / M / L** sets its size, **–** folds it to a small **Legend** button, **×** hides it. +- **Legend**: the terrains used on this map and the badge kinds shown, at the bottom left, by full name (only very long names are cut; hover one for the full name). **S / M / L** sets its size, **–** folds it to a small **Legend** button, **×** hides it. Opening the layers panel or the drawing tools never moves the map. diff --git a/src/hex-map/modeMenu.ts b/src/hex-map/modeMenu.ts index ca150f65..0c340d6c 100644 --- a/src/hex-map/modeMenu.ts +++ b/src/hex-map/modeMenu.ts @@ -42,6 +42,11 @@ export class ModeMenu { this.menu.addSeparator(); } + /** A greyed heading line for the items that follow (not an action). */ + addLabel(text: string): void { + this.menu.addItem((item) => item.setTitle(text).setIcon("hexagon").setDisabled(true)); + } + /** The one-line hint for what was left out (null when nothing was). */ hint(): string | null { return lockedSummary(this.locked); diff --git a/src/hex-map/newChildMap.ts b/src/hex-map/newChildMap.ts index d20a5525..a9642ab2 100644 --- a/src/hex-map/newChildMap.ts +++ b/src/hex-map/newChildMap.ts @@ -17,6 +17,21 @@ export const CHILD_KIND_TEXT: Record = { + region: { title: "Region", desc: "This stretch of space up close, at the same scale as the regions next to it. Not for a single star system or planet." }, + location: { title: "Location", desc: "A star system, planet or station in this hex, with its own map and size. Pick this for a system or a planet." }, +}; + +/** The card text for a map: space wording on space maps (F10). */ +export function childKindText(space: boolean): Record { + return space ? SPACE_CHILD_KIND_TEXT : CHILD_KIND_TEXT; +} + export interface NewChildMapHost { app: App; plugin: HexmakerPlugin; @@ -91,9 +106,23 @@ export class ChildKindModal extends HexmakerModal { const { plugin } = this.host; const existing = regionMapAt(plugin.settings.maps, this.parentMap, `${this.x}_${this.y}`); const regionsOn = hasFeature(plugin.settings, "regions"); + const text = childKindText(plugin.isSpaceMap(this.parentMap)); + + // The hex's maps first (C11): opening what's there is the usual pick; + // making another location stays possible below. + const locations = (plugin.mapStore.get(this.parentMap, `${this.x}_${this.y}`)?.locations ?? []) + .filter((l) => l !== existing?.name && !!plugin.getMap(l)); + if (locations.length && this.host.onEnter) { + contentEl.createDiv({ cls: "setting-item-description", text: "This hex already has:" }); + for (const name of locations) { + const open = contentEl.createEl("button", { cls: "duckmage-child-kind-enter is-existing", text: `Open ${plugin.mapLabel(name)}` }); + open.addEventListener("click", () => { this.close(); this.host.onEnter?.(name); }); + } + contentEl.createDiv({ cls: "setting-item-description", text: "Or make another:" }); + } const card = (kind: SubmapKind, disabledWhy?: string) => { - const t = CHILD_KIND_TEXT[kind]; + const t = text[kind]; const btn = contentEl.createEl("button", { cls: "duckmage-child-kind-card" }); btn.createDiv({ cls: "duckmage-child-kind-title", text: t.title }); btn.createDiv({ cls: "duckmage-child-kind-desc", text: t.desc }); diff --git a/src/hex-map/submapNav.ts b/src/hex-map/submapNav.ts index a8953e5a..8cf03cfd 100644 --- a/src/hex-map/submapNav.ts +++ b/src/hex-map/submapNav.ts @@ -55,14 +55,29 @@ export function uniqueMapSlug(name: string, taken: Iterable): string { /** * Readable default name for a submap of hex (x, y) (NAV2): the hex's name - * when it has one, else " x, y". + * when it has one, else its terrain and this hex's coordinates + * ("Barren world 12, 5"), else " x, y". Coordinates + * never chain: a parent name ending in its own "x, y" loses them (F14: "The + * Drift 2, 7 12, 5"). With `taken` (other maps' names), a name already + * used gets " (2)", " (3)", … so it stays unique. */ export function defaultSubmapLabel( hexName: string | null | undefined, parentLabel: string, x: number, y: number, + opts: { terrain?: string | null; taken?: Iterable } = {}, ): string { - const named = (hexName ?? "").replace(/\s+/g, " ").trim(); - return named || `${parentLabel} ${x}, ${y}`; + const tidy = (s: string | null | undefined) => (s ?? "").replace(/\s+/g, " ").trim(); + const named = tidy(hexName); + const terrain = tidy(opts.terrain); + const parent = tidy(parentLabel).replace(/\s*-?\d+,\s*-?\d+$/, "") || tidy(parentLabel); + const base = named + || (terrain ? `${terrain.charAt(0).toUpperCase()}${terrain.slice(1)} ${x}, ${y}` : `${parent} ${x}, ${y}`); + const used = new Set([...(opts.taken ?? [])].map((t) => tidy(t).toLowerCase())); + if (!used.has(base.toLowerCase())) return base; + for (let i = 2; ; i++) { + const candidate = `${base} (${i})`; + if (!used.has(candidate.toLowerCase())) return candidate; + } } diff --git a/src/hex-map/terrainLegend.ts b/src/hex-map/terrainLegend.ts index 3a90633f..894b5243 100644 --- a/src/hex-map/terrainLegend.ts +++ b/src/hex-map/terrainLegend.ts @@ -63,8 +63,13 @@ export interface LegendOptions { maxName?: number; } -/** Longest name shown in the map's legend before it's cut (MK2). */ -export const MAP_LEGEND_NAME_MAX = 8; +/** + * Longest name shown in the map's legend before it's cut. MK2 asked for + * short names; fresh-eyes F13 found initials ("g. world", "o. world") + * unreadable, so names now show whole up to this length and only longer + * ones are cut, keeping their start. The full name is on hover. + */ +export const MAP_LEGEND_NAME_MAX = 18; /** Cut to `max` characters with "…" (trailing spaces dropped). */ function cut(text: string, max: number): string { @@ -74,44 +79,29 @@ function cut(text: string, max: number): string { } /** - * A legend name shortened to about `max` characters, or unchanged when it - * fits. Several words keep the last one and shrink the rest to initials - * ("mixed forest hills" → "m.f. hills", a few characters of slack), so - * kinds of forest stay apart; one long word is cut ("brokenlands" → - * "brokenl…"). + * A legend name cut to `max` characters, or unchanged when it fits. The + * start is kept ("mixed forest mountains" → "mixed forest moun…"): the first + * word is usually what tells kinds apart ("garden world", "ocean world"), + * so it never shrinks to an initial. */ export function shortLegendName(name: string, max: number): string { - const text = name.replace(/\s+/g, " ").trim(); - if (max < 2 || [...text].length <= max) return text; - const words = text.split(" "); - if (words.length > 1) { - const last = words[words.length - 1]; - const initials = words.slice(0, -1).map((w) => `${[...w][0]}.`).join(""); - const room = max + 3 - initials.length - 1; - if (room >= 3) return `${initials} ${cut(last, room)}`; - } - return cut(text, max); + return cut(tidy(name), max); +} + +/** Runs of whitespace as one space, trimmed. */ +function tidy(name: string): string { + return name.replace(/\s+/g, " ").trim(); } /** * Short names for a whole legend: shortLegendName, except where two short - * forms would clash (the legend must tell them apart): those keep their - * last word whole ("m.f. mountain" / "m.f. mountains"), else the full name. + * forms would clash (the legend must tell them apart): those show in full. */ export function shortLegendNames(names: readonly string[], max: number): Map { const short = new Map(names.map((n) => [n, shortLegendName(n, max)])); - const clashing = () => { - const count = new Map(); - for (const s of short.values()) count.set(s, (count.get(s) ?? 0) + 1); - return [...short].filter(([n, s]) => s !== n && (count.get(s) ?? 0) > 1).map(([n]) => n); - }; - for (const n of clashing()) { - const words = n.replace(/\s+/g, " ").trim().split(" "); - if (words.length > 1) { - short.set(n, `${words.slice(0, -1).map((w) => `${[...w][0]}.`).join("")} ${words[words.length - 1]}`); - } - } - for (const n of clashing()) short.set(n, n); + const count = new Map(); + for (const s of short.values()) count.set(s, (count.get(s) ?? 0) + 1); + for (const [n, s] of short) if (s !== n && (count.get(s) ?? 0) > 1) short.set(n, tidy(n)); return short; } diff --git a/src/maps/submaps.ts b/src/maps/submaps.ts index 2bf1de64..ed98b0e1 100644 --- a/src/maps/submaps.ts +++ b/src/maps/submaps.ts @@ -20,7 +20,7 @@ export function submapKindOf(map: Pick | undef } /** Every map a hex opens into: its region first, then its locations. */ -export function hexChildMaps(h: HexData | undefined): string[] { +export function hexChildMaps(h: Pick | undefined): string[] { if (!h) return []; const out = h.regionMap ? [h.regionMap] : []; for (const l of h.locations ?? []) if (!out.includes(l)) out.push(l); @@ -246,3 +246,39 @@ export function regionMirrorFixes( } return fixes; } + +// ── where a submap came from ───────────────────────────────────────────── + +/** What parentHexTerrain needs (the plugin satisfies it). */ +export interface ParentHexHost { + parentOf(mapName: string): { map: string; hex: string } | undefined; + getMap(mapName: string): Pick | undefined; + mapLabel(mapName: string): string; + mapStore: { get(mapName: string, key: string): Pick | undefined }; +} + +/** + * The terrain of the hex `mapName` was made from (its own, else the parent + * map's base terrain), with a label for that hex ("The Drift 2, 7", or its + * name). From the parent's map data, never its hex note (F11). Undefined + * for a top-level map or a hex with no terrain. + */ +export function parentHexTerrain(host: ParentHexHost, mapName: string): { terrain: string; label: string } | undefined { + const parent = host.parentOf(mapName); + if (!parent) return undefined; + const hex = host.mapStore.get(parent.map, parent.hex); + const terrain = (hex?.terrain ?? host.getMap(parent.map)?.baseTerrain ?? "").trim(); + if (!terrain) return undefined; + const [x, y] = parent.hex.split("_"); + const label = hex?.name?.trim() || `${host.mapLabel(parent.map)} ${x}, ${y}`; + return { terrain, label }; +} + +/** + * The right-click item for making a map from a hex: "New map from this + * hex…" on a hex with none, "Add another map…" once it has one (C11: the + * existing map is the item to pick; making another stays possible). + */ +export function newMapItemTitle(h: Pick | undefined): string { + return hexChildMaps(h).length ? "Add another map…" : "New map from this hex…"; +} diff --git a/src/palettes/PaletteEditorView.ts b/src/palettes/PaletteEditorView.ts index edfd6ec4..8b665ad0 100644 --- a/src/palettes/PaletteEditorView.ts +++ b/src/palettes/PaletteEditorView.ts @@ -74,6 +74,17 @@ export class PaletteEditorView extends ItemView { return all.find((p) => p.name === PaletteEditorView.paletteName) ?? all[0]; } + /** + * The tab and pane header name the palette shown (F16: they kept the + * first palette's name after switching). Same pattern as the map view. + */ + private refreshHeader(): void { + const titleEl = this.containerEl.querySelector(".view-header-title"); + if (titleEl) titleEl.setText(this.getDisplayText()); + interface WithUpdateHeader { updateHeader?(): void; } + (this.leaf as unknown as WithUpdateHeader).updateHeader?.(); + } + /** Coalesce rapid edits into one save (the palette note follows). */ private save(): void { window.clearTimeout(this.saveTimer); @@ -93,6 +104,7 @@ export class PaletteEditorView extends ItemView { contentEl.addClass("duckmage-palette-editor"); const pal = this.palette(); if (pal) PaletteEditorView.paletteName = pal.name; + this.refreshHeader(); // ── Toolbar ── const bar = contentEl.createDiv({ cls: "duckmage-pe-toolbar" }); diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts index 9d5e9d0f..da36db8e 100644 --- a/src/space/WorldTypesModal.ts +++ b/src/space/WorldTypesModal.ts @@ -303,7 +303,9 @@ export class WorldTypesModal extends HexmakerModal { if (this.tab === "worlds" && this.preview.map) blank[col("Map")] = this.preview.map; this.cells[this.tab].push(blank); this.changed(); - this.renderRows(); + // The new row is at the bottom of the list: show it and put the + // cursor in its first field (F9: it appeared off-screen). + this.renderRows({ row: this.cells[this.tab].length - 1, target: "first" }); }); this.statusEl = buttons.createSpan({ cls: "duckmage-world-types-status" }); this.saveBtn = buttons.createEl("button", { text: "Save", cls: "mod-cta" }); @@ -374,9 +376,20 @@ export class WorldTypesModal extends HexmakerModal { return full; } - private renderRows(): void { + /** + * Draw the rows. Re-drawing keeps the list's scroll position; `focus` + * says where the cursor goes after: a row's first field (a new row, + * scrolled into view), its move button (moving again), or the list + * itself (after a delete, so typing never lands in the row that slid into + * the deleted one's place, F9). `keepHeight` keeps the list as tall as + * before (a delete) until the pointer leaves it, so rows above the + * deleted one don't shift under the pointer. + */ + private renderRows(focus?: { row: number; target: "first" | "up" | "down" | "list" }, keepHeight?: number): void { const el = this.rowsEl; + const scrollTop = el.scrollTop; el.empty(); + el.setAttr("tabindex", "-1"); const lock = this.lock(); const lists: Record = {}; for (const [c, types] of Object.entries(SUGGEST_TYPES)) lists[c] = this.datalist(c.toLowerCase(), this.suggestions(types)); @@ -400,21 +413,41 @@ export class WorldTypesModal extends HexmakerModal { : line("duckmage-world-types-line", spec.columns); if (this.tab === "worlds") line("duckmage-world-types-line is-setup", SETUP_COLUMNS); const tools = top.createDiv({ cls: "duckmage-world-types-tools" }); - const btn = (text: string, label: string, fn: () => void, disabled: boolean) => { + const btn = (text: string, label: string, fn: () => void, disabled: boolean, after: () => { row: number; target: "up" | "down" | "list" }, keep = false) => { const b = tools.createEl("button", { text, attr: { "aria-label": label, title: label } }); + b.setAttr("data-tool", text === "↑" ? "up" : text === "↓" ? "down" : "remove"); if (lock) lockButton(b, lock); else b.disabled = disabled; b.addEventListener("click", () => { if (this.lock()) return; + const height = keep ? el.scrollHeight : undefined; fn(); this.changed(); - this.renderRows(); + this.renderRows(after(), height); }); }; - btn("↑", "Move up", () => { [rows[i - 1], rows[i]] = [rows[i], rows[i - 1]]; }, i === 0); - btn("↓", "Move down", () => { [rows[i + 1], rows[i]] = [rows[i], rows[i + 1]]; }, i === rows.length - 1); - btn("✕", "Remove row", () => { rows.splice(i, 1); }, false); + btn("↑", "Move up", () => { [rows[i - 1], rows[i]] = [rows[i], rows[i - 1]]; }, i === 0, () => ({ row: i - 1, target: "up" })); + btn("↓", "Move down", () => { [rows[i + 1], rows[i]] = [rows[i], rows[i + 1]]; }, i === rows.length - 1, () => ({ row: i + 1, target: "down" })); + btn("✕", "Remove row", () => { rows.splice(i, 1); }, false, () => ({ row: i, target: "list" }), true); }); + + // A delete keeps the list's height until the pointer leaves it. + const gap = keepHeight !== undefined ? keepHeight - el.scrollHeight : 0; + if (gap > 0) { + const spacer = el.createDiv({ cls: "duckmage-world-types-spacer" }); + spacer.setCssProps({ "--duckmage-wt-spacer": `${gap}px` }); + el.addEventListener("mouseleave", () => spacer.remove(), { once: true }); + } + el.scrollTop = scrollTop; + + if (!focus) return; + const rowEl = el.querySelectorAll(".duckmage-world-types-row")[focus.row]; + if (focus.target === "list" || !rowEl) { el.focus({ preventScroll: true }); return; } + const target = focus.target === "first" + ? rowEl.querySelector("input, select") + : rowEl.querySelector(`button[data-tool="${focus.target}"]:not(:disabled)`); + rowEl.scrollIntoView({ block: "nearest" }); + (target ?? el).focus({ preventScroll: true }); } private cellInput(parent: HTMLElement, cells: string[], spec: TabSpec, c: string, list: string | undefined, locked: boolean, row: HTMLElement): void { diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index afd2a318..0d0e6b90 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -220,14 +220,16 @@ export class NewMapSetupModal extends HexmakerModal { // ── Name ── const nameRow = this.row(form, "Name"); const nameInput = this.labelled(nameRow, nameRow.createEl("input", { type: "text", cls: "duckmage-setup-name" })); - // Submaps start on a readable name: the hex's name, else " x, y" - // (NAV2). The first click selects it all, so typing replaces it. + // Submaps start on a short readable name: the hex's name, else its + // terrain and coordinates, unique among the maps (NAV2, F14). The first + // click selects it all, so typing replaces it. nameInput.value = this.origin ? defaultSubmapLabel( this.plugin.mapStore.get(this.origin.map, `${this.origin.x}_${this.origin.y}`)?.name, this.plugin.mapLabel(this.origin.map), this.origin.x, this.origin.y, + { terrain: this.originTerrain, taken: this.plugin.settings.maps.map((m) => this.plugin.mapLabel(m.name)) }, ) : (this.prefill?.name ?? ""); nameInput.placeholder = "Map name"; @@ -888,7 +890,9 @@ export class NewMapSetupModal extends HexmakerModal { addGeneratedPaths(this.plugin, result.name, paths); await this.plugin.saveSettings(); } - if (missing.length) new Notice(`Skipped paths with no matching path type: ${missing.join(", ")}`); + // Expected and harmless (an Orbit path crossing a planet hex has no + // path type on the planet's palette): skip quietly (fresh-eyes F12). + if (missing.length) console.warn(`[hexmaker] ${result.name}: skipped generated paths with no matching path type: ${missing.join(", ")}`); } let backgroundImage: string | undefined; let bgPath = this.origin ? null : this.bgPath; diff --git a/styles.css b/styles.css index af1352e0..afe31ed4 100644 --- a/styles.css +++ b/styles.css @@ -8692,7 +8692,11 @@ textarea.duckmage-edit-region-notes-input { color: var(--text-muted); } .duckmage-world-types-rows { - max-height: 40vh; + /* Most of the dialog's height (F9: a short inner list hid new rows). */ + max-height: 55vh; + /* The dialog body is a flex column: without this the list was squeezed + to a few rows to fit the preview, which scrolls with the dialog. */ + flex-shrink: 0; overflow-y: auto; display: flex; flex-direction: column; @@ -8941,3 +8945,46 @@ textarea.duckmage-edit-region-notes-input { .duckmage-ow-gaps .duckmage-region-gen-label { font-weight: var(--font-semibold); } + +/* Token form: note suggestions drop down over the form instead of pushing + it, so the icon grid never moves under the pointer (fresh-eyes F15). */ +.duckmage-note-picker-anchor { + position: relative; + height: 0; +} +.duckmage-note-picker-results.is-dropdown { + position: absolute; + top: 0; + left: 0; + right: 0; + z-index: 3; + margin: 0; + box-shadow: var(--shadow-s); +} + +/* Breadcrumb: what the hex this map was made from is (fresh-eyes F11). */ +.duckmage-map-crumb-from { + font-size: 0.78em; + padding: 0 6px 0 2px; + color: var(--text-faint); + font-style: italic; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 14em; +} +/* "New map from this hex": the hex's existing maps, listed first (C11). */ +.duckmage-child-kind-enter.is-existing { + display: block; + margin: 4px 0 6px; +} + +/* World types: a deleted row's space is kept until the pointer leaves + the list, so rows don't slide under it (fresh-eyes F9). */ +.duckmage-world-types-spacer { + flex: none; + height: var(--duckmage-wt-spacer, 0px); +} +.duckmage-world-types-rows:focus { + outline: none; +} diff --git a/tests/mapMarkers.test.ts b/tests/mapMarkers.test.ts index 340ca2f8..504e353f 100644 --- a/tests/mapMarkers.test.ts +++ b/tests/mapMarkers.test.ts @@ -345,18 +345,20 @@ describe("PNG badges stay inside the hex at every size (round 7 R8)", () => { import { MAP_LEGEND_NAME_MAX, shortLegendName, shortLegendNames } from "../src/hex-map/terrainLegend"; describe("map legend (MK2)", () => { - it("shortens long names but keeps them readable and apart", () => { - expect(MAP_LEGEND_NAME_MAX).toBeGreaterThanOrEqual(6); - expect(MAP_LEGEND_NAME_MAX).toBeLessThanOrEqual(8); + // F13 (fresh-eyes 2026-10-11): initials ("g. world") were unreadable; + // names show whole unless really long, and keep their start when cut. + it("shows common names whole and cuts only long ones, keeping the start", () => { + expect(MAP_LEGEND_NAME_MAX).toBeGreaterThanOrEqual(14); + expect(MAP_LEGEND_NAME_MAX).toBeLessThanOrEqual(18); + for (const n of ["garden world", "ocean world", "desert world", "barren world", "mixed forest hills", "terrestrial planet", "gas giant"]) { + expect(shortLegendName(n, MAP_LEGEND_NAME_MAX)).toBe(n); + } expect(shortLegendName("forest", 8)).toBe("forest"); - expect(shortLegendName("mountains", 9)).toBe("mountains"); - // One long word: cut with an ellipsis. expect(shortLegendName("brokenlands", 8)).toBe("brokenl…"); - // Several words: initials, then the last word. - expect(shortLegendName("mixed forest", 8)).toBe("m. forest"); - expect(shortLegendName("mixed forest hills", 8)).toBe("m.f. hills"); - expect(shortLegendName("evergreen hills", 8)).toBe("e. hills"); - expect([...shortLegendName("mixed forest mountains", 8)].length).toBeLessThanOrEqual(11); + expect(shortLegendName("terrestrial planet", 16)).toBe("terrestrial pla…"); + expect(shortLegendName(" mixed forest ", 16)).toBe("mixed forest"); + // Never initials. + expect(shortLegendName("mixed forest mountains", 16)).not.toMatch(/^\w\./); }); it("a legend never shows two rows with the same short name", () => { @@ -364,8 +366,8 @@ describe("map legend (MK2)", () => { const short = shortLegendNames(names, MAP_LEGEND_NAME_MAX); const shown = names.map((n) => short.get(n)); expect(new Set(shown).size).toBe(names.length); - expect(short.get("mixed forest mountain")).toBe("m.f. mountain"); - expect(short.get("mixed forest mountains")).toBe("m.f. mountains"); + expect(short.get("mixed forest mountain")).toBe("mixed forest mountain"); + expect(short.get("mixed forest mountains")).toBe("mixed forest mountains"); }); it("sits at the view's bottom-left (not over the status bar corner)", () => { diff --git a/tests/spaceSoloFixes.test.ts b/tests/spaceSoloFixes.test.ts new file mode 100644 index 00000000..95148b89 --- /dev/null +++ b/tests/spaceSoloFixes.test.ts @@ -0,0 +1,154 @@ +// Fresh-eyes pass 8 (solo space player, 2026-10-11): F8–F16, C3, C11. +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { defaultSubmapLabel } from "../src/hex-map/submapNav"; +import { newMapItemTitle, parentHexTerrain, type ParentHexHost } from "../src/maps/submaps"; +import { CHILD_KIND_TEXT, SPACE_CHILD_KIND_TEXT, childKindText } from "../src/hex-map/newChildMap"; +import { allows, MENU_ACTIONS } from "../src/workMode"; + +const src = (...p: string[]) => readFileSync(path.join(process.cwd(), ...p), "utf8").replace(/\r\n/g, "\n"); + +describe("F14: default submap names are short and unique", () => { + it("uses the hex's terrain and this level's coordinates, never a chain", () => { + expect(defaultSubmapLabel(undefined, "The Drift 2, 7", 12, 5, { terrain: "barren world" })).toBe("Barren world 12, 5"); + // No terrain: the parent's own trailing coordinates are dropped. + expect(defaultSubmapLabel(undefined, "The Drift 2, 7", 12, 5)).toBe("The Drift 12, 5"); + expect(defaultSubmapLabel(undefined, "The Drift", 12, 5)).toBe("The Drift 12, 5"); + // The hex's own name still wins. + expect(defaultSubmapLabel("Kessia", "The Drift 2, 7", 12, 5, { terrain: "garden world" })).toBe("Kessia"); + }); + + it("stays unique among the maps (case and spacing ignored)", () => { + const taken = ["barren world 12, 5", "Barren world 12, 5 (2)", "Kessia"]; + expect(defaultSubmapLabel(undefined, "X", 12, 5, { terrain: "barren world", taken })).toBe("Barren world 12, 5 (3)"); + expect(defaultSubmapLabel(" Kessia ", "X", 1, 1, { taken })).toBe("Kessia (2)"); + expect(defaultSubmapLabel(undefined, "X", 1, 1, { terrain: "ocean world", taken })).toBe("Ocean world 1, 1"); + }); +}); + +describe("F11: the parent hex's terrain, from the parent's map data", () => { + const host = (hex: { terrain?: string; name?: string } | undefined, base?: string): ParentHexHost => ({ + parentOf: (m) => (m === "system" ? { map: "sector", hex: "2_7" } : undefined), + getMap: (m) => (m === "sector" ? { baseTerrain: base } : undefined), + mapLabel: (m) => (m === "sector" ? "The Drift" : m), + mapStore: { get: (m, k) => (m === "sector" && k === "2_7" ? hex : undefined) }, + }); + + it("reads the hex's terrain and labels the hex", () => { + expect(parentHexTerrain(host({ terrain: "barren world" }), "system")).toEqual({ terrain: "barren world", label: "The Drift 2, 7" }); + expect(parentHexTerrain(host({ terrain: "garden world", name: "Kessia" }), "system")).toEqual({ terrain: "garden world", label: "Kessia" }); + }); + + it("falls back to the parent's base terrain; nothing for top maps or bare hexes", () => { + // No hex entry at all (most hexes have no note): still found via the map's base terrain. + expect(parentHexTerrain(host(undefined, "empty space"), "system")?.terrain).toBe("empty space"); + expect(parentHexTerrain(host(undefined), "system")).toBeUndefined(); + expect(parentHexTerrain(host({ terrain: "x" }), "sector")).toBeUndefined(); + }); + + it("the map view shows it in the breadcrumb", () => { + const view = src("src", "hex-map", "HexMapView.ts"); + expect(view).toContain("parentHexTerrain(this.plugin, this.activeMapName)"); + expect(view).toContain("text: `from: ${from.terrain}`"); + }); +}); + +describe("C11: a hex that has a map offers it first, not a re-make", () => { + it("names the make-a-map item for what it does", () => { + expect(newMapItemTitle(undefined)).toBe("New map from this hex…"); + expect(newMapItemTitle({ locations: [] })).toBe("New map from this hex…"); + expect(newMapItemTitle({ locations: ["planet"] })).toBe("Add another map…"); + expect(newMapItemTitle({ regionMap: "r" })).toBe("Add another map…"); + }); + + it("the hex editor's + menu and the New map dialog list the existing maps", () => { + expect(src("src", "hex-map", "HexEditorModal.ts")).toContain('"editor.new-map", newMapItemTitle('); + const dialog = src("src", "hex-map", "newChildMap.ts"); + expect(dialog).toContain("This hex already has:"); + expect(dialog.indexOf("This hex already has:")).toBeLessThan(dialog.indexOf('card("region", why)')); + }); +}); + +describe("F10: Region vs Location says which fits on a space map", () => { + it("space cards name star systems and planets as Locations", () => { + expect(childKindText(false)).toBe(CHILD_KIND_TEXT); + expect(childKindText(true)).toBe(SPACE_CHILD_KIND_TEXT); + expect(SPACE_CHILD_KIND_TEXT.location.desc).toMatch(/star system/i); + expect(SPACE_CHILD_KIND_TEXT.location.desc).toMatch(/planet/i); + expect(SPACE_CHILD_KIND_TEXT.region.desc).toMatch(/not for a single star system or planet/i); + }); + + it("keys off the map's palette (space terrain types), not terrain names", () => { + const dialog = src("src", "hex-map", "newChildMap.ts"); + expect(dialog).toContain("childKindText(plugin.isSpaceMap(this.parentMap))"); + }); +}); + +describe("F8: a token's menu also has its hex's items", () => { + const view = src("src", "hex-map", "HexMapView.ts"); + it("adds the hex's items after the token's, under a label", () => { + const at = view.indexOf("private showTokenContextMenu"); + const body = view.slice(at, view.indexOf("\n }\n", at)); + expect(body.indexOf('"token.remove"')).toBeLessThan(body.indexOf("this.addHexMenuItems(menu, hx, hy, true)")); + expect(body).toContain("menu.addLabel("); + expect(body).toContain("this.addOverworldMenuItems(menu, evt, hx, hy)"); + }); +}); + +describe("C3: Play can enter existing maps; only making new ones needs Build", () => { + it("entering and opening a hex's maps are allowed in Play", () => { + for (const id of ["hex.enter-region", "hex.open-location", "hex.locations", "ow.enter-region", "ow.locations"] as const) { + expect(allows("play", MENU_ACTIONS[id])).toBe(true); + } + expect(allows("play", MENU_ACTIONS["hex.new-map"])).toBe(false); + expect(allows("build", MENU_ACTIONS["hex.new-map"])).toBe(true); + }); +}); + +describe("F12: no notices for expected, harmless cases", () => { + it("generated paths with no path type on the new map are skipped quietly", () => { + const setup = src("src", "worldgen", "NewMapSetupModal.ts"); + expect(setup).not.toContain("new Notice(`Skipped paths with no matching path type"); + expect(setup).toMatch(/if \(missing\.length\) console\.warn\(/); + }); + + it("a palette installed for a new map is quiet; Add palette still says so", () => { + const plugin = src("src", "HexmakerPlugin.ts"); + expect(plugin).toMatch(/async ensurePaletteInstalled[\s\S]*?installPalettePreset\(name, undefined, \{ quiet: true \}\)/); + expect(plugin).toContain("if (!opts.quiet) new Notice(`Added palette"); + expect(src("src", "palettes", "AddPaletteModal.ts")).toMatch(/installPalettePreset\(preset\.name\)/); + }); +}); + +describe("F15: the token form doesn't jump when note suggestions close", () => { + it("the suggestion list drops down out of flow", () => { + expect(src("src", "hex-map", "TokenModal.ts")).toContain('resultsAnchor.createDiv({ cls: "duckmage-note-picker-results is-dropdown" })'); + const css = src("styles.css"); + expect(css).toMatch(/\.duckmage-note-picker-anchor \{\s*position: relative;\s*height: 0;/); + expect(css).toMatch(/\.duckmage-note-picker-results\.is-dropdown \{\s*position: absolute;/); + }); +}); + +describe("F16: the palette editor's title follows the palette shown", () => { + it("updates the header on every render", () => { + const view = src("src", "palettes", "PaletteEditorView.ts"); + const at = view.indexOf("private render(): void {"); + expect(view.slice(at, at + 400)).toContain("this.refreshHeader();"); + expect(view).toContain("updateHeader?.()"); + }); +}); + +describe("F9: world types rows: a new row shows and takes focus; a delete doesn't shift rows", () => { + const modal = src("src", "space", "WorldTypesModal.ts"); + it("Add row focuses the new row's first field", () => { + expect(modal).toContain('this.renderRows({ row: this.cells[this.tab].length - 1, target: "first" })'); + expect(modal).toContain('rowEl.scrollIntoView({ block: "nearest" })'); + }); + it("a delete keeps scroll and height, and focuses the list, not a field", () => { + expect(modal).toContain("el.scrollTop = scrollTop;"); + expect(modal).toContain('() => ({ row: i, target: "list" }), true)'); + expect(modal).toContain('el.addEventListener("mouseleave", () => spacer.remove(), { once: true })'); + }); +}); diff --git a/tests/toolMode.test.ts b/tests/toolMode.test.ts index 86cb3ff5..adca4c47 100644 --- a/tests/toolMode.test.ts +++ b/tests/toolMode.test.ts @@ -134,13 +134,20 @@ describe("Map navigation buttons say where they go (fresh-eyes T4, owner playtes describe("Hex right-click menu offers Enter submap (fresh-eyes N3)", () => { it("reads the hex's region and locations from the map note, not only when a hex note exists", () => { - const menu = method("onHexContextMenu"); - expect(menu).toMatch(/submapMenuPlan\(this\.plugin\.mapStore\.get\(this\.activeMapName/); + // The hex's items are built by addHexMenuItems (also used under a token's items, F8). + expect(method("onHexContextMenu")).toContain("this.addHexMenuItems(menu, x, y)"); + const menu = method("addHexMenuItems"); + expect(menu).toMatch(/const hexMaps = this\.plugin\.mapStore\.get\(this\.activeMapName/); + expect(menu).toContain("submapMenuPlan(hexMaps)"); expect(menu).not.toMatch(/hexExists \?/); expect(menu).toContain("Enter region: ${this.plugin.mapLabel(region)}"); expect(menu).toContain("Open: ${this.plugin.mapLabel(loc)}"); expect(menu).toContain("Locations (${childPlan.listCount})…"); - expect(menu).toContain('"New map from this hex…"'); + // "New map from this hex…" / "Add another map…" (C11). + expect(menu).toContain('"hex.new-map", newMapItemTitle(hexMaps)'); + // The hex's maps come before everything else (C11). + expect(menu.indexOf('"hex.enter-region"')).toBeLessThan(menu.indexOf('"hex.center"')); + expect(menu.indexOf('"hex.open-location"')).toBeLessThan(menu.indexOf('"hex.center"')); }); }); From f684b11d4e331d26f42748c2daa5c0deb96fd47b Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 10:52:41 -0400 Subject: [PATCH 300/558] feat(space): World types dialog autosaves like the hex editor (SP2) F5: the dialog showed "Unsaved changes" and a Save button but saved on Escape/X anyway, writing a half-made row that changed the Sector odds. - No Save button or "Unsaved changes": edits save a moment after typing stops (the hex editor's 800 ms, now AUTOSAVE_MS) and on close, with the hex editor's status pill ("Changes save automatically" ... "All changes saved"). - Only rows that read are written. A row that doesn't (half made, an unknown map kind) is marked "Incomplete, not saved: ..." and stays in the dialog until fixed or removed; it is dropped on close (with a notice) without touching the note. No write when nothing readable changed, so opening/closing or undoing an edit writes nothing. - Hand edits to the note while the dialog is open: a table the dialog hasn't changed takes the note's rows; one changed in both places takes the note's (with a notice). WorldTypeStore.update takes the caller's base and leaves any table the note changed meanwhile as written, so a save never overwrites a hand edit it hasn't read yet. - Logic lives in DOM-free src/space/worldTypesDraft.ts; F9 scroll/focus behaviour unchanged. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- package.json | 4 +- src/hex-map/HexEditorModal.ts | 4 +- src/hex-map/help.md | 2 +- src/hex-map/saveStatus.ts | 3 + src/space/WorldTypeStore.ts | 21 ++- src/space/WorldTypesModal.ts | 275 ++++++++++++++++++------------- src/space/worldTypes.ts | 8 +- src/space/worldTypesDraft.ts | 186 +++++++++++++++++++++ styles.css | 15 +- tests/worldTypesAutosave.test.ts | 192 +++++++++++++++++++++ 11 files changed, 583 insertions(+), 129 deletions(-) create mode 100644 src/space/worldTypesDraft.ts create mode 100644 tests/worldTypesAutosave.test.ts diff --git a/README.md b/README.md index c6b28263..6f977e37 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it; a land neighbour always shows as at least a small strip or corner patch on its side (a swamp to the south-west, say). - **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one; the map draws a faint dashed tether from each moon to the world or gas giant beside it, hidden with the paths; the PNG export draws it too when it includes paths), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). -- **World types** (Advanced: Terrain generators) — which worlds the space generators place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types` (**Default space** ships, with the odds Star scatter and Orbits have always used; **Restore default** puts them back). Each row is a world (a terrain of your palette) with a **Weight** and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature**. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows, and a preview rolls the table for a map, orbit, star and temperature and shows how often each world comes up next to its odds. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. +- **World types** (Advanced: Terrain generators) — which worlds the space generators place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types` (**Default space** ships, with the odds Star scatter and Orbits have always used; **Restore default** puts them back). Each row is a world (a terrain of your palette) with a **Weight** and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature**. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows, and a preview rolls the table for a map, orbit, star and temperature and shows how often each world comes up next to its odds. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once. Rows that can't be read are reported and left in the note as written. Changes in the editor save automatically, like the hex editor (there is no Save button): a moment after you stop typing, and when you close it. A row that isn't finished yet (no world, or a value it can't read) is marked incomplete and isn't saved; it stays in the editor until you fix or remove it, and is dropped when you close it. Edits you make to the note by hand while the editor is open are kept. Editing needs Build or God. - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. diff --git a/package.json b/package.json index bb3f367f..f54f6cd3 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 967734ea..bf7fd101 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -61,12 +61,12 @@ import { withFeature } from "../advancedHints"; import type { MapData } from "../types"; import { RegionNavigateModal } from "./RegionNavigateModal"; import { displayedEncounterLinks, linkDisplayName } from "../encounterLinks"; -import { DebouncedSave, SAVE_STATUS_TEXT, SAVE_STATUS_TITLE, SaveTracker, type SaveState } from "./saveStatus"; +import { AUTOSAVE_MS, DebouncedSave, SAVE_STATUS_TEXT, SAVE_STATUS_TITLE, SaveTracker, type SaveState } from "./saveStatus"; import { openNoteFocused } from "../openNote"; import { TERRAIN_FILTER_MIN, terrainMatches, terrainStartsCollapsed } from "./terrainSection"; /** Typing pause after which a text section autosaves. */ -const TEXT_AUTOSAVE_MS = 800; +const TEXT_AUTOSAVE_MS = AUTOSAVE_MS; /** Unique ids for label for= ↔ textarea pairs. */ let textFieldSeq = 0; diff --git a/src/hex-map/help.md b/src/hex-map/help.md index d4b8f11c..703dfbe2 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -175,7 +175,7 @@ Neighbouring regions share one set of hex numbers: a new region carries on from A road or river that ends on the edge of a region, next to where the neighbour's road of the same type ends, is drawn on to the shared edge on both maps, so the two join up. -**World types** (space; Advanced: Terrain generators). Which worlds Star scatter and Orbits place, how often, and how each world's own map is made, is a table note in `{world folder}/world-types` (**Default space** ships with the usual odds; **Restore default** puts them back). Each row: a **World** (a terrain of the palette), a **Weight**, optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base**. **Edit world types…** (in the Star scatter and Orbits options, or the command) edits the rows and previews how often each world comes up. The same note also has a **Stars** table (the star Orbits picks when its Star choice is Random, by **Weight**) and a **Sector features** table (Star scatter's special hexes, each with a **Chance** per star system hex, like `1 in 50` or `2%`); the editor has a tab and a preview for each. Needs Build or God. +**World types** (space; Advanced: Terrain generators). Which worlds Star scatter and Orbits place, how often, and how each world's own map is made, is a table note in `{world folder}/world-types` (**Default space** ships with the usual odds; **Restore default** puts them back). Each row: a **World** (a terrain of the palette), a **Weight**, optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base**. **Edit world types…** (in the Star scatter and Orbits options, or the command) edits the rows and previews how often each world comes up. The same note also has a **Stars** table (the star Orbits picks when its Star choice is Random, by **Weight**) and a **Sector features** table (Star scatter's special hexes, each with a **Chance** per star system hex, like `1 in 50` or `2%`); the editor has a tab and a preview for each. Changes save automatically (no Save button); a row marked incomplete isn't saved until it's finished, and is dropped when you close the editor. Hand edits to the note made meanwhile are kept. Needs Build or God. With generators on, new maps can also use the built-in **biomes and presets** (Grassland, Taiga, Swamp, Archipelago, Volcanic and more). They place terrain by type, so they work with any palette whose terrains have types. diff --git a/src/hex-map/saveStatus.ts b/src/hex-map/saveStatus.ts index 161d4275..225ac74b 100644 --- a/src/hex-map/saveStatus.ts +++ b/src/hex-map/saveStatus.ts @@ -28,6 +28,9 @@ export const SAVE_STATUS_TEXT: Record = { /** Tooltip on the status: what "automatically" means. */ export const SAVE_STATUS_TITLE = "Saves a moment after you stop typing, and when you close the editor. There is no Save button."; +/** Typing pause after which an edit autosaves (hex editor, World types). */ +export const AUTOSAVE_MS = 800; + /** How long the fresh "saved" colour stays before settling. */ export const SAVED_SHOWN_MS = 2500; diff --git a/src/space/WorldTypeStore.ts b/src/space/WorldTypeStore.ts index 98905dd0..4cf0b321 100644 --- a/src/space/WorldTypeStore.ts +++ b/src/space/WorldTypeStore.ts @@ -26,7 +26,11 @@ import { copyFeatureRows, copyStarRows, copyWorldTypeRows, + featureCells, parseWorldTypes, + sameOptional, + starCells, + worldTypeCells, updateWorldTypes, upgradeWorldTypes, type SectorFeatureRow, @@ -154,8 +158,13 @@ export class WorldTypeStore { /** * Set a table's rows, and its Stars / Sector features rows when given * (rows the note has that can't be read are kept as written). + * + * `base`: the table as the caller last saw it. A table (Worlds, Stars, + * Sector features) the note no longer has as in `base` was hand-edited + * meanwhile, so it is left as the note has it (the caller hears of it + * through onChange). */ - async update(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}): Promise { + async update(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}, base?: WorldTypeTable): Promise { await this.queue; // hand edits read first const e = this.find(name); if (!e) return false; @@ -163,7 +172,15 @@ export class WorldTypeStore { if (!(f instanceof TFile)) return false; await this.enqueue(async () => { const content = await this.plugin.app.vault.read(f); - const next = updateWorldTypes(content, rows, extras); + let put = rows; + const more: WorldTypeExtras = { ...extras }; + if (base) { + const now = parseWorldTypes(content); + if (!sameOptional(now.rows, base.rows, worldTypeCells)) put = now.rows; + if (!sameOptional(now.stars, base.stars, starCells)) delete more.stars; + if (!sameOptional(now.features, base.features, featureCells)) delete more.features; + } + const next = updateWorldTypes(content, put, more); if (next !== content) await this.plugin.app.vault.modify(f, next); this.take(f.path, next); this.publish(); diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts index da36db8e..f3124847 100644 --- a/src/space/WorldTypesModal.ts +++ b/src/space/WorldTypesModal.ts @@ -9,6 +9,13 @@ * anything typed here reads back the same from the note. Rows the note * has that can't be read are listed, never touched. * + * Changes save automatically, like the hex editor (SP2): a moment after + * typing stops, and when the dialog closes. Only rows that read are + * written; a row that doesn't is marked incomplete and stays here until + * it's fixed or removed (it's dropped on close). Hand edits to the note + * while the dialog is open are taken in, never overwritten + * (worldTypesDraft.ts has the rules). + * * Opened from the space generators' options (New map / submap setup) and * the "Edit world types…" command. Editing follows the map's work mode: * Build and God (canAdd), not Play. @@ -24,29 +31,20 @@ import { ORBIT_ZONES, STAR_COLUMNS, WORLD_TYPE_COLUMNS, - featureCells, formatChance, - readFeatureCells, - readStarCells, - readWorldTypeCells, rollSectorFeatures, rollStars, rollWorldTypes, sectorFeatureOdds, - starCells, starOdds, - worldTypeCells, worldTypeOdds, type OrbitZone, - type SectorFeatureRow, - type StarTypeRow, type WorldTypeColumn, type WorldTypeContext, - type WorldTypeExtras, type WorldTypeMap, - type WorldTypeRow, - type WorldTypeTable, } from "./worldTypes"; +import { TAB_ORDER, WorldTypesDraft, type WorldTypesTab } from "./worldTypesDraft"; +import { AUTOSAVE_MS, DebouncedSave, SAVE_STATUS_TEXT, SaveTracker, type SaveState } from "../hex-map/saveStatus"; /** Why world types can't be edited from this map now, or undefined. */ export function worldTypesEditLock(plugin: HexmakerPlugin, mapName: string | undefined): string | undefined { @@ -85,21 +83,25 @@ const SETUP_COLUMNS: WorldTypeColumn[] = ["Size", "Generator", "Options", "Palet const col = (c: WorldTypeColumn) => WORLD_TYPE_COLUMNS.indexOf(c); -export type WorldTypesTab = "worlds" | "stars" | "features"; +export type { WorldTypesTab }; -/** One tab's table: its columns and how its cells read. */ +/** One tab's table: its columns. */ interface TabSpec { label: string; columns: readonly string[]; - read: (cells: readonly string[]) => { problem?: string }; } const TABS: Record = { - worlds: { label: "Worlds", columns: WORLD_TYPE_COLUMNS, read: readWorldTypeCells }, - stars: { label: "Stars", columns: STAR_COLUMNS, read: readStarCells }, - features: { label: "Sector features", columns: FEATURE_COLUMNS, read: readFeatureCells }, + worlds: { label: "Worlds", columns: WORLD_TYPE_COLUMNS }, + stars: { label: "Stars", columns: STAR_COLUMNS }, + features: { label: "Sector features", columns: FEATURE_COLUMNS }, }; -const TAB_ORDER: WorldTypesTab[] = ["worlds", "stars", "features"]; + +/** Tooltip on the save status. */ +const SAVE_TITLE = "Saves a moment after you stop typing, and when you close the dialog. Rows marked incomplete aren't saved."; + +/** "1 incomplete row" / "2 incomplete rows". */ +const incompleteRows = (n: number) => `${n} incomplete row${n === 1 ? "" : "s"}`; /** Terrain types offered as suggestions for each name column. */ const SUGGEST_TYPES: Record = { @@ -112,16 +114,27 @@ const SUGGEST_TYPES: Record = { export class WorldTypesModal extends HexmakerModal { private tableName: string; private tab: WorldTypesTab; - /** The rows being edited, as note cells, per tab. */ - private cells: Record = { worlds: [], stars: [], features: [] }; - /** Whether the note has a Stars / Sector features table (so an empty one isn't added on save). */ - private has = { stars: false, features: false }; - private dirty = false; + /** The rows being edited and when they need saving (set once the store is ready). */ + private draft: WorldTypesDraft | undefined; private off: (() => void) | undefined; private rowsEl!: HTMLElement; private previewEl!: HTMLElement; - private saveBtn!: HTMLButtonElement; - private statusEl!: HTMLElement; + private problemsEl: HTMLElement | undefined; + private statusEl: HTMLElement | undefined; + private incompleteEl: HTMLElement | undefined; + /** The table names the picker shows (re-drawn when they change). */ + private listed = ""; + private saves = new SaveTracker( + (state) => this.renderSaveStatus(state), + (fn, ms) => window.setTimeout(fn, ms), + (id) => window.clearTimeout(id), + ); + private debounce = new DebouncedSave( + () => this.saveNow(), + AUTOSAVE_MS, + (fn, ms) => window.setTimeout(fn, ms), + (id) => window.clearTimeout(id), + ); private tabButtons = new Map(); private preview: { map: WorldTypeMap | ""; zone: OrbitZone | ""; star: string; temperature: string; n: number } = { map: "", zone: "", star: "", temperature: "", n: 200 }; @@ -140,20 +153,18 @@ export class WorldTypesModal extends HexmakerModal { void this.plugin.worldTypeStore.ensureDefault().then(() => { const store = this.plugin.worldTypeStore; if (!store.get(this.tableName)) this.tableName = store.list()[0]?.name ?? this.tableName; - this.loadRows(); + this.draft = new WorldTypesDraft(store, this.tableName); this.render(); - // Hand edits to the note show up here (unless there are unsaved changes here). - this.off = store.onChange(() => { - if (this.dirty) return; - this.loadRows(); - this.render(); - }); + // Hand edits to the note show up here (worldTypesDraft.ts: sync). + this.off = store.onChange(() => this.storeChanged()); }); } onClose(): void { this.off?.(); - if (this.dirty && !this.lock() && !this.firstProblem()) void this.save(); + this.saveNow(); + this.noteDropped(); + this.saves.dispose(); this.contentEl.empty(); } @@ -161,62 +172,58 @@ export class WorldTypesModal extends HexmakerModal { return worldTypesEditLock(this.plugin, this.mapName); } - private loadRows(): void { - const t = this.plugin.worldTypeStore.get(this.tableName); - this.cells = { - worlds: (t?.rows ?? []).map((r) => worldTypeCells(r)), - stars: (t?.stars ?? []).map((r) => starCells(r)), - features: (t?.features ?? []).map((r) => featureCells(r)), - }; - this.has = { stars: !!t?.stars, features: !!t?.features }; - this.dirty = false; - } - - private rows(): WorldTypeRow[] { - return this.cells.worlds.map((c) => readWorldTypeCells(c).row).filter((r): r is WorldTypeRow => !!r); - } - - private stars(): StarTypeRow[] { - return this.cells.stars.map((c) => readStarCells(c).row).filter((r): r is StarTypeRow => !!r); + /** The rows being edited, as note cells, per tab. */ + private get cells(): Record { + return this.draft?.cells ?? { worlds: [], stars: [], features: [] }; } - private features(): SectorFeatureRow[] { - return this.cells.features.map((c) => readFeatureCells(c).row).filter((r): r is SectorFeatureRow => !!r); + /** Save now if anything that reads changed (incomplete rows never are). */ + private saveNow(): void { + this.debounce.cancel(); + const draft = this.draft; + if (!draft || this.lock() || !draft.hasChanges()) { + this.saves.settle(); + return; + } + void this.saves.track(draft.save().then((ok) => { + if (!ok) throw new Error(`world types table "${draft.name}" not found`); + })); } - /** The table as edited here (readable rows only). */ - private table(): WorldTypeTable { - return { name: this.tableName, rows: this.rows(), stars: this.stars(), features: this.features() }; + /** Incomplete rows are about to be dropped (close, another table): say so. */ + private noteDropped(): void { + const n = this.draft?.incompleteCount() ?? 0; + if (n && !this.lock()) new Notice(`World types: ${incompleteRows(n)} weren't saved.`); } - /** The Stars / Sector features rows to save: only when the note has that table or rows were added here. */ - private extras(): WorldTypeExtras { - const out: WorldTypeExtras = {}; - if (this.has.stars || this.cells.stars.length) out.stars = this.stars(); - if (this.has.features || this.cells.features.length) out.features = this.features(); - return out; + /** Show another table (saving this one's changes first). */ + private switchTable(name: string): void { + this.saveNow(); + this.noteDropped(); + this.tableName = name; + this.draft?.load(name); + this.render(); } - private firstProblem(): string | undefined { - for (const tab of TAB_ORDER) { - const rows = this.cells[tab]; - for (let i = 0; i < rows.length; i++) { - const { problem } = TABS[tab].read(rows[i]); - if (problem) return `${TABS[tab].label} row ${i + 1}: ${problem}.`; - } + /** The store changed: a hand edit, our own save coming back, or another table. */ + private storeChanged(): void { + const draft = this.draft; + if (!draft) return; + const { changed, replaced } = draft.sync(); + if (replaced.length) { + const tabs = replaced.map((t) => TABS[t].label).join(" and "); + new Notice(`The world types note was edited, so ${tabs} now show${replaced.length === 1 ? "s" : ""} the note's rows.`, 8000); + } + if (changed || this.tableNames() !== this.listed) { + this.render(); + } else { + this.renderProblems(); + this.updateStatus(); } - return undefined; } - private async save(): Promise { - const problem = this.firstProblem(); - if (problem) { new Notice(problem); return; } - const extras = this.extras(); - if (await this.plugin.worldTypeStore.update(this.tableName, this.rows(), extras)) { - this.dirty = false; - if (extras.stars) this.has.stars = true; - if (extras.features) this.has.features = true; - } + private tableNames(): string { + return this.plugin.worldTypeStore.list().map((t) => t.name).join("\n"); } // ── rendering ────────────────────────────────────────────────────────── @@ -232,12 +239,8 @@ export class WorldTypesModal extends HexmakerModal { const sel = head.createEl("select", { attr: { "aria-label": "Table" } }); for (const t of store.list()) sel.createEl("option", { value: t.name, text: t.name }); sel.value = this.tableName; - sel.addEventListener("change", () => { - if (this.dirty) void this.save(); - this.tableName = sel.value; - this.loadRows(); - this.render(); - }); + this.listed = this.tableNames(); + sel.addEventListener("change", () => this.switchTable(sel.value)); const newBtn = head.createEl("button", { text: "New table…" }); if (lock) lockButton(newBtn, lock); newBtn.addEventListener("click", () => this.newTable(head)); @@ -251,9 +254,11 @@ export class WorldTypesModal extends HexmakerModal { if (lock) lockButton(restore, lock); restore.addEventListener("click", () => { if (this.lock()) return; + this.debounce.cancel(); void store.restoreDefault(this.tableName).then((ok) => { if (!ok) return; - this.loadRows(); + this.draft?.load(this.tableName); + this.saves.settle(); this.render(); new Notice("World types restored (the old note was backed up)."); }); @@ -265,13 +270,8 @@ export class WorldTypesModal extends HexmakerModal { text: `What the space generators place and how often. Each table is a note in ${store.folder()}.`, }); if (lock) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); - const problems = store.problemsOf(this.tableName); - if (problems.length) { - contentEl.createEl("p", { - cls: "duckmage-world-types-problems", - text: `The note has ${problems.length} problem${problems.length === 1 ? "" : "s"} (rows that can't be read are kept as written): ${problems.map((p) => p.text).join("; ")}`, - }); - } + this.problemsEl = contentEl.createDiv(); + this.renderProblems(); const tabs = contentEl.createDiv({ cls: "duckmage-world-types-tabs", attr: { role: "tablist" } }); this.tabButtons.clear(); @@ -307,10 +307,16 @@ export class WorldTypesModal extends HexmakerModal { // cursor in its first field (F9: it appeared off-screen). this.renderRows({ row: this.cells[this.tab].length - 1, target: "first" }); }); - this.statusEl = buttons.createSpan({ cls: "duckmage-world-types-status" }); - this.saveBtn = buttons.createEl("button", { text: "Save", cls: "mod-cta" }); - if (lock) lockButton(this.saveBtn, lock); - this.saveBtn.addEventListener("click", () => void this.save().then(() => this.updateStatus())); + // Rows that can't be read yet, and the autosave status (as in the hex editor). + this.incompleteEl = buttons.createSpan({ cls: "duckmage-world-types-incomplete" }); + this.statusEl = undefined; + if (!lock) { + this.statusEl = buttons.createSpan({ + cls: "duckmage-editor-notes-status duckmage-world-types-status", + attr: { "aria-live": "polite", title: SAVE_TITLE }, + }); + this.renderSaveStatus(this.saves.current); + } contentEl.createEl("h4", { text: "Preview" }); this.previewEl = contentEl.createDiv({ cls: "duckmage-world-types-preview" }); @@ -326,6 +332,19 @@ export class WorldTypesModal extends HexmakerModal { } } + /** What the note has that can't be read (kept as written, not shown as rows). */ + private renderProblems(): void { + const el = this.problemsEl; + if (!el) return; + el.empty(); + const problems = this.plugin.worldTypeStore.problemsOf(this.tableName); + if (!problems.length) return; + el.createEl("p", { + cls: "duckmage-world-types-problems", + text: `The note has ${problems.length} problem${problems.length === 1 ? "" : "s"} (rows that can't be read are kept as written): ${problems.map((p) => p.text).join("; ")}`, + }); + } + private newTable(head: HTMLElement): void { if (this.lock()) return; const box = head.createDiv({ cls: "duckmage-world-types-new" }); @@ -333,30 +352,47 @@ export class WorldTypesModal extends HexmakerModal { const ok = box.createEl("button", { text: "Create", cls: "mod-cta" }); input.focus(); const go = () => { - void this.plugin.worldTypeStore.create(input.value, this.rows(), { stars: this.stars(), features: this.features() }).then((res) => { + const draft = this.draft; + if (!draft) return; + this.saveNow(); + void this.plugin.worldTypeStore.create(input.value, draft.readable("worlds"), { stars: draft.readable("stars"), features: draft.readable("features") }).then((res) => { if ("error" in res) { new Notice(res.error); return; } - this.tableName = res.name; - this.loadRows(); - this.render(); + this.switchTable(res.name); }); }; ok.addEventListener("click", go); input.addEventListener("keydown", (e) => { if (e.key === "Enter") go(); }); } + /** Rows were edited: save a moment later if anything that reads changed. */ private changed(): void { - this.dirty = true; for (const [t, b] of this.tabButtons) b.setText(`${TABS[t].label} (${this.cells[t].length})`); this.updateStatus(); this.renderPreview(); + if (this.lock()) return; + if (this.draft?.hasChanges()) { + this.debounce.schedule(); + this.saves.markPending(); + } else { + // Nothing to write (only incomplete rows, or the edit was undone). + this.debounce.cancel(); + this.saves.settle(); + } } + /** How many rows can't be saved yet. */ private updateStatus(): void { - if (!this.statusEl) return; - const problem = this.firstProblem(); - this.statusEl.setText(problem ?? (this.dirty ? "Unsaved changes" : "")); - this.statusEl.toggleClass("is-error", !!problem); - if (!this.lock()) this.saveBtn.disabled = !!problem || !this.dirty; + const el = this.incompleteEl; + if (!el) return; + const n = this.draft?.incompleteCount() ?? 0; + el.setText(n ? `${incompleteRows(n)} not saved until finished.` : ""); + } + + private renderSaveStatus(state: SaveState): void { + const el = this.statusEl; + if (!el) return; + el.setText(SAVE_STATUS_TEXT[state]); + el.dataset["state"] = state; } /** Terrain names (all palettes) of these types (any type when undefined), for suggestions. */ @@ -400,9 +436,6 @@ export class WorldTypesModal extends HexmakerModal { if (!rows.length) el.createDiv({ cls: "setting-item-description", text: "No rows yet." }); rows.forEach((cells, i) => { const row = el.createDiv({ cls: "duckmage-world-types-row" }); - const problem = spec.read(cells).problem; - row.toggleClass("is-invalid", !!problem); - if (problem) row.setAttr("title", problem); const line = (cls: string, columns: readonly string[]) => { const l = row.createDiv({ cls }); for (const c of columns) this.cellInput(l, cells, spec, c, lists[c], !!lock, row); @@ -429,6 +462,7 @@ export class WorldTypesModal extends HexmakerModal { btn("↑", "Move up", () => { [rows[i - 1], rows[i]] = [rows[i], rows[i - 1]]; }, i === 0, () => ({ row: i - 1, target: "up" })); btn("↓", "Move down", () => { [rows[i + 1], rows[i]] = [rows[i], rows[i + 1]]; }, i === rows.length - 1, () => ({ row: i + 1, target: "down" })); btn("✕", "Remove row", () => { rows.splice(i, 1); }, false, () => ({ row: i, target: "list" }), true); + this.markRow(row, cells); }); // A delete keeps the list's height until the pointer leaves it. @@ -461,23 +495,30 @@ export class WorldTypesModal extends HexmakerModal { if (cells[i] && !["sector", "system"].includes(cells[i])) sel.createEl("option", { value: cells[i], text: cells[i] }); sel.value = cells[i] ?? ""; sel.disabled = locked; - sel.addEventListener("change", () => { cells[i] = sel.value; this.cellChanged(cells, spec, row); }); + sel.addEventListener("change", () => { cells[i] = sel.value; this.cellChanged(cells, row); }); return; } const input = wrap.createEl("input", { type: "text", value: cells[i] ?? "", attr: { placeholder: PLACEHOLDERS[c] ?? "", "aria-label": c } }); if (list) input.setAttr("list", list); input.disabled = locked; - input.addEventListener("input", () => { cells[i] = input.value; this.cellChanged(cells, spec, row); }); + input.addEventListener("input", () => { cells[i] = input.value; this.cellChanged(cells, row); }); } - private cellChanged(cells: string[], spec: TabSpec, row: HTMLElement): void { - const problem = spec.read(cells).problem; - row.toggleClass("is-invalid", !!problem); - if (problem) row.setAttr("title", problem); - else row.removeAttribute("title"); + private cellChanged(cells: string[], row: HTMLElement): void { + this.markRow(row, cells); this.changed(); } + /** Mark a row that can't be read as incomplete, saying what's missing. */ + private markRow(row: HTMLElement, cells: readonly string[]): void { + const problem = this.draft?.problem(this.tab, cells); + row.toggleClass("is-invalid", !!problem); + let hint = row.querySelector(".duckmage-world-types-row-hint"); + if (!problem) { hint?.remove(); return; } + hint ??= row.createDiv({ cls: "duckmage-world-types-row-hint" }); + hint.setText(`Incomplete, not saved: ${problem}.`); + } + // ── preview ──────────────────────────────────────────────────────────── private renderPreview(): void { @@ -505,7 +546,7 @@ export class WorldTypesModal extends HexmakerModal { if (!rollChoices.some(([v]) => Number(v) === p.n)) p.n = Number(rollChoices[1][0]); select("Rolls", rollChoices, String(p.n), (v) => { p.n = Number(v); }); - const table = this.table(); + const table = this.draft?.table() ?? { name: this.tableName, rows: [] }; const list = () => el.createDiv({ cls: "duckmage-world-types-dist" }); const bar = (parent: HTMLElement, name: string, n: number, odds: string) => { const r = parent.createDiv({ cls: "duckmage-world-types-dist-row" }); diff --git a/src/space/worldTypes.ts b/src/space/worldTypes.ts index 7ed605a1..b0f49761 100644 --- a/src/space/worldTypes.ts +++ b/src/space/worldTypes.ts @@ -985,11 +985,17 @@ export function buildWorldTypes(name: string, rows: readonly WorldTypeRow[], ext } /** Rows compared as their cells (the name in any case). */ -function sameRows(a: readonly R[], b: readonly R[], cellsOf: (r: R) => string[]): boolean { +export function sameRows(a: readonly R[], b: readonly R[], cellsOf: (r: R) => string[]): boolean { const key = (r: R) => JSON.stringify(cellsOf(r).map((c, i) => (i === 0 ? c.toLowerCase() : c))); return a.length === b.length && a.every((r, i) => key(r) === key(b[i])); } +/** Two tables' rows match (none and none match too). */ +export function sameOptional(a: readonly R[] | undefined, b: readonly R[] | undefined, cellsOf: (r: R) => string[]): boolean { + if (!a || !b) return !a && !b; + return sameRows(a, b, cellsOf); +} + /** `table` in place of the span, or appended at the end after `head` (a heading and help). */ function putTable(lines: string[], span: Span | null, table: string[], head: string[]): string[] { if (span) return [...lines.slice(0, span.start), ...table, ...lines.slice(span.end)]; diff --git a/src/space/worldTypesDraft.ts b/src/space/worldTypesDraft.ts new file mode 100644 index 00000000..7f3aea13 --- /dev/null +++ b/src/space/worldTypesDraft.ts @@ -0,0 +1,186 @@ +/** + * The World types dialog's rows while they're edited, and when to save + * them (SP2: autosave like the hex editor). DOM-free so it can be tested. + * + * - Rows are kept as their note cells. Only rows that read are ever + * written; a row that doesn't (half made, an unknown map kind) stays + * here, marked incomplete, until it's fixed or removed, and is dropped + * when the dialog closes. + * - `base` is each table as the note had it when last read or saved. A + * save writes only when the readable rows differ from it, so opening and + * closing (or undoing an edit) writes nothing. + * - Hand edits to the note while the dialog is open (sync()): a table the + * dialog hasn't changed takes the note's rows; one changed in both + * places takes the note's rows too (the note wins, and the caller says + * so). The store also skips a table the note changed under a save + * (WorldTypeStore.update's `base`), so a save never overwrites a hand + * edit it hasn't seen yet. + */ + +import { + featureCells, + readFeatureCells, + readStarCells, + readWorldTypeCells, + sameOptional, + starCells, + worldTypeCells, + type SectorFeatureRow, + type StarTypeRow, + type WorldTypeExtras, + type WorldTypeRow, + type WorldTypeTable, +} from "./worldTypes"; + +export type WorldTypesTab = "worlds" | "stars" | "features"; +export const TAB_ORDER: WorldTypesTab[] = ["worlds", "stars", "features"]; + +/** What the draft needs from WorldTypeStore. */ +export interface DraftStore { + get(name: string): WorldTypeTable | undefined; + update(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras, base?: WorldTypeTable): Promise; +} + +type AnyRow = WorldTypeRow | StarTypeRow | SectorFeatureRow; +interface Codec { + read: (cells: readonly string[]) => { row?: AnyRow; problem?: string }; + cells: (row: never) => string[]; +} +const CODECS: Record = { + worlds: { read: readWorldTypeCells, cells: worldTypeCells }, + stars: { read: readStarCells, cells: starCells }, + features: { read: readFeatureCells, cells: featureCells }, +}; + +/** A table's rows for a tab (undefined: the note has no such table). */ +function rowsOf(t: WorldTypeTable | undefined, tab: WorldTypesTab): AnyRow[] | undefined { + if (!t) return undefined; + return tab === "worlds" ? t.rows : tab === "stars" ? t.stars : t.features; +} + +function same(tab: WorldTypesTab, a: readonly AnyRow[] | undefined, b: readonly AnyRow[] | undefined): boolean { + return sameOptional(a, b, CODECS[tab].cells as (r: AnyRow) => string[]); +} + +export interface SyncResult { + /** The rows shown changed (re-draw). */ + changed: boolean; + /** Tabs where edits made here gave way to the note's hand edits. */ + replaced: WorldTypesTab[]; +} + +export class WorldTypesDraft { + /** The rows being edited, as note cells, per tab. */ + cells: Record = { worlds: [], stars: [], features: [] }; + /** The table as the note had it when last read or saved. */ + private base: WorldTypeTable | undefined; + /** What the save in flight is writing (to tell its echo from a hand edit). */ + private sent: WorldTypeTable | undefined; + + constructor(private store: DraftStore, public name: string) { + this.load(); + } + + /** Read the table from the store (dropping anything not saved). */ + load(name: string = this.name): void { + this.name = name; + this.base = this.store.get(name); + this.sent = undefined; + for (const tab of TAB_ORDER) this.cells[tab] = this.cellsOf(tab, rowsOf(this.base, tab)); + } + + private cellsOf(tab: WorldTypesTab, rows: readonly AnyRow[] | undefined): string[][] { + const toCells = CODECS[tab].cells as (r: AnyRow) => string[]; + return (rows ?? []).map((r) => toCells(r)); + } + + /** A tab's rows that read (the ones that would be saved). */ + readable(tab: "worlds"): WorldTypeRow[]; + readable(tab: "stars"): StarTypeRow[]; + readable(tab: "features"): SectorFeatureRow[]; + readable(tab: WorldTypesTab): AnyRow[]; + readable(tab: WorldTypesTab): AnyRow[] { + const out: AnyRow[] = []; + for (const c of this.cells[tab]) { + const { row } = CODECS[tab].read(c); + if (row) out.push(row); + } + return out; + } + + /** Why a row can't be read, or undefined. */ + problem(tab: WorldTypesTab, cells: readonly string[]): string | undefined { + return CODECS[tab].read(cells).problem; + } + + /** How many rows (all tabs) can't be read yet. */ + incompleteCount(): number { + let n = 0; + for (const tab of TAB_ORDER) for (const c of this.cells[tab]) if (this.problem(tab, c)) n++; + return n; + } + + /** The table as edited here (readable rows only), for the preview. */ + table(): WorldTypeTable { + return { name: this.name, rows: this.readable("worlds"), stars: this.readable("stars"), features: this.readable("features") }; + } + + /** + * What a save would write for a tab: undefined for Stars / Sector + * features when the note has no such table and none of its rows read + * (so a half-made first row doesn't add an empty table). + */ + private wanted(tab: WorldTypesTab): AnyRow[] | undefined { + const rows = this.readable(tab); + if (tab !== "worlds" && !rowsOf(this.base, tab) && !rows.length) return undefined; + return rows; + } + + /** Readable rows differ from the note's (a save would write). */ + hasChanges(): boolean { + if (!this.base) return false; + return TAB_ORDER.some((tab) => !same(tab, this.wanted(tab), rowsOf(this.base, tab))); + } + + /** Write the readable rows if they changed. True when a write was asked for. */ + async save(): Promise { + if (!this.hasChanges() || !this.base) return false; + const rows = this.readable("worlds"); + const extras: WorldTypeExtras = {}; + const stars = this.wanted("stars") as StarTypeRow[] | undefined; + const features = this.wanted("features") as SectorFeatureRow[] | undefined; + if (stars) extras.stars = stars; + if (features) extras.features = features; + this.sent = { name: this.name, rows, ...extras } as WorldTypeTable; + const base = this.base; + try { + return await this.store.update(this.name, rows, extras, base); + } finally { + this.sent = undefined; + } + } + + /** The store changed: take in hand edits (see the file comment). */ + sync(): SyncResult { + const theirs = this.store.get(this.name); + const out: SyncResult = { changed: false, replaced: [] }; + if (!theirs || !this.base) return out; + for (const tab of TAB_ORDER) { + const t = rowsOf(theirs, tab); + const b = rowsOf(this.base, tab); + if (same(tab, t, b)) continue; + // Our own save coming back: the note now matches what we wrote. + const echo = this.sent && same(tab, t, rowsOf(this.sent, tab)); + const ours = this.wanted(tab); + if (!echo && !same(tab, ours, t)) { + if (!same(tab, ours, b)) out.replaced.push(tab); + // Take the note's rows; rows still being made here stay, at the end. + const incomplete = this.cells[tab].filter((c) => this.problem(tab, c)); + this.cells[tab] = [...this.cellsOf(tab, t), ...incomplete]; + out.changed = true; + } + } + this.base = theirs; + return out; + } +} diff --git a/styles.css b/styles.css index afe31ed4..deb718bd 100644 --- a/styles.css +++ b/styles.css @@ -8683,13 +8683,22 @@ textarea.duckmage-edit-region-notes-input { gap: 6px; } .duckmage-world-types-problems, -.duckmage-world-types-status.is-error { +.duckmage-world-types-row-hint { color: var(--text-error); } -.duckmage-world-types-status { +/* Rows not saved until finished (SP2); pushes the save status right. */ +.duckmage-world-types-incomplete { flex: 1 1 auto; font-size: var(--font-ui-smaller); - color: var(--text-muted); + color: var(--text-error); +} +/* The autosave status pill (the hex editor's), in the buttons row. */ +.duckmage-editor-notes-status.duckmage-world-types-status { + margin: 0; +} +.duckmage-world-types-row-hint { + font-size: var(--font-ui-smaller); + margin-top: 2px; } .duckmage-world-types-rows { /* Most of the dialog's height (F9: a short inner list hid new rows). */ diff --git a/tests/worldTypesAutosave.test.ts b/tests/worldTypesAutosave.test.ts new file mode 100644 index 00000000..650cbe97 --- /dev/null +++ b/tests/worldTypesAutosave.test.ts @@ -0,0 +1,192 @@ +/** + * SP2: the World types dialog saves automatically (worldTypesDraft.ts). + * Only rows that read are written; incomplete rows never are; nothing is + * written when nothing changed; hand edits to the note are never + * overwritten. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { MemVault } from "./helpers/memVault"; +import { + DEFAULT_WORLD_TYPES, + FEATURE_COLUMNS, + STAR_COLUMNS, + WORLD_TYPE_COLUMNS, + buildWorldTypes, + copyWorldTypeRows, + updateWorldTypes, +} from "../src/space/worldTypes"; +import { DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { WorldTypeStore } from "../src/space/WorldTypeStore"; +import { WorldTypesDraft } from "../src/space/worldTypesDraft"; +import { TFile } from "obsidian"; + +const NOTE = `world/world-types/${DEFAULT_WORLD_TYPES}.md`; +const W = (c: string) => WORLD_TYPE_COLUMNS.indexOf(c as never); + +function storePlugin(vault: MemVault) { + return { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { worldFolder: "world", worldTypesSeeded: true } as Record, + saveSettings: async () => {}, + }; +} + +/** A store over a note (with or without Stars / Sector features), and a draft listening to it like the dialog. */ +async function setup(text = buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS, { stars: [{ star: "red dwarf", weight: 2 }], features: [{ feature: "anomaly", chance: 0.02 }] })) { + const v = new MemVault({ [NOTE]: text }); + const store = new WorldTypeStore(storePlugin(v) as never); + await store.init(); + v.writes.length = 0; + const draft = new WorldTypesDraft(store, DEFAULT_WORLD_TYPES); + const syncs: ReturnType[] = []; + store.onChange(() => syncs.push(draft.sync())); + /** A hand edit to the note, read back as Obsidian would (vault modify event). */ + const handEdit = async (next: string, notify = true) => { + v.files.set(NOTE, next); + if (!notify) return; + const f = new TFile(); + f.path = NOTE; + f.name = NOTE.slice(NOTE.lastIndexOf("/") + 1); + f.basename = f.name.replace(/\.md$/, ""); + f.extension = "md"; + store.onModify(f); + await store.ensureDefault(); // waits for the store's queue + }; + return { v, store, draft, syncs, handEdit }; +} + +describe("World types autosave (SP2)", () => { + it("writes nothing when nothing changed, or an edit was undone", async () => { + const { v, draft } = await setup(); + expect(draft.hasChanges()).toBe(false); + expect(await draft.save()).toBe(false); + const row = draft.cells.worlds[0]; + const was = row[W("Weight")]; + row[W("Weight")] = "99"; + expect(draft.hasChanges()).toBe(true); + row[W("Weight")] = was; + expect(draft.hasChanges()).toBe(false); + expect(await draft.save()).toBe(false); + expect(v.writes).toEqual([]); + }); + + it("a restart with the dialog opened and closed rewrites nothing (smoke C5)", async () => { + const { v } = await setup(); + const store = new WorldTypeStore(storePlugin(v) as never); + await store.init(); + const draft = new WorldTypesDraft(store, DEFAULT_WORLD_TYPES); + if (draft.hasChanges()) await draft.save(); + expect(v.writes).toEqual([]); + }); + + it("autosave writes rows that read", async () => { + const { v, store, draft, syncs } = await setup(); + draft.cells.worlds[0][W("Weight")] = "42"; + draft.cells.stars.push(["white dwarf", "3", ""]); + expect(await draft.save()).toBe(true); + expect(v.writes).toEqual([NOTE]); + const t = store.get(DEFAULT_WORLD_TYPES)!; + expect(t.rows[0].weight).toBe(42); + expect(t.stars!.map((s) => s.star)).toEqual(["red dwarf", "white dwarf"]); + // Our own save coming back is not a hand edit: the rows stay as typed. + expect(syncs.at(-1)).toEqual({ changed: false, replaced: [] }); + expect(draft.hasChanges()).toBe(false); + expect(await draft.save()).toBe(false); + expect(v.writes).toEqual([NOTE]); + }); + + it("never writes an incomplete row (half made, or an unknown map kind)", async () => { + const { v, store, draft } = await setup(); + const before = v.files.get(NOTE); + const blank = WORLD_TYPE_COLUMNS.map(() => ""); + const unknownKind = [...draft.cells.worlds[0]]; + unknownKind[W("World")] = "ice moon"; + unknownKind[W("Map")] = "planet"; + draft.cells.worlds.push(blank, unknownKind); + draft.cells.features.push(["black hole", "", ""].slice(0, FEATURE_COLUMNS.length)); // no chance yet + expect(draft.incompleteCount()).toBe(3); + expect(draft.hasChanges()).toBe(false); + expect(await draft.save()).toBe(false); + expect(v.files.get(NOTE)).toBe(before); + // A real edit beside them writes only that; the Sector odds stay as they were. + draft.cells.worlds[0][W("Weight")] = "7"; + await draft.save(); + const t = store.get(DEFAULT_WORLD_TYPES)!; + expect(t.rows.map((r) => r.world)).not.toContain("ice moon"); + expect(t.features).toEqual([{ feature: "anomaly", chance: 0.02 }]); + expect(v.files.get(NOTE)).not.toContain("black hole"); + // They stay in the dialog until fixed or removed. + expect(draft.incompleteCount()).toBe(3); + }); + + it("closing with only incomplete edits writes nothing (and adds no empty table)", async () => { + const { v, draft } = await setup(buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS)); + const noExtras = updateWorldTypes(v.files.get(NOTE)!, DEFAULT_WORLD_TYPE_ROWS); + expect(noExtras).toBe(v.files.get(NOTE)); + draft.cells.stars.push(STAR_COLUMNS.map(() => "")); + draft.cells.worlds.push(WORLD_TYPE_COLUMNS.map(() => "")); + // What the dialog does on close. + if (draft.hasChanges()) await draft.save(); + expect(v.writes).toEqual([]); + }); + + it("takes in hand edits to tables it hasn't changed, and keeps its own", async () => { + const { v, store, draft, syncs, handEdit } = await setup(); + draft.cells.stars[0][1] = "5"; // edited here, not saved yet + const rows = copyWorldTypeRows(store.get(DEFAULT_WORLD_TYPES)!.rows); + rows[0].weight = 13; + await handEdit(updateWorldTypes(v.files.get(NOTE)!, rows)); + expect(syncs.at(-1)).toEqual({ changed: true, replaced: [] }); + expect(draft.cells.worlds[0][W("Weight")]).toBe("13"); + expect(draft.cells.stars[0][1]).toBe("5"); + await draft.save(); + const t = store.get(DEFAULT_WORLD_TYPES)!; + expect(t.rows[0].weight).toBe(13); + expect(t.stars![0].weight).toBe(5); + }); + + it("a table changed in both places takes the note's rows (and says so)", async () => { + const { v, store, draft, syncs, handEdit } = await setup(); + draft.cells.worlds.push(WORLD_TYPE_COLUMNS.map(() => "")); // incomplete: kept + draft.cells.worlds[0][W("Weight")] = "1"; + const rows = copyWorldTypeRows(store.get(DEFAULT_WORLD_TYPES)!.rows); + rows[0].weight = 13; + await handEdit(updateWorldTypes(v.files.get(NOTE)!, rows)); + expect(syncs.at(-1)).toEqual({ changed: true, replaced: ["worlds"] }); + expect(draft.cells.worlds[0][W("Weight")]).toBe("13"); + expect(draft.incompleteCount()).toBe(1); + expect(draft.hasChanges()).toBe(false); + }); + + it("a save never overwrites a hand edit it hasn't seen yet", async () => { + const { v, store, draft, handEdit } = await setup(); + draft.cells.worlds[0][W("Weight")] = "1"; + draft.cells.stars[0][1] = "9"; + const rows = copyWorldTypeRows(store.get(DEFAULT_WORLD_TYPES)!.rows); + rows[0].weight = 13; + await handEdit(updateWorldTypes(v.files.get(NOTE)!, rows), false); // on disk, event not yet read + await draft.save(); + const t = store.get(DEFAULT_WORLD_TYPES)!; + expect(t.rows[0].weight).toBe(13); // the hand edit stands + expect(t.stars![0].weight).toBe(9); // the table only edited here is saved + }); +}); + +describe("World types dialog: no Save button, autosave status like the hex editor", () => { + const modal = readFileSync(path.join(process.cwd(), "src", "space", "WorldTypesModal.ts"), "utf8").replace(/\r\n/g, "\n"); + it("has no Save button or 'Unsaved changes'", () => { + expect(modal).not.toContain('text: "Save"'); + expect(modal).not.toContain("Unsaved changes"); + expect(modal).toContain("SAVE_STATUS_TEXT[state]"); + expect(modal).toContain("AUTOSAVE_MS"); + }); + it("saves on close (readable rows only) and marks incomplete rows", () => { + const at = modal.indexOf("onClose(): void {"); + expect(modal.slice(at, at + 200)).toContain("this.saveNow();"); + expect(modal).toContain("Incomplete, not saved:"); + }); +}); From d7101408e3579decd6a1f8ab849d0b9f7b4f51a1 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 10:55:53 -0400 Subject: [PATCH 301/558] feat(notes): NF1-NF3 note formats, with a one-time backed-up rewrite Round-6 owner decisions (fresh-eyes-findings 2026-10-09): - NF1: hex notes link their map note under `map:` (was `hexmaker-map:`, which map notes keep as their format marker). Both are read forever. A note whose `map:` is the user's own keeps it; the link then stays under `hexmaker-map:` (withMapLink, MapStore.cleanHexNotes). - NF2: filled `**Terrain:**` / `**Region:**` body lines move into the Map data callout as `Old terrain:` / `Old region:` lines, kept as typed and never read back into the map. The hex editor's notice-with-buttons flow is gone; syncHexMapData moves such lines whenever it syncs a note (open, leave, hex editor). - NF3: token-map is written as a link to the map note, token-link and workflow template-file as wikilinks. Readers accept the plain forms. src/noteFormatUpgrade.ts runs each rewrite once per vault after the map notes load: full-text backup to backups/note-formats-/.json.gz first (nothing written if that fails), recorded in settings.noteFormatUpgrades, no note written when nothing changes. Compat fixtures pin the old forms (tests/fixtures/compat/note-formats). Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 8 +- src/export/exporters/workflow.ts | 14 +- src/frontmatter.ts | 42 ++- src/hex-map/HexEditorModal.ts | 65 ---- src/hex-map/TokenModal.ts | 4 +- src/hex-map/help.md | 2 +- src/hexBodyFields.ts | 48 ++- src/hexMapData.ts | 30 +- src/maps/MapStore.ts | 8 +- src/maps/calloutSync.ts | 28 +- src/maps/mapNote.ts | 28 +- src/noteFormatUpgrade.ts | 251 ++++++++++++++ src/noteFormats.ts | 196 +++++++++++ src/random-tables/RandomTableView.ts | 13 +- src/random-tables/WorkflowEditorModal.ts | 4 +- src/types.ts | 2 + styles.css | 24 -- tests/calloutSync.test.ts | 17 + .../compat/note-formats/hex-note-1.5.6.md | 16 + .../note-formats/hex-note-own-map-key.md | 10 + .../compat/note-formats/token-note-1.5.6.md | 10 + .../compat/note-formats/token-proxy-1.5.6.md | 7 + .../compat/note-formats/workflow-1.5.6.md | 10 + tests/hexBodyFields.test.ts | 17 +- tests/mapNote.test.ts | 6 +- tests/mapStore.test.ts | 6 +- tests/noteFormats.test.ts | 323 ++++++++++++++++++ tests/smokeSuite.test.ts | 13 +- tests/token.test.ts | 5 +- 30 files changed, 1038 insertions(+), 173 deletions(-) create mode 100644 src/noteFormatUpgrade.ts create mode 100644 src/noteFormats.ts create mode 100644 tests/fixtures/compat/note-formats/hex-note-1.5.6.md create mode 100644 tests/fixtures/compat/note-formats/hex-note-own-map-key.md create mode 100644 tests/fixtures/compat/note-formats/token-note-1.5.6.md create mode 100644 tests/fixtures/compat/note-formats/token-proxy-1.5.6.md create mode 100644 tests/fixtures/compat/note-formats/workflow-1.5.6.md create mode 100644 tests/noteFormats.test.ts diff --git a/package.json b/package.json index 4bc55786..8c5f2c5f 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 4abff905..a1c11816 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -67,7 +67,7 @@ import type { } from "./types"; import DEFAULT_HEX_TEMPLATE from "./defaultHexTemplate.md"; import { migrateMapData, pluginVersion } from "./compat"; -import { getTerrainFromFile, getHexRegionFromFile, clearPendingTerrain, setHexDataSource } from "./frontmatter"; +import { getTerrainFromFile, getHexRegionFromFile, clearPendingTerrain, setHexDataSource, tokenMapValue } from "./frontmatter"; import { MapStore, withoutNotePaths } from "./maps/MapStore"; import { setModeMapLookup } from "./modeGate"; import { cellEdits, UndoBook } from "./undoBook"; @@ -88,6 +88,7 @@ import type { RegionSettings } from "./types"; import { mapDataLines, mapDataSyncMessage, setMapData, shownValues, type HexMapDataView } from "./hexMapData"; import { CalloutMemory } from "./maps/calloutMemory"; import { syncHexMapData as syncHexMapDataWith, type CalloutSyncResult } from "./maps/calloutSync"; +import { runNoteFormatUpgrades } from "./noteFormatUpgrade"; import { hexBiomeAt, overworldOf } from "./overworld/regionsVault"; import { BIOMES, biomeNoteOf } from "./overworld/biomes"; import { hasRegionMapData, regionUse, renameRegionInStore, renamedTokenMap, setRegionMapData, type RegionMapDataView } from "./regionMapData"; @@ -172,6 +173,8 @@ export default class HexmakerPlugin extends Plugin { // BC1, once per vault: every overworld hex's biome in its Biome column. void Promise.all([biomesReady, storesReady]).then(() => fillBiomeColumns(this)).catch((e) => console.error("Hexmaker: filling Biome columns", e)); void storesReady.then(() => this.ensureTablesForNewTerrains()); + // NF1–NF3, once per vault: older hex, token and workflow notes in the new note formats (backed up first). + void storesReady.then(() => runNoteFormatUpgrades(this)).catch((e) => console.error("Hexmaker: note format upgrades", e)); // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. void this.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { if (!sandbox) return; @@ -2133,7 +2136,8 @@ export default class HexmakerPlugin extends Plugin { if (!fm || renamedTokenMap(fm["token-map"], oldName, newName) === null) continue; await this.app.fileManager.processFrontMatter(file, (front: Record) => { const next = renamedTokenMap(front["token-map"], oldName, newName); - if (next !== null) front["token-map"] = next; + // An old plain name becomes a link to the map note (NF3); a link keeps its form. + if (next !== null) front["token-map"] = next === newName ? tokenMapValue(newName) : next; }); n++; } diff --git a/src/export/exporters/workflow.ts b/src/export/exporters/workflow.ts index a3e0dec5..82517d3f 100644 --- a/src/export/exporters/workflow.ts +++ b/src/export/exporters/workflow.ts @@ -32,6 +32,7 @@ import { } from "../../random-tables/randomTable"; import { normalizeFolder } from "../../utils"; import type HexmakerPlugin from "../../HexmakerPlugin"; +import { resolveWorkflowTemplate } from "../../random-tables/workflowFiles"; import { fillPlaceholders, escapeTableCell } from "../../textUtils"; import { exportedMessage, openExported, withExportProvenance } from "../exportFolder"; @@ -243,16 +244,9 @@ async function loadTemplate( workflowFile: TFile, ): Promise { if (!workflow.templateFile) return ""; - // Template may be stored as a vault-relative path (with or without .md) or - // an Obsidian link target — try both. - const tf = - plugin.app.vault.getAbstractFileByPath(workflow.templateFile + ".md") ?? - plugin.app.vault.getAbstractFileByPath(workflow.templateFile) ?? - plugin.app.metadataCache.getFirstLinkpathDest( - workflow.templateFile, - workflowFile.path, - ); - if (!(tf instanceof TFile)) return ""; + // A wikilink (NF3) or, in older workflows, a vault path (with or without .md). + const tf = resolveWorkflowTemplate(plugin.app, workflow.templateFile, workflowFile.path); + if (!tf) return ""; return await plugin.app.vault.read(tf); } diff --git a/src/frontmatter.ts b/src/frontmatter.ts index e8bab595..15232d0d 100644 --- a/src/frontmatter.ts +++ b/src/frontmatter.ts @@ -1,6 +1,7 @@ import { App, TFile, parseYaml } from "obsidian"; import type { TokenEntry, TokenShape, TokenSize } from "./types"; import type { ModeAction } from "./workMode"; +import { mapNameFromRef, mapNoteLink, noteLink, noteRefTarget } from "./noteFormats"; import { type OverlayPatternKey, DEFAULT_OVERLAY_PATTERN_KEY, @@ -423,20 +424,38 @@ export async function setGmIconsInFile( const VALID_SHAPES: TokenShape[] = ["circle", "square", "hexagon"]; const VALID_SIZES: TokenSize[] = ["sm", "md", "lg"]; +/** How a token note names its map: a link to the map note (NF3); "" stays "". */ +export function tokenMapValue(map: string): string { + return map ? mapNoteLink(map) : map; +} + +/** + * The note a reference names: a wikilink (resolved like Obsidian does, + * from `sourcePath`) or a vault path (with or without ".md"). Null when + * it names no note. + */ +export function resolveNoteRef(app: App, value: unknown, sourcePath: string): TFile | null { + const { target, link } = noteRefTarget(value); + if (!target) return null; + const direct = app.vault.getAbstractFileByPath(target) ?? app.vault.getAbstractFileByPath(`${target}.md`); + if (direct instanceof TFile) return direct; + if (!link) return null; + const dest = app.metadataCache.getFirstLinkpathDest?.(target.replace(/\.md$/i, ""), sourcePath); + return dest instanceof TFile ? dest : null; +} + export function getTokenDataFromCache(app: App, file: TFile): TokenEntry | null { const cache = app.metadataCache.getFileCache(file); const fm = cache?.frontmatter; if (!fm?.["token"]) return null; const rawShape = fm["token-shape"] as string | undefined; const rawSize = fm["token-size"] as string | undefined; - const tokenLink = typeof fm["token-link"] === "string" ? fm["token-link"] : undefined; + // A proxy's original note: a link (NF3) or, in older notes, a path. + const linked = resolveNoteRef(app, fm["token-link"], file.path); + const tokenLink = linked?.path ?? (noteRefTarget(fm["token-link"]).target || undefined); // Resolve display title from the linked note if this is a proxy - let title = file.basename; - if (tokenLink) { - const linked = app.vault.getAbstractFileByPath(tokenLink); - if (linked instanceof TFile) title = linked.basename; - } + const title = linked ? linked.basename : file.basename; return { filePath: file.path, @@ -444,7 +463,8 @@ export function getTokenDataFromCache(app: App, file: TFile): TokenEntry | null tokenLink, icon: typeof fm["token-icon"] === "string" ? fm["token-icon"] : undefined, hex: typeof fm["token-hex"] === "string" ? fm["token-hex"] : "", - map: typeof fm["token-map"] === "string" ? fm["token-map"] : "", + // A link to the map note (NF3) or, in older notes, the map's name. + map: mapNameFromRef(fm["token-map"]), visible: fm["token-visible"] !== false, shape: VALID_SHAPES.includes(rawShape as TokenShape) ? (rawShape as TokenShape) @@ -473,7 +493,7 @@ export async function readTokenPlace(app: App, path: string): Promise<{ hex: str try { fm = parseYaml(m[1]) as Record | null; } catch { return null; } if (!fm?.["token"]) return null; const s = (v: unknown) => (typeof v === "string" ? v : ""); - return { hex: s(fm["token-hex"]), map: s(fm["token-map"]) }; + return { hex: s(fm["token-hex"]), map: mapNameFromRef(fm["token-map"]) }; } export async function setTokenHex( @@ -486,7 +506,7 @@ export async function setTokenHex( if (!(file instanceof TFile)) return; await app.fileManager.processFrontMatter(file, (fm: Frontmatter) => { fm["token-hex"] = hex; - fm["token-map"] = map; + fm["token-map"] = tokenMapValue(map); }); } @@ -548,7 +568,7 @@ export async function applyTokenFrontmatter( else delete fm["token-icon"]; } if (data.hex !== undefined) fm["token-hex"] = data.hex; - if (data.map !== undefined) fm["token-map"] = data.map; + if (data.map !== undefined) fm["token-map"] = tokenMapValue(data.map); if (data.visible !== undefined) fm["token-visible"] = data.visible; if (data.shape !== undefined) fm["token-shape"] = data.shape; if (data.size !== undefined) fm["token-size"] = data.size; @@ -558,7 +578,7 @@ export async function applyTokenFrontmatter( if (data.border !== undefined) { if (data.border) fm["token-border"] = data.border; else delete fm["token-border"]; } - if (data.tokenLink !== undefined) fm["token-link"] = data.tokenLink; + if (data.tokenLink !== undefined) fm["token-link"] = data.tokenLink ? noteLink(data.tokenLink) : data.tokenLink; if (data.description !== undefined) { if (data.description) fm["token-description"] = data.description; else delete fm["token-description"]; diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 336d57ff..ae81946a 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -19,11 +19,8 @@ import { getGmIconsFromFile, getHexMapsFromFile, getHexNameFromFile, - getHexRegionFromFile, - setHexRegionInFile, } from "../frontmatter"; import { cleanHexName } from "../maps/hexNames"; -import { BODY_FIELDS, readBodyField, sameName, setBodyField, type BodyField } from "../hexBodyFields"; import { addLinkToSection, removeLinkFromSection, @@ -83,8 +80,6 @@ export class HexEditorModal extends HexmakerModal { private allLinks = new Map(); /** Section key → its heading as written in the note (see getAllSectionData). */ private allHeadings = new Map(); - /** "**Terrain:**" / "**Region:**" values written in the note's body (see hexBodyFields). */ - private bodyFields = new Map(); private directTerrain: string | null = null; private directIcon: string | null = null; private directGmIcon: string | null = null; @@ -132,7 +127,6 @@ export class HexEditorModal extends HexmakerModal { this.allText = new Map(); this.allLinks = new Map(); this.allHeadings = new Map(); - this.bodyFields = new Map(); this.directTerrain = null; this.directIcon = null; this.directGmIcon = null; @@ -168,10 +162,6 @@ export class HexEditorModal extends HexmakerModal { if (gm && this.directGmIcon === null) this.directGmIcon = gm[1].trim(); } - for (const f of BODY_FIELDS) { - const v = readBodyField(rawContent, f); - if (v !== undefined) this.bodyFields.set(f, v); - } ({ text: this.allText, links: this.allLinks, headings: this.allHeadings } = await getAllSectionData( this.app, path, @@ -300,7 +290,6 @@ export class HexEditorModal extends HexmakerModal { "Notes", "hexEditorNotesCollapsed", ); - this.renderBodyFieldNotices(notesBody, path); for (const { key, label } of TEXT_SECTIONS) { if (!this.options.gmLayerActive && (key === "hidden" || key === "secret")) continue; this.renderTextSection( @@ -1466,60 +1455,6 @@ export class HexEditorModal extends HexmakerModal { } } - /** - * A "**Terrain:**" or "**Region:**" line in the note that disagrees with - * the map (an older template's hand-filled lines): say so, and offer to - * apply it to the map or to update the line. The line is never removed. - */ - private renderBodyFieldNotices(container: HTMLElement, path: string): void { - const mapValue: Record = { - Terrain: this.directTerrain, - Region: getHexRegionFromFile(this.app, path), - }; - for (const field of BODY_FIELDS) { - const written = this.bodyFields.get(field); - if (written === undefined || sameName(written, mapValue[field])) continue; - const row = container.createDiv({ cls: "duckmage-editor-body-field" }); - const onMap = mapValue[field]; - row.createSpan({ - text: `This note's text says ${field}: ${written}, but the map has ${onMap ? onMap : "none"}.`, - }); - const actions = row.createDiv({ cls: "duckmage-editor-body-field-actions" }); - // Terrain must be one the map's palette has (matched case-insensitively). - const terrain = field === "Terrain" - ? this.plugin.getMapPalette(this.mapName).find((t) => sameName(t.name, written))?.name - : undefined; - if ((field === "Region" || terrain) && canDo(this.mapName, field === "Region" ? "paint-region-area" : "paint-terrain")) { - actions.createEl("button", { text: `Use "${terrain ?? written}" on the map` }).addEventListener("click", () => { - void this.saves.track((async () => { - if (field === "Terrain") { - await this.ensureHexNote(); - await this.plugin.undoableEdit(this.mapName, () => setTerrainInFile(this.app, path, terrain!)); - await this.plugin.syncHexEncounterTableLink(path, terrain!); - this.onChanged(new Map([[path, terrain!]])); - } else { - await this.plugin.undoableEdit(this.mapName, () => setHexRegionInFile(this.app, path, written)); - this.onChanged(); - } - await this.loadData(); - this.onOpen(); - })()); - }); - } - if (onMap) { - actions.createEl("button", { text: `Change the note to "${onMap}"` }).addEventListener("click", () => { - const file = this.app.vault.getAbstractFileByPath(path); - if (!(file instanceof TFile)) return; - void this.saves.track((async () => { - await this.app.vault.process(file, (c) => setBodyField(c, field, onMap)); - await this.loadData(); - this.onOpen(); - })()); - }); - } - } - } - private renderTextSection( container: HTMLElement, path: string, diff --git a/src/hex-map/TokenModal.ts b/src/hex-map/TokenModal.ts index 919fab3d..0491df30 100644 --- a/src/hex-map/TokenModal.ts +++ b/src/hex-map/TokenModal.ts @@ -3,6 +3,7 @@ import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { TokenShape, TokenSize } from "../types"; import { normalizeFolder, getIconUrl, iconLabel } from "../utils"; +import { noteLink } from "../noteFormats"; import { generatorsFolder } from "../worldgen/generators"; import { DEFAULT_TOKEN_FILL, isTokenNoteCandidate } from "./tokenDefaults"; @@ -477,7 +478,8 @@ export class TokenModal extends HexmakerModal { if (!this.app.vault.getAbstractFileByPath(folder)) { try { await this.app.vault.createFolder(folder); } catch { /* race */ } } - await this.app.vault.create(proxyPath, `---\ntoken-link: ${originalPath}\n---\n# ${base}-${n}\n`); + // A link, so renaming the original note keeps the proxy pointing at it (NF3). + await this.app.vault.create(proxyPath, `---\ntoken-link: ${JSON.stringify(noteLink(originalPath))}\n---\n# ${base}-${n}\n`); return proxyPath; } diff --git a/src/hex-map/help.md b/src/hex-map/help.md index c1be9098..05be42f8 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -51,7 +51,7 @@ The **How to edit this note** box at the top of the map note explains the column The map note's **Summary** (above the Hexes table) and the *Route* column in Paths are written by the plugin: extent, base terrain, a terrain legend with counts, regions, each path's ends, forks and length, and a ⚠ for any terrain or path type not in the palette. They update on each save, so edits there are replaced. -**Map data in hex notes.** Hex notes from the built-in template have a **Map data** box: the hex's terrain, region and name (and its region map, locations and, on an overworld, biome). You can edit Terrain, Region or Name there: when you leave the note or open the hex editor, the change goes onto the map. It doesn't if the map changed that value since (the map wins), if the mode locks it (Play), or if the terrain isn't in the palette; then the box keeps a `Not applied:` line saying why. Lines it can't read become `Not read:` lines. +**Map data in hex notes.** Hex notes from the built-in template have a **Map data** box: the hex's terrain, region and name (and its region map, locations and, on an overworld, biome). You can edit Terrain, Region or Name there: when you leave the note or open the hex editor, the change goes onto the map. It doesn't if the map changed that value since (the map wins), if the mode locks it (Play), or if the terrain isn't in the palette; then the box keeps a `Not applied:` line saying why. Lines it can't read become `Not read:` lines. A hand-filled `**Terrain:**` or `**Region:**` line from an older template moves into the box as an `Old terrain:` / `Old region:` line; it never changes the map. A hex note links its map note with `map: "[[_coast]]"` (older notes: `hexmaker-map:`). Paths are named. The **Paths** table lists each path (name, type, your notes); **Path routes** lists the hexes each one passes through in order, like `0, 8 → 9, 8 → 13, 8`, and the map draws the way between them. A path's `main` row is its main line; other rows are forks that leave it at their first hex. The tables are linked by name, so to rename a path edit it in both. Older notes that listed every hex of a path are converted once, after a backup, with a report of what changed beside it. diff --git a/src/hexBodyFields.ts b/src/hexBodyFields.ts index 7d80e076..5eb98882 100644 --- a/src/hexBodyFields.ts +++ b/src/hexBodyFields.ts @@ -4,16 +4,17 @@ * Older hex templates wrote these as lines to fill in by hand. Terrain and * region now live in the map note, so such a line can disagree with the map * (fresh-eyes audit 2026-10-10: 87 of 98 filled Terrain lines did). They are - * the user's words, so they are never removed: the hex editor shows a line - * that disagrees with the map and offers to apply it to the map or to bring - * the line up to date. + * the user's words, so they are never deleted: a filled line moves into the + * note's Map data callout as an "Old terrain:" / "Old region:" line (NF2, + * see hexMapData.ts), where it sits under the map's own value and never + * changes the map. Empty lines and template placeholders stay where they are. */ export type BodyField = "Terrain" | "Region"; export const BODY_FIELDS: BodyField[] = ["Terrain", "Region"]; -const lineRe = (field: BodyField) => new RegExp(`^([ \\t]*\\*\\*${field}:?\\*\\*:?[ \\t]*)(.*?)([ \\t]*)$`, "mi"); +const lineRe = (field: BodyField, flags = "mi") => new RegExp(`^([ \\t]*\\*\\*${field}:?\\*\\*:?[ \\t]*)(.*?)([ \\t]*)$`, flags); /** Template placeholders like "*(woods / marsh / …)*" or "(fill in)": not a value. */ function isPlaceholder(v: string): boolean { @@ -29,11 +30,40 @@ export function readBodyField(content: string, field: BodyField): string | undef return isPlaceholder(v) ? undefined : v; } -/** The note with its "**Field:**" line set to `value` (unchanged when there's no such line). */ -export function setBodyField(content: string, field: BodyField, value: string): string { - // Trailing spaces are kept: two of them are a Markdown line break. - return content.replace(lineRe(field), (_m, head: string, _old: string, tail: string) => - `${head.replace(/[ \t]*$/, " ")}${value}`.replace(/ $/, "") + tail); +/** A filled body line taken out of a note: which field, and its value exactly as typed. */ +export interface TakenBodyField { + field: BodyField; + value: string; +} + +/** + * The note without its filled "**Terrain:**" / "**Region:**" lines, and + * what they said (as typed, links kept), in note order. Empty lines and + * placeholders stay. A blank line left doubled by a removal is dropped + * too. Nothing to take: the content comes back unchanged. + */ +export function takeBodyFields(content: string): { content: string; taken: TakenBodyField[] } { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.split(/\r?\n/); + // Frontmatter is never read as body. + let from = 0; + if (lines[0]?.trim() === "---") { + const close = lines.findIndex((l, i) => i > 0 && l.trim() === "---"); + if (close > 0) from = close + 1; + } + const taken: TakenBodyField[] = []; + const keep: string[] = lines.slice(0, from); + for (let i = from; i < lines.length; i++) { + const line = lines[i]; + const field = BODY_FIELDS.find((f) => lineRe(f, "i").test(line)); + const m = field ? lineRe(field, "i").exec(line) : null; + if (!field || !m || isPlaceholder(m[2])) { keep.push(line); continue; } + taken.push({ field, value: m[2].trim() }); + // Don't leave two blank lines where the line was. + if (keep.length && keep[keep.length - 1].trim() === "" && (lines[i + 1] ?? "").trim() === "") i++; + } + if (!taken.length) return { content, taken }; + return { content: keep.join(eol), taken }; } /** Two names for the same thing (case and spacing aside)? */ diff --git a/src/hexMapData.ts b/src/hexMapData.ts index a88b134d..58a3ce86 100644 --- a/src/hexMapData.ts +++ b/src/hexMapData.ts @@ -26,8 +26,15 @@ * applied stays in the callout as a `Not applied:` line, and lines it can't * read as `Not read:` lines, so nothing typed is lost. Overworld hexes get * a "Biome:" line too. + * + * NF2: filled "**Terrain:**" / "**Region:**" lines from older templates + * move into the callout as "Old terrain:" / "Old region:" lines + * (`moveBodyFieldsIntoMapData`). Like "Not applied:" lines they're the + * user's words: kept as written, never read back into the map. */ +import { takeBodyFields, type TakenBodyField } from "./hexBodyFields"; + export const MAP_DATA_CALLOUT = "[!hexmaker]"; /** Placeholder the built-in template carries until the note is filled in. */ @@ -132,6 +139,24 @@ export function setMapData(content: string, d: HexMapDataView, insert = false, n return lines.join(eol); } +/** + * NF2: the note with its filled "**Terrain:**" / "**Region:**" body lines + * moved into its Map data callout as "Old terrain:" / "Old region:" lines + * (the callout is added under the title when the note has none). The map's + * own values stay as the callout's Terrain and Region: a moved line never + * changes the map. A note with no such lines comes back unchanged. + */ +export function moveBodyFieldsIntoMapData(content: string, d: HexMapDataView): { content: string; moved: TakenBodyField[] } { + const { content: rest, taken } = takeBodyFields(content); + if (!taken.length) return { content, moved: [] }; + return { content: setMapData(rest, d, true, taken.map(oldFieldLine)), moved: taken }; +} + +/** "Old terrain: forest": how a moved body line reads in the callout. */ +export function oldFieldLine(t: TakenBodyField): string { + return `Old ${t.field.toLowerCase()}: ${t.value}`; +} + /** The values written in the callout (a person may have edited them), or null without one. */ export function readMapData(content: string): { terrain?: string; region?: string; name?: string } | null { const lines = content.replace(/\r\n?/g, "\n").split("\n"); @@ -162,7 +187,7 @@ const KEYS: Record = { export type MapDataShown = Record; /** Lines that hold what a person typed and are kept as they are. */ -const KEPT = /^\s*>\s*(not applied|not read)\s*:/i; +const KEPT = /^\s*>\s*(not applied|not read|old terrain|old region)\s*:/i; const isKeptLine = (l: string) => KEPT.test(l); /** The built-in template's placeholder line. */ const PLACEHOLDER = /^filled in from the map by hexmaker\.?$/i; @@ -239,8 +264,9 @@ export function planCalloutImport(content: string, shown: MapDataShown | undefin } /** The notice after importing callout edits, or null when there's nothing to say. */ -export function mapDataSyncMessage(where: string, r: { applied: string[]; notApplied: string[]; unreadable: string[] }): string | null { +export function mapDataSyncMessage(where: string, r: { applied: string[]; notApplied: string[]; unreadable: string[]; moved?: string[] }): string | null { const parts: string[] = []; + if (r.moved?.length) parts.push(`Moved ${r.moved.length === 1 ? "an old line" : `${r.moved.length} old lines`} (${r.moved.join("; ")}) into Map data; the map keeps its own values.`); if (r.applied.length) parts.push(`Put on the map from the note's Map data: ${r.applied.join("; ")}.`); if (r.notApplied.length) parts.push(`Not applied: ${r.notApplied.join("; ")}.`); if (r.unreadable.length) parts.push(`${r.unreadable.length} line${r.unreadable.length === 1 ? "" : "s"} in Map data couldn't be read; marked "Not read:" in the note.`); diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index 12ad0a6e..701e7449 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -23,6 +23,7 @@ import { import { renamedHexes, syncHexNameAlias } from "./hexNames"; import { regionMirrorFixes } from "./submaps"; import { writeJsonBackup } from "../backup"; +import { HEX_MAP_KEY, hexNoteMapKey, LEGACY_HEX_MAP_KEY } from "../noteFormats"; import { guardWrite } from "../modeGate"; import type { ModeAction } from "../workMode"; import { impassableNames } from "../impassable"; @@ -58,8 +59,6 @@ export interface RouteContextChange { /** Hex-note frontmatter keys that hold map data (moved into the map note). */ export const HEX_DATA_KEYS = ["terrain", "icon", "gm-icons", "gm-icon", "region", "duckmage-submap", "locked"] as const; -/** Pointer left in a cleaned hex note's frontmatter. */ -export const MAP_LINK_KEY = "hexmaker-map"; const HEX_FILE = /^(-?\d+)_(-?\d+)\.md$/; @@ -1344,7 +1343,10 @@ export class MapStore { } await fileManager.processFrontMatter(file, (f: Record) => { for (const k of HEX_DATA_KEYS) delete f[k]; - f[MAP_LINK_KEY] = link; + // `map:` (NF1), unless the note uses `map:` for something of its own. + const key = hexNoteMapKey(f); + if (key === HEX_MAP_KEY) delete f[LEGACY_HEX_MAP_KEY]; + f[key] = link; }); } } diff --git a/src/maps/calloutSync.ts b/src/maps/calloutSync.ts index 848cbdd1..2aa2d8a0 100644 --- a/src/maps/calloutSync.ts +++ b/src/maps/calloutSync.ts @@ -5,9 +5,9 @@ */ import { Notice, TFile } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; -import { mapDataLines, mapDataSyncMessage, planCalloutImport, setMapData, shownValues } from "../hexMapData"; +import { mapDataLines, mapDataSyncMessage, moveBodyFieldsIntoMapData, oldFieldLine, planCalloutImport, setMapData, shownValues } from "../hexMapData"; import { lockedHint } from "../workMode"; -import { sameName } from "../hexBodyFields"; +import { sameName, takeBodyFields } from "../hexBodyFields"; /** What syncHexMapData needs from the plugin. */ export type CalloutSyncHost = Pick { - const out = { wrote: false, applied: [] as string[], notApplied: [] as string[], unreadable: [] as string[] }; + const out = { wrote: false, applied: [] as string[], notApplied: [] as string[], unreadable: [] as string[], moved: [] as string[] }; const path = host.hexPath(x, y, mapName); const file = host.app.vault.getAbstractFileByPath(path); if (!(file instanceof TFile)) return out; @@ -36,8 +38,11 @@ export async function syncHexMapData( const current = await host.app.vault.read(file); const now = () => shownValues(mapDataLines(host.hexMapDataView(mapName, x, y))); const plan = planCalloutImport(current, host.calloutMemory.get(path), now()); + // Old "**Terrain:**" / "**Region:**" body lines move into the callout (NF2), + // which is added for them when the note has none. + const hasOldLines = takeBodyFields(current).taken.length > 0; // No callout and none to add: nothing to do. - if (!plan && !opts.insert) return out; + if (!plan && !opts.insert && !hasOldLines) return out; if (plan) { out.notApplied.push(...plan.notApplied); out.unreadable.push(...plan.unreadable); @@ -67,16 +72,21 @@ export async function syncHexMapData( } const view = host.hexMapDataView(mapName, x, y); const notes = [...out.notApplied.map((s) => `Not applied: ${s}`), ...out.unreadable.map((s) => `Not read: ${s}`)]; + const rewrite = (content: string) => { + const m = moveBodyFieldsIntoMapData(content, view); + return { next: setMapData(m.content, view, opts.insert, notes), moved: m.moved.map(oldFieldLine) }; + }; const latest = await host.app.vault.read(file); - if (setMapData(latest, view, opts.insert, notes) !== latest) { + if (rewrite(latest).next !== latest) { await host.app.vault.process(file, (content) => { - const next = setMapData(content, view, opts.insert, notes); - out.wrote = next !== content; - return next; + const r = rewrite(content); + out.wrote = r.next !== content; + out.moved = r.moved; + return r.next; }); } // Remember what the callout shows now, so the next edit is told from a stale copy. - if (plan || opts.insert) host.calloutMemory.set(path, now()); + if (plan || opts.insert || out.moved.length) host.calloutMemory.set(path, now()); if (!opts.quiet) { const msg = mapDataSyncMessage(`${host.mapLabel(mapName)} ${x}, ${y}`, out); if (msg) new Notice(msg, 8000); diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index ed03d0e7..4488780f 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -3,6 +3,7 @@ import type { HexKey, MapData, MapPath, PathBranch, PathChain, RegionSettings } import { formatAnchors, formatAnchor, parseAnchors } from "../paths/anchorText"; import { legacyChainsToPaths } from "../paths/legacy"; import { pathNameKey, uniquePathName } from "../paths/names"; +import { HEX_MAP_KEY, isMapNoteLink, LEGACY_HEX_MAP_KEY } from "../noteFormats"; /** * Map notes: one note per map ("hexes//_.md") holding the map's @@ -2047,24 +2048,33 @@ export function mapNoteKey(data: MapNoteData): string { /** Hex-note frontmatter keys that hold map data (they live in the map note). */ const HEX_NOTE_DATA_KEY = /^(terrain|icon|gm-icons|gm-icon|region|duckmage-submap|locked|hexmaker-map)\s*:/; +/** A top-level `map:` line, and its value. */ +const MAP_KEY_LINE = /^["']?map["']?\s*:(.*)$/; + /** * Prepare a new hex note's text: drop map-data keys a template may carry * (the default one had `terrain:`) and point at the map note instead, so - * nobody edits a terrain field that the map no longer reads. + * nobody edits a terrain field that the map no longer reads. The link goes + * under `map:` (NF1), or under `hexmaker-map:` when the template has a + * `map:` key of its own, which is kept. */ export function withMapLink(content: string, mapName: string): string { - const link = `hexmaker-map: "[[_${mapName}]]"`; const nl = content.includes("\r\n") ? "\r\n" : "\n"; + const line = (key: string) => `${key}: "[[_${mapName}]]"`; const m = /^---\r?\n([\s\S]*?)\r?\n?---(\r?\n|$)/.exec(content); - if (!m) return `---${nl}${link}${nl}---${nl}${content}`; - const kept: string[] = [link]; + if (!m) return `---${nl}${line(HEX_MAP_KEY)}${nl}---${nl}${content}`; + const kept: string[] = []; let inDropped = false; - for (const line of m[1].split(/\r?\n/)) { - if (HEX_NOTE_DATA_KEY.test(line)) { inDropped = true; continue; } + for (const l of m[1].split(/\r?\n/)) { + const mapKey = MAP_KEY_LINE.exec(l); + // An earlier map link (a template copied from a hex note) is replaced. + const oldLink = !!mapKey && isMapNoteLink(mapKey[1].trim().replace(/^(["'])(.*)\1$/, "$2")); + if (HEX_NOTE_DATA_KEY.test(l) || oldLink) { inDropped = true; continue; } // indented lines (list items) belong to the key above them - if (inDropped && /^\s+\S/.test(line)) continue; + if (inDropped && /^\s+\S/.test(l)) continue; inDropped = false; - if (line.trim()) kept.push(line); + if (l.trim()) kept.push(l); } - return `---${nl}${kept.join(nl)}${nl}---${m[2] || nl}${content.slice(m[0].length)}`; + const key = kept.some((l) => MAP_KEY_LINE.test(l)) ? LEGACY_HEX_MAP_KEY : HEX_MAP_KEY; + return `---${nl}${[line(key), ...kept].join(nl)}${nl}---${m[2] || nl}${content.slice(m[0].length)}`; } diff --git a/src/noteFormatUpgrade.ts b/src/noteFormatUpgrade.ts new file mode 100644 index 00000000..ee8cc682 --- /dev/null +++ b/src/noteFormatUpgrade.ts @@ -0,0 +1,251 @@ +/** + * One-time rewrites of existing notes for the round-6 note-format changes + * (owner decisions NF1, NF2, NF3). Each runs once per vault, after the map + * notes are loaded, and is recorded in `settings.noteFormatUpgrades` so a + * restart never runs it again: + * + * - "hex-map-key" (NF1): hex notes' `hexmaker-map: "[[_coast]]"` becomes + * `map: "[[_coast]]"`. A note with a `map:` key of its own is left alone + * and listed in the notice. + * - "hex-body-lines" (NF2): filled `**Terrain:**` / `**Region:**` lines in + * hex-note bodies move into the note's Map data callout as "Old terrain:" + * / "Old region:" lines (the map keeps its own values). + * - "note-links" (NF3): token notes' `token-map: coast` becomes a link to + * the map note, `token-link: world/npcs/Ana.md` a link to that note, and + * workflows' `template-file:` path a link to the template. + * + * Before anything is written, the full text of every note about to change + * is saved as `/backups/note-formats-/.json.gz`. If that + * can't be saved, nothing is changed and the upgrade isn't recorded, so it + * tries again next time. A vault with nothing to change writes no note + * (the record goes into data.json once). Readers accept the old forms + * forever, so a note synced from an older device still works. + */ +import { Notice, TFile, type App } from "obsidian"; +import { writeJsonBackup } from "./backup"; +import { mapDataLines, moveBodyFieldsIntoMapData, shownValues, type HexMapDataView, type MapDataShown } from "./hexMapData"; +import { linkNotePathKey, linkTokenMap, renameHexMapKey } from "./noteFormats"; +import { takeBodyFields } from "./hexBodyFields"; +import { normalizeFolder } from "./utils"; + +export type NoteFormatUpgradeId = "hex-map-key" | "hex-body-lines" | "note-links"; + +export const NOTE_FORMAT_UPGRADES: readonly NoteFormatUpgradeId[] = ["hex-map-key", "hex-body-lines", "note-links"]; + +/** What the upgrades need from the plugin. */ +export interface NoteFormatHost { + app: App; + manifest: { dir?: string }; + settings: { + hexFolder: string; + workflowsFolder?: string; + maps: { name: string }[]; + noteFormatUpgrades?: string[]; + }; + mapStore: { isReady(map?: string): boolean; resolve(path: string): { map: string; key: string } | null }; + hexMapDataView(map: string, x: number, y: number): HexMapDataView; + calloutMemory?: { set(path: string, values: MapDataShown): void }; + saveSettings(): Promise; +} + +/** One upgrade's plan: path → [original, upgraded]. */ +export interface UpgradePlan { + id: NoteFormatUpgradeId; + changes: Map; + /** Notes left alone on purpose, with why (shown in the notice). */ + skipped: { path: string; reason: string }[]; +} + +export interface UpgradeResult extends UpgradePlan { + /** Paths actually rewritten. */ + changed: string[]; + backup?: string; + /** Set when nothing was written because the backup failed. */ + error?: string; +} + +const HEX_FILE = /^-?\d+_-?\d+\.md$/; + +/** Hex notes of known maps (`{hexFolder}/{map}/{x}_{y}.md`), "_" notes never. */ +function hexNotes(host: NoteFormatHost): { file: TFile; map: string; x: number; y: number }[] { + const known = new Set(host.settings.maps.map((m) => m.name)); + const out: { file: TFile; map: string; x: number; y: number }[] = []; + for (const file of host.app.vault.getMarkdownFiles()) { + if (!HEX_FILE.test(file.name)) continue; + const loc = host.mapStore.resolve(file.path); + if (!loc || !known.has(loc.map)) continue; + const [x, y] = loc.key.split("_").map(Number); + out.push({ file, map: loc.map, x, y }); + } + return out.sort((a, b) => a.file.path.localeCompare(b.file.path)); +} + +/** Could the note's frontmatter have one of `keys`? (Not indexed yet: maybe.) */ +function mayHave(host: NoteFormatHost, file: TFile, keys: string[]): boolean { + const cache = host.app.metadataCache.getFileCache(file); + if (!cache) return true; + const fm = cache.frontmatter; + return !!fm && keys.some((k) => k in fm); +} + +/** Work out what an upgrade would change, reading every note it looks at. */ +export async function planUpgrade(host: NoteFormatHost, id: NoteFormatUpgradeId): Promise { + const plan: UpgradePlan = { id, changes: new Map(), skipped: [] }; + const { vault } = host.app; + const add = (path: string, before: string, after: string) => { if (after !== before) plan.changes.set(path, [before, after]); }; + if (id === "hex-map-key") { + for (const { file } of hexNotes(host)) { + if (!mayHave(host, file, ["hexmaker-map"])) continue; + const text = await vault.cachedRead(file); + if (!/hexmaker-map/.test(text)) continue; + const r = renameHexMapKey(text); + if (r.status === "conflict") plan.skipped.push({ path: file.path, reason: "it uses map: for something else, so its link stays under hexmaker-map:" }); + else add(file.path, text, r.content); + } + } else if (id === "hex-body-lines") { + for (const { file, map, x, y } of hexNotes(host)) { + const text = await vault.cachedRead(file); + if (!/\*\*(terrain|region)/i.test(text) || !takeBodyFields(text).taken.length) continue; + // The callout shows the map's values: a map that isn't loaded can't say them. + if (!host.mapStore.isReady(map)) { plan.skipped.push({ path: file.path, reason: `its map (${map}) isn't loaded; the lines move when the note is next opened` }); continue; } + add(file.path, text, moveBodyFieldsIntoMapData(text, host.hexMapDataView(map, x, y)).content); + } + } else { + const exists = (p: string) => vault.getAbstractFileByPath(p) instanceof TFile; + const wfFolder = normalizeFolder(host.settings.workflowsFolder ?? ""); + for (const file of vault.getMarkdownFiles()) { + if (file.basename.startsWith("_") || !mayHave(host, file, ["token-map", "token-link", "template-file"])) continue; + const text = await vault.cachedRead(file); + if (!text.startsWith("---")) continue; + let next = text; + if (/^token-map\s*:/m.test(next)) next = linkTokenMap(next).content; + if (/^token-link\s*:/m.test(next)) next = linkNotePathKey(next, "token-link", exists).content; + if (wfFolder && file.path.startsWith(wfFolder + "/") && /^template-file\s*:/m.test(next)) next = linkNotePathKey(next, "template-file", exists).content; + add(file.path, text, next); + } + } + return plan; +} + +/** Re-plan one note from what's there now (it may have changed since the plan). */ +async function replanOne(host: NoteFormatHost, id: NoteFormatUpgradeId, path: string, current: string): Promise { + const { vault } = host.app; + if (id === "hex-map-key") { + const r = renameHexMapKey(current); + return r.status === "renamed" ? r.content : current; + } + if (id === "hex-body-lines") { + const loc = host.mapStore.resolve(path); + if (!loc || !host.mapStore.isReady(loc.map)) return current; + const [x, y] = loc.key.split("_").map(Number); + return moveBodyFieldsIntoMapData(current, host.hexMapDataView(loc.map, x, y)).content; + } + const exists = (p: string) => vault.getAbstractFileByPath(p) instanceof TFile; + let next = linkTokenMap(current).content; + next = linkNotePathKey(next, "token-link", exists).content; + const wfFolder = normalizeFolder(host.settings.workflowsFolder ?? ""); + if (wfFolder && path.startsWith(wfFolder + "/")) next = linkNotePathKey(next, "template-file", exists).content; + return next; +} + +function backupDir(host: NoteFormatHost, when: Date): string { + return `${host.manifest.dir ?? ""}/backups/note-formats-${when.toISOString().slice(0, 10)}`; +} + +/** + * Run one upgrade: plan, back up every note about to change, then rewrite + * them. Nothing to change: no backup, no writes. Backup failed: nothing + * written (`error` set). + */ +export async function runUpgrade(host: NoteFormatHost, id: NoteFormatUpgradeId, when = new Date()): Promise { + const plan = await planUpgrade(host, id); + const result: UpgradeResult = { ...plan, changed: [] }; + if (!plan.changes.size) return result; + const notes: Record = {}; + for (const [path, [original]] of plan.changes) notes[path] = original; + try { + const json = JSON.stringify({ kind: `note-format-${id}`, savedAt: when.toISOString(), notes }); + result.backup = await writeJsonBackup(host.app.vault.adapter, backupDir(host, when), id, json); + } catch (e) { + console.error(`Hexmap World Creator: couldn't back up notes for the ${id} upgrade; nothing was changed`, e); + result.error = `Couldn't save a backup (${String(e)}), so no note was changed.`; + return result; + } + for (const [path, [original, upgraded]] of plan.changes) { + const file = host.app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) continue; + let wrote = false; + // Re-planned inside process() when the note changed since it was read. + const current = await host.app.vault.read(file); + const next = current === original ? upgraded : await replanOne(host, id, path, current); + if (next === current) continue; + await host.app.vault.process(file, (c) => { + if (c !== current) return c; // changed again meanwhile: left for the next open + wrote = true; + return next; + }); + if (!wrote) continue; + result.changed.push(path); + if (id === "hex-body-lines" && host.calloutMemory) { + // What the callout shows now, so a later hand edit is told from it. + const loc = host.mapStore.resolve(path); + if (loc) { + const [x, y] = loc.key.split("_").map(Number); + host.calloutMemory.set(path, shownValues(mapDataLines(host.hexMapDataView(loc.map, x, y)))); + } + } + } + return result; +} + +const UPGRADE_LABEL: Record = { + "hex-map-key": "map: links in hex notes", + "hex-body-lines": "old Terrain/Region lines moved into Map data", + "note-links": "links for token maps, token notes and workflow templates", +}; + +/** The notice after the upgrades, or null when nothing changed or was skipped. */ +export function upgradeMessage(results: UpgradeResult[]): string | null { + const parts: string[] = []; + for (const r of results) { + if (r.error) { parts.push(`${UPGRADE_LABEL[r.id]}: ${r.error}`); continue; } + if (r.changed.length) parts.push(`${UPGRADE_LABEL[r.id]}: ${r.changed.length} note${r.changed.length === 1 ? "" : "s"} (backup: ${r.backup})`); + if (r.skipped.length) { + const shown = r.skipped.slice(0, 5).map((s) => `${s.path} (${s.reason})`).join("; "); + parts.push(`left as they were: ${shown}${r.skipped.length > 5 ? `; and ${r.skipped.length - 5} more (see the console)` : ""}`); + } + } + return parts.length ? `Hexmap World Creator updated note formats. ${parts.join(". ")}.` : null; +} + +/** + * Run every upgrade this vault hasn't had yet, once. An upgrade is recorded + * when it finished (or had nothing to do); one whose backup failed isn't, + * so it runs again next time. Settings are saved only when a record was + * added. + */ +export async function runNoteFormatUpgrades(host: NoteFormatHost): Promise { + const done = new Set(host.settings.noteFormatUpgrades ?? []); + const todo = NOTE_FORMAT_UPGRADES.filter((id) => !done.has(id)); + if (!todo.length) return []; + const results: UpgradeResult[] = []; + for (const id of todo) { + try { + const r = await runUpgrade(host, id); + results.push(r); + if (!r.error) done.add(id); + if (r.skipped.length) console.warn(`Hexmap World Creator: ${id} upgrade left these notes as they were`, r.skipped); + } catch (e) { + console.error(`Hexmap World Creator: the ${id} note upgrade failed; it will be tried again next time`, e); + } + } + // Ids from other builds stay recorded. + const before = host.settings.noteFormatUpgrades ?? []; + if (done.size !== new Set(before).size) { + host.settings.noteFormatUpgrades = [...before.filter((id) => done.has(id)), ...[...done].filter((id) => !before.includes(id))]; + await host.saveSettings(); + } + const msg = upgradeMessage(results); + if (msg) new Notice(msg, 15000); + return results; +} diff --git a/src/noteFormats.ts b/src/noteFormats.ts new file mode 100644 index 00000000..3163e189 --- /dev/null +++ b/src/noteFormats.ts @@ -0,0 +1,196 @@ +/** + * Note-format changes approved in round 6 (NF1, NF3), as pure text helpers. + * The one-time vault rewrites that use them are in noteFormatUpgrade.ts. + * + * NF1: a hex note points at its map note with `map: "[[_coast]]"`. Older + * notes say `hexmaker-map: "[[_coast]]"` (the same key map notes use for + * their format number, which made the two hard to tell apart). Both are + * read forever. A hex note whose `map:` key is the user's own (anything but + * a link to a map note) keeps it, and the plugin uses `hexmaker-map` there. + * + * NF3: a token note says which map it's on with `token-map: "[[_coast]]"` + * (a link to the map note, so renames flow through Obsidian's link + * updating). Older notes say `token-map: coast`; both are read forever. + * + * No Obsidian imports, so tests can use it directly. + */ + +/** Hex notes: the key holding the link to the hex's map note. */ +export const HEX_MAP_KEY = "map"; +/** Hex notes before NF1 (still read; written only where `map` is the user's). */ +export const LEGACY_HEX_MAP_KEY = "hexmaker-map"; + +/** A name that can sit inside [[…]] unchanged. */ +const linkSafe = (s: string) => !!s && !/[[\]|#^]/.test(s); + +const WIKILINK = /^\s*!?\[\[([^\]|#]*)(?:[#|][^\]]*)?\]\]\s*$/; + +/** The link to a map's note (`[[_coast]]`), or the plain name when it can't be a link. */ +export function mapNoteLink(map: string): string { + return linkSafe(map) ? `[[_${map}]]` : map; +} + +/** + * The map a `token-map` / hex-note map value names: a link to its map note + * (`[[_coast]]`, `[[hexes/coast/_coast|Coast]]`) or the plain name + * (`coast`, the older form). "" when blank or not a string. + */ +export function mapNameFromRef(value: unknown): string { + if (typeof value !== "string") return ""; + const m = WIKILINK.exec(value); + if (!m) return value.trim(); + return (m[1].trim().split("/").pop() ?? "").replace(/\.md$/i, "").replace(/^_/, ""); +} + +/** Is this value a link to a map note (`[[_name]]`, any folder, alias allowed)? */ +export function isMapNoteLink(value: unknown): boolean { + if (typeof value !== "string") return false; + const m = WIKILINK.exec(value); + return !!m && /^_/.test(m[1].trim().split("/").pop() ?? ""); +} + +/** + * The map a hex note says it belongs to: `map:` when it's a link to a map + * note, else the older `hexmaker-map:`. "" when neither. + */ +export function hexNoteMapName(fm: Record | null | undefined): string { + if (!fm) return ""; + if (isMapNoteLink(fm[HEX_MAP_KEY])) return mapNameFromRef(fm[HEX_MAP_KEY]); + if (isMapNoteLink(fm[LEGACY_HEX_MAP_KEY])) return mapNameFromRef(fm[LEGACY_HEX_MAP_KEY]); + return ""; +} + +/** + * The key to write a hex note's map link under: `map`, unless the note + * already uses `map` for something of its own (then `hexmaker-map`). + */ +export function hexNoteMapKey(fm: Record | null | undefined): string { + if (!fm || !(HEX_MAP_KEY in fm) || fm[HEX_MAP_KEY] === null || fm[HEX_MAP_KEY] === "") return HEX_MAP_KEY; + return isMapNoteLink(fm[HEX_MAP_KEY]) ? HEX_MAP_KEY : LEGACY_HEX_MAP_KEY; +} + +// ── raw frontmatter text (keeps formatting, comments and key order) ────── + +interface FmSpan { start: number; end: number; lines: string[]; eol: string } + +function fmLines(content: string): FmSpan | null { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.split(/\r?\n/); + if (lines[0]?.trim() !== "---") return null; + const end = lines.findIndex((l, i) => i > 0 && l.trim() === "---"); + return end > 0 ? { start: 1, end, lines, eol } : null; +} + +/** `key: value` line at the top level of frontmatter → its index, or -1. */ +function keyLine(span: FmSpan, key: string): number { + const re = new RegExp(`^["']?${key.replace(/[-]/g, "\\-")}["']?\\s*:`); + for (let i = span.start; i < span.end; i++) if (re.test(span.lines[i])) return i; + return -1; +} + +/** A scalar written after `key:` → its string value (quotes taken off). */ +function scalarOf(line: string): string { + const raw = line.slice(line.indexOf(":") + 1).trim(); + if (raw.startsWith('"')) { + try { return JSON.parse(raw) as string; } catch { return raw.slice(1, raw.endsWith('"') ? -1 : undefined); } + } + if (raw.startsWith("'")) return raw.slice(1, raw.endsWith("'") ? -1 : undefined).replace(/''/g, "'"); + return raw.replace(/\s+#.*$/, ""); +} + +export type HexMapKeyRewrite = + /** `hexmaker-map:` became `map:`. */ + | "renamed" + /** Nothing to do (no old key, or it isn't a map link). */ + | "none" + /** The note has its own `map:` key: left as it is. */ + | "conflict"; + +/** + * NF1 for one hex note's text: `hexmaker-map: "[[_coast]]"` → `map: + * "[[_coast]]"`, changing only that key's name (value, quoting, comments + * and other keys stay). Left alone: notes without the old key, notes whose + * old key isn't a link to a map note (a map note's format number), and + * notes that already have a `map:` key of their own ("conflict"). + */ +export function renameHexMapKey(content: string): { content: string; status: HexMapKeyRewrite } { + const span = fmLines(content); + if (!span) return { content, status: "none" }; + const old = keyLine(span, LEGACY_HEX_MAP_KEY); + if (old < 0 || !isMapNoteLink(scalarOf(span.lines[old]))) return { content, status: "none" }; + const cur = keyLine(span, HEX_MAP_KEY); + if (cur >= 0) { + // Already ours (both keys, same link): drop the old one. + if (isMapNoteLink(scalarOf(span.lines[cur])) && mapNameFromRef(scalarOf(span.lines[cur])) === mapNameFromRef(scalarOf(span.lines[old]))) { + const lines = [...span.lines]; + lines.splice(old, 1); + return { content: lines.join(span.eol), status: "renamed" }; + } + return { content, status: "conflict" }; + } + const lines = [...span.lines]; + lines[old] = lines[old].replace(/^["']?hexmaker-map["']?(\s*:)/, `${HEX_MAP_KEY}$1`); + return { content: lines.join(span.eol), status: "renamed" }; +} + +/** + * NF3 for one token note's text: `token-map: coast` → `token-map: + * "[[_coast]]"`. Unchanged when the value is already a link, blank, not a + * name that can be a link, or the note isn't a token (`token:` missing or + * false). + */ +export function linkTokenMap(content: string): { content: string; changed: boolean } { + const span = fmLines(content); + if (!span) return { content, changed: false }; + const token = keyLine(span, "token"); + if (token < 0 || /^(false|no|off|0|)$/i.test(scalarOf(span.lines[token]))) return { content, changed: false }; + const at = keyLine(span, "token-map"); + if (at < 0) return { content, changed: false }; + const value = scalarOf(span.lines[at]); + if (!value.trim() || WIKILINK.test(value) || !linkSafe(value.trim())) return { content, changed: false }; + const lines = [...span.lines]; + lines[at] = `token-map: ${JSON.stringify(mapNoteLink(value.trim()))}`; + return { content: lines.join(span.eol), changed: true }; +} + +// ── links to other notes (token-link, workflow template-file) ───────────── + +/** A vault path as a wikilink (`[[world/npcs/Ana]]`, ".md" off), or the path as is when it can't be one. */ +export function noteLink(path: string): string { + const p = path.trim().replace(/\.md$/i, ""); + return linkSafe(p) ? `[[${p}]]` : path.trim(); +} + +/** + * A note reference as written: `[[path|alias]]` → its link text (`path`), + * a quoted or plain path → the path. Whether it's a link is reported too. + */ +export function noteRefTarget(value: unknown): { target: string; link: boolean } { + if (typeof value !== "string") return { target: "", link: false }; + const v = value.trim().replace(/^(["'])(.*)\1$/, "$2").trim(); + const m = WIKILINK.exec(v); + return m ? { target: m[1].trim(), link: true } : { target: v, link: false }; +} + +/** + * NF3 for one frontmatter key holding a note path (`token-link: + * world/npcs/Ana.md`, `template-file: world/workflows/templates/npc.md`): + * the path becomes a wikilink, `exists(path)` permitting (a path that + * names no note is left as typed). Already a link, blank or missing: + * unchanged. + */ +export function linkNotePathKey(content: string, key: string, exists: (path: string) => boolean): { content: string; changed: boolean } { + const span = fmLines(content); + if (!span) return { content, changed: false }; + const at = keyLine(span, key); + if (at < 0) return { content, changed: false }; + const value = scalarOf(span.lines[at]).trim(); + if (!value || WIKILINK.test(value)) return { content, changed: false }; + const path = /\.md$/i.test(value) ? value : `${value}.md`; + if (!exists(path)) return { content, changed: false }; + const link = noteLink(path); + if (link === value) return { content, changed: false }; + const lines = [...span.lines]; + lines[at] = `${key}: ${JSON.stringify(link)}`; + return { content: lines.join(span.eol), changed: true }; +} diff --git a/src/random-tables/RandomTableView.ts b/src/random-tables/RandomTableView.ts index 3dc984c2..28e0246f 100644 --- a/src/random-tables/RandomTableView.ts +++ b/src/random-tables/RandomTableView.ts @@ -38,6 +38,7 @@ import { import { planTableMigration } from "./tableMigration"; import { processTableNote } from "./TableStore"; import { parseWorkflow, generateDefaultTemplate } from "./workflow"; +import { resolveWorkflowTemplate } from "./workflowFiles"; import { Frontmatter } from "../frontmatter"; import { buildTree, renderFolderTree, type TreeNode } from "./FolderTree"; import { ConfirmDeleteModal } from "./ConfirmDeleteModal"; @@ -929,10 +930,8 @@ export class RandomTableView extends ItemView { const wf = parseWorkflow(content, file.basename); let tmplContent = ""; if (wf.templateFile) { - const tmplFile = this.app.vault.getAbstractFileByPath( - wf.templateFile, - ); - if (tmplFile instanceof TFile) { + const tmplFile = resolveWorkflowTemplate(this.app, wf.templateFile, file.path); + if (tmplFile) { tmplContent = await this.app.vault.read(tmplFile); } } @@ -1034,10 +1033,8 @@ export class RandomTableView extends ItemView { // ── Template link + preview ───────────────────────────────────────── if (workflow.templateFile) { - const tmplFile = this.app.vault.getAbstractFileByPath( - workflow.templateFile, - ); - if (tmplFile instanceof TFile) { + const tmplFile = resolveWorkflowTemplate(this.app, workflow.templateFile, file.path); + if (tmplFile) { const tmplSection = this.detailEl.createDiv({ cls: "duckmage-wf-template-section", }); diff --git a/src/random-tables/WorkflowEditorModal.ts b/src/random-tables/WorkflowEditorModal.ts index 1742a0ab..ed558331 100644 --- a/src/random-tables/WorkflowEditorModal.ts +++ b/src/random-tables/WorkflowEditorModal.ts @@ -16,6 +16,7 @@ import { type WorkflowStep, } from "./workflow"; import { newTemplatePath, resolveWorkflowTemplate, stepDieLabels } from "./workflowFiles"; +import { noteLink } from "../noteFormats"; import { escapeRegex, placeholderPattern } from "../textUtils"; /** Convert a table basename to a default label: spaces → underscores. */ @@ -652,7 +653,8 @@ export class WorkflowEditorModal extends HexmakerModal { name: this.file.basename, description: description || undefined, resultsFolder: resultsFolder || undefined, - templateFile: handSet || templatePath, + // Written as a link, so renaming the template keeps it (NF3). + templateFile: handSet || JSON.stringify(noteLink(templatePath)), steps, }; diff --git a/src/types.ts b/src/types.ts index edef20c8..2eadc4f9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -367,6 +367,8 @@ export interface HexmakerPluginSettings { biomePoolSeeded?: boolean; /** True once every overworld's Biome column was filled (BC1 migration, once per vault). */ biomeColumnsFilled?: boolean; + /** One-time note-format rewrites already done in this vault (src/noteFormatUpgrade.ts: NF1–NF3). */ + noteFormatUpgrades?: string[]; /** Vault folder for world types notes (which worlds space generators place); blank = `/world-types`. */ worldTypesFolder?: string; /** True once the shipped "Default space" world types note was written (once, so a deleted one stays deleted). */ diff --git a/styles.css b/styles.css index af1352e0..8df7d49e 100644 --- a/styles.css +++ b/styles.css @@ -8038,30 +8038,6 @@ button.duckmage-terrain-legend-chip { margin-bottom: 8px; } -/* Hex editor: a "Terrain:" / "Region:" line in the note that disagrees with - the map (src/hexBodyFields.ts), with buttons to apply it either way. */ -.duckmage-editor-body-field { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 0.4em 0.8em; - margin: 0 0 0.6em; - padding: 0.4em 0.6em; - border-left: 3px solid var(--color-orange); - background: var(--background-secondary); - border-radius: var(--radius-s); - font-size: var(--font-ui-small); -} - -.duckmage-editor-body-field-actions { - display: flex; - gap: 0.4em; -} - -.duckmage-editor-body-field-actions button { - font-size: var(--font-ui-smaller); -} - /* Hex editor: sections of the note the editor has no field for. */ .duckmage-editor-other-sections > summary { cursor: pointer; diff --git a/tests/calloutSync.test.ts b/tests/calloutSync.test.ts index 7647c94e..bbad1c56 100644 --- a/tests/calloutSync.test.ts +++ b/tests/calloutSync.test.ts @@ -99,4 +99,21 @@ describe("Map data callout phase 2, end to end (syncHexMapData)", () => { expect(s.hexes.get("3_4")?.terrain).toBe("forest"); expect(r.notApplied).toEqual(["Terrain: lava (not in this map's palette)"]); }); + + it("NF2: moves an old **Terrain:** line into Map data (adding it), never onto the map", async () => { + const s = setup({ hex: { terrain: "forest" }, note: () => "# Hex 3, 4\n\n**Terrain:** swamp\n\nText.\n" }); + const r = await s.sync(); + expect(r).toMatchObject({ wrote: true, applied: [], moved: ["Old terrain: swamp"] }); + expect(s.hexes.get("3_4")?.terrain).toBe("forest"); + expect(s.content()).toBe("# Hex 3, 4\n\n> [!hexmaker] Map data\n> Map: [[_coast|Coast]], hex 3, 4\n> Terrain: forest\n> Region: —\n> Name: —\n> Old terrain: swamp\n\nText.\n"); + expect(s.memory.get("hexes/coast/3_4.md")?.terrain).toBe("forest"); + // Done once: the next sync has nothing to move or write. + expect(await s.sync()).toMatchObject({ wrote: false, moved: [] }); + }); + + it("a note without a callout or old lines is left alone", async () => { + const s = setup({ hex: { terrain: "forest" }, note: () => "# Hex 3, 4\n\n**Terrain:**\n\nText.\n" }); + expect(await s.sync()).toMatchObject({ wrote: false, moved: [] }); + expect(s.content()).toBe("# Hex 3, 4\n\n**Terrain:**\n\nText.\n"); + }); }); diff --git a/tests/fixtures/compat/note-formats/hex-note-1.5.6.md b/tests/fixtures/compat/note-formats/hex-note-1.5.6.md new file mode 100644 index 00000000..c3028d14 --- /dev/null +++ b/tests/fixtures/compat/note-formats/hex-note-1.5.6.md @@ -0,0 +1,16 @@ +--- +hexmaker-map: "[[_the-coast]]" +tags: [hex] # my tag +aliases: + - the-coast 0, 1 +--- +# Hex 0, 1 + +**Region:** [[Dustbowl]] +**Terrain:** mountain + +### Description +Cold wind off the peaks. + +### Encounters Table +- [[world/tables/terrain/encounters/mountain]] diff --git a/tests/fixtures/compat/note-formats/hex-note-own-map-key.md b/tests/fixtures/compat/note-formats/hex-note-own-map-key.md new file mode 100644 index 00000000..f7238539 --- /dev/null +++ b/tests/fixtures/compat/note-formats/hex-note-own-map-key.md @@ -0,0 +1,10 @@ +--- +hexmaker-map: "[[_the-coast]]" +map: Sword Coast (1e boxed set) +--- +# Hex 2, 2 + +**Terrain:** *(woods / marsh / …)* + +### Description +Ruins. diff --git a/tests/fixtures/compat/note-formats/token-note-1.5.6.md b/tests/fixtures/compat/note-formats/token-note-1.5.6.md new file mode 100644 index 00000000..bc087e20 --- /dev/null +++ b/tests/fixtures/compat/note-formats/token-note-1.5.6.md @@ -0,0 +1,10 @@ +--- +token: true +token-icon: place-castle.svg +token-hex: 3_4 +token-map: the-coast +token-visible: true +--- +# Ana the smith + +Runs the forge. diff --git a/tests/fixtures/compat/note-formats/token-proxy-1.5.6.md b/tests/fixtures/compat/note-formats/token-proxy-1.5.6.md new file mode 100644 index 00000000..1ac1f7c7 --- /dev/null +++ b/tests/fixtures/compat/note-formats/token-proxy-1.5.6.md @@ -0,0 +1,7 @@ +--- +token-link: world/npcs/Ana the smith.md +token: true +token-hex: 5_5 +token-map: "[[_the-coast]]" +--- +# Ana the smith-2 diff --git a/tests/fixtures/compat/note-formats/workflow-1.5.6.md b/tests/fixtures/compat/note-formats/workflow-1.5.6.md new file mode 100644 index 00000000..e253327c --- /dev/null +++ b/tests/fixtures/compat/note-formats/workflow-1.5.6.md @@ -0,0 +1,10 @@ +--- +results-folder: world/results +template-file: world/workflows/templates/npc.md +--- + +Roll an NPC. + +| Table | Rolls | Label | +|---|---|---| +| [[world/tables/names]] | 1 | name | diff --git a/tests/hexBodyFields.test.ts b/tests/hexBodyFields.test.ts index b33da376..29bacf5b 100644 --- a/tests/hexBodyFields.test.ts +++ b/tests/hexBodyFields.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { readBodyField, sameName, setBodyField } from "../src/hexBodyFields"; +import { readBodyField, sameName, takeBodyFields } from "../src/hexBodyFields"; const OLD = "# Hex 0, 1\n\n**Region:** Mountains\n**Terrain:** mountain\n\n### description\nCold.\n"; @@ -21,13 +21,14 @@ describe("hex note body fields (older templates' Terrain / Region lines)", () => expect(readBodyField("**Region:** [[Dustbowl]]\n", "Region")).toBe("Dustbowl"); }); - it("updates only that line, keeping everything else", () => { - const out = setBodyField(OLD, "Terrain", "desert rocky"); - expect(out).toBe(OLD.replace("**Terrain:** mountain", "**Terrain:** desert rocky")); - expect(setBodyField("**Terrain:**\nrest", "Terrain", "grass")).toBe("**Terrain:** grass\nrest"); - expect(setBodyField("nothing here", "Terrain", "grass")).toBe("nothing here"); - // A trailing " " (a Markdown line break) stays. - expect(setBodyField("**Region:** Mountains \n**Terrain:** x", "Region", "Dustbowl")).toBe("**Region:** Dustbowl \n**Terrain:** x"); + it("takes filled lines out (as typed), keeping everything else (NF2)", () => { + const r = takeBodyFields(OLD); + expect(r.taken).toEqual([{ field: "Region", value: "Mountains" }, { field: "Terrain", value: "mountain" }]); + expect(r.content).toBe("# Hex 0, 1\n\n### description\nCold.\n"); + // Placeholders and empty lines stay; frontmatter is never read as body. + const tmpl = "---\nnote: \"**Terrain:** x\"\n---\n**Terrain:**\n**Region:** *(fill in)*\n"; + expect(takeBodyFields(tmpl)).toEqual({ content: tmpl, taken: [] }); + expect(takeBodyFields("**Terrain:** a\r\nrest").content).toBe("rest"); }); it("compares names ignoring case and spacing", () => { diff --git a/tests/mapNote.test.ts b/tests/mapNote.test.ts index b651f240..f48a88b4 100644 --- a/tests/mapNote.test.ts +++ b/tests/mapNote.test.ts @@ -301,15 +301,15 @@ describe("region biome", () => { describe("new hex notes", () => { it("swap map-data keys for a link to the map note, keeping the rest", () => { const t = "---\nterrain:\ntags: [hex]\ngm-icons:\n - a.png\n - b.png\nregion: North\n---\n# Hex 1, 2\n"; - expect(withMapLink(t, "coast")).toBe('---\nhexmaker-map: "[[_coast]]"\ntags: [hex]\n---\n# Hex 1, 2\n'); + expect(withMapLink(t, "coast")).toBe('---\nmap: "[[_coast]]"\ntags: [hex]\n---\n# Hex 1, 2\n'); }); it("adds frontmatter to a template without any", () => { - expect(withMapLink("# Hex\n", "m")).toBe('---\nhexmaker-map: "[[_m]]"\n---\n# Hex\n'); + expect(withMapLink("# Hex\n", "m")).toBe('---\nmap: "[[_m]]"\n---\n# Hex\n'); }); it("handles an empty frontmatter block and CRLF", () => { - expect(withMapLink("---\r\n---\r\n\r\n# Hex\r\n", "m")).toBe('---\r\nhexmaker-map: "[[_m]]"\r\n---\r\n\r\n# Hex\r\n'); + expect(withMapLink("---\r\n---\r\n\r\n# Hex\r\n", "m")).toBe('---\r\nmap: "[[_m]]"\r\n---\r\n\r\n# Hex\r\n'); }); }); diff --git a/tests/mapStore.test.ts b/tests/mapStore.test.ts index f0a36458..1e78aa3b 100644 --- a/tests/mapStore.test.ts +++ b/tests/mapStore.test.ts @@ -82,7 +82,9 @@ describe("map store: migration from hex-note frontmatter", () => { for (const p of ["world/hexes/coast/1_2.md", "world/hexes/coast/3_4.md", "world/hexes/coast/0_0.md"]) { const fm = vault.frontmatter(p)!; for (const k of HEX_DATA_KEYS) expect(fm).not.toHaveProperty(k); - expect(fm["hexmaker-map"]).toBe("[[_coast]]"); + // NF1: the link goes under map: (hexmaker-map: in older notes). + expect(fm.map).toBe("[[_coast]]"); + expect(fm).not.toHaveProperty("hexmaker-map"); expect(vault.body(p)).toBe(before.get(p)); } // User frontmatter survives @@ -293,7 +295,7 @@ describe("map store: a broken map note", () => { await store.flush(); expect(v.files.get(path)).toBe(broken); // hex notes were not touched either - expect(v.frontmatter("world/hexes/coast/3_4.md")!["hexmaker-map"]).toBe("[[_coast]]"); + expect(v.frontmatter("world/hexes/coast/3_4.md")!.map).toBe("[[_coast]]"); // the user fixes it v.files.set(path, good); store.onModify(p.app.vault.getAbstractFileByPath(path) as never); diff --git a/tests/noteFormats.test.ts b/tests/noteFormats.test.ts new file mode 100644 index 00000000..4e76a0ca --- /dev/null +++ b/tests/noteFormats.test.ts @@ -0,0 +1,323 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { gunzipSync } from "node:zlib"; +import { TFile } from "obsidian"; +import { + hexNoteMapKey, hexNoteMapName, isMapNoteLink, linkNotePathKey, linkTokenMap, mapNameFromRef, mapNoteLink, + noteLink, noteRefTarget, renameHexMapKey, +} from "../src/noteFormats"; +import { takeBodyFields } from "../src/hexBodyFields"; +import { mapDataLines, moveBodyFieldsIntoMapData, planCalloutImport, readMapData, setMapData, shownValues, type HexMapDataView } from "../src/hexMapData"; +import { withMapLink } from "../src/maps/mapNote"; +import { getTokenDataFromCache, readTokenPlace, setTokenHex, tokenMapValue } from "../src/frontmatter"; +import { runNoteFormatUpgrades, runUpgrade, type NoteFormatHost } from "../src/noteFormatUpgrade"; +import { MemVault } from "./helpers/memVault"; + +/** + * Round-6 note-format changes (NF1 hex notes' `map:` key, NF2 old body + * lines into Map data, NF3 links for token maps, token notes and workflow + * templates). Old forms are pinned by tests/fixtures/compat/note-formats. + */ + +const fixture = (name: string) => + readFileSync(path.join(process.cwd(), "tests", "fixtures", "compat", "note-formats", name), "utf8").replace(/\r\n/g, "\n"); + +describe("NF1: hex notes link their map note under map:", () => { + it("reads the old and the new key", () => { + expect(hexNoteMapName({ "hexmaker-map": "[[_the-coast]]" })).toBe("the-coast"); + expect(hexNoteMapName({ map: "[[_the-coast]]" })).toBe("the-coast"); + expect(hexNoteMapName({ map: "[[hexes/the-coast/_the-coast|The Coast]]" })).toBe("the-coast"); + // A map note's format number isn't a link. + expect(hexNoteMapName({ "hexmaker-map": 5 })).toBe(""); + // map: of the user's own: the old key still names the map. + expect(hexNoteMapName({ map: "Sword Coast", "hexmaker-map": "[[_c]]" })).toBe("c"); + }); + + it("writes under map:, or under hexmaker-map: when map: is the user's", () => { + expect(hexNoteMapKey({})).toBe("map"); + expect(hexNoteMapKey({ map: "[[_coast]]" })).toBe("map"); + expect(hexNoteMapKey({ map: "Sword Coast" })).toBe("hexmaker-map"); + expect(hexNoteMapKey({ map: "[[Sword Coast]]" })).toBe("hexmaker-map"); + }); + + it("renames only the key, keeping the value, comments and the other keys", () => { + const old = fixture("hex-note-1.5.6.md"); + const r = renameHexMapKey(old); + expect(r.status).toBe("renamed"); + expect(r.content).toBe(old.replace('hexmaker-map: "[[_the-coast]]"', 'map: "[[_the-coast]]"')); + // Idempotent. + expect(renameHexMapKey(r.content)).toEqual({ content: r.content, status: "none" }); + }); + + it("leaves a note whose map: is the user's alone", () => { + const own = fixture("hex-note-own-map-key.md"); + expect(renameHexMapKey(own)).toEqual({ content: own, status: "conflict" }); + }); + + it("drops the old key when map: already holds the same link; keeps CRLF", () => { + const both = '---\r\nmap: "[[_c]]"\r\nhexmaker-map: "[[_c]]"\r\n---\r\n# Hex\r\n'; + expect(renameHexMapKey(both)).toEqual({ content: '---\r\nmap: "[[_c]]"\r\n---\r\n# Hex\r\n', status: "renamed" }); + }); + + it("never touches a map note's format marker", () => { + const mapNote = "---\nhexmaker-map: 5\npalette: Default\n---\n# Coast\n"; + expect(renameHexMapKey(mapNote).status).toBe("none"); + }); + + it("new hex notes get map:, or hexmaker-map: beside a template's own map:", () => { + expect(withMapLink("---\ntags: [hex]\n---\n# Hex\n", "coast")).toBe('---\nmap: "[[_coast]]"\ntags: [hex]\n---\n# Hex\n'); + expect(withMapLink("---\nmap: Sword Coast\n---\n# Hex\n", "coast")).toBe('---\nhexmaker-map: "[[_coast]]"\nmap: Sword Coast\n---\n# Hex\n'); + // A template copied from a hex note: its old link is replaced, not doubled. + expect(withMapLink('---\nmap: "[[_old]]"\nhexmaker-map: "[[_old]]"\n---\n# Hex\n', "coast")).toBe('---\nmap: "[[_coast]]"\n---\n# Hex\n'); + }); +}); + +describe("NF2: old Terrain / Region lines move into Map data", () => { + const view: HexMapDataView = { map: "the-coast", mapLabel: "The Coast", x: 0, y: 1, terrain: "desert rocky", region: "Basin" }; + + it("takes filled lines, as typed, and leaves placeholders", () => { + const r = takeBodyFields("# Hex\n\n**Region:** [[Dustbowl]]\n**Terrain:** mountain\n\n### Description\n"); + expect(r.taken).toEqual([{ field: "Region", value: "[[Dustbowl]]" }, { field: "Terrain", value: "mountain" }]); + expect(r.content).toBe("# Hex\n\n### Description\n"); + const blank = "# Hex\n\n**Terrain:** *(woods / marsh / …)*\n**Region:**\n"; + expect(takeBodyFields(blank)).toEqual({ content: blank, taken: [] }); + }); + + it("moves them under the map's own values; the map's values win", () => { + const r = moveBodyFieldsIntoMapData(fixture("hex-note-1.5.6.md"), view); + expect(r.moved.length).toBe(2); + expect(r.content).toContain([ + "# Hex 0, 1", + "", + "> [!hexmaker] Map data", + "> Map: [[_the-coast|The Coast]], hex 0, 1", + "> Terrain: desert rocky", + "> Region: Basin", + "> Name: —", + "> Old region: [[Dustbowl]]", + "> Old terrain: mountain", + "", + "### Description", + ].join("\n")); + expect(r.content).not.toContain("**Terrain:**"); + // The moved lines are never read as map edits. + expect(readMapData(r.content)).toEqual({ terrain: "desert rocky", region: "Basin" }); + const shown = shownValues(mapDataLines(view)); + expect(planCalloutImport(r.content, shown, shown)).toEqual({ apply: {}, notApplied: [], unreadable: [] }); + // Idempotent: a second move changes nothing, and a later refresh keeps the lines. + expect(moveBodyFieldsIntoMapData(r.content, view)).toEqual({ content: r.content, moved: [] }); + const refreshed = setMapData(r.content, { ...view, terrain: "dunes" }); + expect(refreshed).toContain("> Terrain: dunes\n"); + expect(refreshed).toContain("> Old terrain: mountain\n"); + }); + + it("goes into an existing callout, keeping CRLF", () => { + const note = ["# Hex 0, 1", "", ...mapDataLines(view), "", "**Terrain:** forest", "", "Text."].join("\r\n"); + const r = moveBodyFieldsIntoMapData(note, view); + expect(r.content).toBe(["# Hex 0, 1", "", ...mapDataLines(view), "> Old terrain: forest", "", "Text."].join("\r\n")); + }); +}); + +describe("NF3: links for token maps, token notes and workflow templates", () => { + it("reads a map as a link or a plain name", () => { + expect(mapNameFromRef("the-coast")).toBe("the-coast"); + expect(mapNameFromRef("[[_the-coast]]")).toBe("the-coast"); + expect(mapNameFromRef("[[hexes/the-coast/_the-coast|Coast]]")).toBe("the-coast"); + expect(mapNameFromRef(undefined)).toBe(""); + expect(isMapNoteLink("[[_x]]")).toBe(true); + expect(isMapNoteLink("[[x]]")).toBe(false); + expect(mapNoteLink("a|b")).toBe("a|b"); + expect(tokenMapValue("")).toBe(""); + }); + + it("note paths become links ([[path]] without .md); readers take both", () => { + expect(noteLink("world/npcs/Ana.md")).toBe("[[world/npcs/Ana]]"); + expect(noteRefTarget('"[[world/npcs/Ana|Ana]]"')).toEqual({ target: "world/npcs/Ana", link: true }); + expect(noteRefTarget("world/npcs/Ana.md")).toEqual({ target: "world/npcs/Ana.md", link: false }); + }); + + it("rewrites token-map once; leaves links and non-tokens", () => { + const old = fixture("token-note-1.5.6.md"); + const r = linkTokenMap(old); + expect(r.changed).toBe(true); + expect(r.content).toBe(old.replace("token-map: the-coast", 'token-map: "[[_the-coast]]"')); + expect(linkTokenMap(r.content)).toEqual({ content: r.content, changed: false }); + const notToken = "---\ntoken: false\ntoken-map: c\n---\n"; + expect(linkTokenMap(notToken).changed).toBe(false); + }); + + it("rewrites token-link and template-file only when they name a note", () => { + const exists = (p: string) => p === "world/npcs/Ana the smith.md" || p === "world/workflows/templates/npc.md"; + const proxy = fixture("token-proxy-1.5.6.md"); + const r = linkNotePathKey(proxy, "token-link", exists); + expect(r.content).toBe(proxy.replace("token-link: world/npcs/Ana the smith.md", 'token-link: "[[world/npcs/Ana the smith]]"')); + expect(linkNotePathKey(r.content, "token-link", exists).changed).toBe(false); + const wf = fixture("workflow-1.5.6.md"); + expect(linkNotePathKey(wf, "template-file", exists).content).toContain('template-file: "[[world/workflows/templates/npc]]"'); + // A path that names nothing is left as typed. + expect(linkNotePathKey(wf, "template-file", () => false).changed).toBe(false); + }); + + it("token readers accept the old and new forms; writers write links", async () => { + const file = Object.assign(new TFile(), { path: "world/tokens/Ana.md", basename: "Ana" }); + const original = Object.assign(new TFile(), { path: "world/npcs/Ana the smith.md", basename: "Ana the smith" }); + const app = (fm: Record) => ({ + vault: { getAbstractFileByPath: (p: string) => (p === original.path ? original : null) }, + metadataCache: { getFileCache: () => ({ frontmatter: fm }), getFirstLinkpathDest: (t: string) => (t === "Ana the smith" ? original : null) }, + }) as never; + expect(getTokenDataFromCache(app({ token: true, "token-map": "coast", "token-link": "world/npcs/Ana the smith.md" }), file)).toMatchObject({ map: "coast", tokenLink: original.path, title: "Ana the smith" }); + expect(getTokenDataFromCache(app({ token: true, "token-map": "[[_coast]]", "token-link": "[[world/npcs/Ana the smith]]" }), file)).toMatchObject({ map: "coast", tokenLink: original.path }); + // A short link resolves the way Obsidian does. + expect(getTokenDataFromCache(app({ token: true, "token-link": "[[Ana the smith]]" }), file)?.tokenLink).toBe(original.path); + + const vault = new MemVault({ "world/tokens/Ana.md": "---\ntoken: true\ntoken-map: coast\n---\n# Ana\n" }); + const a = vault.app(); + expect(await readTokenPlace(a as never, "world/tokens/Ana.md")).toEqual({ hex: "", map: "coast" }); + await setTokenHex(a as never, "world/tokens/Ana.md", "1_2", "coast"); + expect(vault.frontmatter("world/tokens/Ana.md")?.["token-map"]).toBe("[[_coast]]"); + expect(await readTokenPlace(a as never, "world/tokens/Ana.md")).toEqual({ hex: "1_2", map: "coast" }); + }); +}); + +// ── the one-time rewrite, on an in-memory vault ─────────────────────────── + +const HEX = "hexes"; +function vaultHost(files: Record, settings: Partial = {}) { + const vault = new MemVault(files); + let saves = 0; + const memory = new Map>(); + const hexes: Record = { "0_1": { terrain: "desert rocky", region: "Basin" } }; + const host: NoteFormatHost = { + app: vault.app() as never, + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: HEX, workflowsFolder: "world/workflows", maps: [{ name: "the-coast" }], ...settings }, + mapStore: { + isReady: (m?: string) => m === undefined || m === "the-coast", + resolve: (p: string) => { + const m = /^hexes\/([^/]+)\/(-?\d+_-?\d+)\.md$/.exec(p); + return m ? { map: m[1], key: m[2] } : null; + }, + }, + hexMapDataView: (map, x, y) => ({ map, mapLabel: "The Coast", x, y, ...(hexes[`${x}_${y}`] ?? {}) }), + calloutMemory: { set: (p, v) => { memory.set(p, v); } }, + saveSettings: async () => { saves++; }, + }; + return { vault, host, saves: () => saves, memory }; +} + +const OLD_VAULT = () => ({ + [`${HEX}/the-coast/0_1.md`]: fixture("hex-note-1.5.6.md"), + [`${HEX}/the-coast/2_2.md`]: fixture("hex-note-own-map-key.md"), + [`${HEX}/the-coast/_the-coast.md`]: "---\nhexmaker-map: 5\npalette: Default\n---\n# The Coast\n", + "world/tokens/Ana the smith.md": fixture("token-note-1.5.6.md"), + "world/tokens/Ana the smith-2.md": fixture("token-proxy-1.5.6.md"), + "world/npcs/Ana the smith.md": "# Ana\n", + "world/workflows/npc.md": fixture("workflow-1.5.6.md"), + "world/workflows/templates/npc.md": "## name\n$name\n", + "world/workflows/_notes.md": "---\ntemplate-file: x.md\n---\n", +}); + +function backupNotes(vault: MemVault, id: string): Record { + const entry = [...vault.binaries].find(([p]) => p.includes("/backups/note-formats-") && p.endsWith(`/${id}.json.gz`)); + if (!entry) throw new Error(`no backup for ${id}: ${[...vault.binaries.keys()].join(", ")}`); + return (JSON.parse(gunzipSync(entry[1]).toString("utf8")) as { notes: Record }).notes; +} + +describe("one-time note-format rewrite", () => { + it("rewrites each old form once, backed up first, and records it", async () => { + const before = OLD_VAULT(); + const { vault, host, saves, memory } = vaultHost(before); + const results = await runNoteFormatUpgrades(host); + expect(results.map((r) => [r.id, r.changed.length, r.error])).toEqual([ + ["hex-map-key", 1, undefined], ["hex-body-lines", 1, undefined], ["note-links", 3, undefined], + ]); + expect(host.settings.noteFormatUpgrades).toEqual(["hex-map-key", "hex-body-lines", "note-links"]); + expect(saves()).toBe(1); + + const hex = vault.files.get(`${HEX}/the-coast/0_1.md`)!; + expect(hex).toContain('map: "[[_the-coast]]"'); + expect(hex).not.toContain("hexmaker-map"); + expect(hex).toContain("> Old terrain: mountain"); + expect(hex).toContain("> Old region: [[Dustbowl]]"); + expect(hex).toContain("tags: [hex] # my tag"); + expect(memory.get(`${HEX}/the-coast/0_1.md`)?.terrain).toBe("desert rocky"); + // The note with its own map: key is left as it was, and reported. + expect(vault.files.get(`${HEX}/the-coast/2_2.md`)).toBe(before[`${HEX}/the-coast/2_2.md`]); + expect(results[0].skipped.map((s) => s.path)).toEqual([`${HEX}/the-coast/2_2.md`]); + // Map notes and "_" notes are never touched. + expect(vault.files.get(`${HEX}/the-coast/_the-coast.md`)).toBe(before[`${HEX}/the-coast/_the-coast.md`]); + expect(vault.files.get("world/workflows/_notes.md")).toBe(before["world/workflows/_notes.md"]); + expect(vault.files.get("world/tokens/Ana the smith.md")).toContain('token-map: "[[_the-coast]]"'); + expect(vault.files.get("world/tokens/Ana the smith-2.md")).toContain('token-link: "[[world/npcs/Ana the smith]]"'); + expect(vault.files.get("world/workflows/npc.md")).toContain('template-file: "[[world/workflows/templates/npc]]"'); + + // Backups hold every rewritten note exactly as it was. + expect(backupNotes(vault, "hex-map-key")).toEqual({ [`${HEX}/the-coast/0_1.md`]: before[`${HEX}/the-coast/0_1.md`] }); + expect(Object.keys(backupNotes(vault, "hex-body-lines"))).toEqual([`${HEX}/the-coast/0_1.md`]); + const links = backupNotes(vault, "note-links"); + expect(Object.keys(links).sort()).toEqual(["world/tokens/Ana the smith-2.md", "world/tokens/Ana the smith.md", "world/workflows/npc.md"]); + expect(links["world/workflows/npc.md"]).toBe(before["world/workflows/npc.md"]); + + // Recorded: the next start does nothing at all. + const writes = vault.writes.length; + const binaries = vault.binaries.size; + expect(await runNoteFormatUpgrades(host)).toEqual([]); + expect(vault.writes.length).toBe(writes); + expect(vault.binaries.size).toBe(binaries); + expect(saves()).toBe(1); + }); + + it("is idempotent even when run again unrecorded: nothing changes, no backup", async () => { + const { vault, host } = vaultHost(OLD_VAULT()); + await runNoteFormatUpgrades(host); + const snapshot = new Map(vault.files); + const writes = vault.writes.length; + const binaries = vault.binaries.size; + for (const id of ["hex-map-key", "hex-body-lines", "note-links"] as const) { + const r = await runUpgrade(host, id); + expect(r.changed).toEqual([]); + expect(r.backup).toBeUndefined(); + } + expect(vault.writes.length).toBe(writes); + expect(vault.binaries.size).toBe(binaries); + expect(new Map(vault.files)).toEqual(snapshot); + }); + + it("writes no note and no backup in a vault with nothing to change (records once)", async () => { + const { vault, host, saves } = vaultHost({ + [`${HEX}/the-coast/0_1.md`]: '---\nmap: "[[_the-coast]]"\n---\n# Hex 0, 1\n', + "world/tokens/T.md": '---\ntoken: true\ntoken-map: "[[_the-coast]]"\n---\n', + }); + await runNoteFormatUpgrades(host); + expect(vault.writes).toEqual([]); + expect(vault.binaries.size).toBe(0); + expect(saves()).toBe(1); + await runNoteFormatUpgrades(host); + expect(saves()).toBe(1); + }); + + it("changes nothing and records nothing when the backup can't be saved", async () => { + const before = OLD_VAULT(); + const { vault, host, saves } = vaultHost(before); + vault.failBinary = true; + const results = await runNoteFormatUpgrades(host); + expect(results.every((r) => r.changed.length === 0)).toBe(true); + expect(results.filter((r) => r.error).map((r) => r.id)).toEqual(["hex-map-key", "hex-body-lines", "note-links"]); + expect(new Map(vault.files)).toEqual(new Map(Object.entries(before))); + expect(host.settings.noteFormatUpgrades).toBeUndefined(); + expect(saves()).toBe(0); + }); + + it("leaves a map that isn't loaded for later, and keeps ids it doesn't know", async () => { + const { vault, host } = vaultHost(OLD_VAULT(), { noteFormatUpgrades: ["from-a-newer-build", "hex-map-key", "note-links"] }); + host.mapStore.isReady = () => false; + const [r] = await runNoteFormatUpgrades(host); + expect(r.id).toBe("hex-body-lines"); + expect(r.changed).toEqual([]); + expect(r.skipped.map((s) => s.path)).toEqual([`${HEX}/the-coast/0_1.md`]); + expect(vault.files.get(`${HEX}/the-coast/0_1.md`)).toContain("**Terrain:** mountain"); + expect(host.settings.noteFormatUpgrades).toEqual(["from-a-newer-build", "hex-map-key", "note-links", "hex-body-lines"]); + }); +}); diff --git a/tests/smokeSuite.test.ts b/tests/smokeSuite.test.ts index c6d56dc2..d43cf4d7 100644 --- a/tests/smokeSuite.test.ts +++ b/tests/smokeSuite.test.ts @@ -4,7 +4,7 @@ import { readFileSync } from "node:fs"; import * as path from "node:path"; // The smoke suite's pure helpers (dev/smoke; the suite itself needs Windows Obsidian). import { canon, jsonDiff, oneTimeOnly } from "../dev/smoke/lib/compare.mjs"; -import { diff, hexDataFromFm, paletteTerrains, verifyPaletteUpgrade } from "../dev/smoke/lib/disk.mjs"; +import { bodyFieldLines, comparableBody, diff, hexDataFromFm, hexNoteMapLink, paletteTerrains, verifyPaletteUpgrade } from "../dev/smoke/lib/disk.mjs"; import { JOB_MEM_BYTES, pickJobs, stopUntilGone } from "../dev/smoke/lib/concurrency.mjs"; const read = (...p: string[]) => readFileSync(path.join(process.cwd(), ...p), "utf8").replace(/\r\n/g, "\n"); @@ -61,6 +61,17 @@ describe("smoke suite: legacy hex data and palette upgrades", () => { expect(verifyPaletteUpgrade(OLD, NEW)).toEqual([]); }); + it("NF1/NF2: a hex note's map link under either key; bodies compare without the moved lines", () => { + expect(hexNoteMapLink({ map: "[[_coast]]" })).toBe("[[_coast]]"); + expect(hexNoteMapLink({ map: "Sword Coast", "hexmaker-map": "[[_coast]]" })).toBe("[[_coast]]"); + expect(hexNoteMapLink({ "hexmaker-map": 5 })).toBe(null); + const before = "# Hex 0, 1\n\n**Region:** [[Dustbowl]]\n**Terrain:** mountain\n**Terrain:** *(fill)*\n\n### Description\nCold.\n"; + expect(bodyFieldLines(before)).toEqual([["region", "[[Dustbowl]]"], ["terrain", "mountain"]]); + const after = "# Hex 0, 1\n\n> [!hexmaker] Map data\n> Terrain: dunes\n> Old region: [[Dustbowl]]\n> Old terrain: mountain\n\n**Terrain:** *(fill)*\n\n### Description\nCold.\n"; + expect(comparableBody(after)).toBe(comparableBody(before)); + expect(comparableBody(after.replace("Cold.", "Warm."))).not.toBe(comparableBody(before)); + }); + it("a rewrite that loses or changes a terrain is caught", () => { expect(verifyPaletteUpgrade(OLD, NEW.replace("| water |", "| sea |"))).toEqual(['terrain "water" gone', 'terrain "sea" added']); expect(verifyPaletteUpgrade(OLD, NEW.replace("`#69a168`", "`#000000`"))).toHaveLength(1); diff --git a/tests/token.test.ts b/tests/token.test.ts index 56bff45c..20314b1c 100644 --- a/tests/token.test.ts +++ b/tests/token.test.ts @@ -176,7 +176,8 @@ describe("setTokenHex", () => { const { app, getContent } = makeApp("tokens/hero.md", "---\ntoken: true\n---\n"); await setTokenHex(app, "tokens/hero.md", "5_7", "overworld"); expect(getContent()).toContain("token-hex: 5_7"); - expect(getContent()).toContain("token-map: overworld"); + // NF3: a link to the map note. + expect(getContent()).toContain("token-map: [[_overworld]]"); }); }); @@ -252,7 +253,7 @@ describe("applyTokenFrontmatter", () => { expect(content).toContain("token: true"); expect(content).toContain("token-icon: sword.png"); expect(content).toContain("token-hex: 2_3"); - expect(content).toContain("token-map: overworld"); + expect(content).toContain("token-map: [[_overworld]]"); expect(content).toContain("token-visible: true"); expect(content).toContain("token-shape: square"); expect(content).toContain("token-size: lg"); From b48c5396ac8c671ea2a9448a5146157b3ec5a5e8 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 10:55:53 -0400 Subject: [PATCH 302/558] docs+smoke: note formats in README/help; smoke suite knows the new forms - disk.mjs: a hex note's map link under either key; bodies compared without the Map data callout and the moved Terrain/Region lines, and each moved line must be in the callout; notes changed by a note-format upgrade are allowed in C4 only when their original is in the backup. - compare.mjs: noteFormatUpgrades is a one-time data.json key. - README: the before/after table, backups and the once-per-vault record. Co-Authored-By: Claude Opus 5.5 --- ARCHITECTURE.md | 2 +- README.md | 22 ++++++++++-- dev/smoke/lib/compare.mjs | 2 +- dev/smoke/lib/disk.mjs | 74 ++++++++++++++++++++++++++++++++++++--- dev/smoke/run.mjs | 8 +++-- dev/smoke/setups.mjs | 2 +- 6 files changed, 98 insertions(+), 12 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8bdb6729..cb4c5c03 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -141,7 +141,7 @@ Path: `{hexFolder}/{map}/{x}_{y}.md` — created only when a hex first gets pros ```yaml --- -hexmaker-map: "[[_Overworld]]" +map: "[[_Overworld]]" # NF1; older notes: hexmaker-map: (both read, src/noteFormats.ts) aliases: [Glass Wastes] # the hex's name, when it has one --- diff --git a/README.md b/README.md index f69a4151..41af50e2 100644 --- a/README.md +++ b/README.md @@ -283,7 +283,7 @@ Place movable tokens on the map — useful for tracking party position, NPCs, or - **Drag** a token to a different hex to move it. The target hex is highlighted as you drag. - **Right-click** a token for its menu: **Token info** (the linked note title and hex position, with "Jump to hex" and "Open note"), edit its properties (icon, shape, colours), or remove it from the map. -Token state is stored in the linked note's frontmatter (`token`, `token-hex`, `token-map`, `token-icon`, `token-shape`, `token-color`, `token-border`, `token-visible`). Tokens follow the map they were placed on and persist with the note. +Token state is stored in the linked note's frontmatter (`token`, `token-hex`, `token-map`, `token-icon`, `token-shape`, `token-color`, `token-border`, `token-visible`). `token-map` is a link to the map's note (`"[[_Overworld]]"`), so it follows the map when it's renamed; a plain map name is read too. Tokens follow the map they were placed on and persist with the note. ### Hex table view Open via **Command palette → "Hexmap World Creator: Open hex table"** or the ⊞ button in the hex map toolbar. @@ -376,11 +376,13 @@ The plugin also writes a few things for you to read, worked out from the tables **Map data in hex notes.** A hex note from the built-in template has a **Map data** box under its title: the hex's map and coordinates, terrain, region and name, plus its region map and locations (as links) when it has them, and its biome on an overworld (linked to the biome note). The map note is where these live; the box is a copy, refreshed when you open the hex in the hex editor or open the note. You can edit **Terrain**, **Region** and **Name** in the box: when you leave the note (or open the hex editor, or run *Add map data to this map's hex notes*), the change goes onto the map, as one undo step. It doesn't if the map has changed that value since the box was last written (the map's value is newer), if the map's mode locks it (Play can't paint terrain or regions; names are fine), or if the terrain isn't in the map's palette. Those edits stay in the box as a `Not applied:` line saying why, lines it can't read become `Not read:` lines, and a notice tells you; delete those lines when you're done with them. Change the map, region map, locations and biome on the map itself. The plugin keeps what each box last showed in `map-data-shown.json` in its folder; a note it has no record of (first run, another device) just gets its box refreshed from the map. +Older hex templates had `**Terrain:**` and `**Region:**` lines to fill in by hand. The map is where terrain and region live now, so a filled-in line moves into the Map data box as an `Old terrain:` / `Old region:` line, under the map's own values: your words are kept, and they never change the map. Copy one onto the map by editing the box's Terrain or Region if you want it. This happens once for every hex note when you update (after a backup, see below), and again whenever a note gets such a line (when you leave the note or open the hex editor). Empty lines and template placeholders are left where they are. + Hand edits are forgiving. Each setting is one plain property (the parent map and background image are links, e.g. `parent: "[[_coast]]"` with `parent-hex: 3, 4`), so the Properties panel can edit them too, and deleting a property resets that setting. In the tables, headers can be in any case and any order, you can add your own columns (they're kept), the `| --- |` row is optional, hexes can be written `3_4`, `3, 4` or as a link, and `yes`/`true`/`x`/`✓` all mean yes; the next save tidies the formatting without changing your values. Terrain and palette names in the wrong case are matched to the palette. A row or setting that can't be read is kept exactly as you wrote it and listed in a warning box in the note (and a notice), until you fix it. If the note can't be read at all (say the `---` lines around its properties get broken), the plugin won't write to it and shows a notice until you fix it; your text is never rebuilt over. Map notes written by earlier builds (with JSON values such as `parent: {"map":…}`) still load; the first start of this version converts them once, after saving a copy in the plugin folder's `backups/`. -Older versions kept terrain and the rest in each hex note's frontmatter. The first time this version starts, it moves that data into map notes, keeps a JSON backup in the plugin folder's `backups/`, and replaces those frontmatter fields with a `hexmaker-map:` link to the map note. Note text is never changed or deleted. Older plugin versions on other devices don't read map notes, so update every device that shares the vault. +Older versions kept terrain and the rest in each hex note's frontmatter. The first time this version starts, it moves that data into map notes, keeps a JSON backup in the plugin folder's `backups/`, and replaces those frontmatter fields with a `map:` link to the map note. Note text is never changed or deleted. Older plugin versions on other devices don't read map notes, so update every device that shares the vault. ## Hex notes @@ -388,10 +390,24 @@ Each hex note lives at `{hexFolder}/{map}/{x}_{y}.md` (e.g. `RPG/world/hexes/Ove ```yaml --- -hexmaker-map: "[[_Overworld]]" +map: "[[_Overworld]]" --- ``` +Older notes say `hexmaker-map: "[[_Overworld]]"` (map notes use `hexmaker-map:` for their format number). Both are read. A note that already uses `map:` for something of its own keeps it, and its link stays under `hexmaker-map:`. + +**Note format changes.** The first start after updating rewrites older notes once, so links survive renames: + +| What | Before | After | +|---|---|---| +| Hex notes: link to the map note | `hexmaker-map: "[[_coast]]"` | `map: "[[_coast]]"` | +| Hex notes: hand-filled terrain / region lines | `**Terrain:** forest` in the text | `> Old terrain: forest` in the Map data box | +| Token notes: the map a token is on | `token-map: coast` | `token-map: "[[_coast]]"` | +| Second tokens for a note: the note they stand for | `token-link: world/npcs/Ana.md` | `token-link: "[[world/npcs/Ana]]"` | +| Workflows: their template | `template-file: world/workflows/templates/npc.md` | `template-file: "[[world/workflows/templates/npc]]"` | + +Before changing anything, the full text of every note it changes is saved in the plugin folder's `backups/note-formats-/` (one gzipped file per change). Each change runs once per vault (recorded in `data.json`); a vault with nothing to change has no note written. The old forms are still read, so notes from another device on an older version keep working. Notes skipped on purpose (a `map:` key of your own, a link to a note that doesn't exist) are listed in a notice. + **Sections** (used by the editor and table view): | Heading | Type | Purpose | diff --git a/dev/smoke/lib/compare.mjs b/dev/smoke/lib/compare.mjs index dd0bcadc..4be95db6 100644 --- a/dev/smoke/lib/compare.mjs +++ b/dev/smoke/lib/compare.mjs @@ -24,7 +24,7 @@ export function canon(v) { * more?" check-in, the one-time table-ranges survey): a restart may write * these to data.json. Anything else it writes is a rewrite. */ -export const ONE_TIME_KEYS = new Set(["tableRangesPrompt", "advancedNudgeAt"]); +export const ONE_TIME_KEYS = new Set(["tableRangesPrompt", "advancedNudgeAt", "noteFormatUpgrades"]); /** data.json changed only in ONE_TIME_KEYS (top level). */ diff --git a/dev/smoke/lib/disk.mjs b/dev/smoke/lib/disk.mjs index 8a25a16e..2590d963 100644 --- a/dev/smoke/lib/disk.mjs +++ b/dev/smoke/lib/disk.mjs @@ -96,13 +96,53 @@ export function hexDataFromFm(fm) { return h; } +/** A link to a map note ("[[_coast]]"), as hex notes' map key holds (NF1). */ +const isMapLink = (v) => typeof v === "string" && /^\[\[(?:[^\]|#]*\/)?_[^\]]*\]\]$/.test(v.trim()); + +/** The hex note's link to its map note: `map:` (NF1) or the older `hexmaker-map:`. */ +export const hexNoteMapLink = (fm) => (isMapLink(fm?.map) ? fm.map : isMapLink(fm?.["hexmaker-map"]) ? fm["hexmaker-map"] : null); + +/** Filled "**Terrain:**" / "**Region:**" body lines (older templates), as [field, value]. */ +export function bodyFieldLines(body) { + const out = []; + for (const l of body.split(/\r?\n/)) { + const m = /^[ \t]*\*\*(Terrain|Region):?\*\*:?[ \t]*(.*?)[ \t]*$/i.exec(l); + if (!m) continue; + const v = m[2].trim(); + if (!v || /^\*?\(.*\)\*?$/.test(v) || /^_+$/.test(v) || v === "-" || v === "—") continue; + out.push([m[1].toLowerCase(), v]); + } + return out; +} + +/** + * A body as compared before/after the plugin's note-format work: without + * the Map data callout (the plugin's) and the filled Terrain/Region lines + * it moves into it (NF2), blank runs collapsed. Everything else must be + * identical. + */ +export function comparableBody(body) { + const lines = body.replace(/\r\n?/g, "\n").split("\n"); + const out = []; + let inCallout = false; + for (const l of lines) { + if (/^\s*>\s*\[!hexmaker\]/i.test(l)) { inCallout = true; continue; } + if (inCallout && /^\s*>/.test(l)) continue; + inCallout = false; + if (bodyFieldLines(l).length) continue; + if (l.trim() === "" && out.length && out[out.length - 1].trim() === "") continue; + out.push(l); + } + return out.join("\n").trim(); +} + function parseNote(text) { const mm = FM.exec(text); let fm = null, err = null; if (mm) { try { fm = YAML.parse(mm[1]) ?? {}; } catch (e) { err = String(e).slice(0, 80); } } const body = mm ? text.slice(mm[0].length) : text; const other = {}; - for (const [k, v] of Object.entries(fm ?? {})) if (!DATA_KEYS.includes(k) && k !== "hexmaker-map") other[k] = v; + for (const [k, v] of Object.entries(fm ?? {})) if (!DATA_KEYS.includes(k) && k !== "hexmaker-map" && !(k === "map" && isMapLink(v))) other[k] = v; return { fm, err, body, other }; } @@ -126,7 +166,7 @@ export function legacyTruth(vault, data) { const n = parseNote(text); const h = hexDataFromFm(n.fm); if (Object.keys(h).length) out.maps[m][f.replace(/\.md$/, "")] = h; - out.notes[relPath] = { text: sha(text), body: sha(n.body), other: sha(JSON.stringify(n.other)), dataKeys: DATA_KEYS.filter((k) => n.fm && k in n.fm), yamlError: n.err }; + out.notes[relPath] = { text: sha(text), body: sha(comparableBody(n.body)), bodyFields: bodyFieldLines(n.body), other: sha(JSON.stringify(n.other)), dataKeys: DATA_KEYS.filter((k) => n.fm && k in n.fm), yamlError: n.err }; } } return out; @@ -174,13 +214,17 @@ export function verifyMigration(vault, truth, store) { const file = path.join(vault, p); if (!fs.existsSync(file)) { problems.push(`hex note missing: ${p}`); continue; } const n = parseNote(fs.readFileSync(file, "utf8")); - if (sha(n.body) !== t.body) problems.push(`body changed: ${p}`); else bodies++; + if (sha(comparableBody(n.body)) !== t.body) problems.push(`body changed: ${p}`); else bodies++; + // NF2: filled Terrain/Region lines now sit in the Map data callout. + for (const [field, value] of t.bodyFields ?? []) { + if (!n.body.toLowerCase().includes(`> old ${field}: ${value}`.toLowerCase())) problems.push(`old ${field} line not in Map data: ${p}`); + } if (sha(JSON.stringify(n.other)) !== t.other) problems.push(`user frontmatter changed: ${p}`); const left = DATA_KEYS.filter((k) => n.fm && k in n.fm); if (left.length) problems.push(`data keys left: ${p} ${left}`); else if (t.dataKeys.length) { cleaned++; - if (!n.fm?.["hexmaker-map"]) problems.push(`no map link: ${p}`); + if (!hexNoteMapLink(n.fm)) problems.push(`no map link: ${p}`); } } return { hexesChecked: hexes, notesChecked: Object.keys(truth.notes).length, bodiesIdentical: bodies, cleaned, problems }; @@ -209,6 +253,28 @@ export function verifyBackups(vault, pluginId, seedTexts) { return out; } +/** + * Notes rewritten by the one-time note-format upgrades (NF1–NF3): path → + * hash of the original text in the `backups/note-formats-` files. + * A note may change on the first start only if its original is here. + */ +export function noteFormatBackups(vault, pluginId) { + const bdir = path.join(vault, ".obsidian", "plugins", pluginId, "backups"); + const out = {}; + if (!fs.existsSync(bdir)) return out; + for (const day of fs.readdirSync(bdir)) { + if (!day.startsWith("note-formats-")) continue; + const d = path.join(bdir, day); + for (const f of fs.readdirSync(d)) { + if (!/\.json(\.gz)?$/.test(f)) continue; + const buf = fs.readFileSync(path.join(d, f)); + const b = JSON.parse((f.endsWith(".gz") ? zlib.gunzipSync(buf) : buf).toString("utf8")); + for (const [p, text] of Object.entries(b.notes ?? {})) out[p] ??= sha(Buffer.from(text, "utf8")); + } + } + return out; +} + /** note path → hash of its full text (for verifyBackups). */ export const noteTextHashes = (truth) => Object.fromEntries(Object.entries(truth.notes).map(([p, t]) => [p, t.text])); diff --git a/dev/smoke/run.mjs b/dev/smoke/run.mjs index 1c9ac201..98a62ac2 100644 --- a/dev/smoke/run.mjs +++ b/dev/smoke/run.mjs @@ -39,7 +39,7 @@ import { common, createSandbox, launchSandbox, stopSandbox, connectPage, obsidianProcesses, pluginErrors, shot, sleep, } from "./lib/obsidian.mjs"; import { machineLoad, pickJobs } from "./lib/concurrency.mjs"; -import { snapshot, diff, legacyTruth, verifyMigration, verifyBackups, noteTextHashes, verifyPaletteUpgrade } from "./lib/disk.mjs"; +import { snapshot, diff, legacyTruth, verifyMigration, verifyBackups, noteTextHashes, verifyPaletteUpgrade, noteFormatBackups } from "./lib/disk.mjs"; import * as P from "./lib/page.mjs"; import { canon, jsonDiff, oneTimeOnly } from "./lib/compare.mjs"; import { SETUPS } from "./setups.mjs"; @@ -252,7 +252,11 @@ async function runSetup(setup) { if (probs.length) paletteProbs.push(`${p}: ${probs.slice(0, 4).join(", ")}`); else upgraded.push(p); } if (upgraded.length || paletteProbs.length) rec("M-palettes", paletteProbs.length === 0, paletteProbs.join("; ") || `${upgraded.length} palette notes upgraded, every terrain row kept: ${upgraded.join(", ")}`); - const allowed = (p) => p === `${pluginRel}data.json` || migrated.has(p) || upgraded.includes(p); + // Note-format upgrades (NF1–NF3) may rewrite a note once, backed up first. + const nfBackups = noteFormatBackups(vault, pluginId); + const reformatted = d.changed.filter((p) => nfBackups[p] !== undefined && nfBackups[p] === snap0[p]?.h); + if (reformatted.length) rec("M-note-formats", true, `${reformatted.length} notes rewritten to the new note formats, each backed up first: ${reformatted.slice(0, 6).join(", ")}${reformatted.length > 6 ? ", …" : ""}`); + const allowed = (p) => p === `${pluginRel}data.json` || migrated.has(p) || upgraded.includes(p) || reformatted.includes(p); const changed = d.changed.filter((p) => !allowed(p)); // A backup rewritten with the same bytes loses nothing; other bytes would ("changed"). const touched = d.touched.filter((p) => !allowed(p) && !p.startsWith(`${pluginRel}backups/`)); diff --git a/dev/smoke/setups.mjs b/dev/smoke/setups.mjs index 3f16cdae..cf78c698 100644 --- a/dev/smoke/setups.mjs +++ b/dev/smoke/setups.mjs @@ -342,7 +342,7 @@ async function freshExtra(ctx) { await p.createHexNote(1, 1, res.name); const hexPath = p.hexPath(1, 1, res.name); const text = (await app.vault.adapter.exists(hexPath)) ? await app.vault.adapter.read(hexPath) : null; - return { map: res.name, files, note, hexPath, hasLink: !!text && /hexmaker-map:/.test(text), hasTerrain: !!text && /^terrain\s*:/m.test(text) }; + return { map: res.name, files, note, hexPath, hasLink: !!text && /^map:\s*"\[\[_/m.test(text), hasTerrain: !!text && /^terrain\s*:/m.test(text) }; })(), ctx.pluginId); if (r.error) out.push({ check: "F1-create-paint", ok: false, detail: r.error }); else { From 833d0b090f47e19f5c1174fa317829d1ec3c5ebe Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 11:05:04 -0400 Subject: [PATCH 303/558] feat(setup): install content by map type; Space - Planet palette; focused note pickers (SP3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - What a setup installs follows the map types picked. Each shipped item declares its map type (palette presets, biome presets, palettes' map-kind frontmatter); src/kindContent.ts plans installs from that data. Space only: Space - Sector/System/Planet, no Expanded/Limited (a fresh install's untouched, unused copies are dropped in the first setup), no biome notes, "Palette for new maps" on Space - Sector. Fantasy only is unchanged; both installs both. Turning a type on later in Settings installs its content once (settings.kindContent records it). - Biome notes are only written once the setup has picked the types and World is on (no more biome notes at a fresh install's first startup). - New "Space - Planet" land palette (kind space, overland types, bundled icons); planet/moon submap defaults and the Default space world types open on it instead of Expanded. Existing notes are left as they are. - Palettes carry a kind (paletteKind): pickers, defaults, tables, space context and section words use it instead of guessing from terrain types. - Pickers: the token Note picker is an allow-list (tokens, towns, dungeons, features, quests, factions, regions folders); plugin data folders (palettes, biomes, biome pools, world types, generators) are never offered by any note picker; weather/rumours table choosers (hex editor, map properties) list the tables folder; Run workflow lists the workflows folder; Import… offers md/txt/csv only; blank folder settings mean world/, not the vault (src/notePickers.ts). - Smoke "space" recipe runs the wizard's content step and checks no fantasy palettes, no biome notes after restart, Space - Sector default and planets on Space - Planet. Co-Authored-By: Claude Opus 5.5 --- dev/smoke/setups.mjs | 36 +++- package.json | 4 +- src/HexmakerPlugin.ts | 82 +++++++- src/HexmakerSettingTab.ts | 3 +- src/SetupWizardView.ts | 16 +- src/constants.ts | 4 +- src/hex-map/HexEditorModal.ts | 19 +- src/hex-map/MapModal.ts | 3 +- src/hex-map/TokenModal.ts | 32 +--- src/hex-map/help.md | 2 + src/hex-table/HexTableView.ts | 9 +- src/kindContent.ts | 133 +++++++++++++ src/mapKinds.ts | 26 ++- src/notePickers.ts | 88 +++++++++ src/overworld/BiomeStore.ts | 16 +- src/overworld/biomePresets.ts | 52 ++--- src/palettes/PaletteEditorView.ts | 6 +- src/palettes/PaletteStore.ts | 14 +- src/palettes/paletteNote.ts | 32 +++- src/palettes/paletteOptions.ts | 15 +- src/palettes/presets.ts | 58 +++++- src/random-tables/RandomTableEditorModal.ts | 3 + src/space/worldTypePresets.ts | 10 +- src/space/worldTypes.ts | 2 +- src/templateNotes.ts | 5 +- src/types.ts | 15 ++ src/worldgen/GeneratorPanel.ts | 4 +- src/worldgen/NewMapSetupModal.ts | 3 +- tests/biomeGenerators.test.ts | 2 +- tests/biomeNotes.test.ts | 19 +- tests/mapKinds.test.ts | 5 +- tests/spaceSetup.test.ts | 199 ++++++++++++++++++++ tests/submapDefaults.test.ts | 5 +- tests/terrainTypes.test.ts | 5 +- tests/worldTypes.test.ts | 13 +- 35 files changed, 801 insertions(+), 139 deletions(-) create mode 100644 src/kindContent.ts create mode 100644 src/notePickers.ts create mode 100644 tests/spaceSetup.test.ts diff --git a/dev/smoke/setups.mjs b/dev/smoke/setups.mjs index 3f16cdae..8c56b69c 100644 --- a/dev/smoke/setups.mjs +++ b/dev/smoke/setups.mjs @@ -124,9 +124,15 @@ function recipeSpace(id) { p.settings.setupComplete = true; window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); p.settings.mapKinds = ["space"]; - p.onMapKindsChanged?.(); - const sector = await p.installPalettePreset("Space - Sector"); - const system = await p.installPalettePreset("Space - System"); + // As the wizard does (SP3): install what the picked map types ship, drop + // the fresh install's untouched fantasy palettes. + p.settings.setupComplete = false; + if (p.applyKindContent) await p.applyKindContent({ fromSetup: true }); + else p.onMapKindsChanged?.(); + p.settings.setupComplete = true; + const has = (n) => p.settings.terrainPalettes.some((x) => x.name === n); + const sector = has("Space - Sector") ? "Space - Sector" : await p.installPalettePreset("Space - Sector"); + const system = has("Space - System") ? "Space - System" : await p.installPalettePreset("Space - System"); const made = []; const mk = async (name, cols, rows, pal, parent) => { const r = await p.createNewMap(name, cols, rows, pal, 0, 0, undefined, undefined, undefined, { quiet: true, ...(parent ? { parent } : {}) }); @@ -139,12 +145,15 @@ function recipeSpace(id) { p.mapStore.setMany(s, [["2_2", { terrain: pal[1] ?? pal[0] }], ["3_3", { terrain: pal[2] ?? pal[0] }], ["5_4", { terrain: pal[0] }]]); const sys = await mk("Vega System", 9, 9, system, { map: s, hex: "2_2" }); await p.linkSubmap(s, 2, 2, sys); - const planetPal = p.childPaletteFor(sys); + // Planets open on Space - Planet (the system's submap defaults), else the old child palette. + const planetPal = p.getPaletteByName(system)?.submapDefaults?.["terrestrial planet"]?.palette ?? p.childPaletteFor(sys); const planet = await mk("Vega IV", 8, 6, planetPal, { map: sys, hex: "4_4" }); await p.linkSubmap(sys, 4, 4, planet); await p.saveSettings(); await p.mapStore.flush(); - return { made, palettes: p.settings.terrainPalettes.map((x) => x.name), planetPal }; + const biomeFolder = p.biomeStore?.folder?.(); + const biomeNotes = biomeFolder ? window.app.vault.getMarkdownFiles().filter((f) => f.path.startsWith(biomeFolder + "/")).length : 0; + return { made, palettes: p.settings.terrainPalettes.map((x) => x.name), planetPal, defaultPalette: p.settings.defaultPalette, biomeNotes }; })(); } @@ -361,6 +370,23 @@ async function spaceExtra(ctx) { out.push({ check: "F4-space-maps", ok: spaceMaps.length >= 2, detail: `space maps: ${spaceMaps.join(", ")}` }); const chain = st.maps.filter((m) => m.parent).map((m) => `${m.parent} → ${m.name}`); out.push({ check: "F4-chain", ok: chain.length >= 2, detail: chain.join("; ") }); + // SP3: a space-only setup has nothing fantasy. + const fantasy = st.palettes.filter((n) => n === "Expanded" || n === "Limited"); + out.push({ check: "F4-no-fantasy-palettes", ok: fantasy.length === 0, detail: `palettes: ${st.palettes.join(", ")}` }); + // After a restart: startup wrote no biome notes; planets sit on Space - Planet. + const r = await ctx.ev((id) => { + const p = window.app.plugins.plugins[id]; + const folder = p.biomeStore?.folder?.(); + return { + biomeNotes: folder ? window.app.vault.getMarkdownFiles().filter((f) => f.path.startsWith(folder + "/")).length : 0, + defaultPalette: p.settings.defaultPalette, + planet: p.getMap("vega-iv")?.paletteName ?? p.getMap("Vega IV")?.paletteName, + kindContent: p.settings.kindContent, + }; + }, ctx.pluginId); + out.push({ check: "F4-no-biome-notes", ok: r.biomeNotes === 0, detail: `biome notes: ${r.biomeNotes}` }); + out.push({ check: "F4-default-palette", ok: r.defaultPalette === "Space - Sector", detail: `Palette for new maps: ${r.defaultPalette}; kindContent ${JSON.stringify(r.kindContent)}` }); + out.push({ check: "F4-planet-palette", ok: r.planet === "Space - Planet", detail: `planet palette: ${r.planet}` }); return out; } diff --git a/package.json b/package.json index 4bc55786..07eff57d 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/spaceSetup.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/spaceSetup.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 4abff905..87326365 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -33,7 +33,10 @@ import { } from "./constants"; import { SetupWizardView } from "./SetupWizardView"; import { BiomeStore } from "./overworld/BiomeStore"; -import { fillBiomeColumns } from "./overworld/overworldGen"; +import { biomePoolsFolder, fillBiomeColumns } from "./overworld/overworldGen"; +import { generatorsFolder } from "./worldgen/generators"; +import { planKindContent, resolveKindContent } from "./kindContent"; +import { PLACEHOLDER_MAP_NAME } from "./setupPlaceholder"; import { WorldTypeStore } from "./space/WorldTypeStore"; import { WorldTypesModal } from "./space/WorldTypesModal"; import { PaletteStore, fillPalettePathTypes, clonePalette, missingDefaults, palettesOnLoad } from "./palettes/PaletteStore"; @@ -41,7 +44,7 @@ import { PathsService } from "./paths/PathsService"; import { RoutePins } from "./paths/routePins"; import { setPathEditMapLookup } from "./paths/editGate"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; -import { enabledKinds, isIconHiddenByKind, isSpacePalette, newTerrains, resolveMapKinds, sectionKindFor, sectionWordsFor, terrainsForTables, type SectionWordsFn } from "./mapKinds"; +import { enabledKinds, isIconHiddenByKind, newTerrains, paletteKind, resolveMapKinds, sectionKindFor, sectionWordsFor, terrainsForTables, type MapKind, type SectionWordsFn } from "./mapKinds"; import { enableFeature, hasFeature, resolveFeatureLevel, shouldNudge, type AdvancedFeature, type FeatureLevel } from "./featureLevel"; import { defaultPaletteFor, resolveDefaultPalette, resolveExpandedDefault, setPaletteTerrainSource } from "./palettes/paletteOptions"; import { AdvancedNudgeModal, EnableFeatureModal } from "./advancedHints"; @@ -172,6 +175,11 @@ export default class HexmakerPlugin extends Plugin { // BC1, once per vault: every overworld hex's biome in its Biome column. void Promise.all([biomesReady, storesReady]).then(() => fillBiomeColumns(this)).catch((e) => console.error("Hexmaker: filling Biome columns", e)); void storesReady.then(() => this.ensureTablesForNewTerrains()); + // A fresh install whose setup was finished or turned off without + // picking map types: its types' content goes in now (SP3). + void Promise.all([biomesReady, storesReady]).then(() => { + if (!this.settings.kindContent && (this.settings.setupComplete || this.settings.setupDismissed)) return this.applyKindContent(); + }).catch((e) => console.error("Hexmaker: map type content", e)); // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. void this.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { if (!sandbox) return; @@ -826,6 +834,9 @@ export default class HexmakerPlugin extends Plugin { // (new install / older data) = world, plus space if a palette has space // terrains already. this.settings.mapKinds = resolveMapKinds(data["mapKinds"], this.settings.terrainPalettes); + // Shipped content per map type (SP3): an update has its types' content + // already; a fresh install writes none until its setup picks the types. + this.settings.kindContent = resolveKindContent(rawData, this.settings.mapKinds); // Feature level, also from the raw data: an install that already had // settings (an update) gets Advanced so nothing it used disappears; a // fresh one starts Simple. Saved right away, so the next load doesn't @@ -842,7 +853,8 @@ export default class HexmakerPlugin extends Plugin { // "Palette for new maps": seeded once from the above, then the user's. this.settings.defaultPalette = resolveDefaultPalette(rawData); const firstDefaultPalette = typeof rawData?.["defaultPalette"] !== "string"; - if (firstLevel || firstExpanded || firstDefaultPalette || !rawData?.["installedAt"]) await this.saveData(this.settings); + const firstKindContent = rawData?.["kindContent"] === undefined; + if (firstKindContent || firstLevel || firstExpanded || firstDefaultPalette || !rawData?.["installedAt"]) await this.saveData(this.settings); } /** @@ -1150,7 +1162,13 @@ export default class HexmakerPlugin extends Plugin { const core = loose.internalPlugins?.getPluginById?.("templates"); const coreFolder = core?.enabled ? core.instance?.options?.folder : undefined; const templater = loose.plugins?.plugins?.["templater-obsidian"]?.settings?.templates_folder; - return templateNoteRules(this.settings, [coreFolder, templater]); + return templateNoteRules(this.settings, [coreFolder, templater], [ + this.paletteStore.folder(), + this.biomeStore.folder(), + biomePoolsFolder(this), + this.worldTypeStore.folder(), + generatorsFolder(this), + ]); } /** @@ -2486,6 +2504,50 @@ export default class HexmakerPlugin extends Plugin { return this.getPaletteByName(name)?.terrains ?? getPreset(name)?.terrains ?? []; } + /** The map type of a palette (or a preset not installed yet): see paletteKind. */ + getPaletteOrPresetKind(name: string): MapKind { + return paletteKind(this.getPaletteByName(name) ?? getPreset(name)); + } + + /** + * Install the shipped content of map types that are on and haven't had + * it yet (SP3, src/kindContent.ts): their palettes, biome notes (World) + * and world types (Space). In the first setup, untouched shipped + * palettes of types left off, that no map uses, are dropped again, and + * "Palette for new maps" moves off a type that's off. Run when the setup + * wizard picks the map types (`fromSetup`) and when a type is turned on + * in settings. + */ + async applyKindContent(opts: { fromSetup?: boolean } = {}): Promise { + const s = this.settings; + const placeholder = s.maps.find((m) => m.name === PLACEHOLDER_MAP_NAME); + // The shipped placeholder map doesn't count as using its palette while it's empty. + const placeholderUnused = !!placeholder && this.mapStore.all(PLACEHOLDER_MAP_NAME).size === 0; + const inUse = new Set(s.maps.filter((m) => !(placeholderUnused && m === placeholder)).map((m) => m.paletteName).filter(Boolean)); + const plan = planKindContent({ + kinds: [...enabledKinds(s)], + done: s.kindContent, + firstSetup: !!opts.fromSetup && !s.setupComplete, + palettes: s.terrainPalettes, + inUse, + defaultPalette: s.defaultPalette, + }); + if (plan.remove.length) s.terrainPalettes = s.terrainPalettes.filter((p) => !plan.remove.includes(p.name)); + for (const name of plan.install) { + const preset = getPreset(name); + if (preset) s.terrainPalettes.push(presetToPalette(preset)); + } + if (plan.defaultPalette) s.defaultPalette = plan.defaultPalette; + if (placeholder && plan.remove.includes(placeholder.paletteName)) placeholder.paletteName = defaultPaletteFor(s); + s.kindContent = plan.done; + await this.saveSettings(); + if (plan.newKinds.length) { + await this.biomeStore.seedShipped(); + if (plan.newKinds.includes("space")) await this.worldTypeStore.ensureDefault(); + } + this.onMapKindsChanged(); + } + /** * Path types maps on this palette can draw, in picker order: the palette's * own list (the live array, so editors can change it in place), a preset's @@ -2752,7 +2814,7 @@ export default class HexmakerPlugin extends Plugin { const chain = [...mapAncestors(mapName, (m) => this.parentOf(m)?.map), mapName]; return chain.some((m) => { const paletteName = this.getMap(m)?.paletteName; - return !!paletteName && isSpacePalette(this.getPaletteOrPresetTerrains(paletteName)); + return !!paletteName && this.getPaletteOrPresetKind(paletteName) === "space"; }); } @@ -2764,11 +2826,11 @@ export default class HexmakerPlugin extends Plugin { sectionWordsFor(mapName: string | undefined): SectionWordsFn { if (!mapName || !this.getMap(mapName)) return sectionWordsFor(undefined); const chain = [mapName, ...mapAncestors(mapName, (m) => this.parentOf(m)?.map).reverse()]; - const terrains = chain.map((m) => { - const paletteName = this.getMap(m)?.paletteName; - return paletteName ? this.getPaletteOrPresetTerrains(paletteName) : []; - }); - return sectionWordsFor(sectionKindFor(terrains)); + const palettes = chain.map((m) => this.getMap(m)?.paletteName); + const terrains = palettes.map((n) => (n ? this.getPaletteOrPresetTerrains(n) : [])); + // A palette's declared type counts too (a planet map on Space - Planet). + const declared = palettes.map((n) => (n ? this.getPaletteByName(n)?.kind ?? getPreset(n)?.kind : undefined)); + return sectionWordsFor(sectionKindFor(terrains, undefined, declared)); } getAllTerrains(): TerrainColor[] { diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index dbe78d67..15c04593 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -851,7 +851,8 @@ export class HexmakerSettingTab extends PluginSettingTab { } this.plugin.settings.mapKinds = MAP_KINDS.map((k) => k.id).filter((id) => kinds.has(id)); await this.plugin.saveSettings(); - this.plugin.onMapKindsChanged(); + // A type turned on for the first time gets its content now (SP3). + await this.plugin.applyKindContent(); } /** Choices for "Palette for new maps": first palette, then every palette (the saved one kept even if gone). */ diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index 033257b0..d177cade 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -275,14 +275,14 @@ function makeWelcomeStep(): WizardStep { async onNext(ctx, plugin) { plugin.settings.mapKinds = [...ctx.mapKinds]; plugin.settings.featureLevel = ctx.featureLevel; - // Start the first map on a palette of a chosen map type: Space - // only → a sector chart (Space - Sector, installed on create). - const palIsSpace = isSpacePalette(plugin.getPaletteOrPresetTerrains(ctx.paletteName)); - if (palIsSpace ? !ctx.mapKinds.includes("space") : !ctx.mapKinds.includes("world")) { + // What the setup installs follows the map types picked (SP3): + // space only → space palettes, no biome notes or fantasy + // palettes, "Palette for new maps" on Space - Sector. + await plugin.applyKindContent({ fromSetup: true }); + // Start the first map on a palette of a chosen map type. + if (!ctx.mapKinds.includes(plugin.getPaletteOrPresetKind(ctx.paletteName))) { ctx.paletteName = defaultPaletteFor(plugin.settings); } - await plugin.saveSettings(); - plugin.onMapKindsChanged(); }, }; } @@ -978,7 +978,9 @@ export class SetupWizardView extends ItemView { }); dontShowBtn.addEventListener("click", () => { this.plugin.settings.setupDismissed = true; - void this.plugin.saveSettings().then(() => this.leaf.detach()); + // The map types it has now get their content (once). + const done = this.plugin.settings.kindContent ? this.plugin.saveSettings() : this.plugin.applyKindContent(); + void done.then(() => this.leaf.detach()); }); } diff --git a/src/constants.ts b/src/constants.ts index 956a1acd..fd468a2b 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -365,8 +365,8 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { // Expanded first: the default fantasy palette for new installs (G7b). // Existing installs keep their saved palettes and maps. terrainPalettes: [ - { name: EXPANDED_PALETTE_NAME, terrains: DEFAULT_TERRAIN_PALETTE }, - { name: LIMITED_PALETTE_NAME, terrains: LIMITED_TERRAIN_PALETTE }, + { name: EXPANDED_PALETTE_NAME, terrains: DEFAULT_TERRAIN_PALETTE, kind: "world" }, + { name: LIMITED_PALETTE_NAME, terrains: LIMITED_TERRAIN_PALETTE, kind: "world" }, ], maps: [ { diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 336d57ff..38b295b0 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -62,6 +62,7 @@ import { RegionNavigateModal } from "./RegionNavigateModal"; import { displayedEncounterLinks, linkDisplayName } from "../encounterLinks"; import { DebouncedSave, SAVE_STATUS_TEXT, SAVE_STATUS_TITLE, SaveTracker, type SaveState } from "./saveStatus"; import { openNoteFocused } from "../openNote"; +import { contentFolder } from "../notePickers"; import { TERRAIN_FILTER_MIN, terrainMatches, terrainStartsCollapsed } from "./terrainSection"; /** Typing pause after which a text section autosaves. */ @@ -364,7 +365,7 @@ export class HexEditorModal extends HexmakerModal { path, "Encounters Table", true, - s.tablesFolder, + contentFolder(s, "tablesFolder"), this.encounterLinksFor(path, hexExists, allLinks.get("encounters table") ?? []), ); this.renderDropdownSection( @@ -372,7 +373,7 @@ export class HexEditorModal extends HexmakerModal { path, "Towns", hexExists, - s.townsFolder, + contentFolder(s, "townsFolder"), allLinks.get("towns") ?? [], ); this.renderDropdownSection( @@ -380,7 +381,7 @@ export class HexEditorModal extends HexmakerModal { path, "Dungeons", hexExists, - s.dungeonsFolder, + contentFolder(s, "dungeonsFolder"), allLinks.get("dungeons") ?? [], ); this.renderDropdownSection( @@ -388,7 +389,7 @@ export class HexEditorModal extends HexmakerModal { path, "Quests", hexExists, - s.questsFolder, + contentFolder(s, "questsFolder"), allLinks.get("quests") ?? [], ); this.renderDropdownSection( @@ -396,7 +397,7 @@ export class HexEditorModal extends HexmakerModal { path, "Factions", hexExists, - s.factionsFolder, + contentFolder(s, "factionsFolder"), allLinks.get("factions") ?? [], ); this.renderDropdownSection( @@ -404,7 +405,7 @@ export class HexEditorModal extends HexmakerModal { path, "Features", hexExists, - s.featuresFolder, + contentFolder(s, "featuresFolder"), allLinks.get("features") ?? [], ); @@ -1656,12 +1657,12 @@ export class HexEditorModal extends HexmakerModal { /** "Run workflow" (PA2): pick a workflow note, then run it for this hex. */ private pickWorkflow(): void { - const folder = normalizeFolder(this.plugin.settings.workflowsFolder ?? ""); + // Workflows only: a blank setting is the workflows folder's usual place, never the world folder. const picker = new FileLinkSuggestModal( this.app, this.plugin, (file) => new WorkflowWizardModal(this.app, this.plugin, file, this.rollTarget("description")).open(), - folder || undefined, + contentFolder(this.plugin.settings, "workflowsFolder"), ["md"], ); picker.setPlaceholder("Pick a workflow to run…"); @@ -1719,7 +1720,7 @@ export class HexEditorModal extends HexmakerModal { refresh(); const chooseTable = (onChoose: (file: TFile) => void) => - new FileLinkSuggestModal(this.app, this.plugin, onChoose, "", ["md"]).open(); + new FileLinkSuggestModal(this.app, this.plugin, onChoose, contentFolder(this.plugin.settings, "tablesFolder"), ["md"]).open(); const setMapTable = () => chooseTable((file) => { const map = this.plugin.getMap(this.mapName); diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 5e2ed0f5..e3318bdf 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -6,6 +6,7 @@ import type { HexMapView } from "./HexMapView"; import { IMAGE_EXTENSIONS, attachImageDropZone, mapBgImportFolder, normalizeFolder, slugify, getIconUrl, createIconEl, importBinaryFileToVault } from "../utils"; import { renderMapExportForm } from "../export/MapExportModal"; import { FileLinkSuggestModal } from "./FileLinkSuggestModal"; +import { contentFolder } from "../notePickers"; import { listGenerators, generatorsForRegion, @@ -628,7 +629,7 @@ export class MapModal extends HexmakerModal { map[spec.mapField] = file.path; void this.plugin.saveSettings().then(() => this.render()); }, - "", + contentFolder(this.plugin.settings, "tablesFolder"), ["md"], ).open(); }); diff --git a/src/hex-map/TokenModal.ts b/src/hex-map/TokenModal.ts index 919fab3d..b1acccfa 100644 --- a/src/hex-map/TokenModal.ts +++ b/src/hex-map/TokenModal.ts @@ -3,7 +3,7 @@ import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { TokenShape, TokenSize } from "../types"; import { normalizeFolder, getIconUrl, iconLabel } from "../utils"; -import { generatorsFolder } from "../worldgen/generators"; +import { pickerFolders } from "../notePickers"; import { DEFAULT_TOKEN_FILL, isTokenNoteCandidate } from "./tokenDefaults"; export interface TokenModalResult { @@ -373,32 +373,16 @@ export class TokenModal extends HexmakerModal { .addEventListener("click", () => this.close()); } - /** Notes a token can link: world notes, not tables/workflows/generators/ - * palettes/hex and map notes/exports/icons or `_` notes (round-3 testers - * got a list full of terrain tables). */ + /** Notes a token can stand for: characters and ships (the tokens folder), + * factions, places and quests. An allow-list of content folders + * (notePickers.ts), so tables, biomes, palettes, world types, generators + * and hex notes never show (round-3 testers got terrain tables; SP3: + * biome notes flooded it). */ private tokenNoteCandidates(): TFile[] { - const s = this.plugin.settings; - const include = [ - s.worldFolder, - s.townsFolder, - s.dungeonsFolder, - s.featuresFolder, - s.questsFolder, - s.factionsFolder, - s.regionsFolder, - ].map(normalizeFolder); - const exclude = [ - s.tablesFolder, - s.workflowsFolder, - s.hexFolder, - s.exportFolder, - s.iconsFolder, - this.plugin.paletteStore.folder(), - generatorsFolder(this.plugin), - ].map((f) => normalizeFolder(f ?? "")); + const include = pickerFolders(this.plugin.settings, "token"); return this.app.vault .getMarkdownFiles() - .filter((f) => isTokenNoteCandidate(f.path, f.basename, include, exclude)) + .filter((f) => isTokenNoteCandidate(f.path, f.basename, include, [])) .filter((f) => this.plugin.isLinkableNote(f)); } diff --git a/src/hex-map/help.md b/src/hex-map/help.md index c1be9098..8cd4cca8 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -145,6 +145,8 @@ Tokens show their name underneath. The layers panel's **Labels** group turns coo Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. +**Map types.** What the setup installs follows the map types you pick: World gets the Expanded and Limited palettes and the biome notes; Space alone gets Space - Sector, Space - System and Space - Planet and nothing fantasy. Turning a type on later in **Settings → Map types** installs its content then. Planets and moons open on **Space - Planet**, a land palette for surfaces. Note pickers list only what they're for: the token form's Note list shows the tokens, towns, dungeons, features, quests, factions and regions folders, never biomes, palettes, tables or other plugin notes. + **Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). Right-click a region → **Edit region…** for its name, the hex it's on, **Enter region**, **Open map note**, its biome, facts (size, palette, terrain counts, neighbouring regions, locations) and notes (kept in its map note under `## Notes`, editable in every mode). The biome can only be changed in God mode: there it's a picker with **Reroll** and **Settings…**; in Build and Play it's shown with "Switch to God to change it." The overworld has no hex editor: right-click shows only region-level items. The **Biome** tool sets biomes (see Drawing tools). The terrain tool paints the regions and only works in the Regions view (the Biomes view shows biomes only, so the terrain tool is off there): the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (the `mode:` line in its map note) and opens in it next time; new maps are in **Build**. diff --git a/src/hex-table/HexTableView.ts b/src/hex-table/HexTableView.ts index 506e4b7e..60823f4b 100644 --- a/src/hex-table/HexTableView.ts +++ b/src/hex-table/HexTableView.ts @@ -11,6 +11,7 @@ import { getAllSectionData } from "../sections"; import { displayedEncounterLinks } from "../encounterLinks"; import { getTerrainFromFile, getHexNameFromFile } from "../frontmatter"; import { normalizeFolder, makeTableTemplate } from "../utils"; +import { contentFolder } from "../notePickers"; import { TerrainFilterModal } from "./TerrainFilterModal"; import { HexCellModal } from "./HexCellModal"; import { MultiLinkNavModal } from "./MultiLinkNavModal"; @@ -932,11 +933,11 @@ export class HexTableView extends ItemView { col.key === "encounters table" ) { const sourceFolder = - col.key === "towns" - ? this.plugin.settings.townsFolder + contentFolder(this.plugin.settings, col.key === "towns" + ? "townsFolder" : col.key === "dungeons" - ? this.plugin.settings.dungeonsFolder - : this.plugin.settings.tablesFolder; + ? "dungeonsFolder" + : "tablesFolder"); const section = col.key === "towns" ? "Towns" diff --git a/src/kindContent.ts b/src/kindContent.ts new file mode 100644 index 00000000..4b49d883 --- /dev/null +++ b/src/kindContent.ts @@ -0,0 +1,133 @@ +/** + * What a setup installs follows the map types it picked (owner call SP3: + * a space-only setup gets nothing fantasy). Every shipped content item says + * which map type it belongs to — palette presets (`PalettePreset.kind`), + * biome presets (`kind` on each), the world types table (space) — and this + * plans, from that data alone, what to install or drop. Nothing here looks + * at a palette's name to decide its type. + * + * - A type's content is installed once, the first time the type is on + * (settings.kindContent records which), so a palette or biome note the + * user deleted stays deleted. + * - During the first setup only (before the wizard finishes), shipped + * palettes a fresh install put in for a type the user then left off are + * dropped again, but only when untouched (same terrains as the preset) + * and no map uses them. + * - "Palette for new maps" moves to the first palette of an enabled type + * only when the one it names belongs to a type that's off. + * + * Pure: no Obsidian imports. + */ + +import { ALL_MAP_KINDS, paletteKind, type MapKind } from "./mapKinds"; +import type { TerrainColor } from "./types"; +import { PALETTE_PRESETS, type PalettePreset } from "./palettes/presets"; +import { terrainsEqual } from "./palettes/paletteNote"; + +export interface KindContentInput { + /** Map types on now. */ + kinds: readonly MapKind[]; + /** settings.kindContent: types whose content is in already (null/undefined = none decided yet). */ + done: readonly string[] | null | undefined; + /** The first setup hasn't finished: untouched shipped palettes of types left off may go. */ + firstSetup: boolean; + palettes: readonly { name: string; kind?: string; terrains: readonly TerrainColor[] }[]; + /** Palettes a map uses (the unused placeholder map left out). */ + inUse: ReadonlySet; + /** settings.defaultPalette */ + defaultPalette?: string; + presets?: readonly PalettePreset[]; +} + +export interface KindContentPlan { + /** Preset names to install, in preset order. */ + install: string[]; + /** Installed palettes to drop (first setup only). */ + remove: string[]; + /** Types whose content goes in now (biome notes, world types…). */ + newKinds: MapKind[]; + /** New "Palette for new maps", when it has to change. */ + defaultPalette?: string; + /** settings.kindContent afterwards. */ + done: MapKind[]; +} + +export function planKindContent(input: KindContentInput): KindContentPlan { + const presets = input.presets ?? PALETTE_PRESETS; + const on = new Set(input.kinds); + const done = new Set((input.done ?? []).filter((k): k is MapKind => (ALL_MAP_KINDS as string[]).includes(k))); + const newKinds = ALL_MAP_KINDS.filter((k) => on.has(k) && !done.has(k)); + + const lower = (n: string) => n.toLowerCase(); + const remove = input.firstSetup + ? input.palettes + .filter((p) => !on.has(paletteKind(p)) && !input.inUse.has(p.name)) + .filter((p) => { + const preset = presets.find((x) => lower(x.name) === lower(p.name)); + return !!preset && preset.kind === paletteKind(p) && terrainsEqual([...p.terrains], preset.terrains); + }) + .map((p) => p.name) + : []; + const gone = new Set(remove); + const kept = input.palettes.filter((p) => !gone.has(p.name)); + const have = new Set(kept.map((p) => lower(p.name))); + const install = presets + .filter((p) => newKinds.includes(p.kind) && !have.has(lower(p.name))) + .map((p) => p.name); + + // The palette list once the plan is applied, for the default. + const after = [ + ...kept.map((p) => ({ name: p.name, kind: paletteKind(p) })), + ...install.map((n) => ({ name: n, kind: presets.find((p) => p.name === n)!.kind })), + ]; + const want = input.defaultPalette; + const wantKind = want + ? after.find((p) => p.name === want)?.kind ?? presets.find((p) => p.name === want)?.kind + : undefined; + let defaultPalette: string | undefined; + if (want && (wantKind === undefined ? gone.has(want) : !on.has(wantKind))) { + const first = ALL_MAP_KINDS.filter((k) => on.has(k)) + .map((k) => after.find((p) => p.kind === k)?.name ?? presets.find((p) => p.kind === k)?.name) + .find((n): n is string => !!n); + if (first && first !== want) defaultPalette = first; + } + + return { + install, + remove, + newKinds, + ...(defaultPalette ? { defaultPalette } : {}), + done: ALL_MAP_KINDS.filter((k) => done.has(k) || on.has(k)), + }; +} + +/** + * May shipped content of this type be written now? Only once the setup has + * decided the map types (settings.kindContent is set) and the type is on. + * Gates the stores that seed shipped notes (biome notes, world types). + */ +export function shippedContentOn( + settings: { kindContent?: string[] | null; mapKinds?: string[] }, + kind: MapKind, +): boolean { + if (!Array.isArray(settings.kindContent)) return false; + const kinds = Array.isArray(settings.mapKinds) ? settings.mapKinds : ALL_MAP_KINDS; + return kinds.includes(kind); +} + +/** + * settings.kindContent for data.json as loaded: a saved list wins; `null` + * (saved by a fresh install) means its setup hasn't picked the map types + * yet; no key at all on an install that already had settings (an update + * from before map-type content) counts its enabled types as installed (it + * has their content already). A fresh install starts at `null`. + */ +export function resolveKindContent( + raw: Record | null | undefined, + mapKinds: readonly string[], +): string[] | null { + const saved = raw?.["kindContent"]; + if (Array.isArray(saved)) return saved.filter((k): k is string => typeof k === "string"); + if (saved === null) return null; + return raw && Object.keys(raw).length > 0 ? [...mapKinds] : null; +} diff --git a/src/mapKinds.ts b/src/mapKinds.ts index ae701610..9a2c890c 100644 --- a/src/mapKinds.ts +++ b/src/mapKinds.ts @@ -45,7 +45,7 @@ export const MAP_KINDS: MapKindInfo[] = [ { id: "space", label: "Space", - description: "Sector charts, star systems and planets: Space - Sector / Space - System palettes, Star scatter, Orbits and Planet surface generators, planet generators, the space icon pack.", + description: "Sector charts, star systems and planets: Space - Sector, Space - System and Space - Planet palettes, Star scatter, Orbits and Planet surface generators, planet generators, the space icon pack. Pick Space alone and nothing fantasy is installed.", iconPrefix: "space-", sectionWords: { Towns: { label: "Settlements", one: "Settlement", noun: "a settlement" }, @@ -92,9 +92,12 @@ export function sectionWordsFor(kind?: MapKindInfo): SectionWordsFn { export function sectionKindFor( chain: readonly (readonly { type?: string }[])[], kinds: readonly MapKindInfo[] = MAP_KINDS, + /** Each palette's declared map type (TerrainPalette.kind), same order as `chain`. */ + declared: readonly (string | undefined)[] = [], ): MapKindInfo | undefined { - for (const terrains of chain) { + for (const [i, terrains] of chain.entries()) { const used = new Set(terrains.map((t) => terrainTypeInfo(t.type)?.kind).filter(Boolean)); + if (declared[i]) used.add(declared[i] as MapKind); const hit = kinds.find((k) => k.sectionWords && used.has(k.id)); if (hit) return hit; } @@ -136,6 +139,17 @@ export function isSpacePalette(terrains: readonly { type?: string }[] | undefine return (terrains ?? []).some((t) => terrainTypeInfo(t.type)?.kind === "space"); } +/** + * The map type a palette belongs to: its declared `kind` (the shipped + * palettes say; a palette note's `map-kind`), else space when any terrain + * has a space type, else world. Data on the palette decides, never its name. + */ +export function paletteKind(p: { kind?: string; terrains?: readonly { type?: string }[] } | undefined): MapKind { + const declared = p?.kind; + if (declared && (ALL_MAP_KINDS as string[]).includes(declared)) return declared as MapKind; + return isSpacePalette(p?.terrains) ? "space" : "world"; +} + /** * Terrains that get description / encounter tables: every palette's, but * with World off (a Space-only setup), only the space palettes' — no @@ -143,7 +157,7 @@ export function isSpacePalette(terrains: readonly { type?: string }[] | undefine * by name, in palette order. */ export function terrainsForTables( - palettes: readonly { name?: string; terrains: readonly T[] }[], + palettes: readonly { name?: string; kind?: string; terrains: readonly T[] }[], kinds: Iterable, /** Palettes a map uses: their terrains always get tables (HG5). */ inUse: Iterable = [], @@ -153,7 +167,7 @@ export function terrainsForTables( const seen = new Set(); const out: T[] = []; for (const p of palettes) { - if (spaceOnly && !isSpacePalette(p.terrains) && !(p.name !== undefined && used.has(p.name))) continue; + if (spaceOnly && paletteKind(p) !== "space" && !(p.name !== undefined && used.has(p.name))) continue; for (const t of p.terrains) { if (seen.has(t.name)) continue; seen.add(t.name); @@ -205,8 +219,8 @@ export function isGeneratorShown( */ export function resolveMapKinds( saved: unknown, - palettes: readonly { terrains: readonly { type?: string }[] }[], + palettes: readonly { kind?: string; terrains: readonly { type?: string }[] }[], ): MapKind[] { if (Array.isArray(saved)) return saved.filter((k): k is MapKind => (ALL_MAP_KINDS as unknown[]).includes(k)); - return palettes.some((p) => isSpacePalette(p.terrains)) ? ["world", "space"] : ["world"]; + return palettes.some((p) => paletteKind(p) === "space") ? ["world", "space"] : ["world"]; } diff --git a/src/notePickers.ts b/src/notePickers.ts new file mode 100644 index 00000000..822b68b0 --- /dev/null +++ b/src/notePickers.ts @@ -0,0 +1,88 @@ +/** + * Note pickers list what they're for, never "the vault minus some system + * folders" (owner call SP3: one focus per picker; biome notes flooded the + * token Note picker). Each picker purpose is an ALLOW-list of content + * folders, as data: a new kind of plugin note (biomes, world types, + * palettes…) can't leak in, because it isn't in any purpose's list. + * + * A blank folder setting means that folder's usual place under the world + * folder (`world/towns`…, what "Generate folders" fills in), never the + * whole vault. + * + * Pure: no Obsidian imports. + */ + +/** A content folder setting. */ +export type ContentFolderKey = + | "townsFolder" + | "dungeonsFolder" + | "questsFolder" + | "featuresFolder" + | "factionsFolder" + | "regionsFolder" + | "tablesFolder" + | "workflowsFolder"; + +/** Where each content folder lives under the world folder when its setting is blank. */ +export const CONTENT_FOLDER_DEFAULTS: Record = { + townsFolder: "towns", + dungeonsFolder: "dungeons", + questsFolder: "quests", + featuresFolder: "features", + factionsFolder: "factions", + regionsFolder: "regions", + tablesFolder: "tables", + workflowsFolder: "workflows", +}; + +/** Token notes made from the token form go here, under the world folder. */ +export const TOKENS_SUBFOLDER = "tokens"; + +const trim = (p: string | undefined): string => (p ?? "").trim().replace(/^\/+|\/+$/g, ""); + +/** The world folder ("world" when blank). */ +export function worldFolderOf(settings: { worldFolder?: string }): string { + return trim(settings.worldFolder) || "world"; +} + +/** A content folder: its setting, else its usual place under the world folder. */ +export function contentFolder( + settings: Partial> & { worldFolder?: string }, + key: ContentFolderKey, +): string { + return trim(settings[key]) || `${worldFolderOf(settings)}/${CONTENT_FOLDER_DEFAULTS[key]}`; +} + +/** What a picker is for, and the content folders it lists from. */ +export type PickerPurpose = "token" | "table" | "workflow"; + +export const PICKER_FOLDERS: Record = { + // Things a token stands for: characters and ships (the tokens folder), + // factions, places (towns, dungeons, features, regions) and quests. + token: { + folders: ["townsFolder", "dungeonsFolder", "featuresFolder", "questsFolder", "factionsFolder", "regionsFolder"], + tokens: true, + }, + table: { folders: ["tablesFolder"] }, + workflow: { folders: ["workflowsFolder"] }, +}; + +/** The folders a picker lists notes from (deduplicated). */ +export function pickerFolders( + settings: Partial> & { worldFolder?: string }, + purpose: PickerPurpose, +): string[] { + const spec = PICKER_FOLDERS[purpose]; + const out = spec.folders.map((k) => contentFolder(settings, k)); + if (spec.tokens) out.push(`${worldFolderOf(settings)}/${TOKENS_SUBFOLDER}`); + return [...new Set(out)]; +} + +/** Is `path` inside one of `folders` (case-insensitive)? */ +export function inAnyFolder(path: string, folders: readonly string[]): boolean { + const p = path.toLowerCase(); + return folders.some((f) => !!f && p.startsWith(f.toLowerCase() + "/")); +} + +/** Files the table editor's Import… can read: text with one entry per list item or line. */ +export const IMPORT_LIST_EXTENSIONS = ["md", "txt", "csv"]; diff --git a/src/overworld/BiomeStore.ts b/src/overworld/BiomeStore.ts index d86aa013..f9e250dd 100644 --- a/src/overworld/BiomeStore.ts +++ b/src/overworld/BiomeStore.ts @@ -7,6 +7,9 @@ * * - init(): reads every note, then writes each shipped biome (biomePresets) * that hasn't been seeded yet and has no note: once, never over a note. + * Only biomes whose map type is on, once the setup has picked the types + * (shippedContentOn): a space-only setup gets no biome notes, and turning + * World on later writes them then (seedShipped). * - Hand edits are read back live (vault events); unreadable rows are * reported once per edit and left as written. * - A biome's `id` (frontmatter) is what references use, so renaming the @@ -35,6 +38,7 @@ import { } from "./biomeNote"; import { BIOME_PRESETS, biomePreset } from "./biomePresets"; import { setBiomeSource } from "./biomes"; +import { shippedContentOn } from "../kindContent"; interface Entry { path: string; @@ -121,6 +125,14 @@ export class BiomeStore implements BiomeStoreApi { }); } + /** Write the shipped biomes of map types that are on now (a type was just turned on). */ + async seedShipped(): Promise { + await this.enqueue(async () => { + await this.seed(); + this.publish(); + }); + } + /** Re-read every note (the folder setting changed). */ async reload(): Promise { await this.enqueue(async () => { @@ -338,7 +350,9 @@ export class BiomeStore implements BiomeStoreApi { const seeded = s.biomesSeeded ?? []; const ids = new Set([...this.entries.values()].map((e) => e.fields.id)); const folder = this.folder(); - const plan = presetsToSeed(seeded, ids, (name) => !!this.plugin.app.vault.getAbstractFileByPath(`${folder}/${name}.md`)); + const presets = BIOME_PRESETS.filter((p) => shippedContentOn(s, p.kind)); + if (!presets.length) return; + const plan = presetsToSeed(seeded, ids, (name) => !!this.plugin.app.vault.getAbstractFileByPath(`${folder}/${name}.md`), presets); if (!plan.done.length) return; if (plan.write.length) { await this.ensureFolder(folder); diff --git a/src/overworld/biomePresets.ts b/src/overworld/biomePresets.ts index 0980c32b..c79f9298 100644 --- a/src/overworld/biomePresets.ts +++ b/src/overworld/biomePresets.ts @@ -25,34 +25,44 @@ import type { BiomeNoteFields } from "./biomeNote"; import { copyClimate } from "./biomeClimate"; +import type { MapKind } from "../mapKinds"; -export const BIOME_PRESETS: readonly BiomeNoteFields[] = [ - { id: "tundra", label: "Tundra", color: "#e0f2fe", mix: [{ type: "snow", weight: 26 }, { type: "hills", weight: 21 }, { type: "grassland", weight: 21 }, { type: "water", weight: 10, minPatches: 1 }, { type: "peaks", weight: 6 }, { type: "wetland", weight: 6 }, { type: "desert", weight: 4 }, { type: "forest", weight: 3 }, { type: "mountains", weight: 3 }], transitions: [{ next: "Temperate forest", between: "Taiga" }, { next: "Deep forest", between: "Taiga" }, { next: "Grassland", between: "Taiga" }, { next: "Jungle", between: "Grassland" }, { next: "Savanna", between: "Grassland" }, { next: "Badlands", between: "Grassland" }], climate: { temperature: { lo: 0, hi: 0.36 }, elevation: "low" } }, - { id: "taiga", label: "Taiga", color: "#428a5e", mix: [{ type: "forest", weight: 63 }, { type: "hills", weight: 13, minPatches: 1 }, { type: "water", weight: 12, minPatches: 1 }, { type: "wetland", weight: 7 }, { type: "snow", weight: 3 }, { type: "mountains", weight: 2 }], transitions: [{ next: "Jungle", between: "Temperate forest" }, { next: "Badlands", between: "Grassland" }], climate: { temperature: { lo: 0.18, hi: 0.36 }, moisture: { lo: 0.45, hi: 1 }, elevation: "low" } }, - { id: "temperate-forest", label: "Temperate forest", color: "#2d9553", mix: [{ type: "forest", weight: 67 }, { type: "hills", weight: 17, minPatches: 1 }, { type: "grassland", weight: 8 }, { type: "water", weight: 5 }, { type: "wetland", weight: 3 }], transitions: [], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0.3, hi: 0.62 }, elevation: "low" } }, - { id: "deep-forest", label: "Deep forest", color: "#257445", mix: [{ type: "forest", weight: 80 }, { type: "hills", weight: 14, minPatches: 1 }, { type: "grassland", weight: 3 }, { type: "wetland", weight: 3 }], transitions: [], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0.62, hi: 0.8 }, elevation: "low" } }, - { id: "grassland", label: "Grassland", color: "#69a168", mix: [{ type: "grassland", weight: 59 }, { type: "hills", weight: 17, minPatches: 1 }, { type: "forest", weight: 9, minPatches: 1 }, { type: "desert", weight: 4 }, { type: "water", weight: 4 }, { type: "wetland", weight: 4 }, { type: "mountains", weight: 4 }], transitions: [{ next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0, hi: 0.3 }, elevation: "low" } }, - { id: "savanna", label: "Savanna", color: "#c4b25c", mix: [{ type: "grassland", weight: 46 }, { type: "desert", weight: 26, minPatches: 1 }, { type: "jungle", weight: 10, minPatches: 1 }, { type: "hills", weight: 7 }, { type: "forest", weight: 6 }, { type: "wetland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0.2, hi: 0.5 }, elevation: "low" } }, - { id: "jungle", label: "Jungle", color: "#15803d", mix: [{ type: "jungle", weight: 63 }, { type: "wetland", weight: 14, minPatches: 1 }, { type: "hills", weight: 11, minPatches: 1 }, { type: "mountains", weight: 6 }, { type: "water", weight: 4 }, { type: "grassland", weight: 2 }], transitions: [{ next: "Badlands", between: "Savanna" }], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0.5, hi: 0.85 }, elevation: "low" } }, - { id: "badlands", label: "Badlands", color: "#c2410c", mix: [{ type: "badlands", weight: 42 }, { type: "desert", weight: 26, minPatches: 1 }, { type: "mountains", weight: 21, minPatches: 1 }, { type: "hills", weight: 7 }, { type: "coast", weight: 4 }], transitions: [], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0, hi: 0.2 }, elevation: "low" } }, - { id: "swamp", label: "Swamp", color: "#909f23", mix: [{ type: "wetland", weight: 62 }, { type: "forest", weight: 21, minPatches: 1 }, { type: "water", weight: 10, minPatches: 1 }, { type: "grassland", weight: 6 }, { type: "shallows", weight: 2 }], transitions: [{ next: "Badlands", between: "Grassland" }, { next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.36, hi: 1 }, moisture: { lo: 0.8, hi: 1 }, elevation: "low" } }, - { id: "river-delta", label: "River delta", color: "#5f9a7a", mix: [{ type: "wetland", weight: 39 }, { type: "water", weight: 32 }, { type: "shallows", weight: 13, minPatches: 1 }, { type: "grassland", weight: 10 }, { type: "coast", weight: 4 }, { type: "forest", weight: 2 }], transitions: [], climate: { moisture: { lo: 0.55, hi: 1 }, elevation: "mouth", rare: true } }, - { id: "valley", label: "Valley", color: "#e0e8a1", mix: [{ type: "grassland", weight: 34 }, { type: "hills", weight: 21, minPatches: 1 }, { type: "mountains", weight: 18, minPatches: 1 }, { type: "forest", weight: 12, minPatches: 1 }, { type: "peaks", weight: 11 }, { type: "water", weight: 3 }, { type: "wetland", weight: 2 }], transitions: [], climate: { elevation: "mid", chance: 0.55 } }, - { id: "karst", label: "Karst", color: "#4ade80", mix: [{ type: "grassland", weight: 30 }, { type: "hills", weight: 24 }, { type: "mountains", weight: 18, minPatches: 1 }, { type: "forest", weight: 17, minPatches: 1 }, { type: "water", weight: 5 }, { type: "badlands", weight: 4 }, { type: "wetland", weight: 2 }], transitions: [], climate: { temperature: { lo: 0.62, hi: 1 }, moisture: { lo: 0.6, hi: 1 }, elevation: "mid", chance: 0.55, rare: true } }, - { id: "alpine", label: "Alpine", color: "#bfdbfe", mix: [{ type: "mountains", weight: 44 }, { type: "peaks", weight: 20, minPatches: 2 }, { type: "hills", weight: 18, minPatches: 1 }, { type: "forest", weight: 9, minPatches: 1 }, { type: "snow", weight: 4 }, { type: "grassland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Jungle", between: "Karst" }], climate: { elevation: "high" } }, - { id: "volcanic", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15, minPatches: 1 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1, minPatches: 1 }], transitions: [], climate: { elevation: "high", chance: 0.12, rare: true } }, - { id: "coastal-fjord", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16, minPatches: 1 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10, minPatches: 1 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [], climate: { temperature: { lo: 0, hi: 0.3 }, elevation: "low", coastal: true, chance: 0.5 } }, - { id: "archipelago", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [], landShare: 0.3, minIslands: 2, climate: { elevation: "sea", coastal: true, chance: 0.3 } }, - { id: "coast", label: "Coast", color: "#d9c98f", mix: [{ type: "coast", weight: 30 }, { type: "water", weight: 28 }, { type: "shallows", weight: 18 }, { type: "grassland", weight: 14 }, { type: "hills", weight: 6 }, { type: "wetland", weight: 4 }], transitions: [{ next: "Alpine", between: "Coastal fjord" }], shore: true, climate: { elevation: "low", coastal: true, chance: 0.35 } }, - { id: "open-sea", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20, minPatches: 1 }], transitions: [], climate: { elevation: "sea" } }, - { id: "custom", label: "Custom (blank)", color: "#a8a29e", mix: [], transitions: [], blank: true }, +/** + * A shipped biome: its note fields plus the map type it belongs to (data on + * each item, never decided by name). Its note is only written while that + * type is on (BiomeStore, shippedContentOn): a space-only setup gets none. + * The type isn't written into the note. + */ +export type BiomePreset = BiomeNoteFields & { kind: MapKind }; + +export const BIOME_PRESETS: readonly BiomePreset[] = [ + { id: "tundra", kind: "world", label: "Tundra", color: "#e0f2fe", mix: [{ type: "snow", weight: 26 }, { type: "hills", weight: 21 }, { type: "grassland", weight: 21 }, { type: "water", weight: 10, minPatches: 1 }, { type: "peaks", weight: 6 }, { type: "wetland", weight: 6 }, { type: "desert", weight: 4 }, { type: "forest", weight: 3 }, { type: "mountains", weight: 3 }], transitions: [{ next: "Temperate forest", between: "Taiga" }, { next: "Deep forest", between: "Taiga" }, { next: "Grassland", between: "Taiga" }, { next: "Jungle", between: "Grassland" }, { next: "Savanna", between: "Grassland" }, { next: "Badlands", between: "Grassland" }], climate: { temperature: { lo: 0, hi: 0.36 }, elevation: "low" } }, + { id: "taiga", kind: "world", label: "Taiga", color: "#428a5e", mix: [{ type: "forest", weight: 63 }, { type: "hills", weight: 13, minPatches: 1 }, { type: "water", weight: 12, minPatches: 1 }, { type: "wetland", weight: 7 }, { type: "snow", weight: 3 }, { type: "mountains", weight: 2 }], transitions: [{ next: "Jungle", between: "Temperate forest" }, { next: "Badlands", between: "Grassland" }], climate: { temperature: { lo: 0.18, hi: 0.36 }, moisture: { lo: 0.45, hi: 1 }, elevation: "low" } }, + { id: "temperate-forest", kind: "world", label: "Temperate forest", color: "#2d9553", mix: [{ type: "forest", weight: 67 }, { type: "hills", weight: 17, minPatches: 1 }, { type: "grassland", weight: 8 }, { type: "water", weight: 5 }, { type: "wetland", weight: 3 }], transitions: [], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0.3, hi: 0.62 }, elevation: "low" } }, + { id: "deep-forest", kind: "world", label: "Deep forest", color: "#257445", mix: [{ type: "forest", weight: 80 }, { type: "hills", weight: 14, minPatches: 1 }, { type: "grassland", weight: 3 }, { type: "wetland", weight: 3 }], transitions: [], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0.62, hi: 0.8 }, elevation: "low" } }, + { id: "grassland", kind: "world", label: "Grassland", color: "#69a168", mix: [{ type: "grassland", weight: 59 }, { type: "hills", weight: 17, minPatches: 1 }, { type: "forest", weight: 9, minPatches: 1 }, { type: "desert", weight: 4 }, { type: "water", weight: 4 }, { type: "wetland", weight: 4 }, { type: "mountains", weight: 4 }], transitions: [{ next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.36, hi: 0.66 }, moisture: { lo: 0, hi: 0.3 }, elevation: "low" } }, + { id: "savanna", kind: "world", label: "Savanna", color: "#c4b25c", mix: [{ type: "grassland", weight: 46 }, { type: "desert", weight: 26, minPatches: 1 }, { type: "jungle", weight: 10, minPatches: 1 }, { type: "hills", weight: 7 }, { type: "forest", weight: 6 }, { type: "wetland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0.2, hi: 0.5 }, elevation: "low" } }, + { id: "jungle", kind: "world", label: "Jungle", color: "#15803d", mix: [{ type: "jungle", weight: 63 }, { type: "wetland", weight: 14, minPatches: 1 }, { type: "hills", weight: 11, minPatches: 1 }, { type: "mountains", weight: 6 }, { type: "water", weight: 4 }, { type: "grassland", weight: 2 }], transitions: [{ next: "Badlands", between: "Savanna" }], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0.5, hi: 0.85 }, elevation: "low" } }, + { id: "badlands", kind: "world", label: "Badlands", color: "#c2410c", mix: [{ type: "badlands", weight: 42 }, { type: "desert", weight: 26, minPatches: 1 }, { type: "mountains", weight: 21, minPatches: 1 }, { type: "hills", weight: 7 }, { type: "coast", weight: 4 }], transitions: [], climate: { temperature: { lo: 0.66, hi: 1 }, moisture: { lo: 0, hi: 0.2 }, elevation: "low" } }, + { id: "swamp", kind: "world", label: "Swamp", color: "#909f23", mix: [{ type: "wetland", weight: 62 }, { type: "forest", weight: 21, minPatches: 1 }, { type: "water", weight: 10, minPatches: 1 }, { type: "grassland", weight: 6 }, { type: "shallows", weight: 2 }], transitions: [{ next: "Badlands", between: "Grassland" }, { next: "Alpine", between: "Valley" }], climate: { temperature: { lo: 0.36, hi: 1 }, moisture: { lo: 0.8, hi: 1 }, elevation: "low" } }, + { id: "river-delta", kind: "world", label: "River delta", color: "#5f9a7a", mix: [{ type: "wetland", weight: 39 }, { type: "water", weight: 32 }, { type: "shallows", weight: 13, minPatches: 1 }, { type: "grassland", weight: 10 }, { type: "coast", weight: 4 }, { type: "forest", weight: 2 }], transitions: [], climate: { moisture: { lo: 0.55, hi: 1 }, elevation: "mouth", rare: true } }, + { id: "valley", kind: "world", label: "Valley", color: "#e0e8a1", mix: [{ type: "grassland", weight: 34 }, { type: "hills", weight: 21, minPatches: 1 }, { type: "mountains", weight: 18, minPatches: 1 }, { type: "forest", weight: 12, minPatches: 1 }, { type: "peaks", weight: 11 }, { type: "water", weight: 3 }, { type: "wetland", weight: 2 }], transitions: [], climate: { elevation: "mid", chance: 0.55 } }, + { id: "karst", kind: "world", label: "Karst", color: "#4ade80", mix: [{ type: "grassland", weight: 30 }, { type: "hills", weight: 24 }, { type: "mountains", weight: 18, minPatches: 1 }, { type: "forest", weight: 17, minPatches: 1 }, { type: "water", weight: 5 }, { type: "badlands", weight: 4 }, { type: "wetland", weight: 2 }], transitions: [], climate: { temperature: { lo: 0.62, hi: 1 }, moisture: { lo: 0.6, hi: 1 }, elevation: "mid", chance: 0.55, rare: true } }, + { id: "alpine", kind: "world", label: "Alpine", color: "#bfdbfe", mix: [{ type: "mountains", weight: 44 }, { type: "peaks", weight: 20, minPatches: 2 }, { type: "hills", weight: 18, minPatches: 1 }, { type: "forest", weight: 9, minPatches: 1 }, { type: "snow", weight: 4 }, { type: "grassland", weight: 4 }, { type: "water", weight: 2 }], transitions: [{ next: "Jungle", between: "Karst" }], climate: { elevation: "high" } }, + { id: "volcanic", kind: "world", label: "Volcanic", color: "#b91c1c", mix: [{ type: "desert", weight: 26 }, { type: "badlands", weight: 20 }, { type: "hills", weight: 20 }, { type: "mountains", weight: 15, minPatches: 1 }, { type: "forest", weight: 8 }, { type: "water", weight: 6 }, { type: "shallows", weight: 4 }, { type: "volcanic", weight: 1, minPatches: 1 }], transitions: [], climate: { elevation: "high", chance: 0.12, rare: true } }, + { id: "coastal-fjord", kind: "world", label: "Coastal fjord", color: "#cac181", mix: [{ type: "mountains", weight: 28 }, { type: "water", weight: 22 }, { type: "hills", weight: 16, minPatches: 1 }, { type: "forest", weight: 12 }, { type: "peaks", weight: 10, minPatches: 1 }, { type: "shallows", weight: 9 }, { type: "grassland", weight: 3 }, { type: "coast", weight: 1 }], transitions: [], climate: { temperature: { lo: 0, hi: 0.3 }, elevation: "low", coastal: true, chance: 0.5 } }, + { id: "archipelago", kind: "world", label: "Archipelago", color: "#4a82a5", mix: [{ type: "water", weight: 57 }, { type: "shallows", weight: 14 }, { type: "jungle", weight: 11 }, { type: "deep-water", weight: 4 }, { type: "grassland", weight: 3 }, { type: "forest", weight: 3 }, { type: "hills", weight: 3 }, { type: "coast", weight: 2 }, { type: "mountains", weight: 1 }, { type: "volcanic", weight: 1 }, { type: "peaks", weight: 1 }], transitions: [], landShare: 0.3, minIslands: 2, climate: { elevation: "sea", coastal: true, chance: 0.3 } }, + { id: "coast", kind: "world", label: "Coast", color: "#d9c98f", mix: [{ type: "coast", weight: 30 }, { type: "water", weight: 28 }, { type: "shallows", weight: 18 }, { type: "grassland", weight: 14 }, { type: "hills", weight: 6 }, { type: "wetland", weight: 4 }], transitions: [{ next: "Alpine", between: "Coastal fjord" }], shore: true, climate: { elevation: "low", coastal: true, chance: 0.35 } }, + { id: "open-sea", kind: "world", label: "Open sea", color: "#29507f", mix: [{ type: "water", weight: 80 }, { type: "deep-water", weight: 20, minPatches: 1 }], transitions: [], climate: { elevation: "sea" } }, + { id: "custom", kind: "world", label: "Custom (blank)", color: "#a8a29e", mix: [], transitions: [], blank: true }, ]; /** A copy of a preset's fields (callers may change it). */ export function biomePreset(id: string): BiomeNoteFields | undefined { const p = BIOME_PRESETS.find((b) => b.id === id); if (!p) return undefined; - const out: BiomeNoteFields = { ...p, mix: p.mix.map((r) => ({ ...r })), transitions: p.transitions.map((t) => ({ ...t })) }; + const { kind: _kind, ...fields } = p; + const out: BiomeNoteFields = { ...fields, mix: p.mix.map((r) => ({ ...r })), transitions: p.transitions.map((t) => ({ ...t })) }; const climate = copyClimate(p.climate); if (climate) out.climate = climate; else delete out.climate; diff --git a/src/palettes/PaletteEditorView.ts b/src/palettes/PaletteEditorView.ts index edfd6ec4..570a6452 100644 --- a/src/palettes/PaletteEditorView.ts +++ b/src/palettes/PaletteEditorView.ts @@ -9,7 +9,7 @@ import { inferTerrainType, terrainTypeInfo } from "../terrainTypes"; import { AddPaletteModal } from "./AddPaletteModal"; import { fillPaletteSelect } from "./paletteOptions"; import { listGeneratorKinds, visibleKinds, type TerrainGeneratorKind } from "../worldgen/registry"; -import { isSpacePalette } from "../mapKinds"; +import { paletteKind } from "../mapKinds"; import { impassableSourceText, isImpassable, setImpassable } from "../impassable"; import { buildPathPreviewSvg } from "../hex-map/PathPickerModal"; import { PathTypeEditorModal } from "../hex-map/PathTypeEditorModal"; @@ -430,8 +430,8 @@ export class PaletteEditorView extends ItemView { genSel.createEl("option", { value: "", text: "—" }); // Space generators while Space is off: only for a space palette or a // space submap palette (or the saved value). - const spaceContext = isSpacePalette(pal.terrains) - || (!!d.palette && isSpacePalette(this.plugin.getPaletteOrPresetTerrains(d.palette))); + const spaceContext = paletteKind(pal) === "space" + || (!!d.palette && this.plugin.getPaletteOrPresetKind(d.palette) === "space"); for (const g of visibleKinds(this.generators, this.plugin.settings, spaceContext, d.generator)) { genSel.createEl("option", { value: g.id, text: g.label }); } diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index 55e49337..fd6b6435 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -7,9 +7,11 @@ import { paletteFileName, parsePaletteNote, readChildPalette, + readPaletteKind, readSubmapDefaults, refreshPaletteDerived, setChildPalette, + setPaletteKind, setSubmapDefaults, submapDefaultsKey, terrainsEqual, @@ -93,6 +95,12 @@ function applyNoteMeta(pal: TerrainPalette, content: string, legacy = false): bo else delete pal.childPalette; changed = true; } + const kind = readPaletteKind(content); + if (pal.kind !== kind) { + if (kind) pal.kind = kind; + else delete pal.kind; + changed = true; + } const defaults = readSubmapDefaults(content); if (submapDefaultsKey(pal.submapDefaults) !== submapDefaultsKey(defaults)) { if (defaults) pal.submapDefaults = defaults; @@ -136,7 +144,7 @@ export function wrapNoteColors(content: string): string { /** A fresh note for a palette, metadata included. */ function newNote(pal: TerrainPalette): string { - const note = setSubmapDefaults(buildPaletteNote(pal.terrains, pal.childPalette), pal.submapDefaults); + const note = setSubmapDefaults(buildPaletteNote(pal.terrains, pal.childPalette, pal.kind), pal.submapDefaults); return pal.pathTypes ? setPathTypes(note, pal.pathTypes) : note; } @@ -148,7 +156,7 @@ function newNote(pal: TerrainPalette): string { */ /** A palette's own copy (never alias a shared constant). */ export function clonePalette(p: TerrainPalette): TerrainPalette { - return { name: p.name, terrains: p.terrains.map((t) => ({ ...t })) }; + return { name: p.name, terrains: p.terrains.map((t) => ({ ...t })), ...(p.kind ? { kind: p.kind } : {}) }; } /** @@ -729,7 +737,7 @@ export class PaletteStore { ? editing ? current : refreshPaletteDerived(current) : updatePaletteNote(current, pal.terrains); const withMeta = setSubmapDefaults( - setChildPalette(editing ? base : wrapPathTypeColors(base), pal.childPalette), + setPaletteKind(setChildPalette(editing ? base : wrapPathTypeColors(base), pal.childPalette), pal.kind), pal.submapDefaults, ); const next = pal.pathTypes ? setPathTypes(withMeta, pal.pathTypes) : withMeta; diff --git a/src/palettes/paletteNote.ts b/src/palettes/paletteNote.ts index 620991bb..f6069043 100644 --- a/src/palettes/paletteNote.ts +++ b/src/palettes/paletteNote.ts @@ -2,6 +2,7 @@ import type { SubmapDefault, TerrainColor } from "../types"; import { impassableNoteCell, parseImpassableCell } from "../impassable"; import { isDerivedCell, parseTerrainTypeCell, terrainTypeCell } from "../terrainTypes"; import { colorCell, parseColorCell, wrapColorCellsInRows } from "./colorCell"; +import { ALL_MAP_KINDS, type MapKind } from "../mapKinds"; // Plain-text palette notes. // @@ -221,6 +222,34 @@ export function setChildPalette(content: string, value: string | undefined): str return `---\n${body}---${fm[2]}${text.slice(fm[0].length)}`; } +const MAP_KIND_LINE = /^map-kind:[^\n]*(\n|$)/m; + +/** + * The `map-kind:` frontmatter value: the map type the palette is for + * ("world", "space"; see TerrainPalette.kind). Any other value reads as + * unset (the type is then worked out from the terrain types). + */ +export function readPaletteKind(content: string): MapKind | undefined { + const fm = FRONTMATTER.exec(content.replace(/\r\n?/g, "\n")); + if (!fm) return undefined; + const m = /^map-kind:\s*(.*)$/m.exec(fm[1]); + if (!m) return undefined; + const raw = m[1].trim().replace(/^["']|["']$/g, "").trim().toLowerCase(); + return (ALL_MAP_KINDS as string[]).includes(raw) ? (raw as MapKind) : undefined; +} + +/** Set or clear `map-kind:` in the note's frontmatter (untouched when it already says so). */ +export function setPaletteKind(content: string, value: MapKind | undefined): string { + if (readPaletteKind(content) === value) return content; + const text = content.replace(/\r\n?/g, "\n"); + const line = value ? `map-kind: ${value}\n` : ""; + const fm = FRONTMATTER.exec(text); + if (!fm) return value ? `---\n${line}---\n${text}` : text; + let body = fm[1] + "\n"; + body = MAP_KIND_LINE.test(body) ? body.replace(MAP_KIND_LINE, line) : body + line; + return `---\n${body}---${fm[2]}${text.slice(fm[0].length)}`; +} + // ── Submap defaults table ──────────────────────────────────────────────── // // ## Submap defaults @@ -361,11 +390,12 @@ export function setSubmapDefaults(content: string, defaults: Record | null | unde */ export function defaultPaletteFor(settings: { mapKinds?: string[]; - terrainPalettes: { name: string; terrains: readonly { type?: string }[] }[]; + terrainPalettes: { name: string; kind?: string; terrains: readonly { type?: string }[] }[]; /** See resolveDefaultPalette. Unset or "" = first palette. */ defaultPalette?: string; }): string { const kinds = enabledKinds(settings); const pals = settings.terrainPalettes; - const kindOf = (terrains: readonly { type?: string }[]): MapKind => (isSpacePalette(terrains) ? "space" : "world"); const want = settings.defaultPalette; const installed = want ? pals.find((p) => p.name === want) : undefined; - if (installed && kinds.has(kindOf(installed.terrains))) return installed.name; + if (installed && kinds.has(paletteKind(installed))) return installed.name; for (const kind of ALL_MAP_KINDS) { if (!kinds.has(kind)) continue; - const first = pals.find((p) => kindOf(p.terrains) === kind); + const first = pals.find((p) => paletteKind(p) === kind); if (first) return first.name; } const preset = want && !installed ? PALETTE_PRESETS.find((p) => p.name === want && kinds.has(p.kind)) : undefined; @@ -148,11 +147,11 @@ export function fillPaletteSelect( ): void { select.empty(); const installed = new Set(plugin.settings.terrainPalettes.map((p) => p.name)); - // Installed space palettes are hidden too while Space is off — unless + // Installed palettes of a map type that's off are hidden too (space ones + // while Space is off, fantasy ones in a space-only setup) — unless // selected, so a map or saved default using one still shows it. - const spaceOn = isKindEnabled(plugin.settings, "space"); for (const pal of plugin.settings.terrainPalettes) { - if (!spaceOn && pal.name !== selected && isSpacePalette(pal.terrains)) continue; + if (pal.name !== selected && !isKindEnabled(plugin.settings, paletteKind(pal))) continue; const hint = paletteHint(pal.name); select.createEl("option", { value: pal.name, text: pal.name, ...(hint ? { attr: { title: hint } } : {}) }); } diff --git a/src/palettes/presets.ts b/src/palettes/presets.ts index 2c9bb794..9109a08e 100644 --- a/src/palettes/presets.ts +++ b/src/palettes/presets.ts @@ -44,6 +44,7 @@ export interface PresetPathRoles { export const SPACE_SECTOR_PALETTE_NAME = "Space - Sector"; export const SPACE_SYSTEM_PALETTE_NAME = "Space - System"; +export const SPACE_PLANET_PALETTE_NAME = "Space - Planet"; // Sector scale (Traveller subsector / sector chart): one hex is one parsec // and holds at most one star system, typed by its mainworld. Drill into a @@ -103,6 +104,39 @@ export const SPACE_SYSTEM_TERRAINS: TerrainColor[] = [ { name: "radiation belt", type: "anomaly", color: "#7d6a1f", icon: "space-radioactive.svg", iconColor: "#fef08a", category: "hazards" }, ]; +// Planet scale: one world's surface, opened from a planet or moon in a +// system. Land terrains with the overland types (water, grassland, desert…) +// so the Planet surface generator places them; the rest are for painting. +// Space content all the same (kind "space"), so a space-only setup gets a +// surface palette without the fantasy ones. +export const SPACE_PLANET_TERRAINS: TerrainColor[] = [ + // Seas + { name: "deep ocean", type: "deep-water", color: "#10233f", category: "seas" }, + { name: "ocean", type: "water", color: "#245a87", category: "seas" }, + { name: "shallows", type: "shallows", color: "#3f86a3", category: "seas" }, + { name: "shore", type: "coast", color: "#b9ad84", category: "seas" }, + // Living ground + { name: "plains", type: "grassland", color: "#6f9a5a", icon: "bw-grassland.png", category: "living" }, + { name: "forest", type: "forest", color: "#2f6b4a", icon: "bw-forest.png", category: "living" }, + { name: "jungle", type: "jungle", color: "#1f6b3a", icon: "bw-jungle.png", category: "living" }, + { name: "toxic marsh", type: "wetland", color: "#7d8f2a", icon: "bw-swamp.png", iconColor: "#f7fee7", category: "living" }, + // Barren ground + { name: "regolith", type: "badlands", color: "#8a8178", icon: "bw-desert-rocky.png", category: "barren" }, + { name: "bare rock", type: "badlands", color: "#6b6560", icon: "bw-brokenlands.png", category: "barren" }, + { name: "dunes", type: "desert", color: "#d6b46a", icon: "bw-dunes.png", category: "barren" }, + { name: "ice", type: "snow", color: "#dbeaf5", category: "barren" }, + // Relief + { name: "hills", type: "hills", color: "#a49a72", icon: "bw-hills.png", category: "relief" }, + { name: "crater field", type: "hills", color: "#7b7268", icon: "space-ring.svg", iconColor: "#f5f5f4", category: "relief" }, + { name: "mountains", type: "mountains", color: "#7a6a58", icon: "bw-mountains.png", category: "relief" }, + { name: "peaks", type: "peaks", color: "#c9d3dc", icon: "bw-mountains-snow.png", category: "relief" }, + // Strange ground and sites + { name: "lava field", type: "volcanic", color: "#8f2d1c", icon: "bw-volcano.png", iconColor: "#fde68a", category: "strange" }, + { name: "crystal field", type: "badlands", color: "#6d5bb5", icon: "space-twinkle.svg", iconColor: "#ede9fe", category: "strange" }, + { name: "ruins", type: "settlement", color: "#8c7b6b", icon: "space-debris.svg", iconColor: "#fafaf9", category: "sites" }, + { name: "colony", type: "settlement", color: "#9ca3af", icon: "space-beacon-outline.svg", iconColor: "#111827", category: "sites" }, +]; + // Sector-scale "roads". export const SPACE_PATH_TYPES: PathType[] = [ { name: "Jump route", color: "#60a5fa", width: 2, lineStyle: "dashed", routing: "through", avoidImpassable: true, autoRoute: "direct" }, @@ -127,11 +161,11 @@ const SECTOR_SUBMAP_DEFAULTS: Record = Object.fromEntries "asteroid belt", "gas giant", "star system"].map((t) => [t, { ...SYSTEM_SUBMAP }]), ); -// …and every rocky world in a system opens as a planet-surface region map, -// tuned to the planet type. The sea (or desert) is the base terrain, so -// only land (or oases) gets hex notes up front. +// …and every rocky world in a system opens as a planet-surface map on +// Space - Planet, tuned to the planet type. The sea (or dunes, or +// regolith) is the base terrain. const surface = (water: string, climate: string, base: string, relief = "normal"): SubmapDefault => ({ - palette: EXPANDED_PALETTE_NAME, + palette: SPACE_PLANET_PALETTE_NAME, cols: 20, rows: 14, generator: "procedural:planet-surface", @@ -141,11 +175,11 @@ const surface = (water: string, climate: string, base: string, relief = "normal" const SYSTEM_SUBMAP_DEFAULTS: Record = { "terrestrial planet": surface("65", "temperate", "ocean"), "ocean planet": surface("85", "lush", "ocean"), - "desert planet": surface("10", "arid", "desert"), + "desert planet": surface("10", "arid", "dunes"), "ice planet": surface("30", "frozen", "ocean"), - "rocky planet": surface("10", "arid", "desert", "rugged"), - "molten planet": surface("10", "volcanic", "desert", "rugged"), - moon: surface("10", "frozen", "desert", "rugged"), + "rocky planet": surface("10", "arid", "regolith", "rugged"), + "molten planet": surface("10", "volcanic", "regolith", "rugged"), + moon: surface("10", "frozen", "regolith", "rugged"), }; export const PALETTE_PRESETS: PalettePreset[] = [ @@ -180,6 +214,12 @@ export const PALETTE_PRESETS: PalettePreset[] = [ kind: "space", submapDefaults: SYSTEM_SUBMAP_DEFAULTS, }, + { + name: SPACE_PLANET_PALETTE_NAME, + description: "A planet's surface: seas, plains, regolith, dunes, ice, craters, lava fields, toxic marsh, crystal fields, ruins and colonies. Typed for the Planet surface generator.", + terrains: SPACE_PLANET_TERRAINS, + kind: "space", + }, ]; export function getPreset(name: string): PalettePreset | undefined { @@ -188,7 +228,7 @@ export function getPreset(name: string): PalettePreset | undefined { /** Deep copy of a preset's terrains, safe to mutate. */ export function presetToPalette(preset: PalettePreset, name = preset.name): TerrainPalette { - const pal: TerrainPalette = { name, terrains: preset.terrains.map((t) => ({ ...t })) }; + const pal: TerrainPalette = { name, terrains: preset.terrains.map((t) => ({ ...t })), kind: preset.kind }; if (preset.childPalette) pal.childPalette = preset.childPalette; if (preset.submapDefaults) pal.submapDefaults = cloneSubmapDefaults(preset.submapDefaults); pal.pathTypes = clonePathTypes(preset.pathTypes ?? DEFAULT_PATH_TYPES); diff --git a/src/random-tables/RandomTableEditorModal.ts b/src/random-tables/RandomTableEditorModal.ts index 399a928a..1a933ee5 100644 --- a/src/random-tables/RandomTableEditorModal.ts +++ b/src/random-tables/RandomTableEditorModal.ts @@ -11,6 +11,7 @@ import { type TableWrite, } from "./randomTable"; import { FileLinkSuggestModal } from "../hex-map/FileLinkSuggestModal"; +import { IMPORT_LIST_EXTENSIONS } from "../notePickers"; import { processTableNote } from "./TableStore"; import type HexmakerPlugin from "../HexmakerPlugin"; import { normalizeFolder } from "../utils"; @@ -226,6 +227,8 @@ export class RandomTableEditorModal extends HexmakerModal { })(); }, "", + // Text it can read as entries (list items or lines), not images or PDFs. + IMPORT_LIST_EXTENSIONS, ).open(); }); diff --git a/src/space/worldTypePresets.ts b/src/space/worldTypePresets.ts index d3b2fe4e..015c9268 100644 --- a/src/space/worldTypePresets.ts +++ b/src/space/worldTypePresets.ts @@ -26,7 +26,7 @@ import type { OrbitZone, SectorFeatureRow, StarTypeRow, WorldTypeRow } from "./worldTypes"; const SYSTEM_PALETTE = "Space - System"; -const SURFACE_PALETTE = "Expanded"; +const SURFACE_PALETTE = "Space - Planet"; const system = (world: string, weight: number): WorldTypeRow => ({ world, @@ -74,14 +74,14 @@ export const DEFAULT_WORLD_TYPE_ROWS: readonly WorldTypeRow[] = [ // System: one body per orbit, by zone (Orbits). ...body("terrestrial planet", { inner: 0.5, habitable: 4, outer: 0.5 }, surface("65", "temperate", "ocean")), ...body("ocean planet", { inner: 0.5, habitable: 3, outer: 0.5 }, surface("85", "lush", "ocean")), - ...body("desert planet", { inner: 2, habitable: 3, outer: 0.5 }, surface("10", "arid", "desert")), + ...body("desert planet", { inner: 2, habitable: 3, outer: 0.5 }, surface("10", "arid", "dunes")), ...body("ice planet", { inner: 0.5, habitable: 0.5, outer: 3 }, surface("30", "frozen", "ocean")), - ...body("rocky planet", { inner: 4, habitable: 2, outer: 1 }, surface("10", "arid", "desert", "rugged")), - ...body("molten planet", { inner: 4, habitable: 0.5, outer: 0.5 }, surface("10", "volcanic", "desert", "rugged")), + ...body("rocky planet", { inner: 4, habitable: 2, outer: 1 }, surface("10", "arid", "regolith", "rugged")), + ...body("molten planet", { inner: 4, habitable: 0.5, outer: 0.5 }, surface("10", "volcanic", "regolith", "rugged")), ...body("gas giant", { inner: 0.5, habitable: 0.5, outer: 4 }), ...body("ice giant", { inner: 0.5, habitable: 0.5, outer: 3 }), ...body("asteroid belt", { inner: 0.5, habitable: 1, outer: 1.5 }), - { world: "moon", weight: 0, map: "system", ...surface("10", "frozen", "desert", "rugged"), notes: "placed beside planets, never rolled" }, + { world: "moon", weight: 0, map: "system", ...surface("10", "frozen", "regolith", "rugged"), notes: "placed beside planets, never rolled" }, ]; /** Orbits' random star (its old built-in weights). */ diff --git a/src/space/worldTypes.ts b/src/space/worldTypes.ts index 7ed605a1..a07f190b 100644 --- a/src/space/worldTypes.ts +++ b/src/space/worldTypes.ts @@ -14,7 +14,7 @@ * * | World | Weight | Map | Orbit | Stars | Temperature | Size | Generator | Options | Palette | Base | Notes | * | --- | ---: | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | - * | ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush | Expanded | ocean | | + * | ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush | Space - Planet | ocean | | * * - *World*: the terrain the row places (matched to the palette's terrain * names, any case). The same world may have several rows (different diff --git a/src/templateNotes.ts b/src/templateNotes.ts index 9900a936..1805a8cb 100644 --- a/src/templateNotes.ts +++ b/src/templateNotes.ts @@ -21,6 +21,9 @@ const trimSlashes = (p: string): string => p.trim().replace(/^\/+|\/+$/g, ""); export function templateNoteRules( settings: { templatePath?: string; workflowsFolder?: string; templatesFolder?: string; worldFolder?: string }, extraFolders: (string | undefined)[] = [], + /** Folders of the plugin's own data notes (palettes, biomes, biome pools, + * world types, generators): never listed in a picker either (SP3). */ + dataFolders: (string | undefined)[] = [], ): TemplateNoteRules { const paths: string[] = []; const hexTemplate = trimSlashes(settings.templatePath ?? ""); @@ -30,7 +33,7 @@ export function templateNoteRules( folders.push(wf ? `${wf}/templates` : "templates"); // The plugin's own templates folder (PA3: hex and town templates). folders.push(templatesFolderFor(settings)); - for (const f of extraFolders) { + for (const f of [...extraFolders, ...dataFolders]) { const t = trimSlashes(f ?? ""); if (t) folders.push(t); } diff --git a/src/types.ts b/src/types.ts index edef20c8..e89888ca 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,5 @@ import type { MapExportPrefs } from "./export/exportNames"; +import type { MapKind } from "./mapKinds"; export type TokenShape = "circle" | "square" | "hexagon"; export type TokenSize = "sm" | "md" | "lg"; @@ -274,6 +275,11 @@ export interface TerrainPalette { * picker order. Stored as the "Path types" table in the palette note. * Every palette has them once the palette store has loaded. */ pathTypes?: PathType[]; + /** Map type the palette is for: `map-kind` in its note's frontmatter. + * Unset = worked out from its terrain types (paletteKind in + * mapKinds.ts). The shipped palettes set it, so a land palette made for + * planet surfaces (Space - Planet) counts as space content. */ + kind?: MapKind; } /** Saved choices for new submaps of one terrain. Every field is optional. */ @@ -393,6 +399,15 @@ export interface HexmakerPluginSettings { paletteColorsCode?: boolean; /** Enabled map types (see src/mapKinds.ts). Unset = all. */ mapKinds: string[]; + /** + * Map types whose shipped content (palettes, biome notes, world types) + * is installed (src/kindContent.ts). A type's content goes in once, when + * it is first on (setup wizard, or Map types in settings), so a deleted + * palette or biome note stays deleted. null = a fresh install whose + * setup hasn't picked its map types yet: no biome notes or world types + * are written until it does (saved as null so a restart still knows). + */ + kindContent?: string[] | null; /** Simple or Advanced (see src/featureLevel.ts). */ featureLevel: "simple" | "advanced"; /** Advanced features turned on one by one while in Simple. */ diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 58af5176..85ee484c 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -45,7 +45,7 @@ import { GeneratorLibrary } from "./GeneratorLibrary"; import { BiomePanel } from "./BiomePanel"; import { hasFeature } from "../featureLevel"; import { renderAdvancedHint } from "../advancedHints"; -import { generatorMapKind, isGeneratorShown, isSpacePalette } from "../mapKinds"; +import { generatorMapKind, isGeneratorShown } from "../mapKinds"; import { sizePresets } from "./sizePresets"; import { listSaves, writeSave, readSave, applySave, renameGenerator } from "./saves"; import { ConfirmModal } from "./ConfirmModal"; @@ -230,7 +230,7 @@ export class GeneratorPanel { void listGenerators(this.plugin).then((found) => { // Planet generators (map-kind: planet) are hidden while the Space map // type is off, unless this palette/map is in space or one is loaded. - const spaceContext = isSpacePalette(this.plugin.getPaletteByName(GeneratorPanel.paletteName)?.terrains) + const spaceContext = this.plugin.getPaletteOrPresetKind(GeneratorPanel.paletteName) === "space" || (!!this.mapName && this.plugin.isSpaceMap(this.mapName)); generators = found.filter((g) => isGeneratorShown(this.plugin.settings, generatorMapKind(g.model.meta), { spaceContext, diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index afd2a318..e3229da0 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -525,7 +525,8 @@ export class NewMapSetupModal extends HexmakerModal { // Space generators only for space users or maps in space (a space // palette here, or a planet submap of a star system); a saved // submap default stays visible either way. - const spaceContext = isSpacePalette(terrains) || (!!this.origin && this.plugin.isSpaceMap(this.origin.map)); + const spaceContext = isSpacePalette(terrains) || this.plugin.getPaletteOrPresetKind(paletteSelect.value) === "space" + || (!!this.origin && this.plugin.isSpaceMap(this.origin.map)); const shown = visibleKinds(this.kinds, this.plugin.settings, spaceContext, this.saved?.generator); // "Zoom into the parent hex" generators only for submaps (a neighbour // has context but no parent hex); next to a neighbour, the ones that diff --git a/tests/biomeGenerators.test.ts b/tests/biomeGenerators.test.ts index 7bf54c94..e81dcfa9 100644 --- a/tests/biomeGenerators.test.ts +++ b/tests/biomeGenerators.test.ts @@ -167,7 +167,7 @@ function storePlugin(vault: MemVault) { return { app: vault.app(), manifest: { dir: ".obsidian/plugins/hexmaker" }, - settings: { worldFolder: "world", biomesFolder: "" } as Record, + settings: { worldFolder: "world", biomesFolder: "", kindContent: ["world"], mapKinds: ["world"] } as Record, saveSettings: async () => {}, }; } diff --git a/tests/biomeNotes.test.ts b/tests/biomeNotes.test.ts index 0b89719e..d537a30b 100644 --- a/tests/biomeNotes.test.ts +++ b/tests/biomeNotes.test.ts @@ -257,7 +257,7 @@ function plugin(vault: MemVault, settings: Record = {}) { const p = { app: vault.app(), manifest: { dir: ".obsidian/plugins/hexmaker" }, - settings: { worldFolder: "world", biomesFolder: "", ...settings } as Record, + settings: { worldFolder: "world", biomesFolder: "", kindContent: ["world"], mapKinds: ["world"], ...settings } as Record, saves: 0, saveSettings: async () => { p.saves++; }, }; @@ -284,6 +284,23 @@ describe("BiomeStore", () => { expect(plan.done).toEqual(["taiga", "temperate-forest"]); }); + it("startup in a space-only setup writes no biome notes; turning World on writes them then (SP3)", async () => { + const v = new MemVault(); + const { p, store } = await boot(v, { mapKinds: ["space"], kindContent: ["space"] }); + expect([...v.files.keys()].filter((f) => f.startsWith(FOLDER))).toEqual([]); + expect(store.list()).toEqual([]); + expect(p.settings.biomesSeeded).toBeUndefined(); + // A fresh install before its setup picks the types: none either. + const v2 = new MemVault(); + await boot(v2, { kindContent: undefined }); + expect([...v2.files.keys()].filter((f) => f.startsWith(FOLDER))).toEqual([]); + // World turned on later. + p.settings.mapKinds = ["space", "world"]; + p.settings.kindContent = ["space", "world"]; + await store.seedShipped(); + expect(v.files.has(`${FOLDER}/Tundra.md`)).toBe(true); + }); + it("seeds the built-ins into notes once; a deleted one stays deleted", async () => { const v = new MemVault(); const { p, store } = await boot(v); diff --git a/tests/mapKinds.test.ts b/tests/mapKinds.test.ts index dcb88692..84f36afb 100644 --- a/tests/mapKinds.test.ts +++ b/tests/mapKinds.test.ts @@ -5,6 +5,7 @@ import { generatorMapKind, isGeneratorShown, isSpacePalette, + paletteKind, resolveMapKinds, terrainsForTables, } from "../src/mapKinds"; @@ -42,7 +43,9 @@ describe("isSpacePalette", () => { expect(isSpacePalette(SPACE_SYSTEM_TERRAINS)).toBe(true); expect(isSpacePalette(DEFAULT_TERRAIN_PALETTE)).toBe(false); expect(isSpacePalette(LIMITED_TERRAIN_PALETTE)).toBe(false); - for (const p of PALETTE_PRESETS) expect({ p: p.name, space: isSpacePalette(p.terrains) }).toEqual({ p: p.name, space: p.kind === "space" }); + // Space - Planet is space content on land types (its declared kind says so). + for (const p of PALETTE_PRESETS) expect({ p: p.name, kind: paletteKind(p) }).toEqual({ p: p.name, kind: p.kind }); + expect(isSpacePalette(PALETTE_PRESETS.find((p) => p.name === "Space - Planet")!.terrains)).toBe(false); }); it("needs a typed space terrain (names alone don't count)", () => { diff --git a/tests/spaceSetup.test.ts b/tests/spaceSetup.test.ts new file mode 100644 index 00000000..daf7880b --- /dev/null +++ b/tests/spaceSetup.test.ts @@ -0,0 +1,199 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { planKindContent, resolveKindContent, shippedContentOn } from "../src/kindContent"; +import { DEFAULT_SETTINGS, DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { + PALETTE_PRESETS, + SPACE_PLANET_PALETTE_NAME, + SPACE_PLANET_TERRAINS, + presetToPalette, + getPreset, +} from "../src/palettes/presets"; +import { buildPaletteNote, parsePaletteNote, readPaletteKind, setPaletteKind } from "../src/palettes/paletteNote"; +import { isSpacePalette, paletteKind, terrainsForTables } from "../src/mapKinds"; +import { isTerrainType } from "../src/terrainTypes"; +import { planetRoles, planetSurface, planetSurfaceFits } from "../src/worldgen/procedural/planetSurface"; +import { BUNDLED_ICONS } from "../src/bundledIcons"; +import { defaultPaletteFor } from "../src/palettes/paletteOptions"; +import { DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { BIOME_PRESETS } from "../src/overworld/biomePresets"; +import { IMPORT_LIST_EXTENSIONS, contentFolder, inAnyFolder, pickerFolders } from "../src/notePickers"; +import { isLinkableNotePath, templateNoteRules } from "../src/templateNotes"; +import { isTokenNoteCandidate } from "../src/hex-map/tokenDefaults"; + +/** A fresh install's palettes (what DEFAULT_SETTINGS ships). */ +const fresh = () => DEFAULT_SETTINGS.terrainPalettes.map((p) => ({ ...p, terrains: p.terrains.map((t) => ({ ...t })) })); +const SPACE_PRESETS = PALETTE_PRESETS.filter((p) => p.kind === "space").map((p) => p.name); + +describe("what a setup installs follows the map types picked (SP3)", () => { + it("space only: no fantasy palettes, the space ones, Palette for new maps on Space - Sector", () => { + const plan = planKindContent({ kinds: ["space"], done: undefined, firstSetup: true, palettes: fresh(), inUse: new Set(), defaultPalette: "Expanded" }); + expect(plan.remove).toEqual(["Expanded", "Limited"]); + expect(plan.install).toEqual(["Space - Sector", "Space - System", "Space - Planet"]); + expect(plan.newKinds).toEqual(["space"]); + expect(plan.defaultPalette).toBe("Space - Sector"); + expect(plan.done).toEqual(["space"]); + }); + + it("fantasy only: unchanged (keeps Expanded and Limited, installs nothing, default stays)", () => { + const plan = planKindContent({ kinds: ["world"], done: undefined, firstSetup: true, palettes: fresh(), inUse: new Set(), defaultPalette: "Expanded" }); + expect(plan).toEqual({ install: [], remove: [], newKinds: ["world"], done: ["world"] }); + }); + + it("both: keeps the fantasy palettes and installs the space ones", () => { + const plan = planKindContent({ kinds: ["world", "space"], done: undefined, firstSetup: true, palettes: fresh(), inUse: new Set(), defaultPalette: "Expanded" }); + expect(plan.remove).toEqual([]); + expect(plan.install).toEqual(SPACE_PRESETS); + expect(plan.defaultPalette).toBeUndefined(); + expect(plan.done).toEqual(["world", "space"]); + }); + + it("turning World on later installs its palettes then, once", () => { + const space = SPACE_PRESETS.map((n) => presetToPalette(getPreset(n)!)); + const plan = planKindContent({ kinds: ["world", "space"], done: ["space"], firstSetup: false, palettes: space, inUse: new Set(), defaultPalette: "Space - Sector" }); + expect(plan.install).toEqual(["Expanded", "Limited"]); + expect(plan.newKinds).toEqual(["world"]); + expect(plan.defaultPalette).toBeUndefined(); + // Already done: a deleted palette isn't brought back. + const again = planKindContent({ kinds: ["world", "space"], done: ["world", "space"], firstSetup: false, palettes: space, inUse: new Set(), defaultPalette: "Space - Sector" }); + expect(again.install).toEqual([]); + expect(again.newKinds).toEqual([]); + }); + + it("never drops a palette a map uses, one the user changed, or any outside the first setup", () => { + const pals = fresh(); + pals[1].terrains[0].color = "#123456"; // Limited edited + const plan = planKindContent({ kinds: ["space"], done: undefined, firstSetup: true, palettes: pals, inUse: new Set(["Expanded"]), defaultPalette: "Expanded" }); + expect(plan.remove).toEqual([]); + const later = planKindContent({ kinds: ["space"], done: ["world"], firstSetup: false, palettes: fresh(), inUse: new Set(), defaultPalette: "Expanded" }); + expect(later.remove).toEqual([]); + }); + + it("keeps a Palette for new maps the user set to a type that's on", () => { + const pals = [...fresh(), { name: "My moon", kind: "space", terrains: [{ name: "dust", color: "#999", type: "badlands" }] }]; + const plan = planKindContent({ kinds: ["space"], done: undefined, firstSetup: true, palettes: pals, inUse: new Set(), defaultPalette: "My moon" }); + expect(plan.defaultPalette).toBeUndefined(); + }); + + it("a palette's type is data on it, not its name", () => { + const renamed = { name: "Expanded", kind: "space", terrains: SPACE_PLANET_TERRAINS }; + expect(paletteKind(renamed)).toBe("space"); + const plan = planKindContent({ kinds: ["space"], done: undefined, firstSetup: true, palettes: [renamed], inUse: new Set(), defaultPalette: "Expanded" }); + expect(plan.remove).toEqual([]); + }); + + it("shipped notes wait until the setup picks the types; updates count as done", () => { + expect(shippedContentOn({ mapKinds: ["world"] }, "world")).toBe(false); + expect(shippedContentOn({ mapKinds: ["space"], kindContent: ["space"] }, "world")).toBe(false); + expect(shippedContentOn({ mapKinds: ["world"], kindContent: ["world"] }, "world")).toBe(true); + expect(resolveKindContent(null, ["world"])).toBeNull(); + expect(resolveKindContent({}, ["world"])).toBeNull(); + // A fresh install's first save keeps it undecided across a restart. + expect(resolveKindContent({ featureLevel: "simple", kindContent: null }, ["world"])).toBeNull(); + expect(resolveKindContent({ maps: [] }, ["world", "space"])).toEqual(["world", "space"]); + expect(resolveKindContent({ kindContent: ["space"] }, ["world"])).toEqual(["space"]); + }); + + it("every shipped biome declares its map type (World)", () => { + for (const b of BIOME_PRESETS) expect({ id: b.id, kind: b.kind }).toEqual({ id: b.id, kind: "world" }); + }); +}); + +describe("Space - Planet palette", () => { + const preset = getPreset(SPACE_PLANET_PALETTE_NAME)!; + + it("is a space preset made of typed land terrains", () => { + expect(preset.kind).toBe("space"); + expect(isSpacePalette(preset.terrains)).toBe(false); + expect(paletteKind(presetToPalette(preset))).toBe("space"); + for (const t of preset.terrains) expect({ t: t.name, typed: isTerrainType(t.type) }).toEqual({ t: t.name, typed: true }); + }); + + it("parses from its note, map-kind included", () => { + const note = buildPaletteNote(preset.terrains, undefined, "space"); + expect(parsePaletteNote(note)).toEqual(preset.terrains); + expect(readPaletteKind(note)).toBe("space"); + expect(readPaletteKind(setPaletteKind(note, undefined))).toBeUndefined(); + expect(readPaletteKind(setPaletteKind("---\nhexmaker-palette: 1\n---\nx", "world"))).toBe("world"); + expect(readPaletteKind("---\nmap-kind: fantasy\n---\n")).toBeUndefined(); + }); + + it("uses only bundled icons", () => { + for (const t of preset.terrains) if (t.icon) expect({ icon: t.icon, ok: BUNDLED_ICONS.has(t.icon) }).toEqual({ icon: t.icon, ok: true }); + }); + + it("drives the Planet surface generator (every climate)", () => { + expect(planetSurfaceFits(preset.terrains)).toBe(true); + const r = planetRoles(preset.terrains)!; + expect([r.sea, r.plains, r.desert, r.badlands, r.snow, r.volcano]).toEqual(["ocean", "plains", "dunes", "regolith", "ice", "lava field"]); + const grid = { cols: 20, rows: 14, offset: { x: 0, y: 0 }, stagger: "odd" as const, orientation: "flat" as const }; + for (const climate of ["temperate", "lush", "arid", "frozen", "volcanic"]) { + const out = planetSurface(preset.terrains, grid, 3, { water: "30", climate }); + expect(out.cells.size).toBe(280); + } + }); + + it("planets open on it (system submap defaults and the shipped world types), with base terrains it has", () => { + const names = new Set(preset.terrains.map((t) => t.name)); + const system = getPreset("Space - System")!; + for (const [terrain, d] of Object.entries(system.submapDefaults ?? {})) { + if (d.generator !== "procedural:planet-surface") continue; + expect({ terrain, palette: d.palette, base: names.has(d.baseTerrain!) }).toEqual({ terrain, palette: SPACE_PLANET_PALETTE_NAME, base: true }); + } + const surfaces = DEFAULT_WORLD_TYPE_ROWS.filter((r) => r.generator?.id === "procedural:planet-surface"); + expect(surfaces.length).toBeGreaterThan(0); + for (const r of surfaces) expect({ world: r.world, palette: r.palette, base: names.has(r.baseTerrain!) }).toEqual({ world: r.world, palette: SPACE_PLANET_PALETTE_NAME, base: true }); + }); + + it("gets terrain tables in a space-only setup; Palette for new maps skips it for Space - Sector", () => { + const pals = SPACE_PRESETS.map((n) => presetToPalette(getPreset(n)!)); + const tables = terrainsForTables(pals, ["space"]).map((t) => t.name); + expect(tables).toContain("regolith"); + expect(defaultPaletteFor({ mapKinds: ["space"], terrainPalettes: pals, defaultPalette: "" })).toBe("Space - Sector"); + expect(defaultPaletteFor({ mapKinds: ["world"], terrainPalettes: [...pals, { name: "Limited", kind: "world", terrains: LIMITED_TERRAIN_PALETTE }] })).toBe("Limited"); + expect(planetSurfaceFits(DEFAULT_TERRAIN_PALETTE)).toBe(true); + }); +}); + +describe("pickers list what they're for (SP3)", () => { + const settings = { worldFolder: "world", townsFolder: "", dungeonsFolder: "places/dungeons", tablesFolder: "", workflowsFolder: "" }; + + it("a blank folder setting is its usual place under the world folder, never the vault", () => { + expect(contentFolder(settings, "townsFolder")).toBe("world/towns"); + expect(contentFolder(settings, "dungeonsFolder")).toBe("places/dungeons"); + expect(contentFolder(settings, "workflowsFolder")).toBe("world/workflows"); + expect(contentFolder({}, "tablesFolder")).toBe("world/tables"); + }); + + it("the token Note picker lists characters, ships, factions and places only", () => { + const include = pickerFolders(settings, "token"); + const ok = (p: string) => isTokenNoteCandidate(p, p.split("/").pop()!.replace(/\.md$/, ""), include, []); + expect(ok("world/tokens/Far Horizon.md")).toBe(true); + expect(ok("world/towns/Ashby.md")).toBe(true); + expect(ok("places/dungeons/Barrow.md")).toBe(true); + expect(ok("world/factions/Guild.md")).toBe(true); + expect(ok("world/regions/Marches.md")).toBe(true); + for (const internal of ["world/biomes/Alpine.md", "world/biome-pools/All biomes.md", "world/palettes/Expanded.md", "world/world-types/Default space.md", "world/generators/forest.md", "world/tables/terrain/encounters/ocean.md", "world/hexes/default/1_1.md", "world/templates/hex.md", "world/workflows/npc.md"]) { + expect({ internal, listed: ok(internal) }).toEqual({ internal, listed: false }); + } + }); + + it("table and workflow pickers list their own folders", () => { + expect(pickerFolders(settings, "table")).toEqual(["world/tables"]); + expect(pickerFolders(settings, "workflow")).toEqual(["world/workflows"]); + expect(inAnyFolder("world/tables/weather.md", pickerFolders(settings, "table"))).toBe(true); + expect(inAnyFolder("world/biomes/Alpine.md", pickerFolders(settings, "table"))).toBe(false); + }); + + it("plugin data notes are never offered by any note picker", () => { + const rules = templateNoteRules({ worldFolder: "world" }, [], ["world/palettes", "world/biomes", "world/biome-pools", "world/world-types", "world/generators"]); + expect(isLinkableNotePath("world/biomes/Alpine.md", "Alpine", rules)).toBe(false); + expect(isLinkableNotePath("world/palettes/Expanded.md", "Expanded", rules)).toBe(false); + expect(isLinkableNotePath("world/towns/Ashby.md", "Ashby", rules)).toBe(true); + }); + + it("Import… offers text it can read, not images or PDFs", () => { + expect(IMPORT_LIST_EXTENSIONS).toEqual(expect.arrayContaining(["md", "txt", "csv"])); + for (const ext of ["png", "jpg", "pdf", "svg"]) expect(IMPORT_LIST_EXTENSIONS).not.toContain(ext); + }); +}); diff --git a/tests/submapDefaults.test.ts b/tests/submapDefaults.test.ts index 6304a16f..4a8090a5 100644 --- a/tests/submapDefaults.test.ts +++ b/tests/submapDefaults.test.ts @@ -12,11 +12,12 @@ import { PALETTE_PRESETS, SPACE_SECTOR_PALETTE_NAME, SPACE_SYSTEM_PALETTE_NAME, + SPACE_PLANET_PALETTE_NAME, SPACE_SYSTEM_TERRAINS, SPACE_SECTOR_TERRAINS, presetToPalette, } from "../src/palettes/presets"; -import { DEFAULT_TERRAIN_PALETTE, EXPANDED_PALETTE_NAME, LIMITED_TERRAIN_PALETTE } from "../src/constants"; +import { DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; import { enabledKinds, isIconHiddenByKind, isKindEnabled } from "../src/mapKinds"; import { planetSurface, planetSurfaceFits, planetRoles } from "../src/worldgen/procedural/planetSurface"; import type { SubmapDefault } from "../src/types"; @@ -81,7 +82,7 @@ describe("preset submap defaults", () => { it("system planets open as planet-surface maps tuned per type", () => { expect(system.submapDefaults!["ocean planet"]).toMatchObject({ - palette: EXPANDED_PALETTE_NAME, generator: "procedural:planet-surface", options: { water: "85" }, + palette: SPACE_PLANET_PALETTE_NAME, generator: "procedural:planet-surface", options: { water: "85" }, }); expect(system.submapDefaults!["ice planet"].options!.climate).toBe("frozen"); expect(system.submapDefaults!["desert planet"].options!.climate).toBe("arid"); diff --git a/tests/terrainTypes.test.ts b/tests/terrainTypes.test.ts index 7ef3b117..0243e3ca 100644 --- a/tests/terrainTypes.test.ts +++ b/tests/terrainTypes.test.ts @@ -23,7 +23,10 @@ describe("terrain type vocabulary", () => { for (const p of PALETTE_PRESETS) { for (const t of p.terrains) { expect({ palette: p.name, terrain: t.name, ok: isTerrainType(t.type) }).toMatchObject({ ok: true }); - expect({ palette: p.name, terrain: t.name, kind: terrainTypeInfo(t.type)?.kind }).toMatchObject({ kind: p.kind }); + // A space preset may use land and water types (Space - Planet's surfaces). + const info = terrainTypeInfo(t.type); + const fits = info?.kind === p.kind || (p.kind === "space" && (info?.group === "land" || info?.group === "water")); + expect({ palette: p.name, terrain: t.name, fits }).toMatchObject({ fits: true }); } } }); diff --git a/tests/worldTypes.test.ts b/tests/worldTypes.test.ts index 2ce1a693..abbea3ed 100644 --- a/tests/worldTypes.test.ts +++ b/tests/worldTypes.test.ts @@ -64,15 +64,16 @@ function oldWeightedPick(rand: () => number, names: string[], weights: Record Object.fromEntries(bodies.filter((b) => OLD_BODY_NAMES.includes(b)).map((b) => [b, OLD_ZONE_WEIGHTS[zone][b] ?? 0.5])); const ofTypes = (terrains: TerrainColor[], types: string[]) => terrains.filter((t) => types.includes(t.type ?? "")).map((t) => t.name); -const OLD_SURFACE = { palette: "Expanded", cols: 20, rows: 14, generator: "procedural:planet-surface" }; +// Planet surfaces open on Space - Planet since SP3 (were Expanded, "desert" bases). +const OLD_SURFACE = { palette: "Space - Planet", cols: 20, rows: 14, generator: "procedural:planet-surface" }; const OLD_SYSTEM_DEFAULTS: Record = { "terrestrial planet": { ...OLD_SURFACE, options: { water: "65", climate: "temperate", relief: "normal" }, baseTerrain: "ocean" }, "ocean planet": { ...OLD_SURFACE, options: { water: "85", climate: "lush", relief: "normal" }, baseTerrain: "ocean" }, - "desert planet": { ...OLD_SURFACE, options: { water: "10", climate: "arid", relief: "normal" }, baseTerrain: "desert" }, + "desert planet": { ...OLD_SURFACE, options: { water: "10", climate: "arid", relief: "normal" }, baseTerrain: "dunes" }, "ice planet": { ...OLD_SURFACE, options: { water: "30", climate: "frozen", relief: "normal" }, baseTerrain: "ocean" }, - "rocky planet": { ...OLD_SURFACE, options: { water: "10", climate: "arid", relief: "rugged" }, baseTerrain: "desert" }, - "molten planet": { ...OLD_SURFACE, options: { water: "10", climate: "volcanic", relief: "rugged" }, baseTerrain: "desert" }, - moon: { ...OLD_SURFACE, options: { water: "10", climate: "frozen", relief: "rugged" }, baseTerrain: "desert" }, + "rocky planet": { ...OLD_SURFACE, options: { water: "10", climate: "arid", relief: "rugged" }, baseTerrain: "regolith" }, + "molten planet": { ...OLD_SURFACE, options: { water: "10", climate: "volcanic", relief: "rugged" }, baseTerrain: "regolith" }, + moon: { ...OLD_SURFACE, options: { water: "10", climate: "frozen", relief: "rugged" }, baseTerrain: "regolith" }, }; const OLD_SECTOR_DEFAULT = { palette: "Space - System", cols: 13, rows: 13, generator: "procedural:orbits", baseTerrain: "void" }; @@ -127,7 +128,7 @@ describe("Default space reproduces the old built-in odds", () => { expect(back.problems).toEqual([]); expect(back.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); expect(text).toContain("hexmaker-world-types: 2"); - expect(text).toContain("| ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush, relief=normal | Expanded | ocean | |"); + expect(text).toContain("| ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush, relief=normal | Space - Planet | ocean | |"); }); }); From 9f3d30e5e5f658d3ab9ed635c35e103a3b8dc658 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 11:05:04 -0400 Subject: [PATCH 304/558] docs: map-type content, Space - Planet, focused note pickers (SP3) Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f69a4151..8d8afe82 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Toggle the GM layer from the overlay panel to switch between player-facing and G ## Getting started -After enabling the plugin, a **setup wizard** opens. It asks what you'll map (a fantasy world, space, or both), where your world folder lives, and makes your first map. That last step can **generate the terrain** for you (Overland for a world map, Star scatter for a star sector), with a preview and a re-roll button, or start blank for painting by hand. It also creates the terrain description and encounter tables. That's all you need to start. +After enabling the plugin, a **setup wizard** opens. It asks what you'll map (a fantasy world, space, or both), where your world folder lives, and makes your first map. What it installs follows that choice: a world setup gets the Expanded and Limited palettes and the biome notes; a space-only setup gets the three space palettes (Sector, System, Planet) and nothing fantasy, and **Palette for new maps** starts on Space - Sector; both gets both. Turning a map type on later in **Settings → Map types** installs its content then (once: anything you delete stays deleted). That last step can **generate the terrain** for you (Overland for a world map, Star scatter for a star sector), with a preview and a re-roll button, or start blank for painting by hand. It also creates the terrain description and encounter tables. That's all you need to start. To set things up by hand instead (or later): @@ -275,7 +275,7 @@ Place movable tokens on the map — useful for tracking party position, NPCs, or **Creating a token:** 1. Click the **Token** button in the drawing tools panel. -2. Fill in the token form: choose a note (existing or new), icon, shape (circle / square / hexagon), fill colour, and border colour. +2. Fill in the token form: choose a note (existing or new), icon, shape (circle / square / hexagon), fill colour, and border colour. The note list holds what a token stands for: notes in the tokens folder (`{world folder}/tokens`, where new ones go) and the towns, dungeons, features, quests, factions and regions folders. Tables, biomes, palettes, world types, generators and hex notes are never listed, here or in any other note picker; table pickers list the tables folder, the workflow picker the workflows folder, and a blank folder setting means its usual place under the world folder, not the whole vault. 3. Click **Next: place on map**, then click any hex to place the token there. **Interacting with tokens:** @@ -361,7 +361,7 @@ Open **Settings → Hexmap World Creator** to configure: | **World types folder** | Folder holding the world types tables used by the space generators (default `{world folder}/world-types`). | | **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | | **Add default palettes** | Shown when Expanded or Limited isn't in the list: puts them back. Palettes you delete (in settings, or by deleting a palette note the plugin wrote) stay deleted, with a copy in the plugin folder's `backups/`; an empty palette list stays empty until you add one. A palette whose note isn't there yet for another reason (an upgrade, a new palettes folder, a note sync hasn't delivered) is kept: its note is written, or the palette comes back when the note arrives. | -| **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types) and *Space - System* (stars, planets, belts, stations) for sci-fi games such as Traveller. New-map palette menus list uninstalled presets too, and show the picked palette's terrains as a row of colour swatches (names on hover) under the menu. | +| **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types), *Space - System* (stars, planets, belts, stations) and *Space - Planet* (a planet's surface: seas, plains, regolith, dunes, ice, craters, lava fields, toxic marsh, crystal fields, ruins, colonies; typed for the Planet surface generator, and what planets and moons open on) for sci-fi games such as Traveller. A palette note's `map-kind:` line (`world` or `space`) says which map type it belongs to; without it, a palette with space terrain types counts as space. New-map palette menus list uninstalled presets too, and show the picked palette's terrains as a row of colour swatches (names on hover) under the menu. | | **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | --- From 0d2e70230b42eb7dceab22bfb2dd35b40bd9e569 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 11:24:38 -0400 Subject: [PATCH 305/558] feat(tables): typed rows, attributes and a nested-roll resolver (tables everywhere phases 0-1) Phase 0, all additive (every old table reads, rolls and rewrites the same; tests/fixtures/tables/golden.json was made by the parser before this change): - frontmatter rows: (text/note/table/generator/terrain/biome/any), terrain-type:, shown-as:, and linked-folder: read like linkedFolder: - every extra column is a row attribute (RandomTable.rowInfo, parallel to the entries so entries read exactly as before), shown read-only in the Tables view - shared columns Roll (now / on arrival), Shown as, Once (per world / per map) and When (zone, ring, star, type, terrain, temperature); unreadable values are reported, a bad When never fires - decimal and percentage weights (T10), also in the table editor - tables picked by heading: parseRandomTableWithReport(content, { heading }) Phase 1, resolver only (pickers are another branch's work): - random-tables/resolve.ts: resolveRoll / resolveOdds over a TableLookup, nested rolls, seeded, loop guard (visited set + depth 5, shown as a loop), When / Once / terrain-only rows left out and renormalised, (nothing) rows, on-arrival deferral, findRow, cell kind from the link target (T3) - tableFitsWant is the seam for pickers filtering by row type Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 8 +- src/random-tables/RandomTableEditorModal.ts | 9 +- src/random-tables/RandomTableView.ts | 8 +- src/random-tables/randomTable.ts | 259 ++- src/random-tables/resolve.ts | 453 +++++ src/random-tables/tableConditions.ts | 145 ++ tests/fixtures/tables/broken-ranges.md | 8 + tests/fixtures/tables/d100-zeros.md | 8 + tests/fixtures/tables/d20-ranges.md | 12 + tests/fixtures/tables/d66.md | 8 + tests/fixtures/tables/extra-columns.md | 11 + tests/fixtures/tables/golden.json | 1534 +++++++++++++++++ tests/fixtures/tables/golden.ts | 52 + tests/fixtures/tables/linked-folder-quoted.md | 8 + tests/fixtures/tables/no-table.md | 4 + tests/fixtures/tables/old-no-frontmatter.md | 5 + tests/fixtures/tables/old-result-weight.md | 9 + tests/fixtures/tables/roller-block.md | 14 + tests/fixtures/tables/too-many-rows.md | 10 + tests/fixtures/tables/two-tables.md | 10 + tests/fixtures/tables/unknown-header.md | 6 + tests/tableAttributes.test.ts | 149 ++ tests/tableGolden.test.ts | 28 + tests/tableHeadingRef.test.ts | 81 + tests/tableMigration.test.ts | 2 +- tests/tableResolve.test.ts | 188 ++ tests/tableTypedRows.test.ts | 88 + 28 files changed, 3085 insertions(+), 36 deletions(-) create mode 100644 src/random-tables/resolve.ts create mode 100644 src/random-tables/tableConditions.ts create mode 100644 tests/fixtures/tables/broken-ranges.md create mode 100644 tests/fixtures/tables/d100-zeros.md create mode 100644 tests/fixtures/tables/d20-ranges.md create mode 100644 tests/fixtures/tables/d66.md create mode 100644 tests/fixtures/tables/extra-columns.md create mode 100644 tests/fixtures/tables/golden.json create mode 100644 tests/fixtures/tables/golden.ts create mode 100644 tests/fixtures/tables/linked-folder-quoted.md create mode 100644 tests/fixtures/tables/no-table.md create mode 100644 tests/fixtures/tables/old-no-frontmatter.md create mode 100644 tests/fixtures/tables/old-result-weight.md create mode 100644 tests/fixtures/tables/roller-block.md create mode 100644 tests/fixtures/tables/too-many-rows.md create mode 100644 tests/fixtures/tables/two-tables.md create mode 100644 tests/fixtures/tables/unknown-header.md create mode 100644 tests/tableAttributes.test.ts create mode 100644 tests/tableGolden.test.ts create mode 100644 tests/tableHeadingRef.test.ts create mode 100644 tests/tableResolve.test.ts create mode 100644 tests/tableTypedRows.test.ts diff --git a/package.json b/package.json index bb3f367f..ee3da522 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index cd57e651..52e15c79 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -618,10 +618,8 @@ export default class HexmakerPlugin extends Plugin { ); for (const tableFile of tableFiles) { - const lf: unknown = - this.app.metadataCache.getFileCache(tableFile)?.frontmatter?.[ - "linkedFolder" - ]; + const fm = this.app.metadataCache.getFileCache(tableFile)?.frontmatter; + const lf: unknown = fm?.["linkedFolder"] ?? fm?.["linked-folder"]; if (!lf || typeof lf !== "string") continue; const wikiLinkMatch = /^\[\[(.+?)\]\]$/.exec(lf); const lfClean = wikiLinkMatch ? wikiLinkMatch[1].trim() : lf; @@ -631,7 +629,7 @@ export default class HexmakerPlugin extends Plugin { const updatedLf = newFolder + lfNorm.slice(oldFolder.length); await this.app.vault.process(tableFile, (content) => content.replace( - /^(linkedFolder:\s*).*$/m, + /^((?:linkedFolder|linked-folder):\s*).*$/m, `$1"[[${updatedLf}]]"`, ), ); diff --git a/src/random-tables/RandomTableEditorModal.ts b/src/random-tables/RandomTableEditorModal.ts index 399a928a..08a92842 100644 --- a/src/random-tables/RandomTableEditorModal.ts +++ b/src/random-tables/RandomTableEditorModal.ts @@ -7,6 +7,7 @@ import { rangeCellTexts, resolveTable, dieLabel, + readTableWeight, type RandomTableEntry, type TableWrite, } from "./randomTable"; @@ -308,6 +309,7 @@ export class RandomTableEditorModal extends HexmakerModal { }); weightInput.value = String(entry.weight); weightInput.min = "0"; + weightInput.step = "any"; weightInput.title = "Weight (0 = never rolled)"; weightInput.addEventListener("input", () => { entries[i].weight = readWeight(weightInput.value); @@ -383,6 +385,7 @@ export class RandomTableEditorModal extends HexmakerModal { }); newWeight.value = "1"; newWeight.min = "0"; + newWeight.step = "any"; const addBtn = addRow.createEl("button", { text: "Add", @@ -800,8 +803,8 @@ export class RandomTableEditorModal extends HexmakerModal { } } -/** A typed weight: a whole number ≥ 0; anything else counts as 1. */ +/** A typed weight: a number ≥ 0 (decimals too, T10); anything else counts as 1. */ function readWeight(value: string): number { - const n = parseInt(value, 10); - return Number.isFinite(n) && n >= 0 ? n : 1; + const n = readTableWeight(value); + return Number.isFinite(n) ? n : 1; } diff --git a/src/random-tables/RandomTableView.ts b/src/random-tables/RandomTableView.ts index 3dc984c2..4d6723b2 100644 --- a/src/random-tables/RandomTableView.ts +++ b/src/random-tables/RandomTableView.ts @@ -24,6 +24,7 @@ import { rollLabel, resolveTable, rowOdds, + rowInfoOf, dieLabel, dieFaces, setDiceInFrontmatter, @@ -665,7 +666,7 @@ export class RandomTableView extends ItemView { for (const file of files) { const fm: Frontmatter | undefined = this.app.metadataCache.getFileCache(file)?.frontmatter; - const lf = fm?.["linkedFolder"]; + const lf: unknown = fm?.["linkedFolder"] ?? fm?.["linked-folder"]; if (lf && typeof lf === "string") { const wikiLinkMatch = /^\[\[(.+?)\]\]$/.exec(lf); const lfClean = wikiLinkMatch ? wikiLinkMatch[1].trim() : lf; @@ -1640,6 +1641,9 @@ export class RandomTableView extends ItemView { if (ranges) headerRow.createEl("th", { text: dieLabel(table.dice) }); headerRow.createEl("th", { text: "Result" }); headerRow.createEl("th", { text: "Odds" }); + // Row attributes and shared columns (Roll, Shown as, Once, When), read-only. + const attrCols = [...new Set((table.rowInfo ?? []).flatMap((r) => Object.keys(r.attrs ?? {})))]; + for (const c of attrCols) headerRow.createEl("th", { text: c, cls: "duckmage-rt-attr-col" }); headerRow.createEl("th", { cls: "duckmage-rt-copy-col-header" }); const tbody = tableEl.createEl("tbody"); @@ -1683,6 +1687,8 @@ export class RandomTableView extends ItemView { } tr.createEl("td", { text: odds[i], cls: "duckmage-rt-odds-cell" }); + const attrs = rowInfoOf(table, i).attrs ?? {}; + for (const c of attrCols) tr.createEl("td", { text: attrs[c] ?? "", cls: "duckmage-rt-attr-cell" }); const copyTd = tr.createEl("td", { cls: "duckmage-rt-entry-copy-cell", }); diff --git a/src/random-tables/randomTable.ts b/src/random-tables/randomTable.ts index ccb83856..75542e02 100644 --- a/src/random-tables/randomTable.ts +++ b/src/random-tables/randomTable.ts @@ -18,9 +18,35 @@ * rolls by weight. * - Older `| Result | Weight |` tables still parse exactly as before. * + * Extensions (plan-tables-everywhere §2.2), all optional and additive; a + * table without them reads exactly as before: + * - frontmatter `rows:` what the rows are (text, note, table, generator, + * terrain, biome or any; default any). A constraint for checks and + * pickers, never a parser switch. Each cell's own kind is worked out + * from what it links to (resolve.ts). `terrain-type:` narrows + * `rows: terrain` (`star`, or `world, gas-giant`). `shown-as:` is the + * default for the Shown as column. `linked-folder:` is read like + * `linkedFolder:`. + * - weights may be decimals (`3.5`, `0.5`) or percentages (`50%` = 0.5). + * - every column besides the roll, Result and Weight columns is a row + * attribute, returned with the roll ({column → cell}). Four of them mean + * the same everywhere: Roll (`now` or `on arrival`), Shown as, Once + * (`per world` or `per map`) and When (tableConditions.ts). + * - `parseRandomTableWithReport(content, { heading })` reads the table + * under a heading (a link like `[[Tundra#Mix]]`). + * * Pure: no Obsidian imports. */ +import { parseWhen, unreadableConditions, type TableCondition } from "./tableConditions"; + +/** What a table's rows are (`rows:` in the frontmatter). */ +export type RowType = "text" | "note" | "table" | "generator" | "terrain" | "biome" | "any"; +export const ROW_TYPES: readonly RowType[] = ["text", "note", "table", "generator", "terrain", "biome", "any"]; + +/** The four column names with a shared meaning in every table. */ +export const SHARED_COLUMNS = ["Roll", "Shown as", "Once", "When"] as const; + export interface RandomTableEntry { result: string; weight: number; @@ -29,12 +55,42 @@ export interface RandomTableEntry { range?: string; } +/** + * What a row says besides its result, weight and range (parallel to the + * table's entries, so an entry reads exactly as it always did). + */ +export interface RowInfo { + /** Every other column's non-blank cell, by header as written (shared columns included). */ + attrs?: Record; + /** Roll column: roll it through now (default) or leave it for arrival. */ + roll?: "now" | "on arrival"; + /** Shown as column: what an on-arrival row shows until it is rolled. */ + shownAs?: string; + /** Once column: the row fires once per world or once per map. */ + once?: "world" | "map"; + /** When column: the row only fits these contexts. */ + when?: TableCondition[]; +} + export interface RandomTable { /** Die size: 0 = no die (show % only), 66 = d66. */ dice: number; entries: RandomTableEntry[]; linkedFolder?: string; description?: string; // user-authored blurb shown above the table + /** `rows:` (absent = any). */ + rows?: RowType; + /** `terrain-type:` (lower case). */ + terrainTypes?: string[]; + /** `shown-as:`: the default for the Shown as column. */ + shownAs?: string; + /** Per entry (same order): its other columns. Absent when no row has any. */ + rowInfo?: RowInfo[]; +} + +/** An entry's other columns (an empty object when it has none). */ +export function rowInfoOf(table: RandomTable, index: number): RowInfo { + return table.rowInfo?.[index] ?? {}; } export type TableIssueCode = @@ -49,7 +105,12 @@ export type TableIssueCode = | "range-gap" | "range-weight-mismatch" | "too-many-rows" - | "legacy-roller-link"; + | "legacy-roller-link" + | "rows-unknown" + | "roll-unknown" + | "once-unknown" + | "when-unknown" + | "heading-missing"; export interface TableIssue { code: TableIssueCode; @@ -73,6 +134,8 @@ export interface TableBlock { header: string[]; /** Column indexes; -1 when the column is absent. */ cols: { range: number; result: number; weight: number }; + /** Every other column (row attributes, shared columns included). */ + extra: number[]; /** Line indexes (into lines) of the data rows. */ rows: number[]; /** For each entry, the index into rows of the row it came from. */ @@ -238,7 +301,10 @@ function blockFromRun(run: TableRun, content: string): TableBlock { const lines = run.lines.slice(headerIdx); const header = lines.length ? rowCells(lines[0]) : []; const keys = header.map(headerKey); - let range = keys.findIndex((k) => RANGE_HEADER.test(k)); + // "Roll" is both an old name for the die column and the shared Roll + // column (now / on arrival): with a die column beside it, it's the latter. + const dieCol = keys.findIndex((k) => RANGE_HEADER.test(k) && k !== "roll"); + let range = dieCol >= 0 ? dieCol : keys.findIndex((k) => RANGE_HEADER.test(k)); let result = keys.findIndex((k) => RESULT_HEADER.test(k)); let weight = keys.findIndex((k) => WEIGHT_HEADER.test(k)); const recognized = range >= 0 || result >= 0 || weight >= 0; @@ -259,15 +325,67 @@ function blockFromRun(run: TableRun, content: string): TableBlock { } rows.push(i); } + // A lone "Roll" column whose cells all say now / on arrival is the + // shared Roll column, not the die column. + if (range >= 0 && dieCol < 0) { + const cells = rows.map((i) => (rowCells(lines[i])[range] ?? "").trim().toLowerCase()).filter((c) => c !== ""); + if (cells.length && cells.every((c) => c in ROLL_WORDS)) range = -1; + } // Offsets: start at the header line. let start = run.start; for (let i = 0; i < headerIdx; i++) start = content.indexOf("\n", start) + 1; - return { start, end: run.end, eol, lines, separator, header, cols: { range, result, weight }, rows, entryRows: [], recognized }; + const extra = header.map((_, i) => i).filter((i) => i !== range && i !== result && i !== weight && header[i].trim() !== ""); + return { start, end: run.end, eol, lines, separator, header, cols: { range, result, weight }, extra, rows, entryRows: [], recognized }; +} + +const HEADING = /^(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/; + +/** + * The span of the section under a heading (any level, any case): from the + * line after it to the next heading of the same or a higher level. Null + * when the note has no such heading. Headings in code fences don't count. + */ +export function headingSection(content: string, heading: string): { start: number; end: number } | null { + const want = heading.trim().toLowerCase(); + let pos = frontmatterOf(content)?.length ?? 0; + let fence: string | null = null; + let found: { level: number; start: number } | null = null; + while (pos <= content.length) { + const nl = content.indexOf("\n", pos); + const lineEnd = nl < 0 ? content.length : nl; + const line = content.slice(pos, lineEnd).replace(/\r$/, ""); + const t = line.trim(); + const f = /^(`{3,}|~{3,})/.exec(t); + if (fence) { + if (f && f[1][0] === fence[0]) fence = null; + } else if (f) { + fence = f[1]; + } else { + const h = HEADING.exec(t); + if (h) { + const level = h[1].length; + if (found && level <= found.level) return { start: found.start, end: pos }; + if (!found && h[2].trim().toLowerCase() === want) found = { level, start: nl < 0 ? content.length : nl + 1 }; + } + } + if (nl < 0) break; + pos = nl + 1; + } + return found ? { start: found.start, end: content.length } : null; } -/** The roll table: the first table naming a result, roll or weight column, else the first table. */ -export function locateRollTable(content: string): TableBlock | null { - const runs = findTableRuns(content); +/** + * The roll table: the first table naming a result, roll or weight column, + * else the first table. With a heading, only tables in that heading's + * section count (null when there's no such heading or no table under it). + */ +export function locateRollTable(content: string, heading?: string): TableBlock | null { + let runs = findTableRuns(content); + if (heading !== undefined && heading.trim()) { + const section = headingSection(content, heading); + if (!section) return null; + runs = runs.filter((r) => r.start >= section.start && r.start < section.end); + } if (!runs.length) return null; const blocks = runs.map((r) => blockFromRun(r, content)); const pick = @@ -283,40 +401,86 @@ const LEGACY_ROLLER_LINK = /\[[^\]\n]*\]\(obsidian:\/\/duckmage-roll\?[^)\n]*\)/ const ROLLER_BLOCK = /```duckmage-roller[\s\S]*?```/; /** Parse a random-table note into a RandomTable (see parseRandomTableWithReport). */ -export function parseRandomTable(content: string): RandomTable { - return parseRandomTableWithReport(content).table; +export function parseRandomTable(content: string, opts: ParseOptions = {}): RandomTable { + return parseRandomTableWithReport(content, opts).table; +} + +export interface ParseOptions { + /** Read the table under this heading (a `[[Note#Heading]]` link) instead of the note's roll table. */ + heading?: string; +} + +/** A frontmatter value with outer quotes taken off. */ +function fmValue(body: string, key: string): string | undefined { + const m = new RegExp(`^${key}:[ \\t]*(.*?)[ \\t]*\\r?$`, "m").exec(body); + if (!m) return undefined; + const raw = m[1].trim(); + return /^"(.*)"$/.exec(raw)?.[1] ?? /^'(.*)'$/.exec(raw)?.[1] ?? raw; +} + +/** "3", "3.5", ".5", "50%" → a weight ≥ 0; NaN when unreadable. */ +export function readTableWeight(raw: string): number { + const t = raw.trim(); + if (!/^(?:\d+(?:\.\d*)?|\.\d+)\s*%?$/.test(t)) return NaN; + const n = Number(t.replace(/\s*%$/, "")); + return t.endsWith("%") ? n / 100 : n; } +const ROLL_WORDS: Record = { + now: "now", "": "now", generate: "now", "on generate": "now", + "on arrival": "on arrival", arrival: "on arrival", "on visit": "on arrival", visit: "on arrival", later: "on arrival", +}; +const ONCE_WORDS: Record = { + "": undefined, no: undefined, never: undefined, + "per world": "world", world: "world", "once per world": "world", yes: "world", + "per map": "map", map: "map", "once per map": "map", +}; + /** * Parse a random-table note and report anything that couldn't be read. * Nothing the human typed is dropped: an unreadable weight counts as 1 and * its text is kept in the note; unreadable ranges make the table roll by * weight. See TableIssueCode for what's reported. */ -export function parseRandomTableWithReport(content: string): TableReport { +export function parseRandomTableWithReport(content: string, opts: ParseOptions = {}): TableReport { const issues: TableIssue[] = []; let dice = 0; let linkedFolder: string | undefined; + let rows: RowType | undefined; + let terrainTypes: string[] | undefined; + let shownAs: string | undefined; const fm = frontmatterOf(content); let fmDice = 0; if (fm) { const diceMatch = /^dice:[ \t]*(.*?)[ \t]*$/m.exec(fm.body); if (diceMatch) fmDice = parseDie(diceMatch[1]); - const lfMatch = /^linkedFolder:[ \t]*(.+?)[ \t]*\r?$/m.exec(fm.body); - if (lfMatch) { - const raw = lfMatch[1].trim(); - // Strip outer YAML quotes if present ("[[path]]" → [[path]]) - const unquoted = /^"(.*)"$/.exec(raw)?.[1] ?? raw; - const wikiLinkMatch = /^\[\[(.+?)\]\]$/.exec(unquoted); - linkedFolder = wikiLinkMatch ? wikiLinkMatch[1].trim() : unquoted; + const lf = fmValue(fm.body, "linkedFolder") ?? fmValue(fm.body, "linked-folder"); + if (lf !== undefined && lf !== "") { + const wikiLinkMatch = /^\[\[(.+?)\]\]$/.exec(lf); + linkedFolder = wikiLinkMatch ? wikiLinkMatch[1].trim() : lf; + } + const rowsRaw = fmValue(fm.body, "rows"); + if (rowsRaw !== undefined && rowsRaw !== "") { + const r = rowsRaw.toLowerCase().replace(/s$/, "") as RowType; + if (ROW_TYPES.includes(r)) { + if (r !== "any") rows = r; + } else { + issues.push({ code: "rows-unknown", message: `"rows: ${rowsRaw}" isn't one of ${ROW_TYPES.join(", ")}; reading the rows as any.` }); + } } + const tt = fmValue(fm.body, "terrain-type"); + if (tt) terrainTypes = tt.replace(/^\[|\]$/g, "").split(/\s*,\s*/).map((s) => s.trim().toLowerCase()).filter((s) => s !== ""); + const sa = fmValue(fm.body, "shown-as"); + if (sa) shownAs = sa; } dice = fmDice; - const block = locateRollTable(content); + const heading = opts.heading?.trim() ? opts.heading.trim() : undefined; + const block = locateRollTable(content, heading); - // Description: text between frontmatter and the table, minus the roller. - const afterFmStart = fm ? fm.length : 0; + // Description: text between frontmatter (or the heading) and the table, minus the roller. + const section = heading ? headingSection(content, heading) : null; + const afterFmStart = section ? section.start : fm ? fm.length : 0; const preambleEnd = block ? block.start : afterFmStart; const preambleText = preambleEnd > afterFmStart ? content.slice(afterFmStart, preambleEnd) : ""; const descriptionRaw = preambleText @@ -329,9 +493,17 @@ export function parseRandomTableWithReport(content: string): TableReport { issues.push({ code: "legacy-roller-link", message: "Has an old \"Open in Duckmage Roller\" link; it can be replaced by the roller block." }); } + const extras = (t: RandomTable): RandomTable => { + if (rows) t.rows = rows; + if (terrainTypes?.length) t.terrainTypes = terrainTypes; + if (shownAs) t.shownAs = shownAs; + return t; + }; + if (!block) { - issues.push({ code: "no-table", message: "No table found." }); - return { table: { dice, entries: [], linkedFolder, description }, issues, block }; + if (heading && !section) issues.push({ code: "heading-missing", message: `No heading "${heading}".` }); + issues.push({ code: "no-table", message: heading ? `No table under "${heading}".` : "No table found." }); + return { table: extras({ dice, entries: [], linkedFolder, description }), issues, block }; } const { cols } = block; @@ -349,6 +521,7 @@ export function parseRandomTableWithReport(content: string): TableReport { } const entries: RandomTableEntry[] = []; + const info: RowInfo[] = []; block.rows.forEach((lineIdx, rowIdx) => { const cells = rowCells(block.lines[lineIdx]); // Strip wiki-link syntax so [[Note Name]] → "Note Name" @@ -362,11 +535,13 @@ export function parseRandomTableWithReport(content: string): TableReport { if (rangeText) entry.range = rangeText; if (cols.weight >= 0) { const w = (cells[cols.weight] ?? "").trim(); - if (/^\d+$/.test(w)) entry.weight = parseInt(w, 10); + const n = w ? readTableWeight(w) : NaN; + if (Number.isFinite(n)) entry.weight = n; else if (w) { - issues.push({ code: "weight-unreadable", row: entries.length + 1, message: `Row ${entries.length + 1} ("${result}"): weight "${w}" isn't a whole number; counting it as 1.` }); + issues.push({ code: "weight-unreadable", row: entries.length + 1, message: `Row ${entries.length + 1} ("${result}"): weight "${w}" isn't a number; counting it as 1.` }); } } + info.push(readExtras(result, block.extra.map((i): [string, string] => [block.header[i].trim(), (cells[i] ?? "").trim()]), entries.length + 1, issues)); entries.push(entry); block.entryRows.push(rowIdx); }); @@ -381,11 +556,47 @@ export function parseRandomTableWithReport(content: string): TableReport { } } - const table: RandomTable = { dice, entries, linkedFolder, description }; + const table: RandomTable = extras({ dice, entries, linkedFolder, description }); + if (info.some((i) => Object.keys(i).length)) table.rowInfo = info; issues.push(...resolveTable(table).issues); return { table, issues, block }; } +/** A row's other columns: attributes, and the shared Roll / Shown as / Once / When. */ +function readExtras(result: string, cells: [string, string][], rowNo: number, issues: TableIssue[]): RowInfo { + const entry: RowInfo = {}; + const name = `Row ${rowNo} ("${result}")`; + for (const [header, cell] of cells) { + if (!cell) continue; + (entry.attrs ??= {})[header] = cell; + const key = headerKey(header); + if (key === "roll") { + const r = ROLL_WORDS[cell.toLowerCase()]; + if (r) { + if (r !== "now") entry.roll = r; + } else { + issues.push({ code: "roll-unknown", row: rowNo, message: `${name}: Roll "${cell}" should be now or on arrival; rolling it now.` }); + } + } else if (key === "shown as") { + entry.shownAs = cell; + } else if (key === "once") { + const k = cell.toLowerCase(); + if (k in ONCE_WORDS) { + const o = ONCE_WORDS[k]; + if (o) entry.once = o; + } else { + issues.push({ code: "once-unknown", row: rowNo, message: `${name}: Once "${cell}" should be per world or per map; the row can repeat.` }); + } + } else if (key === "when") { + const when = parseWhen(cell); + if (when.length) entry.when = when; + const bad = unreadableConditions(when); + if (bad.length) issues.push({ code: "when-unknown", row: rowNo, message: `${name}: can't read When "${bad.join("; ")}", so the row never comes up.` }); + } + } + return entry; +} + // ── Ranges ────────────────────────────────────────────────────────────────── /** diff --git a/src/random-tables/resolve.ts b/src/random-tables/resolve.ts new file mode 100644 index 00000000..551dcec5 --- /dev/null +++ b/src/random-tables/resolve.ts @@ -0,0 +1,453 @@ +/** + * One resolver for every table reference (plan-tables-everywhere §2.3): + * roll a random table, follow a row that links another table (nested + * rolls), and say what came out — text, a note, a terrain, a generator, or + * nothing — with the row attributes and the chain of rows taken. + * + * - Seeded: the same seed (or random stream) gives the same chain. + * - Loop guard: a table already on the chain, or a chain deeper than + * `maxDepth` (5), stops with a `loop` result shown as ⟲. + * - When rows (tableConditions.ts) that don't fit the context, rows already + * used (`isUsed`, for Once) and, with `onlyTerrains`, rows that can't be + * a terrain of the palette are left out, and the rest renormalised: the + * hand-roller's "roll again". + * - `odds()` gives the exact distribution `roll()` samples, so a preview + * shows the real odds. + * + * Tables come from a TableLookup, so this file never touches the vault: + * the caller loads the tables (from notes, or from another format through + * an adapter like space/worldTypesSource.ts). + * + * Picker filtering by row type is not done here: tableFitsWant() is the + * seam the pickers call (plan §2.5). + * + * Pure: no Obsidian imports. + */ + +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; +import { conditionsFit, type ConditionContext } from "./tableConditions"; +import { locateRollTable, parseRandomTable, resolveTable, rollTable, rowInfoOf, type RandomTable, type RandomTableEntry, type RowType } from "./randomTable"; + +/** What a cell turned out to be. */ +export type CellKind = "text" | "note" | "table" | "generator" | "terrain" | "nothing"; + +export interface TableLookup { + /** + * The table a link points at (`Note`, `folder/Note` or `Note#Heading`), + * with a key that names it uniquely (its path; used for the loop guard). + * Undefined when the link isn't a table. + */ + table(link: string): { key: string; table: RandomTable } | undefined; + /** What a link that isn't a table points at. Missing: a note that doesn't exist (yet). */ + kindOf?(link: string): "generator" | "note" | "missing"; +} + +export interface ResolveContext extends ConditionContext { + /** The random stream; else one made from `seed` (else Math.random). */ + rand?: () => number; + seed?: number; + /** The palette's terrain names: plain text naming one is a terrain (the palette's spelling). */ + terrains?: readonly string[]; + /** Only rows that can come out as a terrain (or nothing) count; the rest are left out and reported. */ + onlyTerrains?: boolean; + /** Stop at a row whose Roll is "on arrival" instead of rolling it through. */ + deferArrival?: boolean; + /** Once rows already used (the ledger): those rows are left out. */ + isUsed?: (tableKey: string, index: number, entry: RandomTableEntry) => boolean; + /** Deepest nesting followed (default 5). */ + maxDepth?: number; +} + +export interface ResolveStep { + /** The table's key. */ + table: string; + /** The entry's index in the table. */ + index: number; + result: string; + /** The die face, when the table rolled by its ranges. */ + face?: number; +} + +export interface Resolved { + /** `loop`: stopped by the loop guard; `deferred`: an on-arrival row; `empty`: no row could come up. */ + kind: CellKind | "loop" | "deferred" | "empty"; + /** The text, note link, terrain, generator ref, or (loop / deferred) the table link. */ + value: string; + /** The rows' attributes along the chain (an inner row's cell wins). */ + attrs: Record; + chain: ResolveStep[]; + /** The last Once row on the chain, for the caller's ledger. */ + once?: { table: string; index: number; scope: "world" | "map" }; + /** An on-arrival row: what the hex shows until then. */ + shownAs?: string; +} + +export const DEFAULT_MAX_DEPTH = 5; +export const LOOP_MARK = "⟲"; + +const NOTHING = /^\(?nothing\)?$|^\(none\)$/i; + +/** Whether a cell is a (nothing) row. */ +export const isNothing = (text: string): boolean => NOTHING.test(text.trim()); +const GENERATOR_ID = /^(?:procedural|wfc|builtin):\S/; +const lc = (s: string) => s.trim().toLowerCase(); + +/** The link a row's result stands for (a linked-folder row links a note in that folder), or undefined for plain text. */ +export function entryLink(table: RandomTable, entry: RandomTableEntry): string | undefined { + if (table.linkedFolder) return `${table.linkedFolder}/${entry.result}`; + return entry.isLink ? entry.result : undefined; +} + +/** What one cell is (T3: detected from what it links to). */ +export function cellKind(table: RandomTable, entry: RandomTableEntry, lookup: TableLookup, ctx: Pick = {}): { kind: CellKind; value: string } { + const link = entryLink(table, entry); + if (link !== undefined) { + if (lookup.table(link)) return { kind: "table", value: link }; + const k = lookup.kindOf?.(link) ?? "note"; + return { kind: k === "generator" ? "generator" : "note", value: link }; + } + const text = entry.result.trim(); + if (NOTHING.test(text)) return { kind: "nothing", value: "" }; + if (GENERATOR_ID.test(text)) return { kind: "generator", value: text }; + const terrain = ctx.terrains?.find((t) => lc(t) === lc(text)); + if (terrain !== undefined) return { kind: "terrain", value: terrain }; + if (table.rows === "terrain" && !ctx.terrains) return { kind: "terrain", value: text }; + return { kind: "text", value: text }; +} + +export interface RowSkip { + /** The table's key. */ + table: string; + index: number; + result: string; + why: "when" | "used" | "not-terrain" | "dead-end"; +} + +interface Fit { + weights: number[]; + /** Every row fits with its full weight (so the table can roll its die). */ + whole: boolean; + skipped: RowSkip[]; +} + +class Resolver { + private viable = new Map(); + constructor(private lookup: TableLookup, private ctx: ResolveContext) {} + + private get maxDepth() { + return this.ctx.maxDepth ?? DEFAULT_MAX_DEPTH; + } + + /** Each row's weight here (0 = can't come up), and why rows were left out. */ + fit(key: string, table: RandomTable, visited: readonly string[]): Fit { + const resolved = resolveTable(table); + const base = table.entries.map((e, i) => (resolved.mode === "ranges" ? resolved.faces[i].length : Math.max(0, e.weight))); + const skipped: RowSkip[] = []; + const weights = base.map((w, i) => { + if (w <= 0) return 0; + const e = table.entries[i]; + const info = rowInfoOf(table, i); + if (!conditionsFit(info.when, this.ctx)) { skipped.push({ table: key, index: i, result: e.result, why: "when" }); return 0; } + if (info.once && this.ctx.isUsed?.(key, i, e)) { skipped.push({ table: key, index: i, result: e.result, why: "used" }); return 0; } + if (this.ctx.onlyTerrains) { + const { kind, value } = cellKind(table, e, this.lookup, this.ctx); + if (kind === "table") { + if (!this.canYield(value, [...visited, key])) { skipped.push({ table: key, index: i, result: e.result, why: "dead-end" }); return 0; } + } else if (kind !== "terrain" && kind !== "nothing" && !(this.ctx.deferArrival && info.roll === "on arrival")) { + skipped.push({ table: key, index: i, result: e.result, why: "not-terrain" }); + return 0; + } + } + return w; + }); + return { weights, whole: weights.every((w, i) => w === base[i]), skipped }; + } + + /** Whether a linked table can give anything here (not a loop, not too deep, some row fits). */ + private canYield(link: string, visited: readonly string[]): boolean { + const t = this.lookup.table(link); + if (!t || visited.includes(t.key) || visited.length >= this.maxDepth) return false; + const memo = `${t.key}@${visited.length}`; + const known = this.viable.get(memo); + if (known !== undefined) return known; + this.viable.set(memo, false); // a cycle back here can't help + const ok = this.fit(t.key, t.table, visited).weights.some((w) => w > 0); + this.viable.set(memo, ok); + return ok; + } + + roll(link: string, rand: () => number, visited: string[], chain: ResolveStep[], attrs: Record): Resolved { + const t = this.lookup.table(link); + if (!t) return { kind: "empty", value: link, attrs, chain }; + if (visited.includes(t.key) || visited.length >= this.maxDepth) { + return { kind: "loop", value: `${LOOP_MARK} ${link}`, attrs, chain }; + } + const { table, key } = t; + const fit = this.fit(key, table, visited); + let index = -1; + let face: number | undefined; + if (fit.whole) { + const out = rollTable(table, rand); + if (out) { index = out.index; face = out.face; } + } else { + index = pickIndex(rand, fit.weights); + } + if (index < 0) return { kind: "empty", value: link, attrs, chain }; + const entry = table.entries[index]; + const info = rowInfoOf(table, index); + const step: ResolveStep = { table: key, index, result: entry.result }; + if (face !== undefined) step.face = face; + const nextChain = [...chain, step]; + const nextAttrs = { ...attrs, ...(info.attrs ?? {}) }; + const once = info.once ? { table: key, index, scope: info.once } : undefined; + const { kind, value } = cellKind(table, entry, this.lookup, this.ctx); + if (this.ctx.deferArrival && info.roll === "on arrival") { + const out: Resolved = { kind: "deferred", value: kind === "table" ? value : key, attrs: nextAttrs, chain: nextChain }; + const shown = info.shownAs ?? table.shownAs; + if (shown) out.shownAs = shown; + if (once) out.once = once; + return out; + } + if (kind === "table") { + const inner = this.roll(value, rand, [...visited, key], nextChain, nextAttrs); + if (!inner.once && once) inner.once = once; + return inner; + } + const out: Resolved = { kind, value, attrs: nextAttrs, chain: nextChain }; + if (once) out.once = once; + return out; + } + + odds(link: string, visited: string[], p: number, out: Map): void { + const t = this.lookup.table(link); + const add = (kind: ResolvedOdds["kind"], value: string, q: number) => { + const k = `${kind}:${lc(value)}`; + const o = out.get(k); + if (o) o.odds += q; + else out.set(k, { kind, value, odds: q }); + }; + if (!t) { add("empty", link, p); return; } + if (visited.includes(t.key) || visited.length >= this.maxDepth) { add("loop", `${LOOP_MARK} ${link}`, p); return; } + const { weights } = this.fit(t.key, t.table, visited); + const total = weights.reduce((a, b) => a + b, 0); + if (total <= 0) { add("empty", link, p); return; } + t.table.entries.forEach((e, i) => { + if (weights[i] <= 0) return; + const q = (p * weights[i]) / total; + const info = rowInfoOf(t.table, i); + const { kind, value } = cellKind(t.table, e, this.lookup, this.ctx); + if (this.ctx.deferArrival && info.roll === "on arrival") add("deferred", kind === "table" ? value : t.key, q); + else if (kind === "table") this.odds(value, [...visited, t.key], q, out); + else add(kind, value, q); + }); + } + + /** Rows left out here, in this table and the tables it links (loop-guarded). */ + skippedRows(link: string, visited: string[] = []): RowSkip[] { + const t = this.lookup.table(link); + if (!t || visited.includes(t.key) || visited.length >= this.maxDepth) return []; + const own = this.fit(t.key, t.table, visited).skipped; + const nested = t.table.entries.flatMap((e) => { + const { kind, value } = cellKind(t.table, e, this.lookup, this.ctx); + return kind === "table" ? this.skippedRows(value, [...visited, t.key]) : []; + }); + return [...own, ...nested]; + } +} + +/** Weighted pick of an index (one draw); -1 when nothing weighs anything. */ +function pickIndex(rand: () => number, weights: number[]): number { + const total = weights.reduce((a, b) => a + b, 0); + if (!(total > 0)) return -1; + let r = rand() * total; + let last = -1; + for (let i = 0; i < weights.length; i++) { + if (weights[i] <= 0) continue; + last = i; + r -= weights[i]; + if (r < 0) return i; + } + return last; +} + +function streamOf(ctx: ResolveContext): () => number { + if (ctx.rand) return ctx.rand; + if (ctx.seed !== undefined) return mulberry32(ctx.seed >>> 0); + return Math.random; +} + +/** + * Roll the table a link points at and follow it through: nested tables are + * rolled in turn (same stream), until a row that is text, a note, a + * terrain, a generator or nothing. + */ +export function resolveRoll(link: string, lookup: TableLookup, ctx: ResolveContext = {}): Resolved { + return new Resolver(lookup, ctx).roll(link, streamOf(ctx), [], [], {}); +} + +export interface ResolvedOdds { + kind: Resolved["kind"]; + value: string; + /** 0..1 */ + odds: number; +} + +/** The exact odds of every outcome resolveRoll can give for this link and context, most likely first. */ +export function resolveOdds(link: string, lookup: TableLookup, ctx: Omit = {}): ResolvedOdds[] { + const out = new Map(); + new Resolver(lookup, ctx).odds(link, [], 1, out); + return [...out.values()].sort((a, b) => b.odds - a.odds || a.value.localeCompare(b.value)); +} + +/** The rows of a table (and the tables it links) that this context leaves out, and why (for warnings: never drop a row silently). */ +export function skippedRows(link: string, lookup: TableLookup, ctx: Omit = {}): RowSkip[] { + return new Resolver(lookup, ctx).skippedRows(link); +} + +/** + * The first row naming `name` (any case) in a table or the tables it links + * (depth-first, loop-guarded): its attributes along the chain. For a + * lookup like "what does the sector row of this world say". + */ +export function findRow(link: string, name: string, lookup: TableLookup, maxDepth = DEFAULT_MAX_DEPTH): { attrs: Record; chain: ResolveStep[] } | undefined { + const want = lc(name); + const walk = (l: string, visited: string[], attrs: Record, chain: ResolveStep[]): ReturnType => { + const t = lookup.table(l); + if (!t || visited.includes(t.key) || visited.length >= maxDepth) return undefined; + const nested: [string, Record, ResolveStep[]][] = []; + for (let i = 0; i < t.table.entries.length; i++) { + const e = t.table.entries[i]; + const a = { ...attrs, ...(rowInfoOf(t.table, i).attrs ?? {}) }; + const c = [...chain, { table: t.key, index: i, result: e.result }]; + if (lc(e.result) === want) return { attrs: a, chain: c }; + const link = entryLink(t.table, e); + if (link !== undefined && lookup.table(link)) nested.push([link, a, c]); + } + for (const [l2, a, c] of nested) { + const hit = walk(l2, [...visited, t.key], a, c); + if (hit) return hit; + } + return undefined; + }; + return walk(link, [], {}, []); +} + +/** A readable chain: "Sector hexes → Mainworlds → ocean world". */ +export function chainLabel(r: Resolved, nameOf: (key: string) => string = (k) => k.replace(/^.*\//, "").replace(/\.md$/i, "")): string { + const parts = r.chain.map((s) => nameOf(s.table)); + const last = r.chain[r.chain.length - 1]; + if (last) parts.push(r.kind === "nothing" ? "(nothing)" : r.kind === "loop" ? r.value : last.result); + return parts.join(" → "); +} + +// ── row types (the seam for pickers, plan §2.5) ───────────────────────────── + +/** What a picker wants: tables whose rows are one of these, optionally of a terrain type. */ +export interface TableWant { + rows?: readonly RowType[]; + terrainType?: string; +} + +/** + * How well a table fits a picker's want: "exact" (its `rows:` is wanted + * and, for terrain rows, its terrain-type fits), "any" (`rows: any`, which + * fits everything but sorts after exact matches) or "no" (with why, so a + * picker can list it disabled rather than hide it). + */ +export function tableFitsWant(table: Pick, want: TableWant): { fit: "exact" | "any" | "no"; why?: string } { + if (!want.rows?.length) return { fit: table.rows ? "exact" : "any" }; + if (!table.rows) return { fit: "any" }; + if (!want.rows.includes(table.rows)) return { fit: "no", why: `its rows are ${table.rows}, not ${want.rows.join(" or ")}` }; + if (want.terrainType && table.rows === "terrain" && table.terrainTypes?.length && !table.terrainTypes.includes(lc(want.terrainType))) { + return { fit: "no", why: `its terrain type is ${table.terrainTypes.join(", ")}, not ${want.terrainType}` }; + } + return { fit: "exact" }; +} + +/** Which cell kinds a `rows:` type accepts. */ +const ACCEPTS: Record = { + any: ["text", "note", "table", "generator", "terrain", "nothing"], + text: ["text", "nothing"], + note: ["note", "table", "nothing"], + table: ["table", "nothing"], + generator: ["generator", "nothing"], + terrain: ["terrain", "table", "nothing"], + biome: ["note", "table", "nothing"], +}; + +/** + * Rows whose cell doesn't fit the table's `rows:` (a constraint, never a + * parser switch: the row still reads and rolls; this is what the editor + * and checks report). + */ +export function rowTypeProblems(table: RandomTable, lookup: TableLookup, ctx: Pick = {}): { index: number; message: string }[] { + const rows = table.rows ?? "any"; + const out: { index: number; message: string }[] = []; + table.entries.forEach((e, i) => { + const { kind } = cellKind(table, e, lookup, ctx); + if (ACCEPTS[rows].includes(kind)) return; + const what = kind === "text" && rows === "terrain" ? "isn't a terrain of the palette" : `is ${kind === "text" ? "plain text" : `a ${kind}`}`; + out.push({ index: i, message: `Row ${i + 1} ("${e.result}") ${what}, but the table's rows are ${rows}.` }); + }); + return out; +} + +const GENERATOR_MARKERS = /^(?:hex-wfc|hexmaker-recipe|hexmaker-generator|template-file|results-folder):/m; + +/** What a note is, from its text: a generator (generator note, recipe, workflow), a table, or another note. */ +export function noteKind(content: string): "generator" | "table" | "note" { + const fm = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---/.exec(content)?.[1] ?? ""; + if (GENERATOR_MARKERS.test(fm)) return "generator"; + if (/^dice:/m.test(fm) || /^rows:/m.test(fm)) return "table"; + const block = locateRollTable(content); + return block?.recognized ? "table" : "note"; +} + +/** + * A lookup over notes held in memory (path → text). Links resolve by path + * (with or without `.md`) or by note name; `Note#Heading` reads the table + * under that heading, so a table inside another note (a biome's Mix) rolls + * like any table. + */ +export function notesLookup(notes: Record): TableLookup { + const paths = Object.keys(notes); + const find = (target: string): string | undefined => { + const t = lc(target).replace(/\.md$/, ""); + return paths.find((p) => lc(p).replace(/\.md$/, "") === t) + ?? paths.find((p) => lc(p).replace(/\.md$/, "").replace(/^.*\//, "") === t.replace(/^.*\//, "")); + }; + const split = (link: string) => { + const i = link.indexOf("#"); + return i < 0 ? { target: link, heading: undefined } : { target: link.slice(0, i), heading: link.slice(i + 1) }; + }; + const cache = new Map(); + return { + table(link) { + const { target, heading } = split(link); + const path = find(target); + if (!path) return undefined; + const key = heading ? `${path}#${heading}` : path; + if (!cache.has(key)) { + const content = notes[path]; + const isTable = heading ? !!locateRollTable(content, heading) : noteKind(content) === "table"; + cache.set(key, isTable ? { key, table: parseRandomTable(content, { heading }) } : null); + } + return cache.get(key) ?? undefined; + }, + kindOf(link) { + const path = find(split(link).target); + if (!path) return "missing"; + return noteKind(notes[path]) === "generator" ? "generator" : "note"; + }, + }; +} + +/** A lookup over tables held in memory, by key (names match any case, with or without `.md`). */ +export function memoryLookup(tables: Record, kinds: Record = {}): TableLookup { + const norm = (s: string) => lc(s).replace(/\.md$/, ""); + const byKey = new Map(Object.entries(tables).map(([k, t]) => [norm(k), { key: k, table: t }])); + return { + table: (link) => byKey.get(norm(link)), + kindOf: (link) => kinds[link] ?? (byKey.has(norm(link)) ? "note" : "missing"), + }; +} diff --git a/src/random-tables/tableConditions.ts b/src/random-tables/tableConditions.ts new file mode 100644 index 00000000..0e1430df --- /dev/null +++ b/src/random-tables/tableConditions.ts @@ -0,0 +1,145 @@ +/** + * The `When` column of a random table (plan-tables-everywhere §2.8): an + * escape hatch that limits a row to some contexts. Prefer one table per + * context; use When for the rare row that only fits sometimes. + * + * | d6 | Result | Weight | When | + * | 1–4 | gas giant | 4 | zone: outer | + * | 5 | ice moon | 1 | star: red dwarf, white dwarf; zone: outer | + * | 6 | hot jupiter | 1 | zone: inner; ring: 2–3 | + * + * - Conditions are `key: value`, separated by `;`. A comma lists choices + * (any of them fits). Every condition must fit. + * - Keys: zone (inner, habitable, outer), ring (hexes from the star, like + * 2–4), star (star terrains), type (terrain types), terrain (the parent + * hex's terrain), temperature (cold … hot, or 0.2–0.5). + * - A key the roller doesn't know about here (no star, say) lets the row + * through, so a hand roll and the Tables view roll every row. + * - An unknown key, or a value that can't be read, is reported and that + * row never fires. + * + * The rule a hand-roller follows: "if a row's When doesn't fit, roll + * again". The code renormalises over the rows that fit, which is the same + * distribution. + * + * Pure: no Obsidian imports. + */ + +import { TEMPERATURE_WORDS, inClimateRange, parseClimateRange, type ClimateRange } from "../overworld/biomeClimate"; +import { ORBIT_ZONES, readIntRange, readOrbit, type IntRange, type OrbitZone } from "../space/worldTypes"; + +export type TableCondition = + | { key: "zone"; zones: OrbitZone[] } + | { key: "ring"; range: IntRange } + | { key: "star" | "type" | "terrain"; values: string[] } + | { key: "temperature"; range: ClimateRange } + /** Can't be read: the row never fires. */ + | { key: "unknown"; text: string }; + +/** What the roller knows where it rolls. Every field is optional. */ +export interface ConditionContext { + zone?: OrbitZone; + /** Hexes from the star. */ + ring?: number; + /** The system's star terrain. */ + star?: string; + /** The terrain type being placed or the parent hex's type. */ + type?: string; + /** The parent hex's terrain. */ + terrain?: string; + /** 0 (cold) … 1 (hot). */ + temperature?: number; +} + +export const CONDITION_KEYS = ["zone", "ring", "star", "type", "terrain", "temperature"] as const; + +const lc = (s: string) => s.trim().toLowerCase(); +const list = (raw: string) => raw.split(/\s*,\s*/).map(lc).filter((s) => s !== ""); + +/** One `key: value` → a condition (key "unknown" when it can't be read). */ +function readCondition(part: string): TableCondition { + const m = /^([a-z ]+?)\s*[:=]\s*(.+)$/i.exec(part.trim()); + if (!m) return { key: "unknown", text: part.trim() }; + const key = lc(m[1]).replace(/s$/, ""); + const value = m[2].trim(); + switch (key) { + case "zone": + case "orbit": { + const o = readOrbit(value); + if (!o || o.distance || !o.zones?.length) return { key: "unknown", text: part.trim() }; + return { key: "zone", zones: o.zones }; + } + case "ring": + case "distance": { + const r = readIntRange(value); + return r ? { key: "ring", range: r } : { key: "unknown", text: part.trim() }; + } + case "star": + case "type": + case "terrain": { + const values = list(value); + return values.length ? { key, values } : { key: "unknown", text: part.trim() }; + } + case "temperature": + case "temp": { + const r = parseClimateRange(value, TEMPERATURE_WORDS); + return r.range && !r.problem ? { key: "temperature", range: r.range } : { key: "unknown", text: part.trim() }; + } + default: + return { key: "unknown", text: part.trim() }; + } +} + +/** A When cell → its conditions (empty for a blank cell or "any"). */ +export function parseWhen(raw: string): TableCondition[] { + const t = raw.trim(); + if (!t || /^(any|always|-|—)$/i.test(t)) return []; + return t.split(/\s*;\s*/).filter((p) => p !== "").map(readCondition); +} + +/** The parts of a When cell that can't be read (reported; the row never fires). */ +export function unreadableConditions(when: readonly TableCondition[]): string[] { + return when.flatMap((c) => (c.key === "unknown" ? [c.text] : [])); +} + +/** Whether a row's conditions fit the context. Conditions the context can't speak to pass; unreadable ones never do. */ +export function conditionsFit(when: readonly TableCondition[] | undefined, ctx: ConditionContext = {}): boolean { + if (!when?.length) return true; + for (const c of when) { + switch (c.key) { + case "unknown": + return false; + case "zone": + if (ctx.zone && !c.zones.includes(ctx.zone)) return false; + break; + case "ring": + if (ctx.ring !== undefined && (ctx.ring < c.range.lo || ctx.ring > c.range.hi)) return false; + break; + case "star": + case "type": + case "terrain": { + const v = ctx[c.key]; + if (v !== undefined && !c.values.includes(lc(v))) return false; + break; + } + case "temperature": + if (ctx.temperature !== undefined && !inClimateRange(c.range, ctx.temperature)) return false; + break; + } + } + return true; +} + +/** Conditions back as a When cell. */ +export function formatWhen(when: readonly TableCondition[]): string { + const fmt = (r: IntRange) => (r.lo === r.hi ? String(r.lo) : `${r.lo}–${r.hi}`); + return when.map((c) => { + switch (c.key) { + case "zone": return `zone: ${ORBIT_ZONES.filter((z) => c.zones.includes(z)).join(", ")}`; + case "ring": return `ring: ${fmt(c.range)}`; + case "temperature": return `temperature: ${c.range.lo}–${c.range.hi}`; + case "unknown": return c.text; + default: return `${c.key}: ${c.values.join(", ")}`; + } + }).join("; "); +} diff --git a/tests/fixtures/tables/broken-ranges.md b/tests/fixtures/tables/broken-ranges.md new file mode 100644 index 00000000..5b2992ca --- /dev/null +++ b/tests/fixtures/tables/broken-ranges.md @@ -0,0 +1,8 @@ +--- +dice: 6 +--- +| d6 | Result | Weight | +|---|---|---| +| 1-3 | x | 3 | +| 3-5 | y | 2 | +| 9 | z | 1 | diff --git a/tests/fixtures/tables/d100-zeros.md b/tests/fixtures/tables/d100-zeros.md new file mode 100644 index 00000000..2c52f21c --- /dev/null +++ b/tests/fixtures/tables/d100-zeros.md @@ -0,0 +1,8 @@ +--- +dice: 100 +--- +| d100 | Result | +| --- | --- | +| 01–50 | rain | +| 51–90 | wind | +| 91–00 | snow | diff --git a/tests/fixtures/tables/d20-ranges.md b/tests/fixtures/tables/d20-ranges.md new file mode 100644 index 00000000..cd25444f --- /dev/null +++ b/tests/fixtures/tables/d20-ranges.md @@ -0,0 +1,12 @@ +--- +dice: 20 +table-type: encounters +--- +Forest encounters. + +| d20 | Result | Weight | +| --- | --- | ---: | +| 1–10 | deer | 10 | +| 11-15 | bandits | 5 | +| 16+ | owlbear | 5 | +| — | dragon | 0 | diff --git a/tests/fixtures/tables/d66.md b/tests/fixtures/tables/d66.md new file mode 100644 index 00000000..1e30adea --- /dev/null +++ b/tests/fixtures/tables/d66.md @@ -0,0 +1,8 @@ +--- +dice: 66 +--- +| d66 | Result | Weight | +|---|---|---| +| 11–16 | a | 6 | +| 21–36 | b | 12 | +| 41–66 | c | 18 | diff --git a/tests/fixtures/tables/extra-columns.md b/tests/fixtures/tables/extra-columns.md new file mode 100644 index 00000000..f4d87b95 --- /dev/null +++ b/tests/fixtures/tables/extra-columns.md @@ -0,0 +1,11 @@ +--- +dice: 8 +roll-filter: true +--- +# Loot + +| d8 | Result | Weight | Value | Notes | +|----|--------|--------|-------|-------| +| 1–4 | coins | 4 | 10 gp | common | +| 5–7 | [[Gem\|a gem]] | 3 | 50 gp | | +| 8 | [[tables/Relics]] | 1 | priceless | rolls again | diff --git a/tests/fixtures/tables/golden.json b/tests/fixtures/tables/golden.json new file mode 100644 index 00000000..40c360d1 --- /dev/null +++ b/tests/fixtures/tables/golden.json @@ -0,0 +1,1534 @@ +{ + "tests/fixtures/tables/broken-ranges.md": { + "table": { + "dice": 6, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "x", + "weight": 3, + "isLink": false, + "range": "1-3" + }, + { + "result": "y", + "weight": 2, + "isLink": false, + "range": "3-5" + }, + { + "result": "z", + "weight": 1, + "isLink": false, + "range": "9" + } + ] + }, + "issues": [ + { + "code": "range-overlap", + "row": 2 + }, + { + "code": "range-out-of-die", + "row": 3 + } + ], + "mode": "weight", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 2 + ], + "rewrite": "---\ndice: 6\n---\n| d6 | Result | Weight |\n|---|---|---|\n| 1-3 | x | 3 |\n| 3-5 | y | 2 |\n| 9 | z | 1 |\n" + }, + "tests/fixtures/tables/d100-zeros.md": { + "table": { + "dice": 100, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "rain", + "weight": 50, + "isLink": false, + "range": "01–50" + }, + { + "result": "wind", + "weight": 40, + "isLink": false, + "range": "51–90" + }, + { + "result": "snow", + "weight": 10, + "isLink": false, + "range": "91–00" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 2 + ], + "rewrite": "---\ndice: 100\n---\n| d100 | Result |\n| --- | --- |\n| 01–50 | rain |\n| 51–90 | wind |\n| 91–00 | snow |\n" + }, + "tests/fixtures/tables/d20-ranges.md": { + "table": { + "dice": 20, + "linkedFolder": null, + "description": "Forest encounters.", + "entries": [ + { + "result": "deer", + "weight": 10, + "isLink": false, + "range": "1–10" + }, + { + "result": "bandits", + "weight": 5, + "isLink": false, + "range": "11-15" + }, + { + "result": "owlbear", + "weight": 5, + "isLink": false, + "range": "16+" + }, + { + "result": "dragon", + "weight": 0, + "isLink": false, + "range": "—" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 2, + 2 + ], + "rewrite": "---\ndice: 20\ntable-type: encounters\n---\nForest encounters.\n\n| d20 | Result | Weight |\n| --- | --- | ---: |\n| 1–10 | deer | 10 |\n| 11-15 | bandits | 5 |\n| 16+ | owlbear | 5 |\n| — | dragon | 0 |\n" + }, + "tests/fixtures/tables/d66.md": { + "table": { + "dice": 66, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "a", + "weight": 6, + "isLink": false, + "range": "11–16" + }, + { + "result": "b", + "weight": 12, + "isLink": false, + "range": "21–36" + }, + { + "result": "c", + "weight": 18, + "isLink": false, + "range": "41–66" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 1, + 1, + 2, + 2, + 2, + 2 + ], + "rewrite": "---\ndice: 66\n---\n| d66 | Result | Weight |\n|---|---|---|\n| 11–16 | a | 6 |\n| 21–36 | b | 12 |\n| 41–66 | c | 18 |\n" + }, + "tests/fixtures/tables/extra-columns.md": { + "table": { + "dice": 8, + "linkedFolder": null, + "description": "# Loot", + "entries": [ + { + "result": "coins", + "weight": 4, + "isLink": false, + "range": "1–4" + }, + { + "result": "Gem", + "weight": 3, + "isLink": true, + "range": "5–7" + }, + { + "result": "tables/Relics", + "weight": 1, + "isLink": true, + "range": "8" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 2 + ], + "rewrite": "---\ndice: 8\nroll-filter: true\n---\n# Loot\n\n| d8 | Result | Weight | Value | Notes |\n|----|--------|--------|-------|-------|\n| 1–4 | coins | 4 | 10 gp | common |\n| 5–7 | [[Gem\\|a gem]] | 3 | 50 gp | |\n| 8 | [[tables/Relics]] | 1 | priceless | rolls again |\n" + }, + "tests/fixtures/tables/linked-folder-quoted.md": { + "table": { + "dice": 4, + "linkedFolder": "world/towns", + "description": null, + "entries": [ + { + "result": "Saltwatch", + "weight": 2, + "isLink": false, + "range": "1–2" + }, + { + "result": "Rivermeet", + "weight": 2, + "isLink": false, + "range": "3–4" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 1 + ], + "rewrite": "---\ndice: 4\nlinkedFolder: \"[[world/towns]]\"\n---\n| d4 | Result | Weight |\n|---|---|---|\n| 1–2 | [[Saltwatch]] | 2 |\n| 3–4 | [[Rivermeet]] | 2 |\n" + }, + "tests/fixtures/tables/no-table.md": { + "table": { + "dice": 6, + "linkedFolder": null, + "description": null, + "entries": [] + }, + "issues": [ + { + "code": "no-table", + "row": null + } + ], + "mode": "weight", + "rolls": [ + null, + null, + null, + null, + null, + null, + null + ], + "rewrite": "---\ndice: 6\n---\nNothing here yet.\n\n| d6 | Result | Weight |\n|----|--------|--------|\n" + }, + "tests/fixtures/tables/old-no-frontmatter.md": { + "table": { + "dice": 0, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "alpha", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "beta", + "weight": 0, + "isLink": false, + "range": null + }, + { + "result": "gamma", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [ + { + "code": "weight-unreadable", + "row": 3 + } + ], + "mode": "weight", + "rolls": [ + 0, + 0, + 0, + 2, + 2, + 2, + 2 + ], + "rewrite": "| Result | Weight |\n|---|---|\n| alpha | 1 |\n| beta | 0 |\n| gamma | x |\n" + }, + "tests/fixtures/tables/old-result-weight.md": { + "table": { + "dice": 6, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "goblins", + "weight": 2, + "isLink": false, + "range": null + }, + { + "result": "wolves", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "nothing", + "weight": 3, + "isLink": false, + "range": null + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 1, + 2, + 2, + 2, + 2 + ], + "rewrite": "---\ndice: 6\n---\n\n| d6 | Result | Weight |\n|-----|--------|--------|\n| 1–2 | goblins | 2 |\n| 3 | wolves | 1 |\n| 4–6 | nothing | 3 |\n" + }, + "tests/fixtures/tables/roller-block.md": { + "table": { + "dice": 10, + "linkedFolder": null, + "description": "Weather by day.", + "entries": [ + { + "result": "clear", + "weight": 5, + "isLink": false, + "range": "1–5" + }, + { + "result": "cloudy", + "weight": 4, + "isLink": false, + "range": "6–9" + }, + { + "result": "storm", + "weight": 1, + "isLink": false, + "range": "10" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 2 + ], + "rewrite": "---\ndice: 10\n---\n\n```duckmage-roller\n```\n\nWeather by day.\n\n| d10 | Result | Weight |\n|---|---|---|\n| 1–5 | clear | 5 |\n| 6–9 | cloudy | 4 |\n| 10 | storm | 1 |\n" + }, + "tests/fixtures/tables/too-many-rows.md": { + "table": { + "dice": 4, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "a", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "b", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "c", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "d", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "e", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [ + { + "code": "too-many-rows", + "row": null + } + ], + "mode": "weight", + "rolls": [ + 0, + 1, + 1, + 2, + 3, + 4, + 4 + ], + "rewrite": "---\ndice: 4\n---\n| d4 | Result | Weight |\n|---|---|---|\n| | a | 1 |\n| | b | 1 |\n| | c | 1 |\n| | d | 1 |\n| | e | 1 |\n" + }, + "tests/fixtures/tables/two-tables.md": { + "table": { + "dice": 0, + "linkedFolder": null, + "description": "| Name | Age |\n|---|---|\n| Bob | 3 |\n\n## Roll", + "entries": [ + { + "result": "left", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "right", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [], + "mode": "weight", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 1 + ], + "rewrite": "| Name | Age |\n|---|---|\n| Bob | 3 |\n\n## Roll\n\n| Result | Weight |\n|---|---|\n| left | 1 |\n| right | 1 |\n" + }, + "tests/fixtures/tables/unknown-header.md": { + "table": { + "dice": 0, + "linkedFolder": null, + "description": "Some prose.", + "entries": [ + { + "result": "sword", + "weight": 2, + "isLink": false, + "range": null + }, + { + "result": "shield", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [], + "mode": "weight", + "rolls": [ + 0, + 0, + 0, + 0, + 0, + 1, + 1 + ], + "rewrite": "Some prose.\n\n| Thing | Odds |\n|---|---|\n| sword | 2 |\n| shield | 1 |\n" + }, + "tests/fixtures/sim-vault/tables/forest-encounters.md": { + "table": { + "dice": 6, + "linkedFolder": null, + "description": "Weighted forest encounter table.", + "entries": [ + { + "result": "Pack of wolves", + "weight": 2, + "isLink": false, + "range": "1–2" + }, + { + "result": "Lost merchant", + "weight": 1, + "isLink": false, + "range": "3" + }, + { + "result": "Bandit ambush", + "weight": 2, + "isLink": false, + "range": "4–5" + }, + { + "result": "Druid circle", + "weight": 1, + "isLink": false, + "range": "6" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 1, + 2, + 2, + 2, + 3 + ], + "rewrite": "---\ndice: 6\n---\n\nWeighted forest encounter table.\n\n| d6 | Result | Weight |\n|-----|--------|--------|\n| 1–2 | Pack of wolves | 2 |\n| 3 | Lost merchant | 1 |\n| 4–5 | Bandit ambush | 2 |\n| 6 | Druid circle | 1 |\n" + }, + "tests/fixtures/sim-vault/tables/npc-names.md": { + "table": { + "dice": 20, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "Bromund", + "weight": 1, + "isLink": false, + "range": "1–4" + }, + { + "result": "Lirel", + "weight": 1, + "isLink": false, + "range": "5–8" + }, + { + "result": "Vargax", + "weight": 1, + "isLink": false, + "range": "9–12" + }, + { + "result": "Saskia", + "weight": 1, + "isLink": false, + "range": "13–16" + }, + { + "result": "Olwen", + "weight": 1, + "isLink": false, + "range": "17–20" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 1, + 1, + 2, + 3, + 4, + 4 + ], + "rewrite": "---\ndice: 20\n---\n\n| d20 | Result | Weight |\n|-----|--------|--------|\n| 1–4 | Bromund | 1 |\n| 5–8 | Lirel | 1 |\n| 9–12 | Vargax | 1 |\n| 13–16 | Saskia | 1 |\n| 17–20 | Olwen | 1 |\n" + }, + "tests/fixtures/sim-vault/tables/treasure.md": { + "table": { + "dice": 0, + "linkedFolder": "tables/treasure", + "description": "Auto-synced from the treasure folder.", + "entries": [ + { + "result": "gold pile", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "silver ring", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "cursed amulet", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [], + "mode": "weight", + "rolls": [ + 0, + 0, + 1, + 1, + 1, + 2, + 2 + ], + "rewrite": "---\nlinkedFolder: tables/treasure\n---\n\nAuto-synced from the treasure folder.\n\n| Result | Weight |\n|--------|--------|\n| [[gold pile]] | 1 |\n| [[silver ring]] | 1 |\n| [[cursed amulet]] | 1 |\n" + }, + "tests/fixtures/sample-random-table.md": { + "table": { + "dice": 20, + "linkedFolder": null, + "description": "A small fixture table used by the integration test. **Wandering monsters** for a forest hex.", + "entries": [ + { + "result": "Pack of wolves", + "weight": 4, + "isLink": false, + "range": "1–4" + }, + { + "result": "Lost merchant", + "weight": 2, + "isLink": false, + "range": "5–6" + }, + { + "result": "Bandit ambush", + "weight": 3, + "isLink": false, + "range": "7–9" + }, + { + "result": "Druid circle", + "weight": 1, + "isLink": false, + "range": "10" + }, + { + "result": "Wild boar", + "weight": 5, + "isLink": false, + "range": "11–15" + }, + { + "result": "Travelling minstrel", + "weight": 2, + "isLink": false, + "range": "16–17" + }, + { + "result": "Goblin scouts", + "weight": 3, + "isLink": false, + "range": "18–20" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 1, + 2, + 4, + 4, + 5, + 6 + ], + "rewrite": "---\ndice: 20\n---\n\nA small fixture table used by the integration test. **Wandering monsters** for a forest hex.\n\n| d20 | Result | Weight |\n|-----|--------|--------|\n| 1–4 | Pack of wolves | 4 |\n| 5–6 | Lost merchant | 2 |\n| 7–9 | Bandit ambush | 3 |\n| 10 | Druid circle | 1 |\n| 11–15 | Wild boar | 5 |\n| 16–17 | Travelling minstrel | 2 |\n| 18–20 | Goblin scouts | 3 |\n" + }, + "tests/fixtures/compat/legacy-table-1.5.6.md": { + "table": { + "dice": 20, + "linkedFolder": null, + "description": "Beach encounters. Roll when the party camps on the shore.", + "entries": [ + { + "result": "crabmen", + "weight": 4, + "isLink": false, + "range": null + }, + { + "result": "Sea Hag", + "weight": 1, + "isLink": true, + "range": null + }, + { + "result": "fishmen", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "smugglers", + "weight": 2, + "isLink": false, + "range": null + }, + { + "result": "kraken", + "weight": 0, + "isLink": false, + "range": null + } + ] + }, + "issues": [ + { + "code": "legacy-roller-link", + "row": null + } + ], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 2, + 3, + 3 + ], + "rewrite": "---\ndice: 20\ntable-type: encounters\n---\n\n[🎲 Open in Duckmage Roller](obsidian://duckmage-roll?vault=journal&file=RPG%2Fduckmage%2Ftables%2Fbeach.md)\n\nBeach encounters. Roll when the party camps on the shore.\n\n| d20 | Result | Weight | Notes |\n|-----|--------|--------|-------|\n| 1–10 | crabmen | 4 | 2d4, at low tide |\n| 11–13 | [[Sea Hag\\|the hag]] | 1 | |\n| 14–15 | fishmen | 1 | |\n| 16–20 | smugglers | 2 | see [[Smugglers' Cove]] |\n| — | kraken | 0 | only in the epilogue |\n\n## GM notes\nKeep the kraken for later.\n" + }, + "tests/fixtures/tables/broken-ranges.md (crlf)": { + "table": { + "dice": 6, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "x", + "weight": 3, + "isLink": false, + "range": "1-3" + }, + { + "result": "y", + "weight": 2, + "isLink": false, + "range": "3-5" + }, + { + "result": "z", + "weight": 1, + "isLink": false, + "range": "9" + } + ] + }, + "issues": [ + { + "code": "range-overlap", + "row": 2 + }, + { + "code": "range-out-of-die", + "row": 3 + } + ], + "mode": "weight", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 2 + ], + "rewrite": "---\r\ndice: 6\r\n---\r\n| d6 | Result | Weight |\r\n|---|---|---|\r\n| 1-3 | x | 3 |\r\n| 3-5 | y | 2 |\r\n| 9 | z | 1 |\r\n" + }, + "tests/fixtures/tables/d100-zeros.md (crlf)": { + "table": { + "dice": 100, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "rain", + "weight": 50, + "isLink": false, + "range": "01–50" + }, + { + "result": "wind", + "weight": 40, + "isLink": false, + "range": "51–90" + }, + { + "result": "snow", + "weight": 10, + "isLink": false, + "range": "91–00" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 2 + ], + "rewrite": "---\r\ndice: 100\r\n---\r\n| d100 | Result |\r\n| --- | --- |\r\n| 01–50 | rain |\r\n| 51–90 | wind |\r\n| 91–00 | snow |\r\n" + }, + "tests/fixtures/tables/d20-ranges.md (crlf)": { + "table": { + "dice": 20, + "linkedFolder": null, + "description": "Forest encounters.", + "entries": [ + { + "result": "deer", + "weight": 10, + "isLink": false, + "range": "1–10" + }, + { + "result": "bandits", + "weight": 5, + "isLink": false, + "range": "11-15" + }, + { + "result": "owlbear", + "weight": 5, + "isLink": false, + "range": "16+" + }, + { + "result": "dragon", + "weight": 0, + "isLink": false, + "range": "—" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 2, + 2 + ], + "rewrite": "---\r\ndice: 20\r\ntable-type: encounters\r\n---\r\nForest encounters.\r\n\r\n| d20 | Result | Weight |\r\n| --- | --- | ---: |\r\n| 1–10 | deer | 10 |\r\n| 11-15 | bandits | 5 |\r\n| 16+ | owlbear | 5 |\r\n| — | dragon | 0 |\r\n" + }, + "tests/fixtures/tables/d66.md (crlf)": { + "table": { + "dice": 66, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "a", + "weight": 6, + "isLink": false, + "range": "11–16" + }, + { + "result": "b", + "weight": 12, + "isLink": false, + "range": "21–36" + }, + { + "result": "c", + "weight": 18, + "isLink": false, + "range": "41–66" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 1, + 1, + 2, + 2, + 2, + 2 + ], + "rewrite": "---\r\ndice: 66\r\n---\r\n| d66 | Result | Weight |\r\n|---|---|---|\r\n| 11–16 | a | 6 |\r\n| 21–36 | b | 12 |\r\n| 41–66 | c | 18 |\r\n" + }, + "tests/fixtures/tables/extra-columns.md (crlf)": { + "table": { + "dice": 8, + "linkedFolder": null, + "description": "# Loot", + "entries": [ + { + "result": "coins", + "weight": 4, + "isLink": false, + "range": "1–4" + }, + { + "result": "Gem", + "weight": 3, + "isLink": true, + "range": "5–7" + }, + { + "result": "tables/Relics", + "weight": 1, + "isLink": true, + "range": "8" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 2 + ], + "rewrite": "---\r\ndice: 8\r\nroll-filter: true\r\n---\r\n# Loot\r\n\r\n| d8 | Result | Weight | Value | Notes |\r\n|----|--------|--------|-------|-------|\r\n| 1–4 | coins | 4 | 10 gp | common |\r\n| 5–7 | [[Gem\\|a gem]] | 3 | 50 gp | |\r\n| 8 | [[tables/Relics]] | 1 | priceless | rolls again |\r\n" + }, + "tests/fixtures/tables/linked-folder-quoted.md (crlf)": { + "table": { + "dice": 4, + "linkedFolder": "world/towns", + "description": null, + "entries": [ + { + "result": "Saltwatch", + "weight": 2, + "isLink": false, + "range": "1–2" + }, + { + "result": "Rivermeet", + "weight": 2, + "isLink": false, + "range": "3–4" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 1 + ], + "rewrite": "---\r\ndice: 4\r\nlinkedFolder: \"[[world/towns]]\"\r\n---\r\n| d4 | Result | Weight |\r\n|---|---|---|\r\n| 1–2 | [[Saltwatch]] | 2 |\r\n| 3–4 | [[Rivermeet]] | 2 |\r\n" + }, + "tests/fixtures/tables/no-table.md (crlf)": { + "table": { + "dice": 6, + "linkedFolder": null, + "description": null, + "entries": [] + }, + "issues": [ + { + "code": "no-table", + "row": null + } + ], + "mode": "weight", + "rolls": [ + null, + null, + null, + null, + null, + null, + null + ], + "rewrite": "---\r\ndice: 6\r\n---\r\nNothing here yet.\r\n\r\n| d6 | Result | Weight |\r\n|----|--------|--------|\r\n" + }, + "tests/fixtures/tables/old-no-frontmatter.md (crlf)": { + "table": { + "dice": 0, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "alpha", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "beta", + "weight": 0, + "isLink": false, + "range": null + }, + { + "result": "gamma", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [ + { + "code": "weight-unreadable", + "row": 3 + } + ], + "mode": "weight", + "rolls": [ + 0, + 0, + 0, + 2, + 2, + 2, + 2 + ], + "rewrite": "| Result | Weight |\r\n|---|---|\r\n| alpha | 1 |\r\n| beta | 0 |\r\n| gamma | x |\r\n" + }, + "tests/fixtures/tables/old-result-weight.md (crlf)": { + "table": { + "dice": 6, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "goblins", + "weight": 2, + "isLink": false, + "range": null + }, + { + "result": "wolves", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "nothing", + "weight": 3, + "isLink": false, + "range": null + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 1, + 2, + 2, + 2, + 2 + ], + "rewrite": "---\r\ndice: 6\r\n---\r\n\r\n| d6 | Result | Weight |\r\n|-----|--------|--------|\r\n| 1–2 | goblins | 2 |\r\n| 3 | wolves | 1 |\r\n| 4–6 | nothing | 3 |\r\n" + }, + "tests/fixtures/tables/roller-block.md (crlf)": { + "table": { + "dice": 10, + "linkedFolder": null, + "description": "Weather by day.", + "entries": [ + { + "result": "clear", + "weight": 5, + "isLink": false, + "range": "1–5" + }, + { + "result": "cloudy", + "weight": 4, + "isLink": false, + "range": "6–9" + }, + { + "result": "storm", + "weight": 1, + "isLink": false, + "range": "10" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 2 + ], + "rewrite": "---\r\ndice: 10\r\n---\r\n\r\n```duckmage-roller\r\n```\r\n\r\nWeather by day.\r\n\r\n| d10 | Result | Weight |\r\n|---|---|---|\r\n| 1–5 | clear | 5 |\r\n| 6–9 | cloudy | 4 |\r\n| 10 | storm | 1 |\r\n" + }, + "tests/fixtures/tables/too-many-rows.md (crlf)": { + "table": { + "dice": 4, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "a", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "b", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "c", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "d", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "e", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [ + { + "code": "too-many-rows", + "row": null + } + ], + "mode": "weight", + "rolls": [ + 0, + 1, + 1, + 2, + 3, + 4, + 4 + ], + "rewrite": "---\r\ndice: 4\r\n---\r\n| d4 | Result | Weight |\r\n|---|---|---|\r\n| | a | 1 |\r\n| | b | 1 |\r\n| | c | 1 |\r\n| | d | 1 |\r\n| | e | 1 |\r\n" + }, + "tests/fixtures/tables/two-tables.md (crlf)": { + "table": { + "dice": 0, + "linkedFolder": null, + "description": "| Name | Age |\n|---|---|\n| Bob | 3 |\n\n## Roll", + "entries": [ + { + "result": "left", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "right", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [], + "mode": "weight", + "rolls": [ + 0, + 0, + 0, + 1, + 1, + 1, + 1 + ], + "rewrite": "| Name | Age |\r\n|---|---|\r\n| Bob | 3 |\r\n\r\n## Roll\r\n\r\n| Result | Weight |\r\n|---|---|\r\n| left | 1 |\r\n| right | 1 |\r\n" + }, + "tests/fixtures/tables/unknown-header.md (crlf)": { + "table": { + "dice": 0, + "linkedFolder": null, + "description": "Some prose.", + "entries": [ + { + "result": "sword", + "weight": 2, + "isLink": false, + "range": null + }, + { + "result": "shield", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [], + "mode": "weight", + "rolls": [ + 0, + 0, + 0, + 0, + 0, + 1, + 1 + ], + "rewrite": "Some prose.\r\n\r\n| Thing | Odds |\r\n|---|---|\r\n| sword | 2 |\r\n| shield | 1 |\r\n" + }, + "tests/fixtures/sim-vault/tables/forest-encounters.md (crlf)": { + "table": { + "dice": 6, + "linkedFolder": null, + "description": "Weighted forest encounter table.", + "entries": [ + { + "result": "Pack of wolves", + "weight": 2, + "isLink": false, + "range": "1–2" + }, + { + "result": "Lost merchant", + "weight": 1, + "isLink": false, + "range": "3" + }, + { + "result": "Bandit ambush", + "weight": 2, + "isLink": false, + "range": "4–5" + }, + { + "result": "Druid circle", + "weight": 1, + "isLink": false, + "range": "6" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 0, + 1, + 2, + 2, + 2, + 3 + ], + "rewrite": "---\r\ndice: 6\r\n---\r\n\r\nWeighted forest encounter table.\r\n\r\n| d6 | Result | Weight |\r\n|-----|--------|--------|\r\n| 1–2 | Pack of wolves | 2 |\r\n| 3 | Lost merchant | 1 |\r\n| 4–5 | Bandit ambush | 2 |\r\n| 6 | Druid circle | 1 |\r\n" + }, + "tests/fixtures/sim-vault/tables/npc-names.md (crlf)": { + "table": { + "dice": 20, + "linkedFolder": null, + "description": null, + "entries": [ + { + "result": "Bromund", + "weight": 1, + "isLink": false, + "range": "1–4" + }, + { + "result": "Lirel", + "weight": 1, + "isLink": false, + "range": "5–8" + }, + { + "result": "Vargax", + "weight": 1, + "isLink": false, + "range": "9–12" + }, + { + "result": "Saskia", + "weight": 1, + "isLink": false, + "range": "13–16" + }, + { + "result": "Olwen", + "weight": 1, + "isLink": false, + "range": "17–20" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 1, + 1, + 2, + 3, + 4, + 4 + ], + "rewrite": "---\r\ndice: 20\r\n---\r\n\r\n| d20 | Result | Weight |\r\n|-----|--------|--------|\r\n| 1–4 | Bromund | 1 |\r\n| 5–8 | Lirel | 1 |\r\n| 9–12 | Vargax | 1 |\r\n| 13–16 | Saskia | 1 |\r\n| 17–20 | Olwen | 1 |\r\n" + }, + "tests/fixtures/sim-vault/tables/treasure.md (crlf)": { + "table": { + "dice": 0, + "linkedFolder": "tables/treasure", + "description": "Auto-synced from the treasure folder.", + "entries": [ + { + "result": "gold pile", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "silver ring", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "cursed amulet", + "weight": 1, + "isLink": false, + "range": null + } + ] + }, + "issues": [], + "mode": "weight", + "rolls": [ + 0, + 0, + 1, + 1, + 1, + 2, + 2 + ], + "rewrite": "---\r\nlinkedFolder: tables/treasure\r\n---\r\n\r\nAuto-synced from the treasure folder.\r\n\r\n| Result | Weight |\r\n|--------|--------|\r\n| [[gold pile]] | 1 |\r\n| [[silver ring]] | 1 |\r\n| [[cursed amulet]] | 1 |\r\n" + }, + "tests/fixtures/sample-random-table.md (crlf)": { + "table": { + "dice": 20, + "linkedFolder": null, + "description": "A small fixture table used by the integration test. **Wandering monsters** for a forest hex.", + "entries": [ + { + "result": "Pack of wolves", + "weight": 4, + "isLink": false, + "range": "1–4" + }, + { + "result": "Lost merchant", + "weight": 2, + "isLink": false, + "range": "5–6" + }, + { + "result": "Bandit ambush", + "weight": 3, + "isLink": false, + "range": "7–9" + }, + { + "result": "Druid circle", + "weight": 1, + "isLink": false, + "range": "10" + }, + { + "result": "Wild boar", + "weight": 5, + "isLink": false, + "range": "11–15" + }, + { + "result": "Travelling minstrel", + "weight": 2, + "isLink": false, + "range": "16–17" + }, + { + "result": "Goblin scouts", + "weight": 3, + "isLink": false, + "range": "18–20" + } + ] + }, + "issues": [], + "mode": "ranges", + "rolls": [ + 0, + 1, + 2, + 4, + 4, + 5, + 6 + ], + "rewrite": "---\r\ndice: 20\r\n---\r\n\r\nA small fixture table used by the integration test. **Wandering monsters** for a forest hex.\r\n\r\n| d20 | Result | Weight |\r\n|-----|--------|--------|\r\n| 1–4 | Pack of wolves | 4 |\r\n| 5–6 | Lost merchant | 2 |\r\n| 7–9 | Bandit ambush | 3 |\r\n| 10 | Druid circle | 1 |\r\n| 11–15 | Wild boar | 5 |\r\n| 16–17 | Travelling minstrel | 2 |\r\n| 18–20 | Goblin scouts | 3 |\r\n" + }, + "tests/fixtures/compat/legacy-table-1.5.6.md (crlf)": { + "table": { + "dice": 20, + "linkedFolder": null, + "description": "Beach encounters. Roll when the party camps on the shore.", + "entries": [ + { + "result": "crabmen", + "weight": 4, + "isLink": false, + "range": null + }, + { + "result": "Sea Hag", + "weight": 1, + "isLink": true, + "range": null + }, + { + "result": "fishmen", + "weight": 1, + "isLink": false, + "range": null + }, + { + "result": "smugglers", + "weight": 2, + "isLink": false, + "range": null + }, + { + "result": "kraken", + "weight": 0, + "isLink": false, + "range": null + } + ] + }, + "issues": [ + { + "code": "legacy-roller-link", + "row": null + } + ], + "mode": "ranges", + "rolls": [ + 0, + 0, + 0, + 1, + 2, + 3, + 3 + ], + "rewrite": "---\r\ndice: 20\r\ntable-type: encounters\r\n---\r\n\r\n[🎲 Open in Duckmage Roller](obsidian://duckmage-roll?vault=journal&file=RPG%2Fduckmage%2Ftables%2Fbeach.md)\r\n\r\nBeach encounters. Roll when the party camps on the shore.\r\n\r\n| d20 | Result | Weight | Notes |\r\n|-----|--------|--------|-------|\r\n| 1–10 | crabmen | 4 | 2d4, at low tide |\r\n| 11–13 | [[Sea Hag\\|the hag]] | 1 | |\r\n| 14–15 | fishmen | 1 | |\r\n| 16–20 | smugglers | 2 | see [[Smugglers' Cove]] |\r\n| — | kraken | 0 | only in the epilogue |\r\n\r\n## GM notes\r\nKeep the kraken for later.\r\n" + } +} diff --git a/tests/fixtures/tables/golden.ts b/tests/fixtures/tables/golden.ts new file mode 100644 index 00000000..5b11bbd5 --- /dev/null +++ b/tests/fixtures/tables/golden.ts @@ -0,0 +1,52 @@ +/** + * The legacy table corpus as read by the parser before the phase 0 format + * extensions (plan-tables-everywhere): `npx tsx … tests/fixtures/tables/golden.ts` + * regenerates golden.json. tests/tableGolden.test.ts checks every table + * still reads, rolls and rewrites exactly the same. Only regenerate on purpose. + */ +import { readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { parseRandomTableWithReport, rollTable, writeRollTable, resolveTable } from "../../../src/random-tables/randomTable"; + +export const CORPUS_DIRS = ["tests/fixtures/tables", "tests/fixtures/sim-vault/tables", "tests/fixtures"]; +export const EXTRA_FILES = ["tests/fixtures/compat/legacy-table-1.5.6.md"]; + +export function corpus(root: string): { name: string; content: string }[] { + const out: { name: string; content: string }[] = []; + for (const dir of CORPUS_DIRS) { + for (const f of readdirSync(join(root, dir)).filter((n) => n.endsWith(".md")).sort()) { + const content = readFileSync(join(root, dir, f), "utf8").replace(/\r\n/g, "\n"); + if (dir === "tests/fixtures" && !/table/.test(f)) continue; + out.push({ name: `${dir}/${f}`, content }); + } + } + for (const f of EXTRA_FILES) out.push({ name: f, content: readFileSync(join(root, f), "utf8").replace(/\r\n/g, "\n") }); + // Every table again with CRLF line ends. + return [...out, ...out.map((c) => ({ name: `${c.name} (crlf)`, content: c.content.replace(/\n/g, "\r\n") }))]; +} + +/** What the old parser said about one note: the legacy fields only. */ +export function snapshot(content: string): unknown { + const { table, issues } = parseRandomTableWithReport(content); + const seq = [0.01, 0.2, 0.37, 0.5, 0.66, 0.81, 0.99]; + return { + table: { + dice: table.dice, + linkedFolder: table.linkedFolder ?? null, + description: table.description ?? null, + entries: table.entries.map((e) => ({ result: e.result, weight: e.weight, isLink: e.isLink ?? false, range: e.range ?? null })), + }, + issues: issues.map((i) => ({ code: i.code, row: i.row ?? null })), + mode: resolveTable(table).mode, + rolls: seq.map((u) => rollTable(table, () => u)?.index ?? null), + rewrite: writeRollTable(content, { dice: table.dice, rows: table.entries.map((entry, source) => ({ entry, source })), ranges: "keep" }), + }; +} + +if (process.argv[1]?.endsWith("golden.ts")) { + const root = process.cwd(); + const out: Record = {}; + for (const c of corpus(root)) out[c.name] = snapshot(c.content); + writeFileSync(join(root, "tests/fixtures/tables/golden.json"), JSON.stringify(out, null, 1) + "\n"); + console.log(`wrote ${Object.keys(out).length} tables`); +} diff --git a/tests/fixtures/tables/linked-folder-quoted.md b/tests/fixtures/tables/linked-folder-quoted.md new file mode 100644 index 00000000..06cc0080 --- /dev/null +++ b/tests/fixtures/tables/linked-folder-quoted.md @@ -0,0 +1,8 @@ +--- +dice: 4 +linkedFolder: "[[world/towns]]" +--- +| d4 | Result | Weight | +|---|---|---| +| 1–2 | [[Saltwatch]] | 2 | +| 3–4 | [[Rivermeet]] | 2 | diff --git a/tests/fixtures/tables/no-table.md b/tests/fixtures/tables/no-table.md new file mode 100644 index 00000000..3a7ed22d --- /dev/null +++ b/tests/fixtures/tables/no-table.md @@ -0,0 +1,4 @@ +--- +dice: 6 +--- +Nothing here yet. diff --git a/tests/fixtures/tables/old-no-frontmatter.md b/tests/fixtures/tables/old-no-frontmatter.md new file mode 100644 index 00000000..0eadfbce --- /dev/null +++ b/tests/fixtures/tables/old-no-frontmatter.md @@ -0,0 +1,5 @@ +| Result | Weight | +|---|---| +| alpha | 1 | +| beta | 0 | +| gamma | x | diff --git a/tests/fixtures/tables/old-result-weight.md b/tests/fixtures/tables/old-result-weight.md new file mode 100644 index 00000000..9e80df6f --- /dev/null +++ b/tests/fixtures/tables/old-result-weight.md @@ -0,0 +1,9 @@ +--- +dice: 6 +--- + +| Result | Weight | +|--------|--------| +| goblins | 2 | +| wolves | 1 | +| nothing | 3 | diff --git a/tests/fixtures/tables/roller-block.md b/tests/fixtures/tables/roller-block.md new file mode 100644 index 00000000..9c5e416b --- /dev/null +++ b/tests/fixtures/tables/roller-block.md @@ -0,0 +1,14 @@ +--- +dice: 10 +--- + +```duckmage-roller +``` + +Weather by day. + +| d10 | Result | Weight | +|---|---|---| +| 1–5 | clear | 5 | +| 6–9 | cloudy | 4 | +| 10 | storm | 1 | diff --git a/tests/fixtures/tables/too-many-rows.md b/tests/fixtures/tables/too-many-rows.md new file mode 100644 index 00000000..006f6fec --- /dev/null +++ b/tests/fixtures/tables/too-many-rows.md @@ -0,0 +1,10 @@ +--- +dice: 4 +--- +| d4 | Result | Weight | +|---|---|---| +| | a | 1 | +| | b | 1 | +| | c | 1 | +| | d | 1 | +| | e | 1 | diff --git a/tests/fixtures/tables/two-tables.md b/tests/fixtures/tables/two-tables.md new file mode 100644 index 00000000..86fd3450 --- /dev/null +++ b/tests/fixtures/tables/two-tables.md @@ -0,0 +1,10 @@ +| Name | Age | +|---|---| +| Bob | 3 | + +## Roll + +| Result | Weight | +|---|---| +| left | 1 | +| right | 1 | diff --git a/tests/fixtures/tables/unknown-header.md b/tests/fixtures/tables/unknown-header.md new file mode 100644 index 00000000..9b9885f2 --- /dev/null +++ b/tests/fixtures/tables/unknown-header.md @@ -0,0 +1,6 @@ +Some prose. + +| Thing | Odds | +|---|---| +| sword | 2 | +| shield | 1 | diff --git a/tests/tableAttributes.test.ts b/tests/tableAttributes.test.ts new file mode 100644 index 00000000..0c004589 --- /dev/null +++ b/tests/tableAttributes.test.ts @@ -0,0 +1,149 @@ +/** + * Phase 0 (plan-tables-everywhere §2.2): row attributes, the shared + * columns (Roll, Shown as, Once, When), decimal weights (T10), and that + * all of it survives an editor save. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + parseRandomTable, + parseRandomTableWithReport, + readTableWeight, + rollTable, + rowInfoOf, + writeRollTable, +} from "../src/random-tables/randomTable"; +import { conditionsFit, formatWhen, parseWhen } from "../src/random-tables/tableConditions"; + +const HEXES = `--- +dice: 20 +rows: any +shown-as: uncharted system +--- +# Drift sector hexes + +| d20 | Result | Weight | Roll | Shown as | Notes | +| --- | --- | ---: | --- | --- | --- | +| 1 | deep-space station | 1 | now | | known to every chart | +| 2–11 | [[Mainworlds]] | 10 | now | | charted | +| 12–15 | [[Mainworlds]] | 4 | on arrival | star system | somewhat known | +| 16–20 | [[Uncharted]] | 5 | on arrival | | uncharted | +`; + +describe("row attributes", () => { + it("every other column comes back per row, by its header; entries read as before", () => { + const t = parseRandomTable(HEXES); + expect(t.entries.map((e) => [e.result, e.weight, e.range])).toEqual([ + ["deep-space station", 1, "1"], ["Mainworlds", 10, "2–11"], ["Mainworlds", 4, "12–15"], ["Uncharted", 5, "16–20"], + ]); + // Entries carry only what they always did. + expect(Object.keys(t.entries[1]).sort()).toEqual(["isLink", "range", "result", "weight"]); + expect(rowInfoOf(t, 0).attrs).toEqual({ Roll: "now", Notes: "known to every chart" }); + expect(rowInfoOf(t, 2).attrs).toEqual({ Roll: "on arrival", "Shown as": "star system", Notes: "somewhat known" }); + }); + + it("a table with no extra columns has no rowInfo at all", () => { + const t = parseRandomTable("| d6 | Result | Weight |\n|---|---|---|\n| 1–6 | a | 1 |\n"); + expect(t.rowInfo).toBeUndefined(); + expect(rowInfoOf(t, 0)).toEqual({}); + }); + + it("Roll is the die column when it is the only one, the shared Roll column beside a die column", () => { + const old = parseRandomTable("| Roll | Result |\n|---|---|\n| 1–3 | a |\n| 4–6 | b |\n"); + expect(old.entries.map((e) => e.range)).toEqual(["1–3", "4–6"]); + expect(old.rowInfo).toBeUndefined(); + const t = parseRandomTable(HEXES); + expect(t.entries[3].range).toBe("16–20"); + expect(rowInfoOf(t, 3).roll).toBe("on arrival"); + // No die column, but every cell says now / on arrival: the shared column. + const shared = parseRandomTable("| Result | Weight | Roll |\n|---|---|---|\n| a | 1 | on arrival |\n| b | 2 | |\n| c | 1 | now |\n"); + expect(shared.entries.map((e) => e.range)).toEqual([undefined, undefined, undefined]); + expect(rowInfoOf(shared, 0).roll).toBe("on arrival"); + }); +}); + +describe("the shared columns", () => { + it("Roll: now (default) or on arrival; Shown as; the table's shown-as is the default", () => { + const t = parseRandomTable(HEXES); + expect(t.entries.map((_, i) => rowInfoOf(t, i).roll)).toEqual([undefined, undefined, "on arrival", "on arrival"]); + expect(rowInfoOf(t, 2).shownAs).toBe("star system"); + expect(rowInfoOf(t, 3).shownAs).toBeUndefined(); + expect(t.shownAs).toBe("uncharted system"); + }); + + it("Once: per world / per map / blank", () => { + const t = parseRandomTable("| d100 | Result | Weight | Once |\n|---|---|---|---|\n| 01 | [[The Silent Fleet]] | 1 | per world |\n| 02 | a | 1 | per map |\n| 03–100 | (nothing) | 98 | |\n"); + expect(t.entries.map((_, i) => rowInfoOf(t, i).once)).toEqual(["world", "map", undefined]); + }); + + it("unreadable Roll / Once / When are reported; Roll rolls now, Once repeats, a bad When never fires", () => { + const r = parseRandomTableWithReport("| d6 | Result | Weight | Roll | Once | When |\n|---|---|---|---|---|---|\n| 1–3 | a | 1 | sometimes | twice | phase: full moon |\n| 4–6 | b | 1 | | | zone: outer |\n"); + expect(r.issues.filter((i) => i.row).map((i) => [i.code, i.row])).toEqual([["roll-unknown", 1], ["once-unknown", 1], ["when-unknown", 1]]); + const info = rowInfoOf(r.table, 0); + expect(info.roll).toBeUndefined(); + expect(info.once).toBeUndefined(); + expect(conditionsFit(info.when, {})).toBe(false); + // Kept as typed. + expect(info.attrs).toEqual({ Roll: "sometimes", Once: "twice", When: "phase: full moon" }); + }); + + it("When: conditions by key, choices by comma, all must fit; keys the context doesn't know pass", () => { + const w = parseWhen("star: red dwarf, white dwarf; zone: outer; ring: 3–5; temperature: cold"); + expect(w.map((c) => c.key)).toEqual(["star", "zone", "ring", "temperature"]); + expect(conditionsFit(w, {})).toBe(true); + expect(conditionsFit(w, { star: "Red Dwarf", zone: "outer", ring: 4, temperature: 0.1 })).toBe(true); + expect(conditionsFit(w, { star: "yellow star" })).toBe(false); + expect(conditionsFit(w, { zone: "inner" })).toBe(false); + expect(conditionsFit(w, { ring: 6 })).toBe(false); + expect(conditionsFit(w, { temperature: 0.9 })).toBe(false); + expect(conditionsFit(parseWhen("type: gas-giant"), { type: "gas-giant" })).toBe(true); + expect(parseWhen("")).toEqual([]); + expect(parseWhen("any")).toEqual([]); + expect(formatWhen(parseWhen("zone: habitable, outer; star: red dwarf"))).toBe("zone: habitable, outer; star: red dwarf"); + }); +}); + +describe("decimal weights (T10)", () => { + it("3.5, 0.5, .25 and 50% read; anything else is reported and counts as 1", () => { + expect([readTableWeight("3.5"), readTableWeight("0.5"), readTableWeight(".25"), readTableWeight("50%"), readTableWeight("2")]).toEqual([3.5, 0.5, 0.25, 0.5, 2]); + expect(readTableWeight("abc")).toBeNaN(); + expect(readTableWeight("-1")).toBeNaN(); + const r = parseRandomTableWithReport("| Result | Weight |\n|---|---|\n| a | 3.5 |\n| b | 0.5 |\n| c | lots |\n"); + expect(r.table.entries.map((e) => e.weight)).toEqual([3.5, 0.5, 1]); + expect(r.issues.map((i) => i.code)).toEqual(["weight-unreadable"]); + }); + + it("decimal weights roll in proportion and give whole ranges on a die", () => { + const t = parseRandomTable("---\ndice: 8\n---\n| Result | Weight |\n|---|---|\n| a | 3.5 |\n| b | 0.5 |\n"); + let a = 0; + for (let i = 0; i < 8000; i++) if (rollTable(t, () => (i + 0.5) / 8000)?.entry.result === "a") a++; + expect(a / 8000).toBeCloseTo(3.5 / 4, 2); + const written = writeRollTable("---\ndice: 8\n---\n| Result | Weight |\n|---|---|\n| a | 3.5 |\n| b | 0.5 |\n", { dice: 8, rows: t.entries.map((entry, source) => ({ entry, source })), ranges: "regenerate" }); + expect(written).toContain("| 1–7 | a | 3.5 |"); + expect(written).toContain("| 8 | b | 0.5 |"); + }); +}); + +describe("an editor save keeps every column", () => { + it("reweighting, reordering and adding rows keep the attribute and shared cells as typed", () => { + const t = parseRandomTable(HEXES); + const rows = t.entries.map((entry, source) => ({ entry: { ...entry }, source })); + rows[1].entry.weight = 9; + [rows[2], rows[3]] = [rows[3], rows[2]]; + const next = writeRollTable(HEXES, { + dice: 20, + rows: [...rows, { entry: { result: "black hole", weight: 1 } }], + ranges: "regenerate", + }); + const back = parseRandomTable(next); + expect(back.entries.map((e) => e.result)).toEqual(["deep-space station", "Mainworlds", "Uncharted", "Mainworlds", "black hole"]); + expect(rowInfoOf(back, 1).attrs).toEqual({ Roll: "now", Notes: "charted" }); + expect(rowInfoOf(back, 2).roll).toBe("on arrival"); + expect(rowInfoOf(back, 3).attrs).toEqual({ Roll: "on arrival", "Shown as": "star system", Notes: "somewhat known" }); + expect(rowInfoOf(back, 4)).toEqual({}); + expect(back.rows).toBeUndefined(); + expect(back.shownAs).toBe("uncharted system"); + expect(next).toContain("# Drift sector hexes"); + expect(next.split("\n").find((l) => l.includes("black hole"))).toMatch(/^\| \S+ \| black hole \| 1 \| \| \| \|$/); + }); +}); diff --git a/tests/tableGolden.test.ts b/tests/tableGolden.test.ts new file mode 100644 index 00000000..198d0fbe --- /dev/null +++ b/tests/tableGolden.test.ts @@ -0,0 +1,28 @@ +/** + * Phase 0 of plan-tables-everywhere is additive: every table that read + * before reads, rolls and rewrites exactly the same. golden.json was made + * by the parser before the format extensions (tests/fixtures/tables/golden.ts). + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { corpus, snapshot } from "./fixtures/tables/golden"; + +const root = process.cwd(); +const golden = JSON.parse(readFileSync(join(root, "tests/fixtures/tables/golden.json"), "utf8")) as Record; + +describe("old tables read exactly as before (golden)", () => { + const tables = corpus(root); + + it("the corpus is the one the golden file was made from", () => { + expect(tables.map((t) => t.name).sort()).toEqual(Object.keys(golden).sort()); + expect(tables.length).toBeGreaterThan(30); + }); + + for (const t of tables) { + it(t.name, () => { + expect(snapshot(t.content)).toEqual(golden[t.name]); + }); + } +}); diff --git a/tests/tableHeadingRef.test.ts b/tests/tableHeadingRef.test.ts new file mode 100644 index 00000000..59f81c7b --- /dev/null +++ b/tests/tableHeadingRef.test.ts @@ -0,0 +1,81 @@ +/** + * Phase 0 (plan-tables-everywhere §2.2): a link like [[Tundra#Mix]] reads + * the table under that heading, so a table inside another note rolls + * without moving its data. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { headingSection, locateRollTable, parseRandomTable, parseRandomTableWithReport } from "../src/random-tables/randomTable"; +import { notesLookup, resolveOdds, resolveRoll } from "../src/random-tables/resolve"; + +const TUNDRA = `--- +hexmaker-biome: 1 +--- +# Tundra + +Cold and flat. + +## Mix + +| Type | Weight | +| --- | ---: | +| snow | 6 | +| grassland | 3 | +| hills | 1 | + +## Transitions + +| Next to | Becomes | +| --- | --- | +| forest | taiga | + +\`\`\` +## Not a heading +| Result | Weight | +| x | 1 | +\`\`\` + +### Deep + +| Result | Weight | +| --- | --- | +| frost giant | 1 | +`; + +describe("heading-addressed tables", () => { + it("finds the section under a heading, any case, up to the next heading of its level", () => { + const s = headingSection(TUNDRA, "mix")!; + expect(TUNDRA.slice(s.start, s.end)).toContain("| snow | 6 |"); + expect(TUNDRA.slice(s.start, s.end)).not.toContain("Transitions"); + // A deeper heading stays inside its parent's section. + const tr = headingSection(TUNDRA, "Transitions")!; + expect(TUNDRA.slice(tr.start, tr.end)).toContain("frost giant"); + // Headings in code fences don't count. + expect(headingSection(TUNDRA, "Not a heading")).toBeNull(); + }); + + it("reads the table under the heading (Tundra#Mix), weights and all", () => { + const t = parseRandomTable(TUNDRA, { heading: "Mix" }); + expect(t.entries.map((e) => [e.result, e.weight])).toEqual([["snow", 6], ["grassland", 3], ["hills", 1]]); + expect(parseRandomTable(TUNDRA, { heading: "Deep" }).entries.map((e) => e.result)).toEqual(["frost giant"]); + // Without a heading: the note's roll table as before (the first with a Result column). + expect(locateRollTable(TUNDRA)?.header).toEqual(["Result", "Weight"]); + }); + + it("a missing heading, or no table under it, is reported", () => { + const r = parseRandomTableWithReport(TUNDRA, { heading: "Weather" }); + expect(r.table.entries).toEqual([]); + expect(r.issues.map((i) => i.code)).toEqual(["heading-missing", "no-table"]); + const none = parseRandomTableWithReport("# A\n\n## Empty\n\nNothing.\n\n## B\n| Result |\n|---|\n| x |\n", { heading: "Empty" }); + expect(none.issues.map((i) => i.code)).toEqual(["no-table"]); + }); + + it("rolls through a link to it, like any table", () => { + const lookup = notesLookup({ "world/biomes/Tundra.md": TUNDRA, "tables/Ground.md": "---\ndice: 6\n---\n| d6 | Result | Weight |\n|---|---|---|\n| 1–6 | [[Tundra#Mix]] | 1 |\n" }); + const odds = resolveOdds("Ground", lookup); + expect(odds.map((o) => [o.value, Math.round(o.odds * 100)])).toEqual([["snow", 60], ["grassland", 30], ["hills", 10]]); + const r = resolveRoll("Ground", lookup, { seed: 4 }); + expect(["snow", "grassland", "hills"]).toContain(r.value); + expect(r.chain.map((s) => s.table)).toEqual(["tables/Ground.md", "world/biomes/Tundra.md#Mix"]); + }); +}); diff --git a/tests/tableMigration.test.ts b/tests/tableMigration.test.ts index b158596f..2b167932 100644 --- a/tests/tableMigration.test.ts +++ b/tests/tableMigration.test.ts @@ -169,7 +169,7 @@ describe("Check tables report", () => { expect(check.problems.map((p) => p.path)).toEqual(["tables/bad.md", "tables/beach.md", "tables/cool words.md"]); const text = formatTableReport(new Date("2026-10-10T12:00:00Z"), check); expect(text).toContain("### [[tables/bad|bad]]"); - expect(text).toContain("isn't a whole number"); + expect(text).toContain("isn't a number"); const p = await writeTableReport(app(v), SCOPE, text); expect(p).toBe("tables/_table-check.md"); expect(v.files.get(p)).toBe(text); diff --git a/tests/tableResolve.test.ts b/tests/tableResolve.test.ts new file mode 100644 index 00000000..4677d14a --- /dev/null +++ b/tests/tableResolve.test.ts @@ -0,0 +1,188 @@ +/** + * Phase 1 (plan-tables-everywhere §2.3): one resolver for nested and + * seeded rolls, with a loop guard; its odds are the odds it rolls. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { parseRandomTable } from "../src/random-tables/randomTable"; +import { + DEFAULT_MAX_DEPTH, + LOOP_MARK, + chainLabel, + findRow, + memoryLookup, + notesLookup, + resolveOdds, + resolveRoll, + skippedRows, +} from "../src/random-tables/resolve"; +import { mulberry32 } from "../packages/hex-wfc/src/rng"; + +const T = (body: string, fm = "") => parseRandomTable(`${fm ? `---\n${fm}\n---\n` : ""}| d | Result | Weight | Notes |\n|---|---|---|---|\n${body}`); + +const NOTES = { + "tables/Sector hexes.md": "---\ndice: 20\n---\n| d20 | Result | Weight | Roll | Notes |\n|---|---|---|---|---|\n| 1 | deep-space station | 1 | | known |\n| 2–15 | [[Mainworlds]] | 14 | | charted |\n| 16–20 | [[Uncharted]] | 5 | on arrival | uncharted |\n", + "tables/Mainworlds.md": "---\ndice: 6\nrows: terrain\n---\n| d6 | Result | Weight | Mainworld | Size |\n|---|---|---|---|---|\n| 1–4 | garden world | 4 | terrestrial planet | 13×13 |\n| 5–6 | ocean world | 2 | ocean planet | |\n", + "tables/Uncharted.md": "---\ndice: 12\n---\n| d12 | Result | Weight |\n|---|---|---|\n| 1–6 | [[Mainworlds]] | 6 |\n| 7–8 | rogue planet | 2 |\n| 9–10 | black hole | 2 |\n| 11–12 | (nothing) | 2 |\n", +}; + +describe("resolveRoll: nesting", () => { + const lookup = notesLookup(NOTES); + + it("a row that links a table is rolled through, with the chain and the attributes along it", () => { + const seen = new Set(); + for (let seed = 1; seed <= 300; seed++) { + const r = resolveRoll("Sector hexes", lookup, { seed }); + seen.add(r.value); + if (r.value === "garden world") { + // Mainworlds says rows: terrain, so its plain text is a terrain. + expect(r.kind).toBe("terrain"); + const tables = r.chain.map((s) => s.table); + expect([["tables/Sector hexes.md", "tables/Mainworlds.md"], ["tables/Sector hexes.md", "tables/Uncharted.md", "tables/Mainworlds.md"]]).toContainEqual(tables); + expect(r.attrs.Mainworld).toBe("terrestrial planet"); + expect(r.attrs.Size).toBe("13×13"); + expect(chainLabel(r)).toMatch(/^Sector hexes → Mainworlds → garden world$|^Sector hexes → Uncharted → Mainworlds → garden world$/); + } + } + expect([...seen].sort()).toEqual(["", "black hole", "deep-space station", "garden world", "ocean world", "rogue planet"]); + }); + + it("an inner row's cell wins over an outer one's", () => { + const r = resolveRoll("Sector hexes", lookup, { seed: 1, rand: () => 0.3 }); + expect(r.attrs.Notes).toBe("charted"); + expect(r.attrs.Mainworld).toBeDefined(); + }); + + it("(nothing) is its own kind", () => { + const t = memoryLookup({ N: T("| 1 | (nothing) | 1 | |") }); + expect(resolveRoll("N", t, { seed: 1 })).toMatchObject({ kind: "nothing", value: "" }); + }); + + it("with terrains, plain text naming one is a terrain in the palette's spelling", () => { + const r = resolveRoll("Mainworlds", lookup, { seed: 2, terrains: ["Garden World", "Ocean World"] }); + expect(r.kind).toBe("terrain"); + expect(["Garden World", "Ocean World"]).toContain(r.value); + }); + + it("on arrival rows stop there when asked (deferArrival), with what the hex shows", () => { + const lk = notesLookup({ ...NOTES, "tables/Sector hexes.md": NOTES["tables/Sector hexes.md"].replace("| on arrival |", "| on arrival |").replace("| Roll | Notes |", "| Roll | Notes |") }); + const r = resolveRoll("Sector hexes", lk, { rand: () => 0.99, deferArrival: true }); + expect(r.kind).toBe("deferred"); + expect(r.value).toBe("Uncharted"); + // Not deferring (the Tables view, today's generators): rolled through. + expect(resolveRoll("Sector hexes", lk, { rand: () => 0.99 }).kind).not.toBe("deferred"); + }); +}); + +describe("resolveRoll: seeding", () => { + const lookup = notesLookup(NOTES); + it("the same seed gives the same chain; another seed may not", () => { + for (let seed = 1; seed <= 50; seed++) { + expect(resolveRoll("Sector hexes", lookup, { seed })).toEqual(resolveRoll("Sector hexes", lookup, { seed })); + } + const chains = new Set(Array.from({ length: 50 }, (_, i) => JSON.stringify(resolveRoll("Sector hexes", lookup, { seed: i + 1 }).chain))); + expect(chains.size).toBeGreaterThan(3); + }); + + it("a given stream is used as is (nested rolls draw from it in turn)", () => { + const a = resolveRoll("Uncharted", lookup, { rand: mulberry32(9) }); + const b = resolveRoll("Uncharted", lookup, { rand: mulberry32(9) }); + expect(a).toEqual(b); + }); + + it("a table that rolls by its die reports the face", () => { + const r = resolveRoll("Mainworlds", lookup, { rand: () => 0.0 }); + expect(r.chain[0].face).toBe(1); + }); +}); + +describe("resolveRoll: the loop guard", () => { + it("a table that links itself, or a cycle, stops with ⟲ instead of hanging", () => { + const self = memoryLookup({ A: T("| 1 | [[A]] | 1 | |") }); + const r = resolveRoll("A", self, { seed: 1 }); + expect(r.kind).toBe("loop"); + expect(r.value).toBe(`${LOOP_MARK} A`); + const cycle = memoryLookup({ A: T("| 1 | [[B]] | 1 | |"), B: T("| 1 | [[A]] | 1 | |") }); + const c = resolveRoll("A", cycle, { seed: 1 }); + expect(c.kind).toBe("loop"); + expect(c.chain.map((s) => s.table)).toEqual(["A", "B"]); + expect(resolveOdds("A", cycle)).toEqual([{ kind: "loop", value: `${LOOP_MARK} A`, odds: 1 }]); + }); + + it("a chain deeper than the cap stops too (default 5)", () => { + const tables: Record> = {}; + for (let i = 0; i < 9; i++) tables[`L${i}`] = T(`| 1 | [[L${i + 1}]] | 1 | |`); + tables.L9 = T("| 1 | bottom | 1 | |"); + const lk = memoryLookup(tables); + const r = resolveRoll("L0", lk, { seed: 1 }); + expect(r.kind).toBe("loop"); + expect(r.chain).toHaveLength(DEFAULT_MAX_DEPTH); + expect(resolveRoll("L0", lk, { seed: 1, maxDepth: 10 }).value).toBe("bottom"); + }); + + it("a loop row in a terrain-only roll is left out, not rolled into", () => { + const lk = memoryLookup({ A: T("| 1 | [[A]] | 5 | |\n| 2 | rock | 1 | |") }); + for (let seed = 1; seed <= 20; seed++) expect(resolveRoll("A", lk, { seed, terrains: ["rock"], onlyTerrains: true }).value).toBe("rock"); + expect(skippedRows("A", lk, { terrains: ["rock"], onlyTerrains: true })).toEqual([{ table: "A", index: 0, result: "A", why: "dead-end" }]); + }); +}); + +describe("When, Once and terrain-only: left out and renormalised", () => { + const lk = memoryLookup({ + Z: parseRandomTable("| Result | Weight | When | Once |\n|---|---|---|---|\n| hot rock | 3 | zone: inner | |\n| garden | 2 | | |\n| ice ball | 5 | zone: outer | |\n| relic | 1 | | per world |\n| crystal | 4 | | |\n"), + }); + + it("rows whose When doesn't fit never come up; the rest keep their proportions", () => { + const odds = resolveOdds("Z", lk, { zone: "inner" }); + expect(odds.map((o) => [o.value, o.odds])).toEqual([["crystal", 0.4], ["hot rock", 0.3], ["garden", 0.2], ["relic", 0.1]]); + for (let seed = 1; seed <= 200; seed++) expect(resolveRoll("Z", lk, { seed, zone: "inner" }).value).not.toBe("ice ball"); + }); + + it("used Once rows are left out (isUsed: the ledger)", () => { + const isUsed = (_t: string, i: number) => i === 3; + expect(resolveOdds("Z", lk, { zone: "outer", isUsed }).some((o) => o.value === "relic")).toBe(false); + const r = resolveRoll("Z", lk, { rand: () => 0.99, zone: "inner" }); + expect(r.value).toBe("crystal"); + const relic = resolveRoll("R", memoryLookup({ R: parseRandomTable("| Result | Weight | Once |\n|---|---|---|\n| relic | 1 | per map |\n") }), { seed: 1 }); + expect(relic.once).toEqual({ table: "R", index: 0, scope: "map" }); + }); + + it("with onlyTerrains, rows that aren't terrains of the palette are left out and listed", () => { + const odds = resolveOdds("Z", lk, { terrains: ["garden", "crystal"], onlyTerrains: true }); + expect(odds.map((o) => [o.value, o.odds])).toEqual([["crystal", 4 / 6], ["garden", 2 / 6]]); + expect(skippedRows("Z", lk, { terrains: ["garden", "crystal"], onlyTerrains: true }).map((s) => [s.result, s.why])).toEqual([ + ["hot rock", "not-terrain"], ["ice ball", "not-terrain"], ["relic", "not-terrain"], + ]); + }); +}); + +describe("resolveOdds is what resolveRoll rolls", () => { + it("nested odds multiply, sum to 1, and match 20 000 seeded rolls", () => { + const lookup = notesLookup(NOTES); + const odds = resolveOdds("Sector hexes", lookup); + expect(odds.reduce((a, o) => a + o.odds, 0)).toBeCloseTo(1, 12); + const garden = odds.find((o) => o.value === "garden world")!.odds; + // 14/20 · 4/6 + 5/20 · 6/12 · 4/6 + expect(garden).toBeCloseTo(14 / 20 * 4 / 6 + 5 / 20 * 6 / 12 * 4 / 6, 12); + const n = 20000; + const counts = new Map(); + for (let i = 0; i < n; i++) { + const r = resolveRoll("Sector hexes", lookup, { seed: i + 1 }); + counts.set(r.value, (counts.get(r.value) ?? 0) + 1); + } + for (const o of odds) { + const got = (counts.get(o.value) ?? 0) / n; + expect(Math.abs(got - o.odds)).toBeLessThan(4 * Math.sqrt((o.odds * (1 - o.odds)) / n) + 1e-3); + } + }); +}); + +describe("findRow", () => { + it("finds the row naming a result in a table or the tables it links, with its attributes", () => { + const lookup = notesLookup(NOTES); + expect(findRow("Sector hexes", "Ocean World", lookup)?.attrs).toEqual({ Notes: "charted", Mainworld: "ocean planet" }); + expect(findRow("Sector hexes", "nowhere", lookup)).toBeUndefined(); + // Loops are guarded here too. + expect(findRow("A", "x", memoryLookup({ A: T("| 1 | [[A]] | 1 | |") }))).toBeUndefined(); + }); +}); diff --git a/tests/tableTypedRows.test.ts b/tests/tableTypedRows.test.ts new file mode 100644 index 00000000..205529db --- /dev/null +++ b/tests/tableTypedRows.test.ts @@ -0,0 +1,88 @@ +/** + * Phase 0/1 (plan-tables-everywhere §2.2, §2.5): `rows:` per table, each + * cell's kind detected from what it links to (T3), and the picker seam. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { parseRandomTable, parseRandomTableWithReport } from "../src/random-tables/randomTable"; +import { cellKind, memoryLookup, noteKind, notesLookup, rowTypeProblems, tableFitsWant } from "../src/random-tables/resolve"; + +const table = (fm: string, rows: string) => `---\n${fm}\n---\n| d6 | Result | Weight |\n| --- | --- | ---: |\n${rows}`; + +describe("rows: and friends in the frontmatter", () => { + it("reads rows, terrain-type, shown-as and linked-folder", () => { + const t = parseRandomTable(table("dice: 6\nrows: terrain\nterrain-type: world, gas-giant\nshown-as: uncharted system", "| 1–6 | garden world | 1 |")); + expect(t.rows).toBe("terrain"); + expect(t.terrainTypes).toEqual(["world", "gas-giant"]); + expect(t.shownAs).toBe("uncharted system"); + const lf = parseRandomTable(table("dice: 6\nrows: note\nlinked-folder: \"[[Space/Stations]]\"", "| 1–6 | [[Highport]] | 1 |")); + expect(lf.linkedFolder).toBe("Space/Stations"); + expect(lf.rows).toBe("note"); + }); + + it("rows: any (or none) is the default; plurals read; an unknown word is reported and read as any", () => { + expect(parseRandomTable(table("dice: 6\nrows: any", "| 1 | a | 1 |")).rows).toBeUndefined(); + expect(parseRandomTable(table("dice: 6", "| 1 | a | 1 |")).rows).toBeUndefined(); + expect(parseRandomTable(table("dice: 6\nrows: notes", "| 1 | a | 1 |")).rows).toBe("note"); + const r = parseRandomTableWithReport(table("dice: 6\nrows: spaceships", "| 1–6 | a | 1 |")); + expect(r.table.rows).toBeUndefined(); + expect(r.issues.map((i) => i.code)).toContain("rows-unknown"); + // It still rolls: rows: is a constraint, never a parser switch. + expect(r.table.entries.map((e) => e.result)).toEqual(["a"]); + }); +}); + +describe("cell kinds (T3: from what the cell links to)", () => { + const notes = { + "tables/Mainworlds.md": "---\ndice: 6\n---\n| d6 | Result | Weight |\n|---|---|---|\n| 1–6 | garden world | 1 |\n", + "tables/Plain list.md": "| Result | Weight |\n|---|---|\n| a | 1 |\n", + "gen/Desert.md": "---\nhex-wfc: 1\n---\n# Desert\n", + "gen/Drift.md": "---\nhexmaker-recipe: 1\n---\n", + "wf/NPC.md": "---\nresults-folder: npcs\ntemplate-file: t.md\n---\n| Table | Rolls | Label |\n|---|---|---|\n", + "places/Highport.md": "# Highport\nA station.\n", + }; + const lookup = notesLookup(notes); + const t = parseRandomTable("| Result | Weight |\n|---|---|\n| [[Mainworlds]] | 1 |\n| [[Plain list]] | 1 |\n| [[Desert]] | 1 |\n| [[Drift]] | 1 |\n| [[NPC]] | 1 |\n| [[Highport]] | 1 |\n| [[Nowhere]] | 1 |\n| procedural:orbits | 1 |\n| (nothing) | 1 |\n| garden world | 1 |\n| a ghost | 1 |\n"); + + it("tables, generators (generator notes, recipes, workflows, ids), notes, nothing, terrain, text", () => { + const kinds = t.entries.map((e) => cellKind(t, e, lookup, { terrains: ["Garden World"] })); + expect(kinds.map((k) => k.kind)).toEqual(["table", "table", "generator", "generator", "generator", "note", "note", "generator", "nothing", "terrain", "text"]); + // A terrain comes back in the palette's spelling. + expect(kinds[9].value).toBe("Garden World"); + }); + + it("noteKind reads a note's own text", () => { + expect(noteKind(notes["tables/Mainworlds.md"])).toBe("table"); + expect(noteKind(notes["gen/Desert.md"])).toBe("generator"); + expect(noteKind(notes["places/Highport.md"])).toBe("note"); + }); + + it("a linked-folder table's rows are notes in that folder", () => { + const lf = parseRandomTable("---\nlinkedFolder: places\n---\n| Result | Weight |\n|---|---|\n| [[Highport]] | 1 |\n"); + expect(cellKind(lf, lf.entries[0], lookup)).toEqual({ kind: "note", value: "places/Highport" }); + }); + + it("rowTypeProblems: cells that don't fit rows: are reported, never dropped", () => { + const mixed = parseRandomTable("---\nrows: note\n---\n| Result | Weight |\n|---|---|\n| [[Highport]] | 1 |\n| loose text | 1 |\n| [[Mainworlds]] | 1 |\n"); + const p = rowTypeProblems(mixed, lookup); + expect(p.map((x) => x.index)).toEqual([1]); + expect(p[0].message).toMatch(/plain text.*rows are note/); + expect(mixed.entries).toHaveLength(3); + const terr = parseRandomTable("---\nrows: terrain\n---\n| Result | Weight |\n|---|---|\n| garden world | 1 |\n| crystal world | 1 |\n"); + expect(rowTypeProblems(terr, memoryLookup({}), { terrains: ["garden world"] }).map((x) => x.message)).toEqual([ + "Row 2 (\"crystal world\") isn't a terrain of the palette, but the table's rows are terrain.", + ]); + expect(rowTypeProblems(parseRandomTable("| Result | Weight |\n|---|---|\n| a | 1 |\n"), lookup)).toEqual([]); + }); +}); + +describe("tableFitsWant (the seam for pickers)", () => { + it("exact for a wanted rows:, any for rows: any (sorts after), no with a reason otherwise", () => { + expect(tableFitsWant({ rows: "note" }, { rows: ["note"] })).toEqual({ fit: "exact" }); + expect(tableFitsWant({}, { rows: ["note"] })).toEqual({ fit: "any" }); + expect(tableFitsWant({ rows: "biome" }, { rows: ["note"] })).toEqual({ fit: "no", why: "its rows are biome, not note" }); + expect(tableFitsWant({ rows: "terrain", terrainTypes: ["star"] }, { rows: ["terrain"], terrainType: "star" }).fit).toBe("exact"); + expect(tableFitsWant({ rows: "terrain", terrainTypes: ["world"] }, { rows: ["terrain"], terrainType: "star" }).fit).toBe("no"); + expect(tableFitsWant({ rows: "terrain" }, { rows: ["terrain"], terrainType: "star" }).fit).toBe("exact"); + }); +}); From 064ea56d1780ae2d202c6da89b967e31754ffe73 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 11:24:49 -0400 Subject: [PATCH 306/558] feat(space): Star scatter and Orbits roll on World types through generator roles (SP1, tables everywhere phase 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - worldgen/tableRoles.ts: the engine role schema (Sector hexes; Star; Inner, Habitable and Outer orbits), a TableSource per generation, and rollRole / roleOdds through the table resolver. No table, or no row that is a terrain of the palette: equal odds over the palette's typed terrains, said in the warnings. Rows that aren't terrains of the palette are never placed and are named in the warnings (never dropped silently). - space/worldTypesSource.ts: the adapter over today's World types note (worlds, Stars, Sector features become in-memory role tables; filters become When). Same odds as before, new draws (T4). - Star scatter and Orbits read their roles; the built-in weights (WORLD_WEIGHTS, FEATURE_WEIGHTS, STAR_WEIGHTS, ZONE_WEIGHTS, the type weights, the 4% roll) and the name rules (ZONE_HINTS, BODY_NAMES, MAINWORLD_HINTS) are gone. The static Star option no longer lists shipped star names. - World types: a Mainworld column (format 3). A sector row names the body Orbits makes its mainworld; blank = the world itself. Older notes get the shipped rows' mainworlds once, after a backup; typed values are never changed. - A "World types" generator option (Default / a table / None) picks the table; "Edit world types…" sits in that row. - The World types editor's preview rolls through the same source, fallbacks and rolls as the generators, for a chosen palette (F3: preview odds = real odds), and lists rows the generators can't place. - README and help: what World types now really does; the new table columns. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 +- dev/space-gen-preview.ts | 13 +- package.json | 4 +- src/hex-map/help.md | 4 +- src/space/WorldTypeStore.ts | 27 +++- src/space/WorldTypesModal.ts | 129 +++++++++------ src/space/worldTypePresets.ts | 23 +-- src/space/worldTypes.ts | 52 ++++-- src/space/worldTypesSource.ts | 192 ++++++++++++++++++++++ src/worldgen/NewMapSetupModal.ts | 8 +- src/worldgen/procedural/orbits.ts | 157 +++++------------- src/worldgen/procedural/starScatter.ts | 69 ++------ src/worldgen/registry.ts | 25 ++- src/worldgen/tableRoles.ts | 214 +++++++++++++++++++++++++ tests/generatorRoles.test.ts | 173 ++++++++++++++++++++ tests/orbitsTables.test.ts | 148 +++++++++++++++++ tests/proceduralGenerators.test.ts | 16 +- tests/regionContext.test.ts | 29 ++-- tests/starScatterTables.test.ts | 131 +++++++++++++++ tests/worldTypeStars.test.ts | 16 +- tests/worldTypes.test.ts | 12 +- tests/worldgenFirstMap.test.ts | 10 ++ 22 files changed, 1169 insertions(+), 293 deletions(-) create mode 100644 src/space/worldTypesSource.ts create mode 100644 src/worldgen/tableRoles.ts create mode 100644 tests/generatorRoles.test.ts create mode 100644 tests/orbitsTables.test.ts create mode 100644 tests/starScatterTables.test.ts diff --git a/README.md b/README.md index c6b28263..55c3ad16 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it; a land neighbour always shows as at least a small strip or corner patch on its side (a swamp to the south-west, say). - **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one; the map draws a faint dashed tether from each moon to the world or gas giant beside it, hidden with the paths; the PNG export draws it too when it includes paths), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). -- **World types** (Advanced: Terrain generators) — which worlds the space generators place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types` (**Default space** ships, with the odds Star scatter and Orbits have always used; **Restore default** puts them back). Each row is a world (a terrain of your palette) with a **Weight** and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature**. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows, and a preview rolls the table for a map, orbit, star and temperature and shows how often each world comes up next to its odds. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. +- **World types** — which worlds Star scatter and Orbits place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types`. Star scatter and Orbits roll on it: their **World types** option picks the table (**Default**: Default space, or your first table if you deleted it; **None**: equal odds over the palette's worlds, stars and planets, and the generator says so). **Default space** ships with the same odds the two generators used before they read the table (the draws differ, so an old seed gives a different map); **Restore default** puts it back. Each row is a world (a terrain of your palette) with a **Weight** (decimals are fine) and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature** (the generators don't know a temperature yet, so it limits nothing there). A sector row's **Mainworld** names the body Orbits makes that system's mainworld (`ocean world` → `ocean planet`; blank: the world itself, if the system palette has it). No generator guesses anything from a terrain's name any more. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain. The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. A row whose world isn't a terrain of the palette being generated is never placed, and the generator's warnings (and the editor's preview) name it. If no row fits the palette at all, the generator uses equal odds and says so. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows. The preview rolls for a palette, a map (sector or system), an orbit and a star exactly the way the generators do, so the odds it shows are the odds you get. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once, and notes made before the Mainworld column get the shipped sector worlds' mainworlds filled in once (after a backup; a Mainworld you typed is never changed). Rows that can't be read are reported and left in the note as written. Editing needs Build or God. - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. @@ -200,6 +200,14 @@ Table notes are meant to be rolled by hand, too. Each row shows its roll range f What you see in the roll column is what you get: the plugin rolls the same ranges. A range you type by hand is never overwritten; a blank range cell is filled in from the weights. Weight 0 (`—`) is never rolled. d100 accepts `01–05` and `00`; d66 is supported (`dice: d66`). Columns are found by name (Range/Roll/dN, Result/Entry, Weight/W), and extra columns and text around the table are kept. Older `| Result | Weight |` tables still work; **Add roll ranges to tables** upgrades them (after making a backup), and **Check tables** writes a report of anything that couldn't be read to `_table-check.md` in the tables folder. +More a table can say, all optional (a table without them reads exactly as before): + +- **Weights** can be decimals (`3.5`, `0.5`) or percentages (`50%` is 0.5). +- **Extra columns** are kept and shown read-only in the Random Tables view; they travel with a row when something rolls on it (a world's **Size**, **Generator**, **Mainworld**…). +- Four column names will mean the same in every table: **Roll** (`now`, or `on arrival` for a row that stays unknown until someone visits), **Shown as** (what such a hex shows until then), **Once** (`per world` or `per map`) and **When** (`zone: outer`, `star: red dwarf, white dwarf`, `ring: 2–4`, `temperature: cold`, `type: gas-giant`; separate several with `;`; a row whose When doesn't fit is rolled again). For now they are read, kept and checked (**Check tables** lists a value it can't read); rolling on arrival, the once-only record and When in the Random Tables view come later. +- `rows:` in the frontmatter says what the rows are (`text`, `note`, `table`, `generator`, `terrain`, `biome` or `any`, the default), and `terrain-type:` narrows terrain rows (`star`). It is read and checked now; table pickers will use it to offer only tables that fit. +- `linked-folder:` works like `linkedFolder:`. + ### Workflows view Open via the Workflows tab in the Random Tables panel. diff --git a/dev/space-gen-preview.ts b/dev/space-gen-preview.ts index b04f6f4c..dd1daaa0 100644 --- a/dev/space-gen-preview.ts +++ b/dev/space-gen-preview.ts @@ -6,12 +6,14 @@ */ import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS, SPACE_PATH_TYPES, SYSTEM_PATH_TYPES } from "../src/palettes/presets"; import { starScatter, STAR_SCATTER_OPTIONS } from "../src/worldgen/procedural/starScatter"; -import { orbits, ORBITS_OPTIONS } from "../src/worldgen/procedural/orbits"; +import { orbits, orbitsOptions } from "../src/worldgen/procedural/orbits"; import type { GenerationContext, ProcGrid, ProcOption, Side } from "../src/worldgen/procedural/common"; import { planetSurface, REGION_DETAIL_OPTIONS } from "../src/worldgen/procedural/planetSurface"; import { DEFAULT_TERRAIN_PALETTE, DEFAULT_PATH_TYPES } from "../src/constants"; import { routeContextPaths } from "../src/worldgen/procedural/contextPaths"; import { drawPreview } from "../src/worldgen/preview"; +import { worldTypesSource } from "../src/space/worldTypesSource"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; type Gen = "sector" | "system" | "region"; /** Region detail: the parent hex and its N/E/S/W neighbours (terrain names from Expanded). */ @@ -46,7 +48,7 @@ const pathColors = new Map([...SPACE_PATH_TYPES, ...SYSTEM_PATH_TYPES, ...DEFAUL function controls(): void { const box = document.getElementById("controls")!; box.replaceChildren(); - const opts: ProcOption[] = state.gen === "sector" ? STAR_SCATTER_OPTIONS : state.gen === "system" ? ORBITS_OPTIONS : REGION_DETAIL_OPTIONS; + const opts: ProcOption[] = state.gen === "sector" ? STAR_SCATTER_OPTIONS : state.gen === "system" ? orbitsOptions(SPACE_SYSTEM_TERRAINS) : REGION_DETAIL_OPTIONS; if (state.gen === "region") { const names = ["", ...DEFAULT_TERRAIN_PALETTE.map((t) => t.name)]; const pick = (label: string, value: string, set: (v: string) => void) => { @@ -96,6 +98,9 @@ function withPaths; paths: { type: string return { ...r, paths: [...r.paths, ...routeContextPaths(r.cells, DEFAULT_TERRAIN_PALETTE, grid, carry, seed)] }; } +/** The shipped World types table: the generators roll on it like in a vault (SP1). */ +const DEFAULT_SPACE = { name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }; + function render(): void { const grid: ProcGrid = { cols: state.cols, rows: state.rows, offset: { x: 0, y: 0 }, stagger: "odd", orientation: state.orientation, @@ -106,9 +111,9 @@ function render(): void { for (let i = 0; i < 6; i++) { const seed = state.seed + i; const r = state.gen === "sector" - ? starScatter(SPACE_SECTOR_TERRAINS, grid, seed, state.options, "Jump route") + ? starScatter(SPACE_SECTOR_TERRAINS, grid, seed, state.options, "Jump route", worldTypesSource(DEFAULT_SPACE, SPACE_SECTOR_TERRAINS)) : state.gen === "system" - ? orbits(SPACE_SYSTEM_TERRAINS, grid, seed, state.options, "Orbit") + ? orbits(SPACE_SYSTEM_TERRAINS, grid, seed, state.options, "Orbit", undefined, worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS)) : withPaths(planetSurface(DEFAULT_TERRAIN_PALETTE, grid, seed, state.options, regionContext()), grid, seed); const fig = document.createElement("figure"); const canvas = document.createElement("canvas"); diff --git a/package.json b/package.json index ee3da522..a22593ca 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/hex-map/help.md b/src/hex-map/help.md index d4b8f11c..c5e79752 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -175,7 +175,9 @@ Neighbouring regions share one set of hex numbers: a new region carries on from A road or river that ends on the edge of a region, next to where the neighbour's road of the same type ends, is drawn on to the shared edge on both maps, so the two join up. -**World types** (space; Advanced: Terrain generators). Which worlds Star scatter and Orbits place, how often, and how each world's own map is made, is a table note in `{world folder}/world-types` (**Default space** ships with the usual odds; **Restore default** puts them back). Each row: a **World** (a terrain of the palette), a **Weight**, optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base**. **Edit world types…** (in the Star scatter and Orbits options, or the command) edits the rows and previews how often each world comes up. The same note also has a **Stars** table (the star Orbits picks when its Star choice is Random, by **Weight**) and a **Sector features** table (Star scatter's special hexes, each with a **Chance** per star system hex, like `1 in 50` or `2%`); the editor has a tab and a preview for each. Needs Build or God. +**World types** (space). Star scatter and Orbits roll on a World types table note in `{world folder}/world-types`: which worlds they place, how often, and how each world's own map is made. Their **World types** option picks the table (**Default** is Default space, which ships with the usual odds; **None** is equal odds, and the generator says so). Each row: a **World** (a terrain of the palette), a **Weight** (decimals are fine), optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**), a sector world's **Mainworld** (the body Orbits makes its mainworld) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base**. A row that isn't a terrain of the palette is never placed, and the warnings name it. **Edit world types…** (Advanced: Terrain generators; in the Star scatter and Orbits options, or the command) edits the rows, and its preview rolls for a palette, map, orbit and star just as the generators do, so its odds are the real odds. The same note also has a **Stars** table (the star Orbits picks when its Star choice is Random, by **Weight**) and a **Sector features** table (Star scatter's special hexes, each with a **Chance** per star system hex, like `1 in 50` or `2%`); the editor has a tab and a preview for each. Needs Build or God. + +**More in a table** (all optional; old tables read the same). Weights can be decimals (`3.5`) or percentages. Extra columns are kept and shown in the Random Tables view. The columns **Roll** (`now` / `on arrival`), **Shown as**, **Once** (`per world` / `per map`) and **When** (`zone: outer; star: red dwarf`), and `rows:` in the frontmatter (text, note, table, generator, terrain, biome or any), are read and checked now (**Check tables**) and used by later features. With generators on, new maps can also use the built-in **biomes and presets** (Grassland, Taiga, Swamp, Archipelago, Volcanic and more). They place terrain by type, so they work with any palette whose terrains have types. diff --git a/src/space/WorldTypeStore.ts b/src/space/WorldTypeStore.ts index 98905dd0..82f0b2c9 100644 --- a/src/space/WorldTypeStore.ts +++ b/src/space/WorldTypeStore.ts @@ -10,7 +10,10 @@ * - Hand edits are read back live (vault events); rows that can't be read * are reported once per edit, never used, and kept as written. * - A note from before stars and sector features were rows (format 1) - * is given the shipped Stars and Sector features tables once, when read. + * is given the shipped Stars and Sector features tables once, when read; + * one from before the Mainworld column (format 1 or 2) the shipped + * rows' mainworlds (backed up first). + * - source(): a table as the space generators' role tables (SP1). * - Every change is told to onChange listeners. */ @@ -37,6 +40,8 @@ import { type WorldTypeTable, } from "./worldTypes"; import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "./worldTypePresets"; +import { chosenWorldTypes, defaultWorldTypesName, worldTypesSource } from "./worldTypesSource"; +import type { TableSource } from "../worldgen/tableRoles"; interface Entry { path: string; @@ -147,6 +152,23 @@ export class WorldTypeStore { return this.find(name)?.problems ?? []; } + /** What the generators' "Default" World types means now (Default space, else the first table). */ + defaultName(): string | undefined { + return defaultWorldTypesName(this.list().map((t) => t.name), DEFAULT_WORLD_TYPES); + } + + /** + * The space generators' role tables from the World types option's value + * (SP1), for a palette. `source` undefined: no table (None, or none at + * all), so equal odds; `missing`: the picked table isn't there. + */ + sourceFor(value: string | undefined, palette: readonly (string | { name: string })[]): { source?: TableSource; missing?: string } { + const name = chosenWorldTypes(value, this.list().map((t) => t.name), this.defaultName()); + if (!name) return {}; + const t = this.get(name); + return t ? { source: worldTypesSource(t, palette) } : { missing: name }; + } + hasDefault(name: string): boolean { return name.trim().toLowerCase() === DEFAULT_WORLD_TYPES.toLowerCase(); } @@ -285,9 +307,10 @@ export class WorldTypeStore { private async load(f: TFile): Promise { let content = await this.plugin.app.vault.read(f); if (this.lastContent.get(f.path) === content && this.entries.has(f.path)) return false; - const upgraded = upgradeWorldTypes(content, DEFAULT_WORLD_TYPE_EXTRAS); + const upgraded = upgradeWorldTypes(content, { ...DEFAULT_WORLD_TYPE_EXTRAS, rows: DEFAULT_WORLD_TYPE_ROWS }); if (upgraded !== content) { try { + await this.backup("upgrade", { [f.path]: content }); await this.plugin.app.vault.modify(f, upgraded); content = upgraded; } catch (e) { diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts index da36db8e..9671e51d 100644 --- a/src/space/WorldTypesModal.ts +++ b/src/space/WorldTypesModal.ts @@ -3,7 +3,11 @@ * the space generators place, how often, and what each world's own map is * made with — plus its Stars (Orbits' random star) and Sector features * (Star scatter's special hexes), one tab each. Each tab has a small - * preview that rolls its table and shows what comes up. + * preview that rolls its table and shows what comes up: for a palette, + * through the same role tables and rolls as Star scatter and Orbits + * (worldTypesSource.ts, tableRoles.ts), so its odds are the generators' + * odds (F3). Rows the generators can't place (not terrains of the + * palette) are listed under it, never dropped silently. * * Rows are edited as their note cells (the same reading as the note), so * anything typed here reads back the same from the note. Rows the note @@ -29,24 +33,23 @@ import { readFeatureCells, readStarCells, readWorldTypeCells, - rollSectorFeatures, - rollStars, - rollWorldTypes, - sectorFeatureOdds, starCells, - starOdds, worldTypeCells, - worldTypeOdds, type OrbitZone, type SectorFeatureRow, type StarTypeRow, type WorldTypeColumn, - type WorldTypeContext, type WorldTypeExtras, type WorldTypeMap, type WorldTypeRow, type WorldTypeTable, } from "./worldTypes"; +import { worldTypesSource } from "./worldTypesSource"; +import { ZONE_ROLES, roleOdds, rollRole, type RoleId } from "../worldgen/tableRoles"; +import { starScatterOffered, starScatterRoles } from "../worldgen/procedural/starScatter"; +import { orbitRoles, orbitsFits } from "../worldgen/procedural/orbits"; +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; +import type { TerrainColor } from "../types"; /** Why world types can't be edited from this map now, or undefined. */ export function worldTypesEditLock(plugin: HexmakerPlugin, mapName: string | undefined): string | undefined { @@ -74,6 +77,7 @@ const PLACEHOLDERS: Record = { Palette: "same", Base: "none", Notes: "", + Mainworld: "same", Star: "red dwarf", Feature: "black hole", Chance: "1 in 50", @@ -81,7 +85,7 @@ const PLACEHOLDERS: Record = { /** Columns shown on a row's first line (what is picked, and where); the rest are its map setup. */ const PICK_COLUMNS: WorldTypeColumn[] = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature"]; -const SETUP_COLUMNS: WorldTypeColumn[] = ["Size", "Generator", "Options", "Palette", "Base", "Notes"]; +const SETUP_COLUMNS: WorldTypeColumn[] = ["Mainworld", "Size", "Generator", "Options", "Palette", "Base", "Notes"]; const col = (c: WorldTypeColumn) => WORLD_TYPE_COLUMNS.indexOf(c); @@ -123,7 +127,7 @@ export class WorldTypesModal extends HexmakerModal { private saveBtn!: HTMLButtonElement; private statusEl!: HTMLElement; private tabButtons = new Map(); - private preview: { map: WorldTypeMap | ""; zone: OrbitZone | ""; star: string; temperature: string; n: number } = { map: "", zone: "", star: "", temperature: "", n: 200 }; + private preview: { map: WorldTypeMap; zone: OrbitZone; star: string; palette: string; n: number } = { map: "sector", zone: "habitable", star: "", palette: "", n: 200 }; /** `mapName`: the map it was opened for (work mode, preview's map kind). `tab`: the tab to open on. */ constructor(app: App, private plugin: HexmakerPlugin, private mapName?: string, table?: string, previewMap?: WorldTypeMap, tab: WorldTypesTab = "worlds") { @@ -480,6 +484,21 @@ export class WorldTypesModal extends HexmakerModal { // ── preview ──────────────────────────────────────────────────────────── + /** + * The palette the preview rolls for: the one picked, else the map's own, + * else the first palette the previewed generator fits (by terrain types). + */ + private previewPalette(): { name: string; terrains: TerrainColor[] } | undefined { + const palettes = this.plugin.settings.terrainPalettes; + const fits = this.preview.map === "system" ? orbitsFits : starScatterOffered; + const mapPalette = this.mapName ? this.plugin.getMap(this.mapName)?.paletteName : undefined; + const p = palettes.find((x) => x.name === this.preview.palette) + ?? palettes.find((x) => x.name === mapPalette && fits(x.terrains)) + ?? palettes.find((x) => fits(x.terrains)) + ?? palettes[0]; + return p ? { name: p.name, terrains: p.terrains } : undefined; + } + private renderPreview(): void { const el = this.previewEl; if (!el) return; @@ -494,18 +513,41 @@ export class WorldTypesModal extends HexmakerModal { s.addEventListener("change", () => { set(s.value); this.renderPreview(); }); }; if (this.tab === "worlds") { - select("Map", [["", "Any"], ["sector", "Sector"], ["system", "System"]], p.map, (v) => { p.map = v as WorldTypeMap | ""; }); - select("Orbit", [["", "Any"], ...ORBIT_ZONES.map((z): [string, string] => [z, z[0].toUpperCase() + z.slice(1)])], p.zone, (v) => { p.zone = v as OrbitZone | ""; }); - select("Star", [["", "Any"], ...this.suggestions(["star"]).map((s): [string, string] => [s, s])], p.star, (v) => { p.star = v; }); - select("Temperature", [["", "Any"], ["0.1", "Cold"], ["0.3", "Cool"], ["0.5", "Mild"], ["0.7", "Warm"], ["0.9", "Hot"]], p.temperature, (v) => { p.temperature = v; }); + select("Map", [["sector", "Sector (Star scatter)"], ["system", "System (Orbits)"]], p.map, (v) => { p.map = v as WorldTypeMap; p.palette = ""; }); + if (p.map === "system") { + select("Orbit", ORBIT_ZONES.map((z): [string, string] => [z, z[0].toUpperCase() + z.slice(1)]), p.zone, (v) => { p.zone = v as OrbitZone; }); + select("Star", [["", "Any"], ...this.suggestions(["star"]).map((s): [string, string] => [s, s])], p.star, (v) => { p.star = v; }); + } + } else { + p.map = this.tab === "stars" ? "system" : "sector"; } + const palette = this.previewPalette(); + if (!palette) { + el.createDiv({ cls: "setting-item-description", text: "No palettes yet." }); + return; + } + select("Palette", this.plugin.settings.terrainPalettes.map((x): [string, string] => [x.name, x.name]), palette.name, (v) => { p.palette = v; }); const rollChoices: [string, string][] = this.tab === "features" ? [["100", "100 systems"], ["1000", "1000 systems"], ["10000", "10000 systems"]] : [["100", "100"], ["200", "200"], ["1000", "1000"]]; if (!rollChoices.some(([v]) => Number(v) === p.n)) p.n = Number(rollChoices[1][0]); select("Rolls", rollChoices, String(p.n), (v) => { p.n = Number(v); }); - const table = this.table(); + // The generators' own roles, fallback and rolls (worldgen/tableRoles.ts). + const source = worldTypesSource(this.table(), palette.terrains); + const role: RoleId = this.tab === "stars" ? "star" : p.map === "system" ? ZONE_ROLES[p.zone] : "sector-hexes"; + const fallback = role === "sector-hexes" + ? starScatterRoles(palette.terrains)?.worlds ?? [] + : role === "star" ? orbitRoles(palette.terrains)?.stars ?? [] : orbitRoles(palette.terrains)?.bodies ?? []; + const ctx = role === "star" || role === "sector-hexes" ? {} : { zone: p.zone, ...(p.star ? { star: p.star } : {}) }; + const { odds, notes } = roleOdds(source, role, ctx, fallback); + const rolled = new Map(); + for (let i = 0; i < p.n; i++) { + const pick = rollRole(source, role, { ...ctx, rand: mulberry32(i + 1) }, fallback); + const k = pick ? pick.terrain.toLowerCase() : ""; + rolled.set(k, (rolled.get(k) ?? 0) + 1); + } + const list = () => el.createDiv({ cls: "duckmage-world-types-dist" }); const bar = (parent: HTMLElement, name: string, n: number, odds: string) => { const r = parent.createDiv({ cls: "duckmage-world-types-dist-row" }); @@ -516,49 +558,30 @@ export class WorldTypesModal extends HexmakerModal { r.createSpan({ cls: "duckmage-world-types-dist-odds", text: odds }); }; const pct = (x: number) => `${Math.round(x * 1000) / 10}%`; + const showNotes = () => { + // Never silently: rows the generator can't place, and equal-odds fallbacks. + if (notes.length) el.createEl("p", { cls: "duckmage-world-types-problems", text: notes.join(" ") }); + }; - if (this.tab === "stars") { - const odds = starOdds(table); - if (!odds.length) { - el.createDiv({ cls: "setting-item-description", text: "No star rows: Orbits picks the star itself." }); - return; - } - const rolled = new Map(rollStars(table, {}, p.n).map((r) => [r.star.toLowerCase(), r.count])); - const l = list(); - for (const o of odds) bar(l, o.star, rolled.get(o.star.toLowerCase()) ?? 0, `odds ${pct(o.odds)}`); + if (!odds.length) { + el.createDiv({ cls: "setting-item-description", text: `Nothing on ${palette.name} fits: nothing would be placed here.` }); + showNotes(); return; } - + const l = list(); if (this.tab === "features") { - const { features, total } = sectorFeatureOdds(table); - if (!features.length) { - el.createDiv({ cls: "setting-item-description", text: "No feature rows: every star system hex stays a system." }); - return; + const featureNames = new Set(this.features().map((f) => f.feature.trim().toLowerCase())); + let systems = 0; + let systemOdds = 0; + for (const o of odds) { + const k = o.terrain.toLowerCase(); + if (featureNames.has(k)) bar(l, o.terrain, rolled.get(k) ?? 0, `${formatChance(o.odds)} (${pct(o.odds)})`); + else { systems += rolled.get(k) ?? 0; systemOdds += o.odds; } } - const rolled = new Map(rollSectorFeatures(table, {}, p.n).map((r) => [r.feature.toLowerCase(), r.count])); - const l = list(); - let special = 0; - for (const f of features) { - const n = rolled.get(f.feature.toLowerCase()) ?? 0; - special += n; - bar(l, f.feature, n, `${formatChance(f.chance)} (${pct(f.chance)})`); - } - bar(l, "an ordinary system", p.n - special, pct(1 - total)); - return; + bar(l, "an ordinary system", systems, pct(systemOdds)); + } else { + for (const o of odds) bar(l, o.terrain || "(nothing)", rolled.get(o.terrain.toLowerCase()) ?? 0, `odds ${pct(o.odds)}`); } - - const ctx: Omit = {}; - if (p.map) ctx.map = p.map; - if (p.zone) ctx.zone = p.zone; - if (p.star) ctx.starType = p.star; - if (p.temperature) ctx.temperature = Number(p.temperature); - const odds = worldTypeOdds(table, ctx); - if (!odds.length) { - el.createDiv({ cls: "setting-item-description", text: "No row fits: nothing would be placed here." }); - return; - } - const rolled = new Map(rollWorldTypes(table, ctx, p.n).map((r) => [r.world.toLowerCase(), r.count])); - const l = list(); - for (const o of odds) bar(l, o.world, rolled.get(o.world.toLowerCase()) ?? 0, `odds ${pct(o.odds)}`); + showNotes(); } } diff --git a/src/space/worldTypePresets.ts b/src/space/worldTypePresets.ts index d3b2fe4e..b270f016 100644 --- a/src/space/worldTypePresets.ts +++ b/src/space/worldTypePresets.ts @@ -8,7 +8,9 @@ * in (their name tables for the shipped Space palettes) and the shipped * palettes' submap defaults: * - sector rows: Star scatter's mainworld weights (garden 3, ocean 2, …), - * each opening as a 13×13 Orbits system on Space - System; + * each opening as a 13×13 Orbits system on Space - System, with the + * body Orbits makes its mainworld (the pairing Orbits used to guess + * from the names, now written down as data); * - system rows: Orbits' zone weights per body (a body a zone didn't list * weighed 0.5 there), the rocky ones opening as 20×14 Planet surface * maps tuned to the planet; @@ -28,10 +30,11 @@ import type { OrbitZone, SectorFeatureRow, StarTypeRow, WorldTypeRow } from "./w const SYSTEM_PALETTE = "Space - System"; const SURFACE_PALETTE = "Expanded"; -const system = (world: string, weight: number): WorldTypeRow => ({ +const system = (world: string, weight: number, mainworld: string): WorldTypeRow => ({ world, weight, map: "sector", + mainworld, size: { cols: { lo: 13, hi: 13 }, rows: { lo: 13, hi: 13 } }, generator: { id: "procedural:orbits" }, palette: SYSTEM_PALETTE, @@ -63,14 +66,14 @@ function body(world: string, w: Record, setup: Surface = {}): export const DEFAULT_WORLD_TYPE_ROWS: readonly WorldTypeRow[] = [ // Sector: a hex's star system, typed by its mainworld (Star scatter). - system("garden world", 3), - system("ocean world", 2), - system("desert world", 3), - system("ice world", 2), - system("barren world", 3.5), - system("molten world", 1), - system("asteroid belt", 1.5), - system("gas giant", 1), + system("garden world", 3, "terrestrial planet"), + system("ocean world", 2, "ocean planet"), + system("desert world", 3, "desert planet"), + system("ice world", 2, "ice planet"), + system("barren world", 3.5, "rocky planet"), + system("molten world", 1, "molten planet"), + system("asteroid belt", 1.5, "asteroid belt"), + system("gas giant", 1, "gas giant"), // System: one body per orbit, by zone (Orbits). ...body("terrestrial planet", { inner: 0.5, habitable: 4, outer: 0.5 }, surface("65", "temperate", "ocean")), ...body("ocean planet", { inner: 0.5, habitable: 3, outer: 0.5 }, surface("85", "lush", "ocean")), diff --git a/src/space/worldTypes.ts b/src/space/worldTypes.ts index 7ed605a1..77d767b0 100644 --- a/src/space/worldTypes.ts +++ b/src/space/worldTypes.ts @@ -80,8 +80,8 @@ import { } from "../overworld/biomeClimate"; export const WORLD_TYPES_MARKER = "hexmaker-world-types"; -/** 2: the note also has the Stars and Sector features tables. */ -export const WORLD_TYPES_FORMAT = 2; +/** 2: the note also has the Stars and Sector features tables. 3: a Mainworld column. */ +export const WORLD_TYPES_FORMAT = 3; /** The shipped table's name (and note name). */ export const DEFAULT_WORLD_TYPES = "Default space"; @@ -126,6 +126,12 @@ export interface WorldTypeRow { stars?: string[]; /** Only at this temperature (0 cold … 1 hot). Unset: any. */ temperature?: ClimateRange; + /** + * A sector world's mainworld: the body Orbits makes that system's + * mainworld ("ocean world" → "ocean planet"). Unset: the world itself, + * when the system palette has it. + */ + mainworld?: string; /** The world's submap size. Unset: no preference. */ size?: WorldSizeRange; /** The world's submap generator. Unset: no preference. */ @@ -658,11 +664,11 @@ const readList = (raw: string) => { export const WORLD_TYPES_HELP = [ "> [!info] World types", - "> Which worlds the space generators place and how often, and what each world's own map is made with. **World** is a terrain of the palette. **Weight** (1 if blank) is its odds against the other rows that fit; 0 never rolls it. Limits, all optional: **Map** sector (Star scatter's systems) or system (Orbits), **Orbit** inner, habitable, outer or rings like 2–4, **Stars** a list of star terrains, **Temperature** cold, cool, mild, warm, hot or 0.2–0.5. For the world's map: **Size** like 20×14 or 16–24 × 10–14, **Generator** a generator note link or id, **Options** like water=85, climate=lush, **Palette** and **Base** terrain. The same world can have several rows. Add, edit or delete rows freely.", + "> Which worlds the space generators place and how often, and what each world's own map is made with. **World** is a terrain of the palette. **Weight** (1 if blank) is its odds against the other rows that fit; 0 never rolls it. Limits, all optional: **Map** sector (Star scatter's systems) or system (Orbits), **Orbit** inner, habitable, outer or rings like 2–4, **Stars** a list of star terrains, **Temperature** cold, cool, mild, warm, hot or 0.2–0.5. For the world's map: **Mainworld** (sector worlds) the body that is that system's mainworld, **Size** like 20×14 or 16–24 × 10–14, **Generator** a generator note link or id, **Options** like water=85, climate=lush, **Palette** and **Base** terrain. The same world can have several rows. Add, edit or delete rows freely.", ]; /** The note table's columns, in order (the editor keeps each row as these cells). */ -export const WORLD_TYPE_COLUMNS = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; +export const WORLD_TYPE_COLUMNS = ["World", "Weight", "Map", "Orbit", "Stars", "Temperature", "Mainworld", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; export type WorldTypeColumn = (typeof WORLD_TYPE_COLUMNS)[number]; type Column = WorldTypeColumn; const COLUMNS = WORLD_TYPE_COLUMNS; @@ -673,6 +679,7 @@ const HEADER_ALIASES: Record = { orbit: "Orbit", zone: "Orbit", orbits: "Orbit", "orbit zone": "Orbit", stars: "Stars", star: "Stars", "star types": "Stars", temperature: "Temperature", temp: "Temperature", + mainworld: "Mainworld", "main world": "Mainworld", mainworlds: "Mainworld", size: "Size", generator: "Generator", preset: "Generator", options: "Options", @@ -852,6 +859,8 @@ function readRow(cells: string[], cols: (Column | undefined)[]): { row?: WorldTy if (r.problem) return { problem: `temperature ${r.problem}` }; if (r.range) row.temperature = r.range; } + const mw = nameCell(cell("Mainworld")); + if (mw) row.mainworld = mw; const s = cell("Size"); if (s) { const size = readSize(s); @@ -927,6 +936,7 @@ export function worldTypeCells(r: WorldTypeRow): string[] { formatOrbit(r), (r.stars ?? []).join(", "), r.temperature ? formatClimateRange(r.temperature, TEMPERATURE_WORDS) : "", + r.mainworld ?? "", r.size ? formatSize(r.size) : "", formatGenerator(r.generator), formatOptions(r.options), @@ -1030,17 +1040,35 @@ export function updateWorldTypes(content: string, rows: readonly WorldTypeRow[], } /** - * A format 1 note (written before stars and sector features were rows) - * given the shipped Stars and Sector features tables it doesn't have, and - * marked format 2, so it keeps placing what the generators always did. - * Anything else (format 2, or a note without the marker) comes back as is. + * Sector rows without a Mainworld get the shipped row's (same world, any + * case), so a note written before the column keeps the old pairing + * ("ocean world" opens on an "ocean planet"). Rows the shipped table + * doesn't have, or that say something already, are left as they are. + */ +export function withShippedMainworlds(rows: readonly WorldTypeRow[], shipped: readonly WorldTypeRow[]): WorldTypeRow[] { + return copyWorldTypeRows(rows).map((r) => { + if (r.mainworld || r.map === "system") return r; + const s = shipped.find((d) => d.map !== "system" && d.mainworld && lc(d.world) === lc(r.world)); + return s?.mainworld ? { ...r, mainworld: s.mainworld } : r; + }); +} + +/** + * An older note brought up to date, so it keeps placing what the + * generators always did: a format 1 note (written before stars and sector + * features were rows) is given the shipped Stars and Sector features + * tables; a format 1 or 2 note (before the Mainworld column) is given the + * shipped rows' mainworlds. It is marked with the current format. Anything + * else (current, or a note without the marker) comes back as is. */ -export function upgradeWorldTypes(content: string, defaults: Required): string { +export function upgradeWorldTypes(content: string, defaults: Required & { rows?: readonly WorldTypeRow[] }): string { const p = parseWorldTypes(content); if (p.format === undefined || p.format >= WORLD_TYPES_FORMAT) return content; - const next = updateWorldTypes(content, p.rows, { - stars: p.stars ? undefined : defaults.stars, - features: p.features ? undefined : defaults.features, + const old = p.format < 2; + const rows = defaults.rows ? withShippedMainworlds(p.rows, defaults.rows) : p.rows; + const next = updateWorldTypes(content, rows, { + stars: old && !p.stars ? defaults.stars : undefined, + features: old && !p.features ? defaults.features : undefined, }); const eol = next.includes("\r\n") ? "\r\n" : "\n"; const marked = withFormat(next.replace(/\r\n?/g, "\n").split("\n")).join(eol); diff --git a/src/space/worldTypesSource.ts b/src/space/worldTypesSource.ts new file mode 100644 index 00000000..def555df --- /dev/null +++ b/src/space/worldTypesSource.ts @@ -0,0 +1,192 @@ +/** + * SP1: the World types note drives Star scatter and Orbits. An adapter + * that reads a world types table (worldTypes.ts) as the engines' role + * tables (worldgen/tableRoles.ts), so the generators roll on it through + * the table resolver today, before the space tables of phase 3 exist. + * + * The note's tables become in-memory random tables: + * - Mainworlds: the worlds rows for a sector (Map sector or blank). + * - Sector hexes: one row per sector feature (its Chance as the weight, + * so a star system hex is that feature with exactly that chance), and + * the rest of the odds a row that rolls on Mainworlds. Features that + * aren't terrains of the palette are left out (their chance goes to the + * systems, as before) and listed in the notes. + * - Stars: the Stars rows. + * - Inner / Habitable / Outer orbits: the worlds rows for a system (Map + * system or blank) whose Orbit allows that zone; ring, Stars and + * Temperature limits become When conditions. + * Every row keeps its setup columns (Mainworld, Size, Generator, …) as + * row attributes. + * + * The same odds as the old pick functions (pickWorldType, pickStar, + * pickSectorFeature), different draws (T4). + * + * Pure: no Obsidian imports. + */ + +import type { RandomTable, RandomTableEntry, RowInfo } from "../random-tables/randomTable"; +import { findRow, isNothing, memoryLookup } from "../random-tables/resolve"; +import type { TableCondition } from "../random-tables/tableConditions"; +import { EQUAL_ODDS, type RoleId, type TableSource } from "../worldgen/tableRoles"; +import type { ProcOption } from "../worldgen/procedural/common"; +import { + WORLD_TYPE_COLUMNS, + worldTypeCells, + type OrbitZone, + type WorldTypeRow, + type WorldTypeTable, +} from "./worldTypes"; + +const MAINWORLDS = "Mainworlds"; +const SECTOR_HEXES = "Sector hexes"; +const STARS = "Stars"; +const ZONE_TABLES: Record = { inner: "Inner orbits", habitable: "Habitable orbits", outer: "Outer orbits" }; +const ROLE_TABLE: Record = { + "sector-hexes": SECTOR_HEXES, + star: STARS, + "inner-orbits": ZONE_TABLES.inner, + "habitable-orbits": ZONE_TABLES.habitable, + "outer-orbits": ZONE_TABLES.outer, +}; + +/** The columns carried as row attributes. */ +const ATTR_COLUMNS = ["Mainworld", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; + +const lc = (s: string) => s.trim().toLowerCase(); + +function attrsOf(r: WorldTypeRow): Record { + const cells = worldTypeCells(r); + const out: Record = {}; + for (const c of ATTR_COLUMNS) { + const v = cells[WORLD_TYPE_COLUMNS.indexOf(c)]; + if (v) out[c] = v; + } + return out; +} + +/** A worlds row's limits other than map and zone, as When conditions. */ +function conditionsOf(r: WorldTypeRow): TableCondition[] { + const out: TableCondition[] = []; + if (r.distance) out.push({ key: "ring", range: { ...r.distance } }); + if (r.stars?.length) out.push({ key: "star", values: r.stars.map(lc) }); + if (r.temperature) out.push({ key: "temperature", range: { ...r.temperature } }); + return out; +} + +function worldsTable(rows: readonly WorldTypeRow[]): RandomTable { + const entries: RandomTableEntry[] = []; + const rowInfo: RowInfo[] = []; + for (const r of rows) { + if (!r.world.trim()) continue; + entries.push({ result: r.world.trim(), weight: r.weight ?? 1 }); + const info: RowInfo = {}; + const attrs = attrsOf(r); + if (Object.keys(attrs).length) info.attrs = attrs; + const when = conditionsOf(r); + if (when.length) info.when = when; + rowInfo.push(info); + } + return { dice: 0, rows: "terrain", entries, rowInfo }; +} + +const paletteName = (t: string | { name: string }) => (typeof t === "string" ? t : t.name); + +// ── the space generators' "World types" option ──────────────────────────── + +/** Option key: which World types table Star scatter and Orbits roll on. */ +export const WORLD_TYPES_KEY = "worldTypes"; +/** The default table: "Default space" if there is one, else the first. */ +export const WORLD_TYPES_DEFAULT = "(default)"; +/** No table: equal odds (said in the generator's warnings). */ +export const WORLD_TYPES_NONE = "(none)"; + +/** The option, for these table names (`fallbackName` = what "Default" means now). */ +export function worldTypesOption(names: readonly string[], fallbackName?: string): ProcOption { + return { + key: WORLD_TYPES_KEY, + label: "World types", + choices: [ + { value: WORLD_TYPES_DEFAULT, label: fallbackName ? `Default (${fallbackName})` : "Default" }, + ...names.map((n) => ({ value: n, label: n })), + { value: WORLD_TYPES_NONE, label: "None (equal odds)" }, + ], + default: WORLD_TYPES_DEFAULT, + }; +} + +/** The table name an option value means (undefined = none). */ +export function chosenWorldTypes(value: string | undefined, names: readonly string[], fallbackName: string | undefined): string | undefined { + if (value === WORLD_TYPES_NONE) return undefined; + if (!value || value === WORLD_TYPES_DEFAULT) return fallbackName; + return value; +} + +/** What "Default" means: the shipped table's name if there is one, else the first table. */ +export function defaultWorldTypesName(names: readonly string[], shipped: string): string | undefined { + return names.find((n) => lc(n) === lc(shipped)) ?? names[0]; +} + +/** + * The role tables a world types table gives for a palette. `label` names + * it in notes (default "World types: "). + */ +export function worldTypesSource(table: WorldTypeTable, palette: readonly (string | { name: string })[], label = `World types: ${table.name}`): TableSource { + const terrains = palette.map(paletteName); + const inPalette = (n: string) => terrains.some((t) => lc(t) === lc(n)); + + const sectorRows = table.rows.filter((r) => r.map !== "system"); + const systemRows = table.rows.filter((r) => r.map !== "sector"); + const mainworlds = worldsTable(sectorRows); + const anyMainworld = sectorRows.some((r) => (r.weight ?? 1) > 0 && (inPalette(r.world) || isNothing(r.world))); + + // Sector hexes: features by their chance, then the systems. + const featureNotes: string[] = []; + const features: RandomTableEntry[] = []; + let left = 1; + const seen = new Set(); + for (const f of table.features ?? []) { + const name = f.feature.trim(); + if (!name || !(f.chance > 0)) continue; + if (!inPalette(name)) { featureNotes.push(name); continue; } + const key = lc(name); + const chance = Math.max(0, Math.min(f.chance, left)); + left -= chance; + if (seen.has(key)) { + const e = features.find((x) => lc(x.result) === key); + if (e) e.weight += chance; + continue; + } + seen.add(key); + if (chance > 0) features.push({ result: terrains.find((t) => lc(t) === key) ?? name, weight: chance }); + } + const sectorHexes: RandomTable = { + dice: 0, + rows: "terrain", + entries: [ + ...features, + ...(left > 1e-12 ? [{ result: anyMainworld ? MAINWORLDS : EQUAL_ODDS, weight: left, isLink: true }] : []), + ], + }; + + const stars: RandomTable | undefined = table.stars?.length + ? { dice: 0, rows: "terrain", entries: table.stars.filter((s) => s.star.trim()).map((s) => ({ result: s.star.trim(), weight: s.weight ?? 1 })) } + : undefined; + + const tables: Record = { [MAINWORLDS]: mainworlds, [SECTOR_HEXES]: sectorHexes }; + if (stars) tables[STARS] = stars; + for (const z of Object.keys(ZONE_TABLES) as OrbitZone[]) { + tables[ZONE_TABLES[z]] = worldsTable(systemRows.filter((r) => !r.zones?.length || r.zones.includes(z))); + } + const lookup = memoryLookup(tables); + + return { + label, + lookup, + terrains, + tableFor: (role) => (role === "star" && !stars ? undefined : ROLE_TABLE[role]), + rowAttrs: (role, name) => findRow(role === "sector-hexes" ? MAINWORLDS : ROLE_TABLE[role], name, lookup)?.attrs, + notes: (role) => role === "sector-hexes" && featureNotes.length + ? [`${label}: Sector features not a terrain of this palette, so never placed: ${[...new Set(featureNotes)].join(", ")}.`] + : [], + }; +} diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index 0d0e6b90..aaa0f1b4 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -22,6 +22,7 @@ import { renderPreviewLegend } from "../hex-map/terrainLegend"; import { IMAGE_EXTENSIONS, attachImageDropZone, getIconUrl, importBinaryFileToVault, mapBgImportFolder, selectAllOnFocus, slugify } from "../utils"; import { FileLinkSuggestModal } from "../hex-map/FileLinkSuggestModal"; import { WorldTypesModal } from "../space/WorldTypesModal"; +import { WORLD_TYPES_KEY } from "../space/worldTypesSource"; import { STAR_SCATTER_ID } from "./procedural/starScatter"; import { ORBITS_ID } from "./procedural/orbits"; import { SIZE_PRESETS, type SizePreset } from "./sizePresets"; @@ -611,8 +612,10 @@ export class NewMapSetupModal extends HexmakerModal { this.options.sea = seaHint.side; this.seaFromNeighbour = true; } + let worldTypesRow: HTMLElement | undefined; for (const opt of kind ? kindOptions(kind, terrains, this.plugin.getPathTypes(paletteSelect.value)) : []) { const r = this.row(optsBox, opt.label); + if (opt.key === WORLD_TYPES_KEY) worldTypesRow = r; const sel = this.labelled(r, r.createEl("select")); for (const c of opt.choices) sel.createEl("option", { value: c.value, text: c.label }); sel.value = this.options[opt.key] ?? opt.default; @@ -630,9 +633,10 @@ export class NewMapSetupModal extends HexmakerModal { refresh(); }); } - // Space generators: the worlds they place come from a world types table. + // Space generators: the worlds they place come from a world types table + // (the World types option picks it; this edits it). if (kind && (kind.id === STAR_SCATTER_ID || kind.id === ORBITS_ID) && hasFeature(this.plugin.settings, "generators")) { - const r = this.row(optsBox, "World types"); + const r = worldTypesRow ?? this.row(optsBox, "World types"); const btn = r.createEl("button", { text: "Edit world types…" }); btn.addEventListener("click", () => { new WorldTypesModal(this.app, this.plugin, this.origin?.map, undefined, kind.id === ORBITS_ID ? "system" : "sector").open(); diff --git a/src/worldgen/procedural/orbits.ts b/src/worldgen/procedural/orbits.ts index fc91b002..1e1fcce7 100644 --- a/src/worldgen/procedural/orbits.ts +++ b/src/worldgen/procedural/orbits.ts @@ -6,14 +6,14 @@ import { distance, gridKeys, ofType, - typeIndex, - weightedPick, type GenerationContext, type ProcGrid, type ProcOption, type ProcPath, type ProcResult, } from "./common"; +import { ZONE_ROLES, roleOdds, rollRole, type TableSource } from "../tableRoles"; +import { ORBIT_ZONES, orbitZone } from "../../space/worldTypes"; /** * Star-system "orbits": a star at the centre, then one body per orbit ring @@ -28,6 +28,12 @@ import { * role has its own type too — moon, comet, station, starport, jump point, * jump limit — so it is the Type column, never a terrain's name, that * decides what goes where. + * + * Which star, and which body on each orbit, are rolled on the Star and + * Inner / Habitable / Outer orbits roles (tableRoles.ts): the World types + * table when one is given, else equal odds over the palette's stars and + * bodies. The sector hex's row says which body is the mainworld (its + * Mainworld column). No terrain name is special. */ export const ORBITS_ID = "procedural:orbits"; @@ -36,14 +42,8 @@ export const ORBITS_OPTIONS: ProcOption[] = [ { key: "star", label: "Star", - choices: [ - { value: "random", label: "Random" }, - { value: "yellow star", label: "Yellow star" }, - { value: "red dwarf", label: "Red dwarf" }, - { value: "blue giant", label: "Blue giant" }, - { value: "white dwarf", label: "White dwarf" }, - { value: "brown dwarf", label: "Brown dwarf" }, - ], + // The palette's own stars are added per palette (orbitsOptions). + choices: [{ value: "random", label: "Random" }], default: "random", }, { @@ -61,7 +61,7 @@ export const ORBITS_OPTIONS: ProcOption[] = [ /** * Orbits' options for a palette: the Star choice lists that palette's own * stars (star-typed terrains), so it only offers what it can place. With - * no palette given, the shipped star list. + * no palette given, only Random. */ export function orbitsOptions(terrains?: TerrainColor[]): ProcOption[] { if (!terrains) return ORBITS_OPTIONS; @@ -72,46 +72,6 @@ export function orbitsOptions(terrains?: TerrainColor[]): ProcOption[] { }); } -/** Galactic mix: red dwarfs dominate. */ -const STAR_WEIGHTS: Record = { - "red dwarf": 6, - "yellow star": 3, - "brown dwarf": 1.5, - "white dwarf": 1, - "blue giant": 0.5, -}; - -const ZONE_WEIGHTS: Record> = { - inner: { "molten planet": 4, "rocky planet": 4, "desert planet": 2, "asteroid belt": 0.5 }, - habitable: { "terrestrial planet": 4, "ocean planet": 3, "desert planet": 3, "rocky planet": 2, "asteroid belt": 1 }, - outer: { "gas giant": 4, "ice giant": 3, "ice planet": 3, "asteroid belt": 1.5, "rocky planet": 1 }, -}; - -const BODY_NAMES = [ - "terrestrial planet", "ocean planet", "desert planet", "ice planet", "rocky planet", - "molten planet", "gas giant", "ice giant", "asteroid belt", -]; - -type Zone = "inner" | "habitable" | "outer"; - -/** - * Zone weights for bodies the tables above don't name, by name hint (the - * type vocabulary is coarse: "world" covers lava rocks and ocean planets - * alike), else by type. - */ -const ZONE_HINTS: { re: RegExp; w: Record }[] = [ - { re: /molten|lava|magma|volcan|inferno|ember|cinder|scorch/i, w: { inner: 4, habitable: 0.5, outer: 0.2 } }, - { re: /\bice|frozen|frost|snow|glacier|\bcold/i, w: { inner: 0.2, habitable: 0.5, outer: 3 } }, - { re: /ocean|water|garden|terra|earth|jungle|green|eden|haven/i, w: { inner: 0.5, habitable: 4, outer: 0.3 } }, - { re: /desert|arid|dune|dust|sand/i, w: { inner: 2, habitable: 3, outer: 0.5 } }, - { re: /\brock|barren|stone/i, w: { inner: 4, habitable: 2, outer: 1 } }, -]; -const ZONE_TYPE_WEIGHTS: Record> = { - world: { inner: 2, habitable: 3, outer: 1 }, - "gas-giant": { inner: 0.3, habitable: 0.5, outer: 4 }, - asteroids: { inner: 0.5, habitable: 1, outer: 1.5 }, -}; - export interface OrbitRoles { background: string; stars: string[]; @@ -127,8 +87,6 @@ export interface OrbitRoles { belts: string[]; /** Bodies that may get two moons (gas-giant type). */ giants: string[]; - /** Per-zone body weights (lower-case names) for weightedPick. */ - zoneWeights: Record>; } /** @@ -143,7 +101,6 @@ export function orbitRoles(terrains: TerrainColor[]): OrbitRoles | undefined { const stars = ofType(terrains, ["star"]); const bodies = ofType(terrains, ["world", "gas-giant", "asteroids"]); if (!background || stars.length === 0 || bodies.length === 0) return undefined; - const types = typeIndex(terrains); const first = (type: string) => ofType(terrains, [type])[0]; const belts = ofType(terrains, ["asteroids"]); return { @@ -159,36 +116,9 @@ export function orbitRoles(terrains: TerrainColor[]): OrbitRoles | undefined { belt: belts[0], belts, giants: ofType(terrains, ["gas-giant"]), - zoneWeights: { - inner: zoneWeights(bodies, types, "inner"), - habitable: zoneWeights(bodies, types, "habitable"), - outer: zoneWeights(bodies, types, "outer"), - }, }; } -/** - * Weights for one zone. The shipped body names keep their table weights - * (0.5 when the zone doesn't list them); other names go by hint, then type. - */ -function zoneWeights(bodies: string[], types: Map, zone: Zone): Record { - const out: Record = {}; - for (const b of bodies) { - const k = b.toLowerCase(); - if (BODY_NAMES.includes(k)) { - out[k] = ZONE_WEIGHTS[zone][k] ?? 0.5; - continue; - } - const type = types.get(k); - // Giants go by type first: "ice giant" belongs outside, not with ice planets. - const w = (type === "gas-giant" ? ZONE_TYPE_WEIGHTS[type] : undefined) - ?? ZONE_HINTS.find((h) => h.re.test(b))?.w - ?? ZONE_TYPE_WEIGHTS[type ?? ""]; - if (w) out[k] = w[zone]; - } - return out; -} - export function orbitsFits(terrains: TerrainColor[]): boolean { return orbitRoles(terrains) !== undefined; } @@ -200,8 +130,10 @@ export function orbits( options: Record = {}, /** Path type to draw occupied orbits with (e.g. "Orbit"); none = no rings. */ orbitPathType?: string, - /** The sector hex this system sits in: its terrain picks the mainworld. */ + /** The sector hex this system sits in: its row's Mainworld picks the mainworld. */ context?: GenerationContext, + /** The role tables (World types); none = equal odds over the palette's stars and bodies, said in the warnings. */ + tables?: TableSource, ): ProcResult { const roles = orbitRoles(terrains); if (!roles) { @@ -234,7 +166,7 @@ export function orbits( const wanted = options.star && options.star !== "random" ? roles.stars.find((s) => s.toLowerCase() === options.star) : undefined; - const star = wanted ?? weightedPick(rand, roles.stars, STAR_WEIGHTS)!; + const star = wanted ?? rollRole(tables, "star", { rand }, roles.stars)?.terrain ?? roles.stars[0]; set(center, star); // The 100-diameter limit hugs the star: mark the first ring. if (roles.jumpLimit && fullRing >= 3) for (const h of ring(1)) set(h, roles.jumpLimit); @@ -244,26 +176,34 @@ export function orbits( const last = Math.max(first, fullRing); const skip = options.bodies === "few" ? 0.45 : options.bodies === "crowded" ? 0.05 : 0.2; const warnings: string[] = []; + // Rows that can't be placed, and roles with no table, are said (never dropped silently). + const notes = new Set(); + if (!wanted) for (const n of roleOdds(tables, "star", {}, roles.stars).notes) notes.add(n); + for (const z of ORBIT_ZONES) for (const n of roleOdds(tables, ZONE_ROLES[z], { zone: z, star }, roles.bodies).notes) notes.add(n); + warnings.push(...notes); if (fullRing < 2) warnings.push("Map is too small for orbits — try Medium or Large."); let mainworld: [number, number] | undefined; const paths: ProcPath[] = []; - // The sector says what the mainworld is ("ocean world" → an ocean planet - // in the habitable zone); that orbit is never skipped. - const mainBody = mainworldFor(context?.parent?.terrain, roles.bodies); + // The sector hex's row says what the mainworld is (its Mainworld: "ocean + // world" → an ocean planet), placed in the habitable zone; that orbit is + // never skipped. + const mainBody = mainworldFor(context?.parent?.terrain, roles.bodies, tables); const mainRing = mainBody ? first + Math.round(0.45 * (last - first)) : -1; /** Planets placed (not belts), for the moon guarantee below. */ const planets: { pos: [number, number]; body: string }[] = []; let moonCount = 0; for (let d = first; d <= last; d++) { if (d !== mainRing && rand() < skip) continue; + const zone = orbitZone(d, first, last); + const pick = d === mainRing ? { terrain: mainBody! } : rollRole(tables, ZONE_ROLES[zone], { rand, zone, ring: d, star }, roles.bodies); + // A (nothing) row: an empty orbit. + if (!pick?.terrain) continue; + const body = pick.terrain; // Draw the orbit itself: the ring, in order around the star, closed. if (orbitPathType) { const around = sortAround(ring(d), center, grid).map((h) => cellKey(h[0], h[1])); if (around.length > 2) paths.push({ type: orbitPathType, hexes: [...around, around[0]] }); } - const t = (d - first) / Math.max(1, last - first); - const zone = t < 0.3 ? "inner" : t < 0.6 ? "habitable" : "outer"; - const body = d === mainRing ? mainBody! : weightedPick(rand, roles.bodies, roles.zoneWeights[zone], 0.5)!; const hexesOnRing = ring(d); if (hexesOnRing.length === 0) continue; // A moon from the orbit inside may sit on this ring: leave it be. @@ -349,33 +289,14 @@ function sortAround(hexes: [number, number][], center: [number, number], grid: P return [...hexes].sort((a, b) => angle(a) - angle(b)); } -/** Parent-terrain words → body-name words, most specific first. */ -const MAINWORLD_HINTS: [string, string][] = [ - ["gas giant", "gas giant"], - ["ice giant", "ice giant"], - ["asteroid", "belt"], - ["ocean", "ocean"], - ["water", "ocean"], - ["garden", "terrestrial"], - ["terrestrial", "terrestrial"], - ["earth", "terrestrial"], - ["desert", "desert"], - ["ice", "ice"], - ["frozen", "ice"], - ["molten", "molten"], - ["lava", "molten"], - ["barren", "rocky"], - ["rocky", "rocky"], -]; - -/** The body that should be the system's mainworld, given the sector hex's terrain name. */ -export function mainworldFor(parentTerrain: string | undefined, bodies: string[]): string | undefined { - if (!parentTerrain) return undefined; - const p = parentTerrain.toLowerCase(); - for (const [from, to] of MAINWORLD_HINTS) { - if (!p.includes(from)) continue; - const hit = bodies.find((b) => b.toLowerCase().includes(to)); - if (hit) return hit; - } - return undefined; +/** + * The body that should be the system's mainworld: the Mainworld of the + * sector hex's row in the tables ("ocean world" → "ocean planet"), else + * the sector terrain itself; only when it is one of the palette's bodies. + * Data, not names: nothing here knows what an ocean is. + */ +export function mainworldFor(parentTerrain: string | undefined, bodies: string[], tables?: TableSource): string | undefined { + if (!parentTerrain?.trim()) return undefined; + const want = tables?.rowAttrs("sector-hexes", parentTerrain)?.Mainworld?.trim() || parentTerrain.trim(); + return bodies.find((b) => b.toLowerCase() === want.toLowerCase()); } diff --git a/src/worldgen/procedural/starScatter.ts b/src/worldgen/procedural/starScatter.ts index 763810cc..15cb9361 100644 --- a/src/worldgen/procedural/starScatter.ts +++ b/src/worldgen/procedural/starScatter.ts @@ -1,5 +1,6 @@ import { mulberry32 } from "../../../packages/hex-wfc/src"; import { orbitsFits } from "./orbits"; +import { roleOdds, rollRole, type TableSource } from "../tableRoles"; import type { TerrainColor } from "../../types"; import { cellKey, @@ -7,7 +8,6 @@ import { gridKeys, ofType, typeIndex, - weightedPick, type ProcGrid, type ProcOption, type ProcPath, @@ -16,10 +16,12 @@ import { /** * Sector "star scatter": the classic subsector roll. Each hex holds a star - * system with some probability (standard = 50%, the 4+ on 1d6 rule), typed - * by its mainworld. A few nebula / dust patches thin out the systems inside - * them, rare features (black hole, anomaly, deep-space station) are - * sprinkled in, and nearby systems can be joined by jump routes. + * system with some probability (standard = 50%, the 4+ on 1d6 rule). What + * each system hex is (its mainworld, or a special hex like a station) is + * rolled on the Sector hexes role (tableRoles.ts): the World types table + * when one is given, else equal odds over the palette's world terrains. + * A few nebula / dust patches thin out the systems inside them, and nearby + * systems can be joined by jump routes. * * Works on any palette with a background terrain (type void) and at least * one world (type world / gas-giant / asteroids, or a star-system terrain). @@ -63,24 +65,6 @@ export const STAR_SCATTER_OPTIONS: ProcOption[] = [ const DENSITY: Record = { sparse: 1 / 3, standard: 1 / 2, dense: 2 / 3, cluster: 5 / 6 }; -/** Rough mainworld mix for a habitable-ish sector. Unlisted world terrains weigh 1. */ -const WORLD_WEIGHTS: Record = { - "garden world": 3, - "desert world": 3, - "barren world": 3.5, - "ocean world": 2, - "ice world": 2, - "asteroid belt": 1.5, - "molten world": 1, - "gas giant": 1, -}; - -const FEATURE_WEIGHTS: Record = { - "deep-space station": 3, - anomaly: 2, - "black hole": 1, -}; - export interface StarScatterRoles { background: string; worlds: string[]; @@ -88,10 +72,6 @@ export interface StarScatterRoles { features: string[]; } -/** Weights for typed terrains whose names aren't in the tables above. */ -const WORLD_TYPE_WEIGHTS: Record = { world: 2.5, "gas-giant": 1, asteroids: 1.5 }; -const FEATURE_TYPE_WEIGHTS: Record = { station: 3, starport: 3, "jump-point": 3, anomaly: 1.5 }; - /** Feature types that host a system (and so a jump route). */ const HOSTS_SYSTEM = new Set(["station", "starport", "jump-point"]); @@ -115,22 +95,6 @@ export function starScatterRoles(terrains: TerrainColor[]): StarScatterRoles | u return { background, worlds, clouds, features }; } -/** Name weights, else the terrain's type weight; unknowns fall through to the default. */ -function weightsFor( - names: string[], - types: Map, - byName: Record, - byType: Record, -): Record { - const out: Record = {}; - for (const n of names) { - const k = n.toLowerCase(); - const w = byName[k] ?? byType[types.get(k) ?? ""]; - if (w !== undefined) out[k] = w; - } - return out; -} - export function starScatterFits(terrains: TerrainColor[]): boolean { return starScatterRoles(terrains) !== undefined; } @@ -141,6 +105,8 @@ export function starScatter( seed: number, options: Record = {}, jumpRouteType?: string, + /** The role tables (World types); none = equal odds over the palette's worlds, said in the warnings. */ + tables?: TableSource, ): ProcResult { const roles = starScatterRoles(terrains); if (!roles) { @@ -148,10 +114,10 @@ export function starScatter( } const rand = mulberry32(seed); const types = typeIndex(terrains); - const worldWeights = weightsFor(roles.worlds, types, WORLD_WEIGHTS, WORLD_TYPE_WEIGHTS); - const featureWeights = weightsFor(roles.features, types, FEATURE_WEIGHTS, FEATURE_TYPE_WEIGHTS); + const warnings: string[] = [...roleOdds(tables, "sector-hexes", {}, roles.worlds).notes]; // Stations host a system (and so a route); black holes and anomalies don't. const hostsSystem = (t: string) => HOSTS_SYSTEM.has(types.get(t.toLowerCase()) ?? ""); + const isFeature = (t: string) => roles.features.some((f) => f.toLowerCase() === t.toLowerCase()); const density = DENSITY[options.density ?? "standard"] ?? 0.5; const hexes = gridKeys(grid); const cells = new Map(); @@ -183,18 +149,17 @@ export function starScatter( const k = cellKey(x, y); const odds = inCloud.has(k) ? density / 2 : density; if (rand() >= odds) continue; - const roll = rand(); - const feature = roles.features.length > 0 && roll < 0.04 - ? weightedPick(rand, roles.features, featureWeights) - : undefined; - cells.set(k, feature ?? weightedPick(rand, roles.worlds, worldWeights)!); - if (!feature || hostsSystem(feature)) systems.push([x, y]); + const pick = rollRole(tables, "sector-hexes", { rand }, roles.worlds); + // A (nothing) row: empty space after all. + if (!pick || pick.nothing) continue; + cells.set(k, pick.terrain); + // A world hosts a system (and so a route); of the rest, only station-like types do. + if (!isFeature(pick.terrain) || hostsSystem(pick.terrain)) systems.push([x, y]); } // Jump routes: each system links to its nearest neighbour within range. const paths: ProcPath[] = []; const range = options.routes === "none" ? 0 : Number(options.routes ?? 2) || 0; - const warnings: string[] = []; if (range > 0 && systems.length > 1) { if (!jumpRouteType) { warnings.push("No path type for routes, so none were drawn. Pick one under Path type for routes (or add a path type to the palette)."); diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index f7deaada..db9e6c5a 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -36,6 +36,7 @@ import { generatorMapKind, isGeneratorShown, isSpacePalette, type MapKind } from import { routeContextPaths } from "./procedural/contextPaths"; import { hasFeature, type FeatureSettings } from "../featureLevel"; import { generateConnected, type NewRegion } from "./neighbours"; +import { WORLD_TYPES_KEY, worldTypesOption } from "../space/worldTypesSource"; import { BUILTIN_GENERATORS, BUILTIN_PREFIX, builtinModel, builtinPathType, fitBuiltinModel } from "./builtinGenerators"; import type { HexWfcModel } from "../../packages/hex-wfc/src"; @@ -186,6 +187,14 @@ export function suggestBaseTerrain(terrains: TerrainColor[]): string | undefined return ofType(terrains, ["void"])[0]; } +/** The World types option with the vault's tables (Star scatter and Orbits roll on the chosen one, SP1). */ +function worldTypesChoice(plugin: HexmakerPlugin): ProcOption { + const store = plugin.worldTypeStore; + return worldTypesOption(store.list().map((t) => t.name), store.defaultName()); +} + +const missingWorldTypes = (name: string) => `No World types table called "${name}", so equal odds.`; + function procGrid(plugin: HexmakerPlugin, grid: GridSpec): ProcGrid { return { ...grid, orientation: plugin.settings.hexOrientation }; } @@ -210,14 +219,16 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise [...STAR_SCATTER_OPTIONS, pathTypeOption(ROUTE_TYPE_KEY, "routes", pathTypes)], + options: [...STAR_SCATTER_OPTIONS, worldTypesOption([]), staticPathTypeOption(ROUTE_TYPE_KEY, "routes")], + optionsFor: (_terrains, pathTypes) => [...STAR_SCATTER_OPTIONS, worldTypesChoice(plugin), pathTypeOption(ROUTE_TYPE_KEY, "routes", pathTypes)], fits: starScatterOffered, generate: (req) => { const routeType = chosenPathType(req.options[ROUTE_TYPE_KEY], "routes", req.pathTypes); // None picked on purpose: no routes, and nothing to warn about. const options = !routeType && req.options[ROUTE_TYPE_KEY] === NO_PATHS ? { ...req.options, routes: "none" } : req.options; - const r = starScatter(req.terrains, procGrid(plugin, req.grid), req.seed, options, routeType); + const wt = plugin.worldTypeStore.sourceFor(req.options[WORLD_TYPES_KEY], req.terrains); + const r = starScatter(req.terrains, procGrid(plugin, req.grid), req.seed, options, routeType, wt.source); + if (wt.missing) r.warnings.unshift(missingWorldTypes(wt.missing)); return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; }, toPaths, @@ -228,12 +239,14 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise [...orbitsOptions(terrains), pathTypeOption(ORBIT_TYPE_KEY, "orbits", pathTypes)], + options: [...ORBITS_OPTIONS, worldTypesOption([]), staticPathTypeOption(ORBIT_TYPE_KEY, "orbits")], + optionsFor: (terrains, pathTypes) => [...orbitsOptions(terrains), worldTypesChoice(plugin), pathTypeOption(ORBIT_TYPE_KEY, "orbits", pathTypes)], fits: orbitsFits, generate: (req) => { const orbitType = chosenPathType(req.options[ORBIT_TYPE_KEY], "orbits", req.pathTypes); - const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitType, req.context); + const wt = plugin.worldTypeStore.sourceFor(req.options[WORLD_TYPES_KEY], req.terrains); + const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitType, req.context, wt.source); + if (wt.missing) r.warnings.unshift(missingWorldTypes(wt.missing)); // No type and not None on purpose: say why there are no rings. if (!orbitType && req.options[ORBIT_TYPE_KEY] !== NO_PATHS && r.cells.size) r.warnings.push("No path type for orbits, so the rings weren't drawn. Pick one under Path type for orbits (or add a path type to the palette)."); diff --git a/src/worldgen/tableRoles.ts b/src/worldgen/tableRoles.ts new file mode 100644 index 00000000..71707a0b --- /dev/null +++ b/src/worldgen/tableRoles.ts @@ -0,0 +1,214 @@ +/** + * Generators roll on tables by role (plan-tables-everywhere §2.4). + * + * Each engine has a fixed list of named roles (ENGINE_ROLES, engine + * schema). Where a role's table comes from is a TableSource: today the + * World types note (space/worldTypesSource.ts, the SP1 adapter); later + * plain table notes chosen per map, recipe or module (phase 3), with no + * change to the engines. + * + * Engines and previews both go through rollRole / roleOdds, so the odds a + * preview shows are the odds the generator rolls (F3). Every roll goes + * through the table resolver (random-tables/resolve.ts). + * + * A role with no table, or whose table has no row that is a terrain of + * the palette, is honest: equal odds over the palette's terrains of the + * role's types, and a note saying so (rule 4). Rows that can't be placed + * (not terrains of the palette) are never dropped silently: they are + * listed in the notes. + * + * Pure: no Obsidian imports. + */ + +import type { RandomTable, RowType } from "../random-tables/randomTable"; +import { resolveOdds, resolveRoll, skippedRows, type ResolveContext, type TableLookup } from "../random-tables/resolve"; +import type { ConditionContext } from "../random-tables/tableConditions"; +import type { OrbitZone } from "../space/worldTypes"; + +export type RoleId = "sector-hexes" | "star" | "inner-orbits" | "habitable-orbits" | "outer-orbits"; + +export interface EngineRole { + id: RoleId; + /** The generator id that rolls on it. */ + engine: string; + /** Its name, as shown and as written in a recipe's Tables section. */ + name: string; + /** What its rows must be. */ + rows: RowType; + /** Terrain types its rows place, and what equal odds fall back to. */ + terrainTypes: readonly string[]; + /** What the generator does with a roll (help text). */ + help: string; + /** What equal odds run over when there is no table (plain words). */ + fallback: string; +} + +/** The engine role schema. Roles are only added by engines (tests/generatorRoles.test.ts checks coverage). */ +export const ENGINE_ROLES: readonly EngineRole[] = [ + { + id: "sector-hexes", + engine: "procedural:star-scatter", + name: "Sector hexes", + rows: "terrain", + terrainTypes: ["world", "gas-giant", "asteroids", "station", "starport", "jump-point", "anomaly"], + help: "What each star system hex of a sector is: its mainworld, or a special hex like a station. A row's Mainworld says which body is that system's mainworld.", + fallback: "world terrains (no special hexes)", + }, + { + id: "star", + engine: "procedural:orbits", + name: "Star", + rows: "terrain", + terrainTypes: ["star"], + help: "The star at the centre of a system, when the Star option is Random.", + fallback: "star terrains", + }, + { + id: "inner-orbits", + engine: "procedural:orbits", + name: "Inner orbits", + rows: "terrain", + terrainTypes: ["world", "gas-giant", "asteroids"], + help: "The body on each orbit in the inner zone (the first 30% of the rings).", + fallback: "planet terrains", + }, + { + id: "habitable-orbits", + engine: "procedural:orbits", + name: "Habitable orbits", + rows: "terrain", + terrainTypes: ["world", "gas-giant", "asteroids"], + help: "The body on each orbit in the habitable zone (30–60% of the rings).", + fallback: "planet terrains", + }, + { + id: "outer-orbits", + engine: "procedural:orbits", + name: "Outer orbits", + rows: "terrain", + terrainTypes: ["world", "gas-giant", "asteroids"], + help: "The body on each orbit in the outer zone (the rest of the rings).", + fallback: "planet terrains", + }, +]; + +export const ZONE_ROLES: Record = { + inner: "inner-orbits", + habitable: "habitable-orbits", + outer: "outer-orbits", +}; + +export function engineRole(id: RoleId): EngineRole { + const r = ENGINE_ROLES.find((x) => x.id === id); + if (!r) throw new Error(`unknown role ${id}`); + return r; +} + +export function rolesOf(engine: string): EngineRole[] { + return ENGINE_ROLES.filter((r) => r.engine === engine); +} + +/** Where a generator's roles roll: a table per role, read through the resolver. */ +export interface TableSource { + /** Shown in notes ("World types: Default space"). */ + readonly label: string; + readonly lookup: TableLookup; + /** The palette's terrain names (rows naming anything else are never placed). */ + readonly terrains: readonly string[]; + /** The table link a role rolls on; undefined = no table for it (equal odds). */ + tableFor(role: RoleId): string | undefined; + /** The attributes of the row naming `name` in a role's table (Mainworld, Size, …). */ + rowAttrs(role: RoleId, name: string): Record | undefined; + /** Anything the source itself has to say about a role (rows it couldn't use). */ + notes?(role: RoleId): string[]; +} + +/** What the engine knows where it rolls (conditions), plus its random stream. */ +export interface RoleContext extends ConditionContext { + rand: () => number; +} + +export interface RolePick { + /** The terrain to place; "" for a (nothing) row. */ + terrain: string; + nothing?: boolean; + attrs: Record; +} + +/** + * The link of the in-memory equal-odds table: the palette's terrains of a + * role's types, weight 1 each. A source may link it (a remainder row whose + * own table has nothing for this palette). + */ +export const EQUAL_ODDS = "(equal odds)"; + +function withEqualOdds(lookup: TableLookup, fallback: readonly string[]): TableLookup { + const table: RandomTable = { dice: 0, rows: "terrain", entries: fallback.map((n) => ({ result: n, weight: 1 })) }; + return { + table: (link) => (link === EQUAL_ODDS ? { key: EQUAL_ODDS, table } : lookup.table(link)), + kindOf: (link) => lookup.kindOf?.(link) ?? "note", + }; +} + +const NO_SOURCE: TableLookup = { table: () => undefined }; + +function resolveCtx(source: TableSource | undefined, fallback: readonly string[], ctx: ConditionContext): ResolveContext { + return { ...ctx, terrains: source?.terrains ?? fallback, onlyTerrains: true }; +} + +/** Whether the role's own table gives anything here (else equal odds). */ +function usesTable(source: TableSource | undefined, role: RoleId, fallback: readonly string[], ctx: ConditionContext): string | undefined { + const link = source?.tableFor(role); + if (!link || !source) return undefined; + const odds = resolveOdds(link, withEqualOdds(source.lookup, fallback), resolveCtx(source, fallback, ctx)); + return odds.some((o) => o.kind !== "empty") ? link : undefined; +} + +/** + * Roll a role: its table through the resolver, else equal odds over + * `fallback` (the palette's terrains of the role's types). Undefined when + * there is nothing at all to place. + */ +export function rollRole(source: TableSource | undefined, role: RoleId, ctx: RoleContext, fallback: readonly string[]): RolePick | undefined { + const lookup = withEqualOdds(source?.lookup ?? NO_SOURCE, fallback); + const { rand, ...cond } = ctx; + const link = usesTable(source, role, fallback, cond) ?? EQUAL_ODDS; + const r = resolveRoll(link, lookup, { ...resolveCtx(source, fallback, cond), rand }); + if (r.kind === "nothing") return { terrain: "", nothing: true, attrs: r.attrs }; + if (r.kind === "terrain") return { terrain: r.value, attrs: r.attrs }; + return undefined; +} + +export interface RoleOdds { + /** Each outcome's exact odds (0..1), most likely first; terrain "" = (nothing). */ + odds: { terrain: string; odds: number }[]; + /** Where the odds come from: the table, or "equal odds". */ + from: string; + /** Rows that are never placed and why, and the fallback, in plain words. */ + notes: string[]; +} + +/** The exact odds rollRole samples for this role and context, and what to tell the user. */ +export function roleOdds(source: TableSource | undefined, role: RoleId, ctx: ConditionContext, fallback: readonly string[]): RoleOdds { + const spec = engineRole(role); + const lookup = withEqualOdds(source?.lookup ?? NO_SOURCE, fallback); + const notes: string[] = [...(source?.notes?.(role) ?? [])]; + const own = source?.tableFor(role); + const link = usesTable(source, role, fallback, ctx); + const rctx = resolveCtx(source, fallback, ctx); + if (own && source) { + const skipped = skippedRows(own, lookup, rctx).filter((s) => s.why === "not-terrain"); + if (skipped.length) { + notes.push(`${source.label}: ${spec.name} ${skipped.length === 1 ? "row" : "rows"} not a terrain of this palette, so never placed: ${[...new Set(skipped.map((s) => s.result))].join(", ")}.`); + } + } + if (!link) { + notes.push(!source || !own + ? `${spec.name}: no table, so equal odds over the palette's ${spec.fallback}.` + : `${source.label}: no ${spec.name} row fits this palette here, so equal odds over its ${spec.fallback}.`); + } + const odds = resolveOdds(link ?? EQUAL_ODDS, lookup, rctx) + .filter((o) => o.kind === "terrain" || o.kind === "nothing") + .map((o) => ({ terrain: o.kind === "nothing" ? "" : o.value, odds: o.odds })); + return { odds, from: link && source ? source.label : "equal odds", notes }; +} diff --git a/tests/generatorRoles.test.ts b/tests/generatorRoles.test.ts new file mode 100644 index 00000000..3b0f7dc2 --- /dev/null +++ b/tests/generatorRoles.test.ts @@ -0,0 +1,173 @@ +/** + * Phase 2 (plan-tables-everywhere §2.4, SP1): the engine role schema, the + * World types adapter, and that the shipped Default space gives the old + * built-in odds exactly (T4: same odds, new draws). + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import { ENGINE_ROLES, ZONE_ROLES, engineRole, roleOdds, rolesOf, type RoleId } from "../src/worldgen/tableRoles"; +import { STAR_SCATTER_ID, starScatterRoles } from "../src/worldgen/procedural/starScatter"; +import { ORBITS_ID, orbitRoles } from "../src/worldgen/procedural/orbits"; +import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; +import { + WORLD_TYPES_DEFAULT, + WORLD_TYPES_NONE, + chosenWorldTypes, + defaultWorldTypesName, + worldTypesOption, + worldTypesSource, +} from "../src/space/worldTypesSource"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { + DEFAULT_WORLD_TYPES, + WORLD_TYPES_FORMAT, + buildWorldTypes, + parseWorldTypes, + upgradeWorldTypes, + type WorldTypeTable, +} from "../src/space/worldTypes"; + +const DEFAULT_SPACE: WorldTypeTable = { name: DEFAULT_WORLD_TYPES, rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }; + +// Frozen copies of the weights Star scatter and Orbits had built in (now deleted from the code). +const OLD_WORLD_WEIGHTS: Record = { + "garden world": 3, "desert world": 3, "barren world": 3.5, "ocean world": 2, + "ice world": 2, "asteroid belt": 1.5, "molten world": 1, "gas giant": 1, +}; +const OLD_FEATURES: Record = { "deep-space station": 3, anomaly: 2, "black hole": 1 }; +const OLD_STAR_WEIGHTS: Record = { "red dwarf": 6, "yellow star": 3, "brown dwarf": 1.5, "white dwarf": 1, "blue giant": 0.5 }; +const OLD_ZONE_WEIGHTS: Record> = { + inner: { "molten planet": 4, "rocky planet": 4, "desert planet": 2, "asteroid belt": 0.5 }, + habitable: { "terrestrial planet": 4, "ocean planet": 3, "desert planet": 3, "rocky planet": 2, "asteroid belt": 1 }, + outer: { "gas giant": 4, "ice giant": 3, "ice planet": 3, "asteroid belt": 1.5, "rocky planet": 1 }, +}; + +const asMap = (odds: { terrain: string; odds: number }[]) => Object.fromEntries(odds.map((o) => [o.terrain, o.odds])); +const expectClose = (got: Record, want: Record) => { + expect(Object.keys(got).sort()).toEqual(Object.keys(want).sort()); + for (const k of Object.keys(want)) expect(got[k]).toBeCloseTo(want[k], 12); +}; + +describe("the engine role schema", () => { + it("every role names its engine, rows, types, help and fallback; engines list their roles", () => { + for (const r of ENGINE_ROLES) { + expect([STAR_SCATTER_ID, ORBITS_ID]).toContain(r.engine); + expect(r.name.trim()).not.toBe(""); + expect(r.help.length).toBeGreaterThan(20); + expect(r.fallback.trim()).not.toBe(""); + expect(r.terrainTypes.length).toBeGreaterThan(0); + expect(engineRole(r.id)).toBe(r); + } + expect(new Set(ENGINE_ROLES.map((r) => r.id)).size).toBe(ENGINE_ROLES.length); + expect(rolesOf(STAR_SCATTER_ID).map((r) => r.id)).toEqual(["sector-hexes"]); + expect(rolesOf(ORBITS_ID).map((r) => r.id)).toEqual(["star", "inner-orbits", "habitable-orbits", "outer-orbits"]); + expect(Object.values(ZONE_ROLES).sort()).toEqual(["habitable-orbits", "inner-orbits", "outer-orbits"]); + }); + + it("the World types adapter gives a table for every role", () => { + const s = worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS); + for (const r of ENGINE_ROLES) { + const link = s.tableFor(r.id); + expect(link).toBeDefined(); + expect(s.lookup.table(link!)).toBeDefined(); + } + // A note with no Stars table: the Star role has none (equal odds, said so). + expect(worldTypesSource({ ...DEFAULT_SPACE, stars: undefined }, SPACE_SYSTEM_TERRAINS).tableFor("star")).toBeUndefined(); + }); + + it("the engines hold no terrain names and no built-in weights any more (no special defaults)", () => { + for (const f of ["src/worldgen/procedural/starScatter.ts", "src/worldgen/procedural/orbits.ts"]) { + const code = readFileSync(f, "utf8").replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ""); + for (const name of ["garden", "ocean", "desert", "barren", "molten", "red dwarf", "yellow star", "black hole", "deep-space", "terrestrial", "rocky", "ice giant"]) { + expect({ f, name, found: code.toLowerCase().includes(name) }).toEqual({ f, name, found: false }); + } + expect(code).not.toMatch(/WEIGHTS|_HINTS|BODY_NAMES|0\.04/); + } + }); +}); + +describe("Default space gives the old built-in odds (T4: same odds, new draws)", () => { + it("Sector hexes: 1 in 50 / 75 / 150 features, the rest the old mainworld mix", () => { + const s = worldTypesSource(DEFAULT_SPACE, SPACE_SECTOR_TERRAINS); + const o = roleOdds(s, "sector-hexes", {}, starScatterRoles(SPACE_SECTOR_TERRAINS)!.worlds); + expect(o.notes).toEqual([]); + expect(o.from).toBe("World types: Default space"); + const want: Record = {}; + const featureTotal = Object.values(OLD_FEATURES).reduce((a, b) => a + b, 0); + for (const [k, w] of Object.entries(OLD_FEATURES)) want[k] = 0.04 * w / featureTotal; + const worldTotal = Object.values(OLD_WORLD_WEIGHTS).reduce((a, b) => a + b, 0); + for (const [k, w] of Object.entries(OLD_WORLD_WEIGHTS)) want[k] = 0.96 * w / worldTotal; + expectClose(asMap(o.odds), want); + }); + + it("Star: the old galactic mix", () => { + const o = roleOdds(worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS), "star", {}, orbitRoles(SPACE_SYSTEM_TERRAINS)!.stars); + const total = Object.values(OLD_STAR_WEIGHTS).reduce((a, b) => a + b, 0); + expectClose(asMap(o.odds), Object.fromEntries(Object.entries(OLD_STAR_WEIGHTS).map(([k, w]) => [k, w / total]))); + }); + + for (const zone of ["inner", "habitable", "outer"] as const) { + it(`${zone} orbits: the old zone weights (a body the zone didn't list weighed 0.5)`, () => { + const roles = orbitRoles(SPACE_SYSTEM_TERRAINS)!; + const o = roleOdds(worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS), ZONE_ROLES[zone], { zone }, roles.bodies); + expect(o.notes).toEqual([]); + const w = Object.fromEntries(roles.bodies.map((b) => [b, OLD_ZONE_WEIGHTS[zone][b] ?? 0.5])); + const total = Object.values(w).reduce((a, b) => a + b, 0); + expectClose(asMap(o.odds), Object.fromEntries(Object.entries(w).map(([k, v]) => [k, v / total]))); + }); + } +}); + +describe("the World types option", () => { + it("Default means Default space, else the first table; None means no table", () => { + expect(defaultWorldTypesName(["Hard SF", "default space"], DEFAULT_WORLD_TYPES)).toBe("default space"); + expect(defaultWorldTypesName(["Hard SF"], DEFAULT_WORLD_TYPES)).toBe("Hard SF"); + expect(defaultWorldTypesName([], DEFAULT_WORLD_TYPES)).toBeUndefined(); + expect(chosenWorldTypes(undefined, ["A"], "A")).toBe("A"); + expect(chosenWorldTypes(WORLD_TYPES_DEFAULT, ["A"], "A")).toBe("A"); + expect(chosenWorldTypes(WORLD_TYPES_NONE, ["A"], "A")).toBeUndefined(); + expect(chosenWorldTypes("B", ["A"], "A")).toBe("B"); + const opt = worldTypesOption(["Default space", "Hard SF"], "Default space"); + expect(opt.choices.map((c) => c.label)).toEqual(["Default (Default space)", "Default space", "Hard SF", "None (equal odds)"]); + expect(opt.default).toBe(WORLD_TYPES_DEFAULT); + }); +}); + +describe("older World types notes get the Mainworld column (format 3)", () => { + // A format 2 note: no Mainworld column, a hand-made row, and the Stars table deleted. + const v3 = buildWorldTypes(DEFAULT_WORLD_TYPES, [...DEFAULT_WORLD_TYPE_ROWS, { world: "Eden", weight: 2, map: "sector" }], DEFAULT_WORLD_TYPE_EXTRAS); + const v2 = v3 + .replace(`hexmaker-world-types: ${WORLD_TYPES_FORMAT}`, "hexmaker-world-types: 2") + .split("\n") + .map((l) => { + if (!l.startsWith("|") || !l.includes("|")) return l; + const cells = l.split("|"); + // Drop the 7th column (Mainworld) from the worlds table only. + return cells.length === 15 ? [...cells.slice(0, 7), ...cells.slice(8)].join("|") : l; + }) + .join("\n"); + const noStars = v2.slice(0, v2.indexOf("## Stars")) + v2.slice(v2.indexOf("## Sector features")); + + it("the shipped sector worlds get their mainworld; hand-made rows and deleted tables stay as they were", () => { + expect(noStars).not.toContain("| Mainworld |"); + const p0 = parseWorldTypes(noStars); + expect(p0.rows.every((r) => !r.mainworld)).toBe(true); + const up = upgradeWorldTypes(noStars, { ...DEFAULT_WORLD_TYPE_EXTRAS, rows: DEFAULT_WORLD_TYPE_ROWS }); + const p = parseWorldTypes(up); + expect(p.format).toBe(WORLD_TYPES_FORMAT); + expect(p.rows).toEqual([...DEFAULT_WORLD_TYPE_ROWS, { world: "Eden", weight: 2, map: "sector" }]); + expect(p.stars).toBeUndefined(); + expect(p.features).toEqual(DEFAULT_WORLD_TYPE_EXTRAS.features); + expect(upgradeWorldTypes(up, { ...DEFAULT_WORLD_TYPE_EXTRAS, rows: DEFAULT_WORLD_TYPE_ROWS })).toBe(up); + }); + + it("a Mainworld someone typed is never overwritten", () => { + const typed = buildWorldTypes("T", [{ world: "ocean world", map: "sector", mainworld: "waterworld" }]).replace(`hexmaker-world-types: ${WORLD_TYPES_FORMAT}`, "hexmaker-world-types: 2"); + expect(parseWorldTypes(upgradeWorldTypes(typed, { ...DEFAULT_WORLD_TYPE_EXTRAS, rows: DEFAULT_WORLD_TYPE_ROWS })).rows[0].mainworld).toBe("waterworld"); + }); +}); + +// Keep the RoleId union and the schema in step. +const _all: Record = { "sector-hexes": true, star: true, "inner-orbits": true, "habitable-orbits": true, "outer-orbits": true }; +void _all; diff --git a/tests/orbitsTables.test.ts b/tests/orbitsTables.test.ts new file mode 100644 index 00000000..f7fbc570 --- /dev/null +++ b/tests/orbitsTables.test.ts @@ -0,0 +1,148 @@ +/** + * SP1: Orbits rolls its star and each orbit's body on the World types + * table (Star and Inner / Habitable / Outer orbits roles), and takes the + * mainworld from the sector row's Mainworld column. No name rules. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; +import { mainworldFor, orbitRoles, orbits } from "../src/worldgen/procedural/orbits"; +import { centerHex, distance, type ProcGrid } from "../src/worldgen/procedural/common"; +import { roleOdds } from "../src/worldgen/tableRoles"; +import { worldTypesSource } from "../src/space/worldTypesSource"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { orbitZone, type WorldTypeTable } from "../src/space/worldTypes"; +import type { TerrainColor } from "../src/types"; + +const DEFAULT_SPACE: WorldTypeTable = { name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }; +const grid = (n: number): ProcGrid => ({ cols: n, rows: n, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }); +const key = (k: string) => k.split("_").map(Number) as [number, number]; + +/** The last full ring of a grid, as Orbits works it out. */ +function lastRing(g: ProcGrid): number { + const c = centerHex(g); + let min = Infinity; + for (let i = 0; i < g.cols; i++) for (let j = 0; j < g.rows; j++) { + if (i === 0 || j === 0 || i === g.cols - 1 || j === g.rows - 1) min = Math.min(min, distance(c, [i, j], g)); + } + return min; +} + +describe("Orbits rolls on the World types table (SP1)", () => { + it("each orbit's body comes from its zone's rows", () => { + const palette: TerrainColor[] = [ + { name: "Dark", color: "#000", type: "void" }, + { name: "Sun", color: "#ff0", type: "star" }, + { name: "Scorch", color: "#f00", type: "world" }, + { name: "Eden", color: "#0f0", type: "world" }, + { name: "Rime", color: "#0ff", type: "world" }, + ]; + const table: WorldTypeTable = { + name: "Zones", + rows: [ + { world: "Scorch", map: "system", zones: ["inner"] }, + { world: "Eden", map: "system", zones: ["habitable"] }, + { world: "Rime", map: "system", zones: ["outer"] }, + ], + }; + const g = grid(15); + const c = centerHex(g); + const last = lastRing(g); + const zoneOf: Record = { Scorch: "inner", Eden: "habitable", Rime: "outer" }; + let bodies = 0; + for (let seed = 1; seed <= 60; seed++) { + const r = orbits(palette, g, seed, { bodies: "crowded" }, undefined, undefined, worldTypesSource(table, palette)); + // No Stars table: equal odds, and the warning says so. + expect(r.warnings.join(" ")).toMatch(/Star: no table/); + for (const [k, t] of r.cells) { + if (!(t in zoneOf)) continue; + bodies++; + expect({ t, zone: orbitZone(distance(c, key(k), g), 2, last) }).toEqual({ t, zone: zoneOf[t] }); + } + } + expect(bodies).toBeGreaterThan(200); + }); + + it("the star comes up at the Stars table's odds (the preview's)", () => { + const g = grid(9); + const c = centerHex(g); + const src = worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS); + const odds = roleOdds(src, "star", {}, orbitRoles(SPACE_SYSTEM_TERRAINS)!.stars).odds; + const n = 3000; + const counts = new Map(); + for (let seed = 1; seed <= n; seed++) { + const star = orbits(SPACE_SYSTEM_TERRAINS, g, seed, { bodies: "few" }, undefined, undefined, worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS)).cells.get(`${c[0]}_${c[1]}`)!; + counts.set(star, (counts.get(star) ?? 0) + 1); + } + for (const o of odds) { + const se = Math.sqrt((o.odds * (1 - o.odds)) / n); + expect(Math.abs((counts.get(o.terrain) ?? 0) / n - o.odds)).toBeLessThan(4.5 * se); + } + }); + + it("a custom body added to the palette and the table is placed in its zone at its weight", () => { + const palette: TerrainColor[] = [...SPACE_SYSTEM_TERRAINS, { name: "Crystal planet", color: "#aef", type: "world" }]; + const table: WorldTypeTable = { ...DEFAULT_SPACE, rows: [...DEFAULT_SPACE.rows, { world: "crystal planet", weight: 40, map: "system", zones: ["outer"] }] }; + const src = worldTypesSource(table, palette); + const outer = roleOdds(src, "outer-orbits", { zone: "outer" }, orbitRoles(palette)!.bodies); + expect(outer.odds[0]).toEqual({ terrain: "Crystal planet", odds: expect.any(Number) }); + expect(outer.odds[0].odds).toBeGreaterThan(0.6); + expect(roleOdds(src, "inner-orbits", { zone: "inner" }, orbitRoles(palette)!.bodies).odds.some((o) => o.terrain === "Crystal planet")).toBe(false); + const g = grid(15); + const c = centerHex(g); + const last = lastRing(g); + let crystal = 0; + for (let seed = 1; seed <= 40; seed++) { + for (const [k, t] of orbits(palette, g, seed, { bodies: "crowded" }, undefined, undefined, src).cells) { + if (t !== "Crystal planet") continue; + crystal++; + expect(orbitZone(distance(c, key(k), g), 2, last)).toBe("outer"); + } + } + expect(crystal).toBeGreaterThan(20); + }); + + it("rows that aren't terrains of the palette are named in the warnings, never placed", () => { + const table: WorldTypeTable = { ...DEFAULT_SPACE, rows: [...DEFAULT_SPACE.rows, { world: "Dyson sphere", weight: 50, map: "system" }] }; + const r = orbits(SPACE_SYSTEM_TERRAINS, grid(13), 3, { bodies: "crowded" }, undefined, undefined, worldTypesSource(table, SPACE_SYSTEM_TERRAINS)); + expect([...r.cells.values()]).not.toContain("Dyson sphere"); + expect(r.warnings.join(" ")).toMatch(/orbits row not a terrain of this palette, so never placed: Dyson sphere/); + }); + + it("Default space on the shipped palette: no warnings", () => { + const r = orbits(SPACE_SYSTEM_TERRAINS, grid(13), 3, {}, undefined, undefined, worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS)); + expect(r.warnings).toEqual([]); + }); +}); + +describe("the mainworld comes from the sector row's Mainworld (data, not names)", () => { + const palette: TerrainColor[] = [ + { name: "Dark", color: "#000", type: "void" }, + { name: "Sun", color: "#ff0", type: "star" }, + { name: "Paradise", color: "#0f0", type: "world" }, + { name: "Rock", color: "#777", type: "world" }, + ]; + const table: WorldTypeTable = { + name: "Mine", + rows: [ + { world: "Eden", map: "sector", mainworld: "Paradise" }, + { world: "Rock", map: "system" }, + ], + }; + + it("a custom sector world opens on the body its row names, every time", () => { + const src = worldTypesSource(table, palette); + expect(mainworldFor("eden", ["Paradise", "Rock"], src)).toBe("Paradise"); + for (let seed = 1; seed <= 20; seed++) { + const r = orbits(palette, grid(13), seed, { bodies: "few" }, undefined, { parent: { terrain: "Eden", type: "world" } }, src); + expect([...r.cells.values()]).toContain("Paradise"); + } + }); + + it("no Mainworld and no such body: no mainworld forced; the shipped pairing lives in the table", () => { + const src = worldTypesSource({ name: "Bare", rows: [{ world: "ocean world", map: "sector" }] }, SPACE_SYSTEM_TERRAINS); + const bodies = orbitRoles(SPACE_SYSTEM_TERRAINS)!.bodies; + expect(mainworldFor("ocean world", bodies, src)).toBeUndefined(); + expect(mainworldFor("ocean world", bodies, worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS))).toBe("ocean planet"); + }); +}); diff --git a/tests/proceduralGenerators.test.ts b/tests/proceduralGenerators.test.ts index bcaa5f41..900aa004 100644 --- a/tests/proceduralGenerators.test.ts +++ b/tests/proceduralGenerators.test.ts @@ -18,6 +18,7 @@ import { type ProcGrid, } from "../src/worldgen/procedural/common"; import { mulberry32 } from "../packages/hex-wfc/src"; +import { ZONE_ROLES, roleOdds } from "../src/worldgen/tableRoles"; import { suggestBaseTerrain } from "../src/worldgen/registry"; import type { TerrainColor } from "../src/types"; @@ -348,13 +349,14 @@ describe("terrain types", () => { expect(r.station).toBe("Outpost"); }); - it("weights custom bodies by zone: hints, then type", () => { - const w = orbitRoles(custom)!.zoneWeights; - expect(w.habitable["hearthworld"]).toBeGreaterThan(w.inner["hearthworld"]); - expect(w.outer["frostbite"]).toBeGreaterThan(w.habitable["frostbite"]); - expect(w.outer["big blue"]).toBeGreaterThan(w.inner["big blue"]); - // No hint: plain world-type weights. - expect(w.habitable["luna"]).toBe(3); + it("no name rules: without a table every body has the same odds in every zone, and the warnings say so", () => { + const roles = orbitRoles(custom)!; + for (const zone of ["inner", "habitable", "outer"] as const) { + const o = roleOdds(undefined, ZONE_ROLES[zone], { zone }, roles.bodies); + expect(o.odds.map((x) => x.odds)).toEqual(roles.bodies.map(() => 1 / roles.bodies.length)); + expect(o.from).toBe("equal odds"); + } + expect(orbits(custom, grid(13, 13), 1, {}).warnings.join(" ")).toMatch(/no table, so equal odds/); }); it("puts the typed star at the centre, sweeps asteroid-type belts, uses only palette terrains", () => { diff --git a/tests/regionContext.test.ts b/tests/regionContext.test.ts index 67443a98..691e5c5e 100644 --- a/tests/regionContext.test.ts +++ b/tests/regionContext.test.ts @@ -6,6 +6,10 @@ import { planetSurface } from "../src/worldgen/procedural/planetSurface"; import { mainworldFor, orbits } from "../src/worldgen/procedural/orbits"; import { sideOf, type GenerationContext, type ProcGrid } from "../src/worldgen/procedural/common"; import { regionDetailDescription } from "../src/worldgen/registry"; +import { worldTypesSource } from "../src/space/worldTypesSource"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; + +const DEFAULT_SPACE = { name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }; const grid: ProcGrid = { cols: 16, rows: 12, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; const typeOf = new Map(DEFAULT_TERRAIN_PALETTE.map((t) => [t.name, t.type])); @@ -113,20 +117,27 @@ describe("Region detail (planet surface with context)", () => { describe("Orbits mainworld from the sector hex", () => { const bodies = SPACE_SYSTEM_TERRAINS.filter((t) => ["world", "gas-giant", "asteroids"].includes(t.type ?? "")).map((t) => t.name); - it("maps sector terrain names to bodies", () => { - expect(mainworldFor("ocean world", bodies)).toBe("ocean planet"); - expect(mainworldFor("garden world", bodies)).toBe("terrestrial planet"); - expect(mainworldFor("gas giant", bodies)).toBe("gas giant"); - expect(mainworldFor("ice world", bodies)).toBe("ice planet"); - expect(mainworldFor("asteroid belt", bodies)).toBe("asteroid belt"); - expect(mainworldFor("nebula", bodies)).toBeUndefined(); - expect(mainworldFor(undefined, bodies)).toBeUndefined(); + it("reads the sector row's Mainworld (data, not name rules)", () => { + const src = worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS); + expect(mainworldFor("ocean world", bodies, src)).toBe("ocean planet"); + expect(mainworldFor("garden world", bodies, src)).toBe("terrestrial planet"); + expect(mainworldFor("gas giant", bodies, src)).toBe("gas giant"); + expect(mainworldFor("ice world", bodies, src)).toBe("ice planet"); + expect(mainworldFor("asteroid belt", bodies, src)).toBe("asteroid belt"); + expect(mainworldFor("nebula", bodies, src)).toBeUndefined(); + expect(mainworldFor(undefined, bodies, src)).toBeUndefined(); + }); + + it("without a table nothing is guessed from names: only a sector terrain that is itself a body", () => { + expect(mainworldFor("ocean world", bodies)).toBeUndefined(); + expect(mainworldFor("garden world", bodies)).toBeUndefined(); + expect(mainworldFor("Gas Giant", bodies)).toBe("gas giant"); }); it("the system always contains the hinted mainworld, even with few planets", () => { const g: ProcGrid = { cols: 13, rows: 13, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }; for (let seed = 1; seed <= 20; seed++) { - const r = orbits(SPACE_SYSTEM_TERRAINS, g, seed, { bodies: "few" }, undefined, { parent: { terrain: "ocean world", type: "world" } }); + const r = orbits(SPACE_SYSTEM_TERRAINS, g, seed, { bodies: "few" }, undefined, { parent: { terrain: "ocean world", type: "world" } }, worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS)); expect([...r.cells.values()]).toContain("ocean planet"); } }); diff --git a/tests/starScatterTables.test.ts b/tests/starScatterTables.test.ts new file mode 100644 index 00000000..80cdc4e2 --- /dev/null +++ b/tests/starScatterTables.test.ts @@ -0,0 +1,131 @@ +/** + * SP1 / F3: Star scatter places what the World types table says, a custom + * world added to the palette included, and the World types preview's odds + * (roleOdds over the same source) are the odds it really places. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { SPACE_SECTOR_TERRAINS } from "../src/palettes/presets"; +import { starScatter, starScatterRoles } from "../src/worldgen/procedural/starScatter"; +import { roleOdds } from "../src/worldgen/tableRoles"; +import { worldTypesSource } from "../src/space/worldTypesSource"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import type { WorldTypeTable } from "../src/space/worldTypes"; +import type { ProcGrid } from "../src/worldgen/procedural/common"; +import type { TerrainColor } from "../src/types"; + +const DEFAULT_SPACE: WorldTypeTable = { name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }; +const grid = (n: number): ProcGrid => ({ cols: n, rows: n, offset: { x: 0, y: 0 }, stagger: "odd", orientation: "flat" }); + +/** Share of each terrain among the system hexes of many dense sectors. */ +function placedShares(terrains: TerrainColor[], table: WorldTypeTable | undefined, seeds = 12): { shares: Record; n: number; warnings: string[] } { + const bg = starScatterRoles(terrains)!.background; + const counts = new Map(); + let n = 0; + const warnings = new Set(); + for (let seed = 1; seed <= seeds; seed++) { + const src = table ? worldTypesSource(table, terrains) : undefined; + const r = starScatter(terrains, grid(36), seed, { density: "cluster", clouds: "none", routes: "none" }, undefined, src); + r.warnings.forEach((w) => warnings.add(w)); + for (const t of r.cells.values()) { + if (t === bg) continue; + counts.set(t, (counts.get(t) ?? 0) + 1); + n++; + } + } + return { shares: Object.fromEntries([...counts].map(([k, c]) => [k, c / n])), n, warnings: [...warnings] }; +} + +/** Each placed share within 4.5 standard errors of the preview's odds (and nothing else placed). */ +function expectMatches(shares: Record, n: number, odds: { terrain: string; odds: number }[]) { + const want = Object.fromEntries(odds.map((o) => [o.terrain, o.odds])); + for (const k of Object.keys(shares)) expect({ k, inOdds: k in want }).toEqual({ k, inOdds: true }); + for (const [k, p] of Object.entries(want)) { + const got = shares[k] ?? 0; + const se = Math.sqrt((p * (1 - p)) / n); + expect({ k, ok: Math.abs(got - p) <= 4.5 * se + 1e-3 }).toEqual({ k, ok: true }); + } +} + +describe("Star scatter rolls on the World types table (SP1)", () => { + it("Default space: what it places matches the preview's odds, with no warnings", () => { + const src = worldTypesSource(DEFAULT_SPACE, SPACE_SECTOR_TERRAINS); + const preview = roleOdds(src, "sector-hexes", {}, starScatterRoles(SPACE_SECTOR_TERRAINS)!.worlds); + const { shares, n, warnings } = placedShares(SPACE_SECTOR_TERRAINS, DEFAULT_SPACE); + expect(n).toBeGreaterThan(10000); + expect(warnings).toEqual([]); + expectMatches(shares, n, preview.odds); + }); + + it("F3: a custom world added to the palette comes up at the odds the preview promises", () => { + const palette: TerrainColor[] = [...SPACE_SECTOR_TERRAINS, { name: "Crystal world", color: "#aef", type: "world" }]; + const table: WorldTypeTable = { ...DEFAULT_SPACE, rows: [...DEFAULT_SPACE.rows, { world: "crystal world", weight: 17, map: "sector" }] }; + const preview = roleOdds(worldTypesSource(table, palette), "sector-hexes", {}, starScatterRoles(palette)!.worlds); + // 17 of 34 world weight, of the 96% that aren't features. The palette's spelling. + expect(preview.odds.find((o) => o.terrain === "Crystal world")!.odds).toBeCloseTo(0.48, 12); + const { shares, n } = placedShares(palette, table); + expectMatches(shares, n, preview.odds); + expect(shares["Crystal world"]).toBeGreaterThan(0.45); + }); + + it("a weight change moves the odds (the table is what counts)", () => { + const table: WorldTypeTable = { ...DEFAULT_SPACE, features: [], rows: DEFAULT_SPACE.rows.map((r) => (r.world === "ocean world" ? { ...r, weight: 100 } : r)) }; + const { shares } = placedShares(SPACE_SECTOR_TERRAINS, table, 4); + expect(shares["ocean world"]).toBeGreaterThan(0.8); + expect(shares["black hole"]).toBeUndefined(); + }); + + it("rows that aren't terrains of the palette are never placed, and the warnings name them", () => { + const table: WorldTypeTable = { + ...DEFAULT_SPACE, + rows: [...DEFAULT_SPACE.rows, { world: "crystal world", weight: 50, map: "sector" }], + features: [...(DEFAULT_SPACE.features ?? []), { feature: "wormhole", chance: 0.1 }], + }; + const { shares, warnings } = placedShares(SPACE_SECTOR_TERRAINS, table, 2); + expect(shares["crystal world"]).toBeUndefined(); + expect(warnings.join(" ")).toMatch(/Sector hexes row not a terrain of this palette, so never placed: crystal world/); + expect(warnings.join(" ")).toMatch(/Sector features not a terrain of this palette, so never placed: wormhole/); + }); + + it("a custom palette with no shipped names, and its own table, works end to end", () => { + const palette: TerrainColor[] = [ + { name: "Abyssal Drift", color: "#000", type: "void" }, + { name: "Hearthworld", color: "#0f0", type: "world" }, + { name: "Cinder", color: "#f00", type: "world" }, + { name: "Waystation", color: "#888", type: "station" }, + ]; + const table: WorldTypeTable = { + name: "Mine", + rows: [{ world: "Hearthworld", weight: 3, map: "sector" }, { world: "Cinder", weight: 1, map: "sector" }], + features: [{ feature: "Waystation", chance: 0.1 }], + }; + const preview = roleOdds(worldTypesSource(table, palette), "sector-hexes", {}, starScatterRoles(palette)!.worlds); + expect(Object.fromEntries(preview.odds.map((o) => [o.terrain, o.odds]))).toEqual({ Hearthworld: 0.9 * 0.75, Cinder: 0.9 * 0.25, Waystation: 0.1 }); + const { shares, n, warnings } = placedShares(palette, table); + expect(warnings).toEqual([]); + expectMatches(shares, n, preview.odds); + }); + + it("no table (None, or the shipped palette with nothing set): equal odds over the worlds, and it says so", () => { + const worlds = starScatterRoles(SPACE_SECTOR_TERRAINS)!.worlds; + const preview = roleOdds(undefined, "sector-hexes", {}, worlds); + expect(preview.from).toBe("equal odds"); + for (const o of preview.odds) expect(o.odds).toBeCloseTo(1 / worlds.length, 12); + const { shares, n, warnings } = placedShares(SPACE_SECTOR_TERRAINS, undefined, 6); + expect(warnings.join(" ")).toMatch(/Sector hexes: no table, so equal odds/); + expectMatches(shares, n, preview.odds); + }); + + it("a table with no row for this palette falls back to equal odds, and says so", () => { + const palette: TerrainColor[] = [{ name: "Black", color: "#000", type: "void" }, { name: "Haven", color: "#0f0", type: "world" }]; + const r = starScatter(palette, grid(10), 1, { density: "dense" }, undefined, worldTypesSource(DEFAULT_SPACE, palette)); + expect(new Set(r.cells.values())).toEqual(new Set(["Black", "Haven"])); + expect(r.warnings.join(" ")).toMatch(/never placed/); + }); + + it("a (nothing) row is empty space", () => { + const table: WorldTypeTable = { name: "Empty", rows: [{ world: "(nothing)", weight: 1, map: "sector" }], features: [] }; + const r = starScatter(SPACE_SECTOR_TERRAINS, grid(10), 1, { density: "cluster", clouds: "none" }, undefined, worldTypesSource(table, SPACE_SECTOR_TERRAINS)); + expect(new Set(r.cells.values())).toEqual(new Set(["empty space"])); + }); +}); diff --git a/tests/worldTypeStars.test.ts b/tests/worldTypeStars.test.ts index 40f7f971..534dff2b 100644 --- a/tests/worldTypeStars.test.ts +++ b/tests/worldTypeStars.test.ts @@ -239,7 +239,7 @@ describe("Stars and Sector features in the note", () => { const text = buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS, DEFAULT_WORLD_TYPE_EXTRAS); const p = parseWorldTypes(text); expect(p.problems).toEqual([]); - expect(p.format).toBe(2); + expect(p.format).toBe(3); expect(p.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); expect(p.stars).toEqual(DEFAULT_STAR_ROWS); expect(p.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); @@ -317,19 +317,19 @@ describe("Stars and Sector features in the note", () => { expect(updateWorldTypes(text, [{ world: "B" }])).toContain("| Gate | 2% |"); }); - it("a format 1 note is given the shipped stars and features once, and marked format 2", () => { + it("a format 1 note is given the shipped stars and features once, and marked with the current format", () => { const v2 = buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS); - const v1 = v2.slice(0, v2.indexOf("## Stars")).replace("hexmaker-world-types: 2", "hexmaker-world-types: 1").trimEnd() + "\n\nMy own words.\n"; + const v1 = v2.slice(0, v2.indexOf("## Stars")).replace("hexmaker-world-types: 3", "hexmaker-world-types: 1").trimEnd() + "\n\nMy own words.\n"; const up = upgradeWorldTypes(v1, DEFAULT_WORLD_TYPE_EXTRAS); const p = parseWorldTypes(up); - expect(p.format).toBe(2); + expect(p.format).toBe(3); expect(p.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); expect(p.stars).toEqual(DEFAULT_STAR_ROWS); expect(p.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); expect(up).toContain("My own words."); - expect(up.startsWith(v1.slice(0, v1.indexOf("My own words.")).replace("world-types: 1", "world-types: 2"))).toBe(true); + expect(up.startsWith(v1.slice(0, v1.indexOf("My own words.")).replace("world-types: 1", "world-types: 3"))).toBe(true); expect(upgradeWorldTypes(up, DEFAULT_WORLD_TYPE_EXTRAS)).toBe(up); - // A format 2 note whose Stars table was deleted stays without it. + // A current note whose Stars table was deleted stays without it. const deleted = up.slice(0, up.indexOf("## Stars")) + up.slice(up.indexOf("## Sector features")); expect(upgradeWorldTypes(deleted, DEFAULT_WORLD_TYPE_EXTRAS)).toBe(deleted); // A format 1 note that already has a Stars table keeps its own. @@ -376,11 +376,11 @@ describe("WorldTypeStore: stars and sector features", () => { it("upgrades a format 1 note when it reads it", async () => { const v2 = buildWorldTypes(DEFAULT_WORLD_TYPES, DEFAULT_WORLD_TYPE_ROWS); - const v1 = v2.slice(0, v2.indexOf("## Stars")).replace("hexmaker-world-types: 2", "hexmaker-world-types: 1"); + const v1 = v2.slice(0, v2.indexOf("## Stars")).replace("hexmaker-world-types: 3", "hexmaker-world-types: 1"); const v = new MemVault({ [NOTE]: v1 }); const store = new WorldTypeStore(storePlugin(v, { worldTypesSeeded: true }) as never); await store.init(); - expect(v.files.get(NOTE)).toContain("hexmaker-world-types: 2"); + expect(v.files.get(NOTE)).toContain("hexmaker-world-types: 3"); expect(v.files.get(NOTE)).toContain("## Sector features"); expect(store.get(DEFAULT_WORLD_TYPES)!.stars).toEqual(DEFAULT_STAR_ROWS); expect(store.get(DEFAULT_WORLD_TYPES)!.features).toEqual(DEFAULT_SECTOR_FEATURE_ROWS); diff --git a/tests/worldTypes.test.ts b/tests/worldTypes.test.ts index 2ce1a693..7b5202db 100644 --- a/tests/worldTypes.test.ts +++ b/tests/worldTypes.test.ts @@ -126,8 +126,8 @@ describe("Default space reproduces the old built-in odds", () => { const back = parseWorldTypes(text); expect(back.problems).toEqual([]); expect(back.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); - expect(text).toContain("hexmaker-world-types: 2"); - expect(text).toContain("| ocean planet | 3 | system | habitable | | | 20×14 | procedural:planet-surface | water=85, climate=lush, relief=normal | Expanded | ocean | |"); + expect(text).toContain("hexmaker-world-types: 3"); + expect(text).toContain("| ocean planet | 3 | system | habitable | | | | 20×14 | procedural:planet-surface | water=85, climate=lush, relief=normal | Expanded | ocean | |"); }); }); @@ -140,7 +140,7 @@ describe("world types note", () => { it("round-trips every column and keeps prose", () => { const text = buildWorldTypes("Mine", rows).replace("# Mine", "# Mine\n\nMy own words."); - expect(parseWorldTypes(text)).toEqual({ rows, problems: [], unreadable: [], stars: [], features: [], unreadableStars: [], unreadableFeatures: [], format: 2 }); + expect(parseWorldTypes(text)).toEqual({ rows, problems: [], unreadable: [], stars: [], features: [], unreadableStars: [], unreadableFeatures: [], format: 3 }); expect(updateWorldTypes(text, rows)).toBe(text); const next = updateWorldTypes(text, rows.slice(1)); expect(next).toContain("My own words."); @@ -173,8 +173,8 @@ describe("world types note", () => { const next = updateWorldTypes(text, [{ world: "A", weight: 2 }, { world: "C" }]); expect(next).toContain("| B | lots |"); expect(parseWorldTypes(next).rows.map((r) => r.world)).toEqual(["A", "C"]); - for (const bad of [["X", "", "galaxy"], ["X", "", "", "nowhere"], ["X", "", "", "", "", "", "big"], ["X", "", "", "", "", "boiling"], ["X", "", "", "", "", "", "", "", "water"]]) { - const cells = [...bad, ...Array(12 - bad.length).fill("")]; + for (const bad of [["X", "", "galaxy"], ["X", "", "", "nowhere"], ["X", "", "", "", "", "", "", "big"], ["X", "", "", "", "", "boiling"], ["X", "", "", "", "", "", "", "", "", "water"]]) { + const cells = [...bad, ...Array(13 - bad.length).fill("")]; expect(readWorldTypeCells(cells).problem).toBeTruthy(); } expect(parseWorldTypes("no table").problems[0].text).toMatch(/no table/); @@ -271,7 +271,7 @@ describe("WorldTypeStore", () => { const plugin = storePlugin(v); const store = new WorldTypeStore(plugin as never); await store.init(); - expect(v.files.get(NOTE)).toContain("hexmaker-world-types: 2"); + expect(v.files.get(NOTE)).toContain("hexmaker-world-types: 3"); expect(store.get(DEFAULT_WORLD_TYPES)!.rows).toEqual(DEFAULT_WORLD_TYPE_ROWS); expect(plugin.settings.worldTypesSeeded).toBe(true); v.files.delete(NOTE); diff --git a/tests/worldgenFirstMap.test.ts b/tests/worldgenFirstMap.test.ts index 3991f990..c48a8534 100644 --- a/tests/worldgenFirstMap.test.ts +++ b/tests/worldgenFirstMap.test.ts @@ -26,6 +26,10 @@ import { neighbourSeaText } from "../src/worldgen/NewMapSetupModal"; import type { ProcGrid } from "../src/worldgen/procedural/common"; import { hexNeighbors } from "../packages/hex-wfc/src"; import type { PathType, TerrainColor } from "../src/types"; +import { worldTypesSource } from "../src/space/worldTypesSource"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; + +const DEFAULT_SPACE = { name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }; /** Fresh-eyes 2026-10-09 (#36): first-run wizard, Overland, Frozen, palette defaults. */ @@ -561,6 +565,12 @@ describe("Star scatter and Orbits: the path type is an option from the palette", const fakePlugin = { settings: { worldFolder: "world", hexOrientation: "flat", staggerOffset: "odd", terrainPalettes: [] }, app: { vault: { getMarkdownFiles: () => [] } }, + // The shipped World types table, as a vault would have it (SP1). + worldTypeStore: { + list: () => [DEFAULT_SPACE], + defaultName: () => DEFAULT_SPACE.name, + sourceFor: (_v: string | undefined, palette: TerrainColor[]) => ({ source: worldTypesSource(DEFAULT_SPACE, palette) }), + }, }; const kindsP = listGeneratorKinds(fakePlugin as never); const kindOf = async (id: string) => (await kindsP).find((k) => k.id === id)!; From 3acfb6614135065babee5977248bc4e3a820aef3 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 11:31:15 -0400 Subject: [PATCH 307/558] fix(setup): never install map-type content at startup; biomes for overworlds Full smoke after merging SP3 failed in overworld, custom-palette and deleted: a startup hook installed World content (Expanded, Limited, biome notes) into vaults set up without the wizard, and a recipe-built overworld had no biomes because seeding waited for a kindContent record. - Content installs only from an explicit setup pick or a type turned on in Settings. A vault whose setup is over without a record gets one inferred from its enabled types (inferKindContent, at load and on save); nothing is written. "Don't show again" just records. SM-DEL holds: no refill. - Biome notes (biomeSeedingOn): never for a type that's off; otherwise when picked/turned on, when Regions and overworlds is on (also seeded the moment it's turned on), or to top up a vault that already has them. - Tests for each smoke case; full smoke matrix passes (10 setups). Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +-- src/HexmakerPlugin.ts | 22 +++++++++++------ src/SetupWizardView.ts | 5 ++-- src/kindContent.ts | 46 +++++++++++++++++++++++++++-------- src/overworld/BiomeStore.ts | 23 +++++++++++------- src/overworld/biomePresets.ts | 2 +- tests/biomeNotes.test.ts | 16 +++++++++--- tests/spaceSetup.test.ts | 30 ++++++++++++++++++++--- 8 files changed, 107 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index eef3eeac..30d95ebc 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Toggle the GM layer from the overlay panel to switch between player-facing and G ## Getting started -After enabling the plugin, a **setup wizard** opens. It asks what you'll map (a fantasy world, space, or both), where your world folder lives, and makes your first map. What it installs follows that choice: a world setup gets the Expanded and Limited palettes and the biome notes; a space-only setup gets the three space palettes (Sector, System, Planet) and nothing fantasy, and **Palette for new maps** starts on Space - Sector; both gets both. Turning a map type on later in **Settings → Map types** installs its content then (once: anything you delete stays deleted). That last step can **generate the terrain** for you (Overland for a world map, Star scatter for a star sector), with a preview and a re-roll button, or start blank for painting by hand. It also creates the terrain description and encounter tables. That's all you need to start. +After enabling the plugin, a **setup wizard** opens. It asks what you'll map (a fantasy world, space, or both), where your world folder lives, and makes your first map. What it installs follows that choice: a world setup gets the Expanded and Limited palettes and the biome notes; a space-only setup gets the three space palettes (Sector, System, Planet) and nothing fantasy, and **Palette for new maps** starts on Space - Sector; both gets both. Turning a map type on later in **Settings → Map types** installs its content then (once: anything you delete stays deleted). Nothing is installed at startup: a vault set up without the wizard keeps exactly the palettes it has. That last step can **generate the terrain** for you (Overland for a world map, Star scatter for a star sector), with a preview and a re-roll button, or start blank for painting by hand. It also creates the terrain description and encounter tables. That's all you need to start. To set things up by hand instead (or later): @@ -140,7 +140,7 @@ Notes, settings and palettes are never locked. There are no confirm boxes for th Which biome a hex is comes from its terrain's **Type**, never its name: forest-type terrains are temperate forest, wetland swamp, and so on. Where a type has variants, the **last** terrains of that type in the palette stand for them, in this order: forest → taiga, deep forest; grassland → savanna; hills → karst; wetland → river delta. Reorder the palette to choose (on Expanded: evergreen, evergreen heavy, savanna, jungle hills, river delta). A terrain with no type has no biome. -**Your own biomes.** Every biome is a plain note in the biomes folder (default `{world folder}/biomes`, see Settings). The built-in ones are written there once when the plugin starts, so you can edit them like any other note; delete one and it stays deleted. A biome note has a name, a colour, a **Mix** table of terrain *types* with weights (never terrain names, so it works on any palette with types), a **Transitions** table (biomes it shouldn't touch and the biome put between them), and in its frontmatter `blend` (narrow, normal or wide), `land-share` and `min-islands` (for watery biomes) and an optional `generator: [[…]]` link. Rows that can't be read are reported and left as you wrote them; your own text in the note is kept. On an overworld's **Biomes** view, **Biomes…** lists them: **Add biome…** opens a form (pick **Blend (built-in mixing)** or one of your generators, name, colour, type weights, blend, land share, fewest islands, transitions) with a live preview of one region, and **Save** writes the note. **Edit…** opens the same form for an existing biome (built-in ones also have **Restore default**, which backs up the old note first). **Edit generator…** (also in **Edit region…**) opens the biome's generator, or its note for now. Biomes linked to a generator say "available once generator regions land" and blend until then. Your biomes appear in the biome picker and make regions with the blend field straight away. Adding and editing biomes needs Build or God. A region keeps its biome when you rename the biome's note; if you delete the note, the region keeps its terrain and **Edit region…** shows "Unknown biome". Inside a region, click the middle of the hex flower to open **Edit region…** for it; the overworld's right-click menu has **Create token here** to mark the party. +**Your own biomes.** Every biome is a plain note in the biomes folder (default `{world folder}/biomes`, see Settings). The built-in ones are written there once (when the setup picks World, World is turned on in Settings, or Regions and overworlds is turned on; never in a space-only setup), so you can edit them like any other note; delete one and it stays deleted. A biome note has a name, a colour, a **Mix** table of terrain *types* with weights (never terrain names, so it works on any palette with types), a **Transitions** table (biomes it shouldn't touch and the biome put between them), and in its frontmatter `blend` (narrow, normal or wide), `land-share` and `min-islands` (for watery biomes) and an optional `generator: [[…]]` link. Rows that can't be read are reported and left as you wrote them; your own text in the note is kept. On an overworld's **Biomes** view, **Biomes…** lists them: **Add biome…** opens a form (pick **Blend (built-in mixing)** or one of your generators, name, colour, type weights, blend, land share, fewest islands, transitions) with a live preview of one region, and **Save** writes the note. **Edit…** opens the same form for an existing biome (built-in ones also have **Restore default**, which backs up the old note first). **Edit generator…** (also in **Edit region…**) opens the biome's generator, or its note for now. Biomes linked to a generator say "available once generator regions land" and blend until then. Your biomes appear in the biome picker and make regions with the blend field straight away. Adding and editing biomes needs Build or God. A region keeps its biome when you rename the biome's note; if you delete the note, the region keeps its terrain and **Edit region…** shows "Unknown biome". Inside a region, click the middle of the hex flower to open **Edit region…** for it; the overworld's right-click menu has **Create token here** to mark the party. **Terrain weights.** A biome's Mix is by terrain type; an optional **Terrain weights** table (`| Terrain | Weight |`) says how one type's share is split between its terrains, so different forests can go together in different ratios: `Pine forest | 3` and `Oak forest | 1` make three pine hexes for every oak. Terrains not listed count 1, and 0 leaves one out. Names are matched ignoring case; rows that can't be read are reported. diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 7ca050f5..4296c44d 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -35,7 +35,7 @@ import { SetupWizardView } from "./SetupWizardView"; import { BiomeStore } from "./overworld/BiomeStore"; import { biomePoolsFolder, fillBiomeColumns } from "./overworld/overworldGen"; import { generatorsFolder } from "./worldgen/generators"; -import { planKindContent, resolveKindContent } from "./kindContent"; +import { inferKindContent, planKindContent, resolveKindContent } from "./kindContent"; import { PLACEHOLDER_MAP_NAME } from "./setupPlaceholder"; import { WorldTypeStore } from "./space/WorldTypeStore"; import { WorldTypesModal } from "./space/WorldTypesModal"; @@ -178,11 +178,6 @@ export default class HexmakerPlugin extends Plugin { void storesReady.then(() => this.ensureTablesForNewTerrains()); // NF1–NF3, once per vault: older hex, token and workflow notes in the new note formats (backed up first). void storesReady.then(() => runNoteFormatUpgrades(this)).catch((e) => console.error("Hexmaker: note format upgrades", e)); - // A fresh install whose setup was finished or turned off without - // picking map types: its types' content goes in now (SP3). - void Promise.all([biomesReady, storesReady]).then(() => { - if (!this.settings.kindContent && (this.settings.setupComplete || this.settings.setupDismissed)) return this.applyKindContent(); - }).catch((e) => console.error("Hexmaker: map type content", e)); // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. void this.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { if (!sandbox) return; @@ -839,7 +834,8 @@ export default class HexmakerPlugin extends Plugin { this.settings.mapKinds = resolveMapKinds(data["mapKinds"], this.settings.terrainPalettes); // Shipped content per map type (SP3): an update has its types' content // already; a fresh install writes none until its setup picks the types. - this.settings.kindContent = resolveKindContent(rawData, this.settings.mapKinds); + // Setup over without a pick: inferred, nothing installed (saved with the next save). + this.settings.kindContent = inferKindContent({ ...this.settings, kindContent: resolveKindContent(rawData, this.settings.mapKinds) }); // Feature level, also from the raw data: an install that already had // settings (an update) gets Advanced so nothing it used disappears; a // fresh one starts Simple. Saved right away, so the next load doesn't @@ -900,6 +896,9 @@ export default class HexmakerPlugin extends Plugin { async saveSettings() { this.settings.savedWith = pluginVersion(this); + // The setup just finished or was turned off without picking map types + // (e.g. "Don't show again", a recipe): record its types, install nothing. + this.settings.kindContent = inferKindContent(this.settings); await this.saveData(this.settings); // Mirror palette edits (from any editor) into the palette notes. void this.paletteStore.sync(); @@ -1000,6 +999,7 @@ export default class HexmakerPlugin extends Plugin { async setFeatureLevel(level: FeatureLevel): Promise { this.settings.featureLevel = level; await this.saveSettings(); + await this.biomesForOverworlds(); this.onFeaturesChanged(); } @@ -1007,9 +1007,15 @@ export default class HexmakerPlugin extends Plugin { async enableAdvancedFeature(f: AdvancedFeature): Promise { enableFeature(this.settings, f); await this.saveSettings(); + await this.biomesForOverworlds(); this.onFeaturesChanged(); } + /** Overworlds need biomes: the shipped ones (of map types that are on) once Regions and overworlds is on. */ + private async biomesForOverworlds(): Promise { + if (hasFeature(this.settings, "regions")) await this.biomeStore.seedShipped(); + } + /** Turn off one Advanced feature that was turned on by itself (Simple only). */ async disableAdvancedFeature(f: AdvancedFeature): Promise { this.settings.advancedFeatures = this.settings.advancedFeatures.filter((x) => x !== f); @@ -2546,7 +2552,7 @@ export default class HexmakerPlugin extends Plugin { s.kindContent = plan.done; await this.saveSettings(); if (plan.newKinds.length) { - await this.biomeStore.seedShipped(); + await this.biomeStore.seedShipped(true); if (plan.newKinds.includes("space")) await this.worldTypeStore.ensureDefault(); } this.onMapKindsChanged(); diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index d177cade..4ced36dd 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -978,9 +978,8 @@ export class SetupWizardView extends ItemView { }); dontShowBtn.addEventListener("click", () => { this.plugin.settings.setupDismissed = true; - // The map types it has now get their content (once). - const done = this.plugin.settings.kindContent ? this.plugin.saveSettings() : this.plugin.applyKindContent(); - void done.then(() => this.leaf.detach()); + // Not a pick: the types it has are recorded on save, nothing installed. + void this.plugin.saveSettings().then(() => this.leaf.detach()); }); } diff --git a/src/kindContent.ts b/src/kindContent.ts index 4b49d883..8fdeac78 100644 --- a/src/kindContent.ts +++ b/src/kindContent.ts @@ -6,9 +6,11 @@ * plans, from that data alone, what to install or drop. Nothing here looks * at a palette's name to decide its type. * - * - A type's content is installed once, the first time the type is on - * (settings.kindContent records which), so a palette or biome note the - * user deleted stays deleted. + * - A type's content is installed only when the setup wizard picks the + * type or it's turned on in Settings, and once (settings.kindContent + * records which), so a palette or biome note the user deleted stays + * deleted. Startup never installs: a vault without a record gets one + * inferred from its enabled types (inferKindContent) and nothing written. * - During the first setup only (before the wizard finishes), shipped * palettes a fresh install put in for a type the user then left off are * dropped again, but only when untouched (same terrains as the preset) @@ -23,6 +25,7 @@ import { ALL_MAP_KINDS, paletteKind, type MapKind } from "./mapKinds"; import type { TerrainColor } from "./types"; import { PALETTE_PRESETS, type PalettePreset } from "./palettes/presets"; import { terrainsEqual } from "./palettes/paletteNote"; +import { hasFeature, type FeatureSettings } from "./featureLevel"; export interface KindContentInput { /** Map types on now. */ @@ -102,17 +105,40 @@ export function planKindContent(input: KindContentInput): KindContentPlan { } /** - * May shipped content of this type be written now? Only once the setup has - * decided the map types (settings.kindContent is set) and the type is on. - * Gates the stores that seed shipped notes (biome notes, world types). + * May the shipped biome notes of map type `kind` be written? Never while the + * type is off (a space-only setup gets none). Otherwise when it's asked for + * (`explicit`: the setup picked the type, or it was turned on in + * Settings), when the overworld tools are on (Regions and overworlds: they + * need biomes, however the vault was made), or when the vault already has + * shipped biome notes (later shipped biomes top them up, once each). + * A vault that never had biome notes and doesn't use overworlds gets none + * written on its own (no content into a vault that didn't ask for it). */ -export function shippedContentOn( - settings: { kindContent?: string[] | null; mapKinds?: string[] }, +export function biomeSeedingOn( + settings: FeatureSettings & { mapKinds?: string[]; biomesSeeded?: string[] }, kind: MapKind, + explicit = false, ): boolean { - if (!Array.isArray(settings.kindContent)) return false; const kinds = Array.isArray(settings.mapKinds) ? settings.mapKinds : ALL_MAP_KINDS; - return kinds.includes(kind); + if (!kinds.includes(kind)) return false; + return explicit || hasFeature(settings, "regions") || (settings.biomesSeeded?.length ?? 0) > 0; +} + +/** + * settings.kindContent once the setup is over (finished or turned off) + * without picking the map types (a vault set up by hand, a recipe, an + * older build): the types it has on count as decided, and nothing is + * installed for them. Undecided while the setup is still to come. + */ +export function inferKindContent(settings: { + kindContent?: string[] | null; + mapKinds?: string[]; + setupComplete?: boolean; + setupDismissed?: boolean; +}): string[] | null { + if (Array.isArray(settings.kindContent)) return settings.kindContent; + if (!settings.setupComplete && !settings.setupDismissed) return null; + return [...(Array.isArray(settings.mapKinds) ? settings.mapKinds : ALL_MAP_KINDS)]; } /** diff --git a/src/overworld/BiomeStore.ts b/src/overworld/BiomeStore.ts index f9e250dd..5dc6e73e 100644 --- a/src/overworld/BiomeStore.ts +++ b/src/overworld/BiomeStore.ts @@ -7,9 +7,10 @@ * * - init(): reads every note, then writes each shipped biome (biomePresets) * that hasn't been seeded yet and has no note: once, never over a note. - * Only biomes whose map type is on, once the setup has picked the types - * (shippedContentOn): a space-only setup gets no biome notes, and turning - * World on later writes them then (seedShipped). + * Only biomes whose map type is on, and only when asked for or needed + * (biomeSeedingOn): a space-only setup gets no biome notes; picking or + * turning on World, or turning on the overworld tools, writes them then + * (seedShipped). * - Hand edits are read back live (vault events); unreadable rows are * reported once per edit and left as written. * - A biome's `id` (frontmatter) is what references use, so renaming the @@ -38,7 +39,7 @@ import { } from "./biomeNote"; import { BIOME_PRESETS, biomePreset } from "./biomePresets"; import { setBiomeSource } from "./biomes"; -import { shippedContentOn } from "../kindContent"; +import { biomeSeedingOn } from "../kindContent"; interface Entry { path: string; @@ -125,10 +126,14 @@ export class BiomeStore implements BiomeStoreApi { }); } - /** Write the shipped biomes of map types that are on now (a type was just turned on). */ - async seedShipped(): Promise { + /** + * Write the shipped biomes of map types that are on now. `explicit`: the + * setup picked the type or it was just turned on; otherwise only when + * biomeSeedingOn allows (the overworld tools were just turned on). + */ + async seedShipped(explicit = false): Promise { await this.enqueue(async () => { - await this.seed(); + await this.seed(explicit); this.publish(); }); } @@ -345,12 +350,12 @@ export class BiomeStore implements BiomeStoreApi { if (key && this.ready) new Notice(`Biome ${label}: couldn't read ${key}. Those rows are left as written.`, 8000); } - private async seed(): Promise { + private async seed(explicit = false): Promise { const s = this.plugin.settings; const seeded = s.biomesSeeded ?? []; const ids = new Set([...this.entries.values()].map((e) => e.fields.id)); const folder = this.folder(); - const presets = BIOME_PRESETS.filter((p) => shippedContentOn(s, p.kind)); + const presets = BIOME_PRESETS.filter((p) => biomeSeedingOn(s, p.kind, explicit)); if (!presets.length) return; const plan = presetsToSeed(seeded, ids, (name) => !!this.plugin.app.vault.getAbstractFileByPath(`${folder}/${name}.md`), presets); if (!plan.done.length) return; diff --git a/src/overworld/biomePresets.ts b/src/overworld/biomePresets.ts index c79f9298..2f0fb5cc 100644 --- a/src/overworld/biomePresets.ts +++ b/src/overworld/biomePresets.ts @@ -30,7 +30,7 @@ import type { MapKind } from "../mapKinds"; /** * A shipped biome: its note fields plus the map type it belongs to (data on * each item, never decided by name). Its note is only written while that - * type is on (BiomeStore, shippedContentOn): a space-only setup gets none. + * type is on (BiomeStore, biomeSeedingOn): a space-only setup gets none. * The type isn't written into the note. */ export type BiomePreset = BiomeNoteFields & { kind: MapKind }; diff --git a/tests/biomeNotes.test.ts b/tests/biomeNotes.test.ts index d537a30b..c68edb31 100644 --- a/tests/biomeNotes.test.ts +++ b/tests/biomeNotes.test.ts @@ -290,14 +290,22 @@ describe("BiomeStore", () => { expect([...v.files.keys()].filter((f) => f.startsWith(FOLDER))).toEqual([]); expect(store.list()).toEqual([]); expect(p.settings.biomesSeeded).toBeUndefined(); - // A fresh install before its setup picks the types: none either. + // A fresh Simple install before its setup picks the types: none either. const v2 = new MemVault(); - await boot(v2, { kindContent: undefined }); + const fresh = await boot(v2, { kindContent: null, featureLevel: "simple" }); expect([...v2.files.keys()].filter((f) => f.startsWith(FOLDER))).toEqual([]); - // World turned on later. + // ...until it asks: Regions and overworlds turned on (smoke "overworld": a recipe vault). + fresh.p.settings.advancedFeatures = ["regions"]; + await fresh.store.seedShipped(); + expect(v2.files.has(`${FOLDER}/Tundra.md`)).toBe(true); + // A Simple vault that never had biomes and doesn't use overworlds: none at startup. + const v3 = new MemVault(); + await boot(v3, { kindContent: ["world"], featureLevel: "simple" }); + expect([...v3.files.keys()].filter((f) => f.startsWith(FOLDER))).toEqual([]); + // World turned on later (an explicit pick). p.settings.mapKinds = ["space", "world"]; p.settings.kindContent = ["space", "world"]; - await store.seedShipped(); + await store.seedShipped(true); expect(v.files.has(`${FOLDER}/Tundra.md`)).toBe(true); }); diff --git a/tests/spaceSetup.test.ts b/tests/spaceSetup.test.ts index daf7880b..1569c3aa 100644 --- a/tests/spaceSetup.test.ts +++ b/tests/spaceSetup.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "node:test"; import expect from "expect"; -import { planKindContent, resolveKindContent, shippedContentOn } from "../src/kindContent"; +import { biomeSeedingOn, inferKindContent, planKindContent, resolveKindContent } from "../src/kindContent"; import { DEFAULT_SETTINGS, DEFAULT_TERRAIN_PALETTE, LIMITED_TERRAIN_PALETTE } from "../src/constants"; import { PALETTE_PRESETS, @@ -82,10 +82,32 @@ describe("what a setup installs follows the map types picked (SP3)", () => { expect(plan.remove).toEqual([]); }); + it("biome notes: never for a type that's off; else when asked, for overworlds, or to top up", () => { + expect(biomeSeedingOn({ mapKinds: ["space"], featureLevel: "advanced" }, "world", true)).toBe(false); + expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "simple" }, "world")).toBe(false); + expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "simple" }, "world", true)).toBe(true); + expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "advanced" }, "world")).toBe(true); + expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "simple", advancedFeatures: ["regions"] }, "world")).toBe(true); + expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "simple", biomesSeeded: ["tundra"] }, "world")).toBe(true); + }); + + it("a vault set up without a pick (recipe, Don't show again, custom or deleted palettes) is recorded, nothing installed", () => { + // smoke custom-palette / deleted: setup done by hand, no record. + const done = inferKindContent({ kindContent: null, mapKinds: ["world"], setupComplete: true }); + expect(done).toEqual(["world"]); + expect(inferKindContent({ kindContent: null, mapKinds: ["world"], setupDismissed: true })).toEqual(["world"]); + expect(inferKindContent({ kindContent: null, mapKinds: ["world"] })).toBeNull(); + expect(inferKindContent({ kindContent: ["space"], mapKinds: ["world"], setupComplete: true })).toEqual(["space"]); + // With that record nothing is planned: Moorland alone, or no palettes at all, stay so (SM-DEL). + for (const palettes of [[{ name: "Moorland", terrains: [{ name: "moor", color: "#556b2f", type: "grassland" }] }], []]) { + const plan = planKindContent({ kinds: ["world"], done, firstSetup: false, palettes, inUse: new Set(), defaultPalette: "Expanded" }); + expect(plan.install).toEqual([]); + expect(plan.remove).toEqual([]); + expect(plan.newKinds).toEqual([]); + } + }); + it("shipped notes wait until the setup picks the types; updates count as done", () => { - expect(shippedContentOn({ mapKinds: ["world"] }, "world")).toBe(false); - expect(shippedContentOn({ mapKinds: ["space"], kindContent: ["space"] }, "world")).toBe(false); - expect(shippedContentOn({ mapKinds: ["world"], kindContent: ["world"] }, "world")).toBe(true); expect(resolveKindContent(null, ["world"])).toBeNull(); expect(resolveKindContent({}, ["world"])).toBeNull(); // A fresh install's first save keeps it undecided across a restart. From c716246f682b46c5c1c0d56416bbc3990d8772b5 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 12:31:07 -0400 Subject: [PATCH 308/558] feat(notes): write the remaining plain references as wikilinks (NF3 follow-up) Map notes' palette and region-palette, palette notes' child-palette, generators' palette / source-map(s) / blend-of, generator saves' generator-path and the world types Palette column are written as links to the notes they name, so renames flow through Obsidian's link updates. Readers take the plain form forever (generator meta is read back to plain names, so every meta reader keeps working); a name that names no note stays as typed. hex-wfc keeps list meta written as YAML lists (inline or Obsidian's block style). A one-time "ref-links" rewrite (backed up, recorded in noteFormatUpgrades) converts existing notes; it waits for the world types store too. Co-Authored-By: Claude Opus 5.5 --- packages/hex-wfc/src/format.ts | 19 +- src/HexmakerPlugin.ts | 7 +- src/maps/MapStore.ts | 4 + src/maps/mapNote.ts | 29 +++- src/noteFormatUpgrade.ts | 91 +++++++++- src/noteFormats.ts | 103 +++++++++++ src/palettes/PaletteStore.ts | 15 +- src/palettes/paletteNote.ts | 26 ++- src/space/WorldTypeStore.ts | 21 ++- src/space/worldTypes.ts | 65 ++++++- src/worldgen/GeneratorPanel.ts | 4 +- src/worldgen/biomeRegion.ts | 6 +- src/worldgen/generatorRefs.ts | 78 +++++++++ src/worldgen/generators.ts | 47 ++++- src/worldgen/regionGenerator.ts | 5 +- src/worldgen/saveFormat.ts | 34 +++- src/worldgen/saves.ts | 13 +- tests/noteFormats.test.ts | 13 +- tests/noteRefLinks.test.ts | 296 ++++++++++++++++++++++++++++++++ tests/palettes.test.ts | 11 +- 20 files changed, 815 insertions(+), 72 deletions(-) create mode 100644 src/worldgen/generatorRefs.ts create mode 100644 tests/noteRefLinks.test.ts diff --git a/packages/hex-wfc/src/format.ts b/packages/hex-wfc/src/format.ts index 9870cb1f..95548317 100644 --- a/packages/hex-wfc/src/format.ts +++ b/packages/hex-wfc/src/format.ts @@ -273,6 +273,17 @@ function yamlValue(v: string): string { return /^[A-Za-z0-9_][A-Za-z0-9 _./()-]*$/.test(v) && !v.endsWith(" ") ? v : JSON.stringify(v); } +/** A meta value that is a list of strings in JSON form (`["a", "b"]`): written as a YAML flow list. */ +function isFlowList(v: string): boolean { + if (!v.startsWith("[") || v.startsWith("[[")) return false; + try { + const x = JSON.parse(v) as unknown; + return Array.isArray(x) && x.every((i) => typeof i === "string"); + } catch { + return false; + } +} + function parseYamlValue(raw: string): string { const v = raw.trim(); if (v.startsWith('"')) { @@ -347,7 +358,7 @@ export function modelToMarkdown(model: HexWfcModel): string { } for (const [k, v] of Object.entries(model.meta)) { if (reserved.has(k)) continue; - fm.push(`${k}: ${yamlValue(v)}`); + fm.push(`${k}: ${isFlowList(v) ? v : yamlValue(v)}`); } const withLayout = model.terrains.filter((t) => layoutSize(t.layout)); const layout5 = withLayout.some((t) => layoutSize(t.layout) === 5); @@ -515,6 +526,12 @@ export function parseModelMarkdown(text: string, fallbackName = "Untitled"): Par const decoded = decodeSetting(field, value); if ("error" in decoded) warnings.push(`Setting "${key}: ${value}" ${decoded.error}, ignored`); else settings[field] = decoded.value; + } else if (value === "" && /^\s+-(\s|$)/.test(lines[i + 1] ?? "")) { + // A block list (Obsidian's Properties panel writes lists this way): + // kept as a flow list, `["a", "b"]`, like one written inline. + const items: string[] = []; + while (/^\s+-(\s|$)/.test(lines[i + 1] ?? "")) items.push(parseYamlValue(lines[++i].replace(/^\s+-/, ""))); + meta[key] = `[${items.map((x) => JSON.stringify(x)).join(", ")}]`; } else meta[key] = value; } i++; diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index eb285067..ec629a9a 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -171,13 +171,14 @@ export default class HexmakerPlugin extends Plugin { // Palettes first (maps reference them), then map notes — which may // migrate per-hex data out of hex notes on the first run. const biomesReady = this.biomeStore.init(); - void this.worldTypeStore.init(); + const worldTypesReady = this.worldTypeStore.init(); const storesReady = this.paletteStore.init().then(() => this.mapStore.init()); // BC1, once per vault: every overworld hex's biome in its Biome column. void Promise.all([biomesReady, storesReady]).then(() => fillBiomeColumns(this)).catch((e) => console.error("Hexmaker: filling Biome columns", e)); void storesReady.then(() => this.ensureTablesForNewTerrains()); - // NF1–NF3, once per vault: older hex, token and workflow notes in the new note formats (backed up first). - void storesReady.then(() => runNoteFormatUpgrades(this)).catch((e) => console.error("Hexmaker: note format upgrades", e)); + // NF1–NF3, once per vault: older hex, token, workflow, map, palette, + // generator and world types notes in the new note formats (backed up first). + void Promise.all([storesReady, worldTypesReady.catch(() => undefined)]).then(() => runNoteFormatUpgrades(this)).catch((e) => console.error("Hexmaker: note format upgrades", e)); // Sandbox vaults (dev/demo-world.mjs) get the demo builders; nothing else does. void this.app.vault.adapter.exists(SANDBOX_MARKER).then((sandbox) => { if (!sandbox) return; diff --git a/src/maps/MapStore.ts b/src/maps/MapStore.ts index 701e7449..805af1e4 100644 --- a/src/maps/MapStore.ts +++ b/src/maps/MapStore.ts @@ -797,6 +797,10 @@ export class MapStore { const used = p.mapPaletteName?.call(this.plugin, map.name); const note = used && used === map.paletteName ? p.paletteStore?.notePathOf(used) : undefined; if (note) ctx.paletteNote = note.replace(/.md$/i, ""); + // The region palette's note, when installed, so `region-palette:` is written as a link. + const regPal = map.regions?.palette; + const regNote = regPal ? p.paletteStore?.notePathOf(regPal) : undefined; + if (regNote) ctx.regionPaletteNote = regNote.replace(/.md$/i, ""); } catch (e) { console.error("Hexmaker: couldn't read the palette for a map note's summary", e); } diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index 4488780f..906f0cab 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -174,8 +174,14 @@ export interface MapNoteContext { paletteTerrains?: string[]; /** Path type names the map's palette has (plugin.getMapPathTypes). Empty/absent: not checked. */ pathTypes?: string[]; - /** The palette's note (vault path without .md), for the Summary's link. */ + /** + * The palette's note (vault path without .md), for the Summary's link and + * the `palette:` key (written as a link to it; plain when absent, e.g. a + * palette that isn't installed). + */ paletteNote?: string; + /** The note of the region palette (`region-palette:`), likewise. */ + regionPaletteNote?: string; /** * Routed facts per path, keyed by pathNameKey(name), for the Route column. * The writer can't route (no terrain or palette here); without them Route @@ -699,6 +705,10 @@ function readFrontmatter(src: string, opts: MapNoteReadOptions): FmRead { bad(k, field, "should be small, medium, large, huge or a size like 120%"); } else if (field === "hexNameStyle" && !parseNameStyle(t)) { bad(k, field, "should be bold, bold italic, regular or italic"); + } else if (field === "paletteName") { + // A link to the palette's note (`[[world/palettes/Default]]`) or its name. + const name = noteName(t); + if (name) out[field] = name; } else if (field === "submapKind") { if (/^(region|location)$/i.test(t)) out[field] = t.toLowerCase(); else bad(k, field, "should be region or location"); @@ -822,12 +832,19 @@ function readFrontmatter(src: string, opts: MapNoteReadOptions): FmRead { return { settings: out, format, problems }; } -function frontmatterLines(settings: Partial, keep: Set = new Set()): string[] { +/** A palette name as a link to its note when it has one (`[[world/palettes/Default]]`), else as typed. */ +function paletteRef(name: unknown, note: string | undefined): unknown { + if (typeof name !== "string" || !name || !note) return name; + const p = note.replace(/\.md$/i, ""); + return linkSafe(p) && (p.split("/").pop() ?? "") === name ? `[[${p}]]` : name; +} + +function frontmatterLines(settings: Partial, keep: Set = new Set(), ctx: MapNoteContext = {}): string[] { const s = settings as Record; const lines = [`${MAP_NOTE_MARKER}: ${MAP_NOTE_FORMAT}`]; const put = (key: string, v: unknown) => { if (v !== undefined && !keep.has(key)) lines.push(...yamlValueLines(key, v)); }; put("display-name", s.displayName); - put("palette", s.paletteName); + put("palette", paletteRef(s.paletteName, ctx.paletteNote)); if (settings.gridSize) { put("cols", settings.gridSize.cols); put("rows", settings.gridSize.rows); } if (settings.gridOffset) { put("offset-x", settings.gridOffset.x); put("offset-y", settings.gridOffset.y); } for (const [field, key, kind] of SIMPLE_KEYS) { @@ -876,7 +893,7 @@ function frontmatterLines(settings: Partial, keep: Set = ne put(REGION_KEYS.shape, reg.footprint === "hex" ? "hex flower" : "rectangle"); put(REGION_KEYS.size, regionSizeText(reg as RegionSettings)); put(REGION_KEYS.blend, reg.blend); - put(REGION_KEYS.palette, reg.palette); + put(REGION_KEYS.palette, paletteRef(reg.palette, ctx.regionPaletteNote)); put(REGION_KEYS.world, reg.worldId); put(REGION_KEYS.stagger, reg.stagger); put(REGION_KEYS.generator, reg.generator); @@ -1860,7 +1877,7 @@ export function mapNoteFormat(content: string): number | null { export function buildMapNote(name: string, data: MapNoteData, ctx: MapNoteContext = {}): string { return [ "---", - ...frontmatterLines(data.settings), + ...frontmatterLines(data.settings, new Set(), ctx), "---", `# ${data.settings.displayName || name}`, "", @@ -2000,7 +2017,7 @@ export function updateMapNote(content: string, name: string, data: MapNoteData, lines = placeSummary(lines, summaryLines(data, ctx)); const fmProblems = front.problems; if (fmProblems.length) lines = [...problemCallout(fmProblems, "settings"), "", ...lines]; - return ["---", ...frontmatterLines(data.settings, keep), ...userFm, "---", ...lines].join("\n"); + return ["---", ...frontmatterLines(data.settings, keep, ctx), ...userFm, "---", ...lines].join("\n"); } /** diff --git a/src/noteFormatUpgrade.ts b/src/noteFormatUpgrade.ts index ee8cc682..f69f7d1a 100644 --- a/src/noteFormatUpgrade.ts +++ b/src/noteFormatUpgrade.ts @@ -13,6 +13,11 @@ * - "note-links" (NF3): token notes' `token-map: coast` becomes a link to * the map note, `token-link: world/npcs/Ana.md` a link to that note, and * workflows' `template-file:` path a link to the template. + * - "ref-links" (NF3, the remaining references): map notes' `palette:` and + * `region-palette:`, palette notes' `child-palette:`, generators' + * `palette:`, `source-map(s):` and `blend-of:`, generator saves' + * `generator-path:`, and world types tables' Palette column become links + * to the notes they name. A name that names no note is left as typed. * * Before anything is written, the full text of every note about to change * is saved as `/backups/note-formats-/.json.gz`. If that @@ -24,13 +29,14 @@ import { Notice, TFile, type App } from "obsidian"; import { writeJsonBackup } from "./backup"; import { mapDataLines, moveBodyFieldsIntoMapData, shownValues, type HexMapDataView, type MapDataShown } from "./hexMapData"; -import { linkNotePathKey, linkTokenMap, renameHexMapKey } from "./noteFormats"; +import { linkFrontmatterKey, linkFrontmatterList, linkNotePathKey, linkTokenMap, mapNoteLink, pathLink, renameHexMapKey } from "./noteFormats"; +import { linkWorldTypePalettes, WORLD_TYPES_MARKER } from "./space/worldTypes"; import { takeBodyFields } from "./hexBodyFields"; import { normalizeFolder } from "./utils"; -export type NoteFormatUpgradeId = "hex-map-key" | "hex-body-lines" | "note-links"; +export type NoteFormatUpgradeId = "hex-map-key" | "hex-body-lines" | "note-links" | "ref-links"; -export const NOTE_FORMAT_UPGRADES: readonly NoteFormatUpgradeId[] = ["hex-map-key", "hex-body-lines", "note-links"]; +export const NOTE_FORMAT_UPGRADES: readonly NoteFormatUpgradeId[] = ["hex-map-key", "hex-body-lines", "note-links", "ref-links"]; /** What the upgrades need from the plugin. */ export interface NoteFormatHost { @@ -39,10 +45,15 @@ export interface NoteFormatHost { settings: { hexFolder: string; workflowsFolder?: string; + worldFolder?: string; maps: { name: string }[]; noteFormatUpgrades?: string[]; }; - mapStore: { isReady(map?: string): boolean; resolve(path: string): { map: string; key: string } | null }; + mapStore: { isReady(map?: string): boolean; resolve(path: string): { map: string; key: string } | null; notePath?(map: string): string }; + /** Palette notes ("ref-links"); without it no palette name is linked. */ + paletteStore?: { notePathOf(name: string): string | undefined; folder(): string }; + /** World types tables ("ref-links"). */ + worldTypeStore?: { folder(): string }; hexMapDataView(map: string, x: number, y: number): HexMapDataView; calloutMemory?: { set(path: string, values: MapDataShown): void }; saveSettings(): Promise; @@ -110,6 +121,13 @@ export async function planUpgrade(host: NoteFormatHost, id: NoteFormatUpgradeId) if (!host.mapStore.isReady(map)) { plan.skipped.push({ path: file.path, reason: `its map (${map}) isn't loaded; the lines move when the note is next opened` }); continue; } add(file.path, text, moveBodyFieldsIntoMapData(text, host.hexMapDataView(map, x, y)).content); } + } else if (id === "ref-links") { + const refs = refLinker(host); + for (const file of vault.getMarkdownFiles()) { + if (!refs.mayHave(file.path)) continue; + const text = await vault.cachedRead(file); + add(file.path, text, refs.rewrite(file.path, text)); + } } else { const exists = (p: string) => vault.getAbstractFileByPath(p) instanceof TFile; const wfFolder = normalizeFolder(host.settings.workflowsFolder ?? ""); @@ -140,6 +158,7 @@ async function replanOne(host: NoteFormatHost, id: NoteFormatUpgradeId, path: st const [x, y] = loc.key.split("_").map(Number); return moveBodyFieldsIntoMapData(current, host.hexMapDataView(loc.map, x, y)).content; } + if (id === "ref-links") return refLinker(host).rewrite(path, current); const exists = (p: string) => vault.getAbstractFileByPath(p) instanceof TFile; let next = linkTokenMap(current).content; next = linkNotePathKey(next, "token-link", exists).content; @@ -148,6 +167,69 @@ async function replanOne(host: NoteFormatHost, id: NoteFormatUpgradeId, path: st return next; } +/** + * "ref-links": which notes can hold a plain reference, and the rewrite of + * one. Map notes (one per known map), palette notes (the palettes folder), + * generators and their saves (the generators folder), world types tables + * (their folder). Each key is rewritten on its own line; nothing else in + * the note changes. + */ +function refLinker(host: NoteFormatHost): { mayHave(path: string): boolean; rewrite(path: string, text: string): string } { + const { vault } = host.app; + const isFile = (p: string | undefined): p is string => !!p && vault.getAbstractFileByPath(p) instanceof TFile; + const world = normalizeFolder(host.settings.worldFolder ?? ""); + const generators = world ? `${world}/generators` : "generators"; + const saves = `${generators}/saves`; + const palettes = host.paletteStore ? normalizeFolder(host.paletteStore.folder()) : ""; + const worldTypes = host.worldTypeStore ? normalizeFolder(host.worldTypeStore.folder()) : ""; + const mapNotes = new Set(host.mapStore.notePath ? host.settings.maps.map((m) => host.mapStore.notePath!(m.name)) : []); + const maps = new Set(host.settings.maps.map((m) => m.name)); + const under = (path: string, folder: string) => !!folder && path.startsWith(folder + "/"); + /** A palette name → a link to its note (it must exist). */ + const paletteLink = (name: string) => { + const path = host.paletteStore?.notePathOf(name); + const link = isFile(path) ? pathLink(path) : undefined; + return link && link.replace(/^\[\[|\]\]$/g, "").split("/").pop() === name ? link : undefined; + }; + const mapLink = (name: string) => (maps.has(name) && host.mapStore.notePath && isFile(host.mapStore.notePath(name)) ? mapNoteLink(name) : undefined); + const generatorLink = (name: string) => { + const path = `${generators}/${name}.md`; + if (isFile(path)) return pathLink(path); + const hit = vault.getMarkdownFiles().find((f) => f.basename === name && under(f.path, generators) && !under(f.path, saves)); + return hit ? pathLink(hit.path) : undefined; + }; + const fm = (text: string) => /^---\r?\n/.test(text); + return { + mayHave: (path) => mapNotes.has(path) || under(path, palettes) || under(path, generators) || under(path, worldTypes), + rewrite(path, text) { + if (!fm(text)) return text; + if (mapNotes.has(path)) { + let next = linkFrontmatterKey(text, "palette", paletteLink).content; + next = linkFrontmatterKey(next, "region-palette", paletteLink).content; + return next; + } + if (under(path, worldTypes) && new RegExp(`^${WORLD_TYPES_MARKER}\\s*:`, "m").test(text)) { + return linkWorldTypePalettes(text, { paletteNote: (n) => (paletteLink(n) ? host.paletteStore?.notePathOf(n) : undefined) }); + } + if (under(path, saves) && /^hexmaker-save\s*:/m.test(text)) { + return linkFrontmatterKey(text, "generator-path", (v) => { + const p = /\.md$/i.test(v) ? v : `${v}.md`; + return isFile(p) ? pathLink(p) : undefined; + }).content; + } + if (under(path, generators) && /^hex-wfc\s*:/m.test(text)) { + let next = linkFrontmatterKey(text, "palette", paletteLink).content; + next = linkFrontmatterKey(next, "source-map", mapLink).content; + next = linkFrontmatterList(next, "source-maps", mapLink).content; + next = linkFrontmatterList(next, "blend-of", generatorLink).content; + return next; + } + if (under(path, palettes)) return linkFrontmatterKey(text, "child-palette", paletteLink).content; + return text; + }, + }; +} + function backupDir(host: NoteFormatHost, when: Date): string { return `${host.manifest.dir ?? ""}/backups/note-formats-${when.toISOString().slice(0, 10)}`; } @@ -202,6 +284,7 @@ const UPGRADE_LABEL: Record = { "hex-map-key": "map: links in hex notes", "hex-body-lines": "old Terrain/Region lines moved into Map data", "note-links": "links for token maps, token notes and workflow templates", + "ref-links": "links for palettes, generators and source maps in map, palette, generator and world types notes", }; /** The notice after the upgrades, or null when nothing changed or was skipped. */ diff --git a/src/noteFormats.ts b/src/noteFormats.ts index 3163e189..2abd223d 100644 --- a/src/noteFormats.ts +++ b/src/noteFormats.ts @@ -194,3 +194,106 @@ export function linkNotePathKey(content: string, key: string, exists: (path: str lines[at] = `${key}: ${JSON.stringify(link)}`; return { content: lines.join(span.eol), changed: true }; } + +// ── the remaining references (palettes, generators, maps by name) ───────── + +/** + * A note's name from a reference as written: `[[world/palettes/Default]]` + * or `[[Default|My palette]]` → `Default`, plain `Default` → `Default`. + * "" when blank or not a string. Readers of the keys below take both forms + * forever (NF3 follow-up: links are written from now on). + */ +export function refBasename(value: unknown): string { + if (typeof value !== "string") return ""; + const m = WIKILINK.exec(value); + if (!m) return value.trim(); + return (m[1].trim().split("/").pop() ?? "").replace(/\.md$/i, "").trim(); +} + +/** A note path (".md" optional) as `[[path]]`, or undefined when it can't be a link. */ +export function pathLink(path: string | undefined): string | undefined { + if (!path) return undefined; + const p = path.trim().replace(/\.md$/i, ""); + return linkSafe(p) ? `[[${p}]]` : undefined; +} + +/** + * The items of a list value: a YAML flow list (`["[[_a]]", b]`) or names + * joined by " + " (the older form: `a + b`). Quotes are taken off; links + * stay as written. + */ +export function refListItems(raw: string | undefined): string[] { + const t = (raw ?? "").trim(); + if (!t) return []; + if (t.startsWith("[") && !t.startsWith("[[")) { + try { + const v = JSON.parse(t) as unknown; + if (Array.isArray(v)) return v.map((x) => String(x).trim()).filter(Boolean); + } catch { /* not JSON: read it loosely */ } + return splitFlow(t.slice(1, t.endsWith("]") ? -1 : undefined)); + } + return t.split(" + ").map((s) => s.trim()).filter(Boolean); +} + +/** `a, "b, c", [[d]]` → items (commas inside quotes or [[ ]] don't split). */ +function splitFlow(body: string): string[] { + const out: string[] = []; + let cur = "", quote = "", depth = 0; + for (let i = 0; i < body.length; i++) { + const c = body[i]; + if (quote) { if (c === quote) quote = ""; else cur += c; continue; } + if (c === '"' || c === "'") { quote = c; continue; } + if (c === "[" && body[i + 1] === "[") { depth++; cur += "[["; i++; continue; } + if (c === "]" && body[i + 1] === "]") { depth = Math.max(0, depth - 1); cur += "]]"; i++; continue; } + if (c === "," && !depth) { if (cur.trim()) out.push(cur.trim()); cur = ""; continue; } + cur += c; + } + if (cur.trim()) out.push(cur.trim()); + return out; +} + +/** Items as a YAML flow list (`["[[_a]]", "b"]`): Obsidian reads it as a list property, links and all. */ +export function flowList(items: readonly string[]): string { + return `[${items.map((i) => JSON.stringify(i)).join(", ")}]`; +} + +/** + * One frontmatter key's plain value → a link: `toLink(value)` gives the + * link text, or undefined to leave it as typed (a name that names no + * note). Already a link, blank or missing: unchanged. Only that line + * changes. + */ +export function linkFrontmatterKey(content: string, key: string, toLink: (value: string) => string | undefined): { content: string; changed: boolean } { + const span = fmLines(content); + if (!span) return { content, changed: false }; + const at = keyLine(span, key); + if (at < 0) return { content, changed: false }; + const value = scalarOf(span.lines[at]).trim(); + if (!value || WIKILINK.test(value) || value.startsWith("[")) return { content, changed: false }; + const link = toLink(value); + if (!link || link === value) return { content, changed: false }; + const lines = [...span.lines]; + lines[at] = `${key}: ${JSON.stringify(link)}`; + return { content: lines.join(span.eol), changed: true }; +} + +/** + * A key holding names joined by " + " (`source-maps: a + b`) → a flow list + * of links (`["[[_a]]", "[[_b]]"]`); each name `toLink` can't link stays as + * typed in the list. Unchanged when no name links, or the value is already + * a list. + */ +export function linkFrontmatterList(content: string, key: string, toLink: (name: string) => string | undefined): { content: string; changed: boolean } { + const span = fmLines(content); + if (!span) return { content, changed: false }; + const at = keyLine(span, key); + if (at < 0) return { content, changed: false }; + const raw = span.lines[at].slice(span.lines[at].indexOf(":") + 1).trim(); + if (!raw || raw.startsWith("[")) return { content, changed: false }; + const names = refListItems(scalarOf(span.lines[at])); + const items = names.map((n) => (WIKILINK.test(n) ? n : toLink(n) ?? n)); + if (!items.some((v, i) => v !== names[i])) return { content, changed: false }; + const lines = [...span.lines]; + lines[at] = `${key}: ${flowList(items)}`; + return { content: lines.join(span.eol), changed: true }; +} diff --git a/src/palettes/PaletteStore.ts b/src/palettes/PaletteStore.ts index fd6b6435..5f29aea2 100644 --- a/src/palettes/PaletteStore.ts +++ b/src/palettes/PaletteStore.ts @@ -143,8 +143,8 @@ export function wrapNoteColors(content: string): string { } /** A fresh note for a palette, metadata included. */ -function newNote(pal: TerrainPalette): string { - const note = setSubmapDefaults(buildPaletteNote(pal.terrains, pal.childPalette, pal.kind), pal.submapDefaults); +function newNote(pal: TerrainPalette, childNote?: string): string { + const note = setSubmapDefaults(buildPaletteNote(pal.terrains, pal.childPalette, pal.kind, childNote), pal.submapDefaults); return pal.pathTypes ? setPathTypes(note, pal.pathTypes) : note; } @@ -242,6 +242,11 @@ export class PaletteStore { return this.boundPath.get(pal) ?? this.pathFor(name); } + /** The note of a palette's child palette, when that palette is installed (so `child-palette:` is a link). */ + private childNoteOf(pal: TerrainPalette): string | undefined { + return pal.childPalette ? this.notePathOf(pal.childPalette) : undefined; + } + private pathFor(name: string): string { return `${this.folder()}/${paletteFileName(name)}.md`; } @@ -372,7 +377,7 @@ export class PaletteStore { name = uniquePaletteName(safe, siblings); } if (name !== pal.name) this.renamePalette(pal, name); - const content = newNote(pal); + const content = newNote(pal, this.childNoteOf(pal)); const path = this.pathFor(pal.name); this.bind(pal, path, content); await this.plugin.app.vault.create(path, content); @@ -737,7 +742,7 @@ export class PaletteStore { ? editing ? current : refreshPaletteDerived(current) : updatePaletteNote(current, pal.terrains); const withMeta = setSubmapDefaults( - setPaletteKind(setChildPalette(editing ? base : wrapPathTypeColors(base), pal.childPalette), pal.kind), + setPaletteKind(setChildPalette(editing ? base : wrapPathTypeColors(base), pal.childPalette, this.childNoteOf(pal)), pal.kind), pal.submapDefaults, ); const next = pal.pathTypes ? setPathTypes(withMeta, pal.pathTypes) : withMeta; @@ -747,7 +752,7 @@ export class PaletteStore { } this.bind(pal, target, next); } else { - const content = newNote(pal); + const content = newNote(pal, this.childNoteOf(pal)); this.bind(pal, target, content); await vault.create(target, content); } diff --git a/src/palettes/paletteNote.ts b/src/palettes/paletteNote.ts index f6069043..772c986b 100644 --- a/src/palettes/paletteNote.ts +++ b/src/palettes/paletteNote.ts @@ -3,6 +3,7 @@ import { impassableNoteCell, parseImpassableCell } from "../impassable"; import { isDerivedCell, parseTerrainTypeCell, terrainTypeCell } from "../terrainTypes"; import { colorCell, parseColorCell, wrapColorCellsInRows } from "./colorCell"; import { ALL_MAP_KINDS, type MapKind } from "../mapKinds"; +import { pathLink, refBasename } from "../noteFormats"; // Plain-text palette notes. // @@ -203,18 +204,29 @@ export function readChildPalette(content: string): string | undefined { if (!m) return undefined; const raw = m[1].trim(); const unquoted = /^(["']).*\1$/.test(raw) ? raw.slice(1, -1) : raw; - return unquoted.trim() || undefined; + // A link to the palette's note (`[[world/palettes/Space - System]]`) or its name. + return refBasename(unquoted) || undefined; } /** - * Set or clear `child-palette:` in the note's frontmatter. Returns the - * content untouched when it already holds that value (so a CRLF note isn't + * The `child-palette:` value to write: a link to the palette's note when + * it has one (`note`, its vault path), else the name as typed. + */ +export function childPaletteValue(value: string, note?: string): string { + const link = pathLink(note); + return link && refBasename(link) === value ? link : value; +} + +/** + * Set or clear `child-palette:` in the note's frontmatter (a link when + * `note`, the child palette's note path, is given). Returns the content + * untouched when it already holds that value (so a CRLF note isn't * rewritten just to normalise line endings). */ -export function setChildPalette(content: string, value: string | undefined): string { +export function setChildPalette(content: string, value: string | undefined, note?: string): string { if (readChildPalette(content) === (value || undefined)) return content; const text = content.replace(/\r\n?/g, "\n"); - const line = value ? `child-palette: ${JSON.stringify(value)}\n` : ""; + const line = value ? `child-palette: ${JSON.stringify(childPaletteValue(value, note))}\n` : ""; const fm = FRONTMATTER.exec(text); if (!fm) return value ? `---\n${line}---\n${text}` : text; let body = fm[1] + "\n"; @@ -390,11 +402,11 @@ export function setSubmapDefaults(content: string, defaults: Record { + const path = (this.plugin as { paletteStore?: { notePathOf(n: string): string | undefined } }).paletteStore?.notePathOf(name); + return path && this.plugin.app.vault.getAbstractFileByPath(path) instanceof TFile ? path : undefined; + }, + }; + } + folder(): string { return worldTypesFolder(this.settings); } @@ -202,7 +213,7 @@ export class WorldTypeStore { if (!sameOptional(now.stars, base.stars, starCells)) delete more.stars; if (!sameOptional(now.features, base.features, featureCells)) delete more.features; } - const next = updateWorldTypes(content, put, more); + const next = updateWorldTypes(content, put, more, this.links()); if (next !== content) await this.plugin.app.vault.modify(f, next); this.take(f.path, next); this.publish(); @@ -223,7 +234,7 @@ export class WorldTypeStore { if (this.find(clean) || this.plugin.app.vault.getAbstractFileByPath(path)) return { error: `There's already a table called ${clean}.` }; await this.enqueue(async () => { await this.ensureFolder(folder); - const text = buildWorldTypes(clean, copyWorldTypeRows(rows), extras); + const text = buildWorldTypes(clean, copyWorldTypeRows(rows), extras, this.links()); await this.plugin.app.vault.create(path, text); this.take(path, text); this.publish(); @@ -244,7 +255,7 @@ export class WorldTypeStore { if (f instanceof TFile) { const content = await this.plugin.app.vault.read(f); await this.backup("default-space", { [f.path]: content }); - const next = updateWorldTypes(content, DEFAULT_WORLD_TYPE_ROWS, DEFAULT_WORLD_TYPE_EXTRAS); + const next = updateWorldTypes(content, DEFAULT_WORLD_TYPE_ROWS, DEFAULT_WORLD_TYPE_EXTRAS, this.links()); if (next !== content) await this.plugin.app.vault.modify(f, next); this.take(f.path, next); } else { @@ -324,7 +335,7 @@ export class WorldTypeStore { private async load(f: TFile): Promise { let content = await this.plugin.app.vault.read(f); if (this.lastContent.get(f.path) === content && this.entries.has(f.path)) return false; - const upgraded = upgradeWorldTypes(content, { ...DEFAULT_WORLD_TYPE_EXTRAS, rows: DEFAULT_WORLD_TYPE_ROWS }); + const upgraded = upgradeWorldTypes(content, { ...DEFAULT_WORLD_TYPE_EXTRAS, rows: DEFAULT_WORLD_TYPE_ROWS }, this.links()); if (upgraded !== content) { try { await this.backup("upgrade", { [f.path]: content }); @@ -368,7 +379,7 @@ export class WorldTypeStore { const path = `${folder}/${DEFAULT_WORLD_TYPES}.md`; if (this.plugin.app.vault.getAbstractFileByPath(path)) return; await this.ensureFolder(folder); - const text = buildWorldTypes(DEFAULT_WORLD_TYPES, copyWorldTypeRows(DEFAULT_WORLD_TYPE_ROWS), DEFAULT_WORLD_TYPE_EXTRAS); + const text = buildWorldTypes(DEFAULT_WORLD_TYPES, copyWorldTypeRows(DEFAULT_WORLD_TYPE_ROWS), DEFAULT_WORLD_TYPE_EXTRAS, this.links()); try { await this.plugin.app.vault.create(path, text); this.take(path, text); diff --git a/src/space/worldTypes.ts b/src/space/worldTypes.ts index ea16a6c3..a398b90b 100644 --- a/src/space/worldTypes.ts +++ b/src/space/worldTypes.ts @@ -78,6 +78,7 @@ import { parseClimateRange, type ClimateRange, } from "../overworld/biomeClimate"; +import { pathLink, refBasename } from "../noteFormats"; export const WORLD_TYPES_MARKER = "hexmaker-world-types"; /** 2: the note also has the Stars and Sector features tables. 3: a Mainworld column. */ @@ -872,7 +873,8 @@ function readRow(cells: string[], cols: (Column | undefined)[]): { row?: WorldTy const opts = readOptions(cell("Options")); if (!opts) return { problem: `options "${cell("Options")}" should look like water=85, climate=lush` }; if (Object.keys(opts).length) row.options = opts; - if (cell("Palette")) row.palette = cell("Palette"); + // A link to the palette's note ([[world/palettes/Space - Planet]]) or its name. + if (cell("Palette")) row.palette = refBasename(cell("Palette")) || cell("Palette"); if (cell("Base")) row.baseTerrain = cell("Base"); if (cell("Notes")) row.notes = cell("Notes"); return { row }; @@ -965,8 +967,32 @@ function markdownTable(columns: readonly string[], rightAligned: string, cells: ]; } -const tableLines = (rows: readonly WorldTypeRow[], keep: readonly string[] = []) => - markdownTable(COLUMNS, "Weight", rows.map(worldTypeCells), keep); +/** + * Where the notes a world types table names are: the Palette column is + * written as a link to the palette's note when it has one (NF3 follow-up), + * else the name as typed. Readers take both. + */ +export interface WorldTypeLinks { + /** A palette's note path, when it has one. */ + paletteNote?(name: string): string | undefined; +} + +/** A Palette cell: a link to the palette's note when `links` knows it, else the name. */ +export function paletteCell(name: string | undefined, links?: WorldTypeLinks): string { + if (!name) return ""; + const link = pathLink(links?.paletteNote?.(name)); + return link && refBasename(link) === name ? link : name; +} + +/** worldTypeCells, with the Palette cell a link where `links` can make one. */ +export function worldTypeCellsLinked(r: WorldTypeRow, links?: WorldTypeLinks): string[] { + const cells = worldTypeCells(r); + cells[COLUMNS.indexOf("Palette")] = paletteCell(r.palette, links); + return cells; +} + +const tableLines = (rows: readonly WorldTypeRow[], keep: readonly string[] = [], links?: WorldTypeLinks) => + markdownTable(COLUMNS, "Weight", rows.map((r) => worldTypeCellsLinked(r, links)), keep); const starTableLines = (rows: readonly StarTypeRow[], keep: readonly string[] = []) => markdownTable(STAR_COLUMNS, "Weight", rows.map(starCells), keep); const featureTableLines = (rows: readonly SectorFeatureRow[], keep: readonly string[] = []) => @@ -979,12 +1005,12 @@ export interface WorldTypeExtras { } /** A fresh table note (Stars and Sector features are written even when empty). */ -export function buildWorldTypes(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}): string { +export function buildWorldTypes(name: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}, links?: WorldTypeLinks): string { return [ "---", `${WORLD_TYPES_MARKER}: ${WORLD_TYPES_FORMAT}`, "---", "", `# ${name}`, "", ...WORLD_TYPES_HELP, "", - ...tableLines(rows), "", + ...tableLines(rows, [], links), "", STARS_HEADING, "", ...STARS_HELP, "", ...starTableLines(extras.stars ?? []), "", @@ -1022,14 +1048,14 @@ function putTable(lines: string[], span: Span | null, table: string[], h * be read (after the new rows of their table, as written). A table that * didn't change isn't rewritten; same string when nothing changes. */ -export function updateWorldTypes(content: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}): string { +export function updateWorldTypes(content: string, rows: readonly WorldTypeRow[], extras: WorldTypeExtras = {}, links?: WorldTypeLinks): string { const eol = content.includes("\r\n") ? "\r\n" : "\n"; let lines = content.replace(/\r\n?/g, "\n").split("\n"); const parsed = parseWorldTypes(content); let changed = false; const t = findTable(lines); if (!t || !sameRows(parsed.rows, rows, worldTypeCells)) { - lines = putTable(lines, t, tableLines(rows, parsed.unreadable), []); + lines = putTable(lines, t, tableLines(rows, parsed.unreadable, links), []); changed = true; } if (extras.stars && !(parsed.stars && sameRows(parsed.stars, extras.stars, starCells))) { @@ -1067,7 +1093,7 @@ export function withShippedMainworlds(rows: readonly WorldTypeRow[], shipped: re * shipped rows' mainworlds. It is marked with the current format. Anything * else (current, or a note without the marker) comes back as is. */ -export function upgradeWorldTypes(content: string, defaults: Required & { rows?: readonly WorldTypeRow[] }): string { +export function upgradeWorldTypes(content: string, defaults: Required & { rows?: readonly WorldTypeRow[] }, links?: WorldTypeLinks): string { const p = parseWorldTypes(content); if (p.format === undefined || p.format >= WORLD_TYPES_FORMAT) return content; const old = p.format < 2; @@ -1075,12 +1101,33 @@ export function upgradeWorldTypes(content: string, defaults: Required !!cell && !cell.startsWith("[[") && paletteCell(cell, links) !== cell; + let any = false; + for (let i = t.start + 2; i < t.end && !any; i++) any = plain(splitRow(lines[i])[col] ?? ""); + if (!any) return content; + const parsed = parseWorldTypes(content); + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + return putTable(lines, t, tableLines(parsed.rows, parsed.unreadable, links), []).join(eol); +} + /** A deep copy of rows (callers may change it). */ export function copyWorldTypeRows(rows: readonly WorldTypeRow[]): WorldTypeRow[] { return rows.map((r) => { diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 85ee484c..68581911 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -31,6 +31,7 @@ import { remakeBlend, saveGeneratorModel, type GeneratorFile, + generatorText, } from "./generators"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "./preview"; import { renderPreviewLegend } from "../hex-map/terrainLegend"; @@ -71,7 +72,6 @@ import { type CountRange, COMPASS, type Compass, - modelToMarkdown, type HexWfcModel, } from "../../packages/hex-wfc/src"; import type { TFile } from "obsidian"; @@ -878,7 +878,7 @@ export class GeneratorPanel { cells: snapshot.cells, paths: snapshot.paths, // A draft has no file; the save keeps its own copy either way. - generatorMarkdown: g.file ? await this.app.vault.read(g.file) : modelToMarkdown(model), + generatorMarkdown: g.file ? await this.app.vault.read(g.file) : generatorText(this.plugin, model), }; const file = await writeSave(this.plugin, saved); GeneratorPanel.loadedSave = { ...saved, name: file.basename }; diff --git a/src/worldgen/biomeRegion.ts b/src/worldgen/biomeRegion.ts index 2989e368..c434cccb 100644 --- a/src/worldgen/biomeRegion.ts +++ b/src/worldgen/biomeRegion.ts @@ -15,8 +15,8 @@ import { TFile } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { HexKey, MapPath, PathType, TerrainPalette } from "../types"; -import { isModelMarkdown, parseModelMarkdown, type HexWfcModel } from "../../packages/hex-wfc/src"; -import { blendSourcesOf, drawnPathType, generatorFitsPalette, toPathsOn, type GridSpec } from "./generators"; +import { isModelMarkdown, type HexWfcModel } from "../../packages/hex-wfc/src"; +import { blendSourcesOf, drawnPathType, generatorFitsPalette, parseGeneratorText, toPathsOn, type GridSpec } from "./generators"; import { BUILTIN_GENERATORS, BUILTIN_PREFIX, builtinModel, builtinPathType, fitBuiltinModel } from "./builtinGenerators"; import { solveWithRing } from "./neighbours"; import { listGeneratorKinds, optionsWithDefaults } from "./registry"; @@ -103,7 +103,7 @@ async function load(plugin: HexmakerPlugin, ref: GeneratorRef): Promise const text = await vault.cachedRead(file); if (!isModelMarkdown(text)) throw new BiomeRegionError(`${file.basename} isn't a generator note.`); try { - return { name: file.basename, model: parseModelMarkdown(text, file.basename).model, preset: false }; + return { name: file.basename, model: parseGeneratorText(text, file.basename).model, preset: false }; } catch (e) { throw new BiomeRegionError(`Couldn't read generator ${file.basename}: ${e instanceof Error ? e.message : String(e)}`); } diff --git a/src/worldgen/generatorRefs.ts b/src/worldgen/generatorRefs.ts new file mode 100644 index 00000000..f407f0e1 --- /dev/null +++ b/src/worldgen/generatorRefs.ts @@ -0,0 +1,78 @@ +/** + * Links in generator notes (NF3 follow-up): the palette a generator was + * learned with, the region(s) it came from and the generators a blend was + * made from are written as links, so renaming one of those notes through + * Obsidian updates the generator: + * + * palette: "[[world/palettes/Default]]" + * source-map: "[[_the-coast]]" + * source-maps: ["[[_the-coast]]", "[[_the-north]]"] + * blend-of: ["[[world/generators/valley]]", "[[world/generators/deep-forest]]"] + * + * The older plain forms (`palette: Default`, `source-maps: a + b`) are read + * forever. In memory (HexWfcModel.meta) the values are always plain names, + * lists joined with " + " as before, so every reader of the meta keeps + * working: names on read (generatorMetaNames), links on write + * (generatorMetaLinks). A name that names no note is written as typed. + * + * Pure: no Obsidian imports. + */ + +import { flowList, mapNameFromRef, mapNoteLink, pathLink, refBasename, refListItems } from "../noteFormats"; + +export const GEN_PALETTE_KEY = "palette"; +export const GEN_SOURCE_MAP_KEY = "source-map"; +export const GEN_SOURCE_MAPS_KEY = "source-maps"; +export const GEN_BLEND_OF_KEY = "blend-of"; +const JOIN = " + "; + +/** Where the notes a generator names are (each undefined when there is none). */ +export interface GeneratorRefNotes { + /** A palette's note path. */ + palette?: (name: string) => string | undefined; + /** Does the map have a map note? */ + map?: (name: string) => boolean; + /** A generator's note path. */ + generator?: (name: string) => string | undefined; +} + +/** The meta with every reference read as a plain name (lists joined with " + "). */ +export function generatorMetaNames(meta: Record): Record { + const out = { ...meta }; + if (out[GEN_PALETTE_KEY] !== undefined) out[GEN_PALETTE_KEY] = refBasename(out[GEN_PALETTE_KEY]); + if (out[GEN_SOURCE_MAP_KEY] !== undefined) out[GEN_SOURCE_MAP_KEY] = mapNameFromRef(out[GEN_SOURCE_MAP_KEY]); + if (out[GEN_SOURCE_MAPS_KEY] !== undefined) out[GEN_SOURCE_MAPS_KEY] = refListItems(out[GEN_SOURCE_MAPS_KEY]).map(mapNameFromRef).filter(Boolean).join(JOIN); + if (out[GEN_BLEND_OF_KEY] !== undefined) out[GEN_BLEND_OF_KEY] = refListItems(out[GEN_BLEND_OF_KEY]).map(refBasename).filter(Boolean).join(JOIN); + return out; +} + +const mapLink = (notes: GeneratorRefNotes) => (name: string): string | undefined => + notes.map?.(name) ? linkOr(mapNoteLink(name)) : undefined; +const notePathLink = (find: ((name: string) => string | undefined) | undefined) => (name: string): string | undefined => { + const link = pathLink(find?.(name)); + return link && refBasename(link) === name ? link : undefined; +}; +const linkOr = (s: string) => (s.startsWith("[[") ? s : undefined); + +/** The meta to write: names that have a note become links to it (lists as flow lists). */ +export function generatorMetaLinks(meta: Record, notes: GeneratorRefNotes): Record { + const out = { ...meta }; + const one = (key: string, link: (name: string) => string | undefined) => { + const v = out[key]; + if (!v || v.startsWith("[")) return; + const l = link(v.trim()); + if (l) out[key] = l; + }; + const many = (key: string, link: (name: string) => string | undefined) => { + const v = out[key]; + if (!v || v.startsWith("[")) return; + const names = v.split(JOIN).map((s) => s.trim()).filter(Boolean); + const items = names.map((n) => link(n) ?? n); + if (items.some((x, i) => x !== names[i])) out[key] = flowList(items); + }; + one(GEN_PALETTE_KEY, notePathLink(notes.palette)); + one(GEN_SOURCE_MAP_KEY, mapLink(notes)); + many(GEN_SOURCE_MAPS_KEY, mapLink(notes)); + many(GEN_BLEND_OF_KEY, notePathLink(notes.generator)); + return out; +} diff --git a/src/worldgen/generators.ts b/src/worldgen/generators.ts index c33c2b61..a4e42329 100644 --- a/src/worldgen/generators.ts +++ b/src/worldgen/generators.ts @@ -43,6 +43,8 @@ import { isCompass, type Compass, } from "../../packages/hex-wfc/src"; +import { generatorMetaLinks, generatorMetaNames, type GeneratorRefNotes } from "./generatorRefs"; +import { pathLink } from "../noteFormats"; /** Frontmatter key that keeps a hex's terrain when a map is regenerated. */ export const LOCK_KEY = "locked"; @@ -58,6 +60,36 @@ export function generatorsFolder(plugin: HexmakerPlugin): string { return world ? `${world}/generators` : "generators"; } +/** Where the palettes, maps and generators a generator names have notes (for writing links; see generatorRefs.ts). */ +export function generatorRefNotes(plugin: HexmakerPlugin): GeneratorRefNotes { + // Tolerant of a partial plugin (tests, early startup): no store, no link. + const p = plugin as Partial> & Pick; + const isFile = (path: string | undefined) => !!path && p.app.vault.getAbstractFileByPath(path) instanceof TFile; + return { + palette: (name) => { + const path = p.paletteStore?.notePathOf?.(name); + return isFile(path) ? path : undefined; + }, + map: (name) => !!p.getMap?.call(plugin, name) && isFile(p.mapStore?.notePath?.(name)), + generator: (name) => { + const folder = generatorsFolder(plugin) + "/"; + return p.app.vault.getMarkdownFiles?.().find((f) => f.basename === name && f.path.startsWith(folder))?.path; + }, + }; +} + +/** A generator note's text, with the notes it names written as links. */ +export function generatorText(plugin: HexmakerPlugin, model: HexWfcModel): string { + return modelToMarkdown({ ...model, meta: generatorMetaLinks(model.meta, generatorRefNotes(plugin)) }); +} + +/** Read a generator note: its references (links or plain names) come back as plain names. */ +export function parseGeneratorText(text: string, fallbackName?: string): ReturnType { + const r = parseModelMarkdown(text, fallbackName); + r.model.meta = generatorMetaNames(r.model.meta); + return r; +} + /** Where generator saves (presets with their generated map) are kept. */ export function savesFolder(plugin: HexmakerPlugin): string { return `${generatorsFolder(plugin)}/saves`; @@ -75,7 +107,7 @@ export async function listGenerators(plugin: HexmakerPlugin): Promise { + const link = pathLink(generatorRefNotes(plugin).palette?.(palette)); await plugin.app.fileManager.processFrontMatter(file, (fm: Record) => { - fm.palette = palette; + fm.palette = link ?? palette; }); } @@ -655,7 +688,7 @@ export async function relearnGenerator( if ("error" in learned) return learned; const { model } = learned; keepSettings(model, g.model, dirs); - await plugin.app.vault.modify(g.file, modelToMarkdown(model)); + await plugin.app.vault.modify(g.file, generatorText(plugin, model)); return { model }; } @@ -738,7 +771,7 @@ export async function saveGeneratorModel(plugin: HexmakerPlugin, model: HexWfcMo path = `${folder}/${name}-${n}.md`; saved.name = `${name}-${n}`; } - const file = await plugin.app.vault.create(path, modelToMarkdown(saved)); + const file = await plugin.app.vault.create(path, generatorText(plugin, saved)); return { file, model: saved }; } @@ -775,6 +808,6 @@ export async function reblendGenerator( directions?: Compass[], ): Promise<{ model: HexWfcModel } | { error: string }> { const r = await remakeBlend(plugin, g.model, influence, directions); - if ("model" in r) await plugin.app.vault.modify(g.file, modelToMarkdown(r.model)); + if ("model" in r) await plugin.app.vault.modify(g.file, generatorText(plugin, r.model)); return r; } diff --git a/src/worldgen/regionGenerator.ts b/src/worldgen/regionGenerator.ts index d7da42cb..3e21dfb1 100644 --- a/src/worldgen/regionGenerator.ts +++ b/src/worldgen/regionGenerator.ts @@ -20,8 +20,7 @@ import { biomeSlug, type BiomeMixRow, type BiomeNoteFields, type BiomeTerrainWei import { copyClimate } from "../overworld/biomeClimate"; import { SIMILAR } from "../overworld/biomes"; import { hexBiomeAt, regionBiomeStatus } from "../overworld/regionsVault"; -import { learnGeneratorFromMap, listGenerators, saveGeneratorFromMap, sourceMapsOf, type GeneratorFile } from "./generators"; -import { modelToMarkdown } from "../../packages/hex-wfc/src"; +import { generatorText, learnGeneratorFromMap, listGenerators, saveGeneratorFromMap, sourceMapsOf, type GeneratorFile } from "./generators"; export type OverwriteReason = "own" | "parent" | "learned" | "related" | "other"; @@ -271,7 +270,7 @@ export async function makeRegionGenerator(plugin: HexmakerPlugin, mapName: strin console.error("Hexmap World Creator: couldn't back up the generator before overwriting it", e); return { error: `Couldn't back up ${f.path}, so it wasn't overwritten.` }; } - await plugin.app.vault.modify(f, modelToMarkdown(learned.model)); + await plugin.app.vault.modify(f, generatorText(plugin, learned.model)); file = f; } const link = file.path.replace(/\.md$/i, ""); diff --git a/src/worldgen/saveFormat.ts b/src/worldgen/saveFormat.ts index 147f87d2..3caab1e9 100644 --- a/src/worldgen/saveFormat.ts +++ b/src/worldgen/saveFormat.ts @@ -31,6 +31,25 @@ import { VERSION_KEY } from "../compat"; import type { GeneratorSettings } from "../../packages/hex-wfc/src"; +import { noteRefTarget, pathLink } from "../noteFormats"; + +/** + * `generator-path` as read: a link (`[[world/generators/bay-area]]`, the + * form written now, so renaming the generator through Obsidian updates it) + * or a plain path (older saves) → a vault path ending in ".md". A short + * link (`[[bay-area]]`, what Obsidian may write after a rename) comes back + * as `bay-area.md`: the caller resolves it like a link (saves.ts). + */ +export function generatorPathOf(value: string | undefined): string { + const { target } = noteRefTarget(value ?? ""); + if (!target) return ""; + return /\.md$/i.test(target) ? target : `${target}.md`; +} + +/** `generator-path` as written: a link to the generator's note (plain when it can't be one). */ +export function generatorPathValue(path: string): string { + return (path && pathLink(path)) || path; +} export const SAVE_FORMAT = 1; export const SAVE_MARKER = "hexmaker-save"; @@ -147,13 +166,18 @@ export function retargetSave(text: string, from: { name: string; path: string }, return raw; } }; - const path = value("generator-path"), name = value("generator"); - if (!(path ? path === from.path : name === from.name)) return text; + // A link may already point at the new path: Obsidian updates links when + // the file is renamed (a short link `[[name]]` matches by name). + const path = generatorPathOf(value("generator-path")), name = value("generator"); + const base = (p: string) => p.slice(p.lastIndexOf("/") + 1); + const pointsAt = (p: string) => path === p || (!path.includes("/") && path === base(p)); + if (!(path ? pointsAt(from.path) || pointsAt(to.path) : name === from.name)) return text; const set = (h: string, key: string, v: string) => new RegExp(`^${key}:[^\\r\\n]*$`, "m").test(h) ? h.replace(new RegExp(`^${key}:[^\\r\\n]*$`, "m"), () => `${key}: ${yaml(v)}`) : h; - return set(set(head, "generator", to.name), "generator-path", to.path) + rest; + const next = set(set(head, "generator", to.name), "generator-path", generatorPathValue(to.path)) + rest; + return next; } export function serializeSave(s: GeneratorSave): string { @@ -162,7 +186,7 @@ export function serializeSave(s: GeneratorSave): string { `${VERSION_KEY}: ${yaml(s.version)}`, `name: ${yaml(s.name)}`, `generator: ${yaml(s.generatorName)}`, - `generator-path: ${yaml(s.generatorPath)}`, + `generator-path: ${yaml(generatorPathValue(s.generatorPath))}`, `palette: ${yaml(s.palette)}`, `seed: ${s.seed}`, `size: ${s.cols}x${s.rows}`, @@ -272,7 +296,7 @@ export function parseSave(text: string, fallbackName = "save"): { save: Generato format, created: fm.created ?? "", generatorName: fm.generator ?? "", - generatorPath: fm["generator-path"] ?? "", + generatorPath: generatorPathOf(fm["generator-path"]), palette: fm.palette ?? "", seed: Number(fm.seed) >>> 0, cols, diff --git a/src/worldgen/saves.ts b/src/worldgen/saves.ts index 4fab0522..b3e2b5e0 100644 --- a/src/worldgen/saves.ts +++ b/src/worldgen/saves.ts @@ -7,9 +7,9 @@ import { TFile, TFolder } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import { slugify } from "../utils"; import { VERSION_KEY } from "../compat"; -import { generatorsFolder, savesFolder, listGenerators, saveGeneratorSettings, type GeneratorFile } from "./generators"; +import { generatorsFolder, savesFolder, listGenerators, parseGeneratorText, saveGeneratorSettings, type GeneratorFile } from "./generators"; import { parseSave, retargetSave, serializeSave, SAVE_MARKER, type GeneratorSave } from "./saveFormat"; -import { parseModelMarkdown, SETTING_KEYS, type GeneratorSettings } from "../../packages/hex-wfc/src"; +import { SETTING_KEYS, type GeneratorSettings } from "../../packages/hex-wfc/src"; /** A save as listed (frontmatter only; the file is parsed on load). */ export interface SaveEntry { @@ -77,8 +77,13 @@ export async function applySave( save: GeneratorSave, ): Promise<{ file: TFile; recreated: boolean } | { error: string }> { const generators = await listGenerators(plugin); + // generator-path is a link (or an older plain path); a short link resolves the way Obsidian does. + const linked = save.generatorPath + ? plugin.app.metadataCache.getFirstLinkpathDest(save.generatorPath.replace(/\.md$/i, ""), "")?.path + : undefined; let g: GeneratorFile | undefined = - generators.find((x) => x.file.path === save.generatorPath) ?? generators.find((x) => x.model.name === save.generatorName); + generators.find((x) => x.file.path === save.generatorPath || x.file.path === linked) + ?? generators.find((x) => x.model.name === save.generatorName); let recreated = false; if (!g) { if (!save.generatorMarkdown) return { error: `Generator "${save.generatorName}" no longer exists and the save has no copy of it.` }; @@ -88,7 +93,7 @@ export async function applySave( let path = `${folder}/${base}.md`; for (let n = 2; plugin.app.vault.getAbstractFileByPath(path); n++) path = `${folder}/${base}-${n}.md`; const file = await plugin.app.vault.create(path, save.generatorMarkdown); - const { model, warnings } = parseModelMarkdown(save.generatorMarkdown, file.basename); + const { model, warnings } = parseGeneratorText(save.generatorMarkdown, file.basename); g = { file, model, warnings }; recreated = true; } diff --git a/tests/noteFormats.test.ts b/tests/noteFormats.test.ts index 4e76a0ca..1b0e07a7 100644 --- a/tests/noteFormats.test.ts +++ b/tests/noteFormats.test.ts @@ -231,9 +231,9 @@ describe("one-time note-format rewrite", () => { const { vault, host, saves, memory } = vaultHost(before); const results = await runNoteFormatUpgrades(host); expect(results.map((r) => [r.id, r.changed.length, r.error])).toEqual([ - ["hex-map-key", 1, undefined], ["hex-body-lines", 1, undefined], ["note-links", 3, undefined], + ["hex-map-key", 1, undefined], ["hex-body-lines", 1, undefined], ["note-links", 3, undefined], ["ref-links", 0, undefined], ]); - expect(host.settings.noteFormatUpgrades).toEqual(["hex-map-key", "hex-body-lines", "note-links"]); + expect(host.settings.noteFormatUpgrades).toEqual(["hex-map-key", "hex-body-lines", "note-links", "ref-links"]); expect(saves()).toBe(1); const hex = vault.files.get(`${HEX}/the-coast/0_1.md`)!; @@ -275,7 +275,7 @@ describe("one-time note-format rewrite", () => { const snapshot = new Map(vault.files); const writes = vault.writes.length; const binaries = vault.binaries.size; - for (const id of ["hex-map-key", "hex-body-lines", "note-links"] as const) { + for (const id of ["hex-map-key", "hex-body-lines", "note-links", "ref-links"] as const) { const r = await runUpgrade(host, id); expect(r.changed).toEqual([]); expect(r.backup).toBeUndefined(); @@ -306,8 +306,9 @@ describe("one-time note-format rewrite", () => { expect(results.every((r) => r.changed.length === 0)).toBe(true); expect(results.filter((r) => r.error).map((r) => r.id)).toEqual(["hex-map-key", "hex-body-lines", "note-links"]); expect(new Map(vault.files)).toEqual(new Map(Object.entries(before))); - expect(host.settings.noteFormatUpgrades).toBeUndefined(); - expect(saves()).toBe(0); + // Only the upgrade with nothing to change here (no palettes) is recorded. + expect(host.settings.noteFormatUpgrades).toEqual(["ref-links"]); + expect(saves()).toBe(1); }); it("leaves a map that isn't loaded for later, and keeps ids it doesn't know", async () => { @@ -318,6 +319,6 @@ describe("one-time note-format rewrite", () => { expect(r.changed).toEqual([]); expect(r.skipped.map((s) => s.path)).toEqual([`${HEX}/the-coast/0_1.md`]); expect(vault.files.get(`${HEX}/the-coast/0_1.md`)).toContain("**Terrain:** mountain"); - expect(host.settings.noteFormatUpgrades).toEqual(["from-a-newer-build", "hex-map-key", "note-links", "hex-body-lines"]); + expect(host.settings.noteFormatUpgrades).toEqual(["from-a-newer-build", "hex-map-key", "note-links", "hex-body-lines", "ref-links"]); }); }); diff --git a/tests/noteRefLinks.test.ts b/tests/noteRefLinks.test.ts new file mode 100644 index 00000000..998b5a77 --- /dev/null +++ b/tests/noteRefLinks.test.ts @@ -0,0 +1,296 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { gunzipSync } from "node:zlib"; +import { + flowList, linkFrontmatterKey, linkFrontmatterList, pathLink, refBasename, refListItems, +} from "../src/noteFormats"; +import { buildMapNote, parseMapNote, updateMapNote, type MapNoteData } from "../src/maps/mapNote"; +import { buildPaletteNote, readChildPalette, setChildPalette } from "../src/palettes/paletteNote"; +import { generatorMetaLinks, generatorMetaNames } from "../src/worldgen/generatorRefs"; +import { modelToMarkdown, parseModelMarkdown, type HexWfcModel } from "../packages/hex-wfc/src"; +import { generatorPathOf, parseSave, retargetSave, serializeSave, type GeneratorSave } from "../src/worldgen/saveFormat"; +import { + buildWorldTypes, linkWorldTypePalettes, parseWorldTypes, updateWorldTypes, worldTypeCells, worldTypeCellsLinked, WORLD_TYPE_COLUMNS, + type WorldTypeRow, +} from "../src/space/worldTypes"; +import { runNoteFormatUpgrades, runUpgrade, type NoteFormatHost } from "../src/noteFormatUpgrade"; +import { MemVault } from "./helpers/memVault"; + +/** + * NF3 follow-up: the remaining plain references (map notes' palette, + * palettes' child-palette, generators' palette / source-map(s) / blend-of, + * saves' generator-path, world types' Palette column) are written as links + * from now on, read in both forms forever, and rewritten once (backed up). + */ + +describe("reference helpers", () => { + it("reads a link or a plain name", () => { + expect(refBasename("Default")).toBe("Default"); + expect(refBasename("[[world/palettes/Default]]")).toBe("Default"); + expect(refBasename("[[Default|My palette]]")).toBe("Default"); + expect(refBasename("[[world/palettes/Space - Planet.md]]")).toBe("Space - Planet"); + expect(refBasename(undefined)).toBe(""); + expect(pathLink("world/palettes/Default.md")).toBe("[[world/palettes/Default]]"); + expect(pathLink("a|b")).toBeUndefined(); + }); + + it("reads lists written inline, block-style (JSON) or joined with +", () => { + expect(refListItems("a + b")).toEqual(["a", "b"]); + expect(refListItems('["[[_a]]", "b"]')).toEqual(["[[_a]]", "b"]); + expect(refListItems(`[ "[[_a]]", 'b, c' ]`)).toEqual(["[[_a]]", "b, c"]); + expect(refListItems("[[_a]]")).toEqual(["[[_a]]"]); + expect(flowList(["[[_a]]", "b"])).toBe('["[[_a]]", "b"]'); + }); + + it("rewrites one key's plain value, leaving links, unknown names and other lines", () => { + const text = "---\r\npalette: Default\r\n# mine\r\nother: Default\r\n---\r\nbody\r\n"; + const link = (n: string) => (n === "Default" ? "[[world/palettes/Default]]" : undefined); + const r = linkFrontmatterKey(text, "palette", link); + expect(r).toEqual({ content: text.replace("palette: Default", 'palette: "[[world/palettes/Default]]"'), changed: true }); + expect(linkFrontmatterKey(r.content, "palette", link).changed).toBe(false); + expect(linkFrontmatterKey("---\npalette: Gone\n---\n", "palette", link).changed).toBe(false); + const list = linkFrontmatterList("---\nsource-maps: a + gone\n---\n", "source-maps", (n) => (n === "a" ? "[[_a]]" : undefined)); + expect(list.content).toBe('---\nsource-maps: ["[[_a]]", "gone"]\n---\n'); + expect(linkFrontmatterList(list.content, "source-maps", () => "[[_x]]").changed).toBe(false); + expect(linkFrontmatterList("---\nsource-maps: gone + lost\n---\n", "source-maps", () => undefined).changed).toBe(false); + }); +}); + +describe("map notes: palette and region-palette", () => { + const data: MapNoteData = { + settings: { paletteName: "Default", regions: { footprint: "hex", size: 3, palette: "Badlands" } }, + hexes: new Map(), paths: [], + }; + + it("writes a link to an installed palette's note, the name otherwise", () => { + const linked = buildMapNote("coast", data, { paletteNote: "world/palettes/Default", regionPaletteNote: "world/palettes/Badlands" }); + expect(linked).toContain('palette: "[[world/palettes/Default]]"'); + expect(linked).toContain('region-palette: "[[world/palettes/Badlands]]"'); + const plain = buildMapNote("coast", data); + expect(plain).toMatch(/^palette: Default$/m); + expect(plain).toMatch(/^region-palette: Badlands$/m); + }); + + it("reads both forms as the palette's name; a rewrite keeps the link", () => { + const ctx = { paletteNote: "world/palettes/Default", regionPaletteNote: "world/palettes/Badlands" }; + const linked = buildMapNote("coast", data, ctx); + for (const text of [linked, buildMapNote("coast", data), linked.replace('"[[world/palettes/Default]]"', '"[[Default|The default]]"')]) { + const back = parseMapNote(text)!; + expect(back.settings.paletteName).toBe("Default"); + expect(back.settings.regions?.palette).toBe("Badlands"); + } + expect(updateMapNote(linked, "coast", parseMapNote(linked)!, ctx)).toBe(linked); + }); +}); + +describe("palette notes: child-palette", () => { + it("writes a link when the child palette has a note; reads both forms", () => { + const note = buildPaletteNote([], "Expanded", undefined, "world/palettes/Expanded.md"); + expect(note).toContain('child-palette: "[[world/palettes/Expanded]]"'); + expect(readChildPalette(note)).toBe("Expanded"); + expect(buildPaletteNote([], "Gone")).toContain('child-palette: "Gone"'); + expect(readChildPalette('---\nchild-palette: "[[Space - System|System]]"\n---\n')).toBe("Space - System"); + const changed = setChildPalette(note, "Space - System", "world/palettes/Space - System.md"); + expect(changed).toContain('child-palette: "[[world/palettes/Space - System]]"'); + // Same palette: left as it is (a plain name isn't rewritten on every sync). + expect(setChildPalette('---\nchild-palette: "Expanded"\n---\n', "Expanded", "world/palettes/Expanded.md")).toBe('---\nchild-palette: "Expanded"\n---\n'); + }); +}); + +describe("generator notes: palette, source-map(s), blend-of", () => { + const notes = { + palette: (n: string) => (n === "Default" ? "world/palettes/Default.md" : undefined), + map: (n: string) => n === "the-coast" || n === "the-north", + generator: (n: string) => (n === "valley" ? "world/generators/valley.md" : undefined), + }; + const model = (meta: Record): HexWfcModel => ({ + name: "g", terrains: [{ name: "grass", weight: 1 }, { name: "hill", weight: 1 }], adjacency: [{ a: "grass", b: "hill", weight: 1 }] as never, meta, + }); + + it("names in memory, links on disk; unknown names stay as typed", () => { + const meta = { palette: "Default", "source-maps": "the-coast + lost", "blend-of": "valley + preset-thing", created: "2026-10-11" }; + const out = generatorMetaLinks(meta, notes); + expect(out).toEqual({ + palette: "[[world/palettes/Default]]", + "source-maps": '["[[_the-coast]]", "lost"]', + "blend-of": '["[[world/generators/valley]]", "preset-thing"]', + created: "2026-10-11", + }); + expect(generatorMetaNames(out)).toEqual(meta); + expect(generatorMetaLinks({ "source-map": "the-north" }, notes)).toEqual({ "source-map": "[[_the-north]]" }); + expect(generatorMetaNames({ "source-map": "[[_the-north]]" })).toEqual({ "source-map": "the-north" }); + // Older plain files read the same. + expect(generatorMetaNames({ palette: "Default", "source-maps": "a + b" })).toEqual({ palette: "Default", "source-maps": "a + b" }); + }); + + it("round-trips through the file, inline lists and Obsidian's block lists alike", () => { + const meta = { palette: "Default", "source-maps": "the-coast + the-north" }; + const text = modelToMarkdown(model(generatorMetaLinks(meta, notes))); + expect(text).toContain('palette: "[[world/palettes/Default]]"'); + expect(text).toContain('source-maps: ["[[_the-coast]]", "[[_the-north]]"]'); + expect(generatorMetaNames(parseModelMarkdown(text).model.meta)).toMatchObject(meta); + // The Properties panel (processFrontMatter) writes lists as block lists. + const block = text.replace('source-maps: ["[[_the-coast]]", "[[_the-north]]"]', 'source-maps:\n - "[[_the-coast]]"\n - "[[_the-north]]"'); + const back = parseModelMarkdown(block).model; + expect(generatorMetaNames(back.meta)).toMatchObject(meta); + expect(back.terrains.map((t) => t.name)).toEqual(["grass", "hill"]); + expect(modelToMarkdown(back)).toContain('source-maps: ["[[_the-coast]]", "[[_the-north]]"]'); + }); +}); + +describe("generator saves: generator-path", () => { + const save: GeneratorSave = { + name: "s", version: "9.9.9", format: 1, created: "2026-10-11", generatorName: "valley", generatorPath: "world/generators/valley.md", + palette: "Default", seed: 1, cols: 1, rows: 1, stagger: "odd", orientation: "flat", settings: {}, + cells: new Map([["0_0", "grass"]]), paths: [], generatorMarkdown: "", + }; + + it("writes a link; reads a link, a short link or an old plain path", () => { + const text = serializeSave(save); + expect(text).toContain('generator-path: "[[world/generators/valley]]"'); + const back = parseSave(text); + if ("error" in back) throw new Error(back.error); + expect(back.save.generatorPath).toBe("world/generators/valley.md"); + expect(generatorPathOf("world/generators/valley.md")).toBe("world/generators/valley.md"); + expect(generatorPathOf("[[valley]]")).toBe("valley.md"); + expect(generatorPathOf("'[[world/generators/valley]]'")).toBe("world/generators/valley.md"); + }); + + it("follows a rename even when Obsidian already updated the link", () => { + const text = serializeSave(save); + const to = { name: "dale", path: "world/generators/dale.md" }; + const from = { name: "valley", path: "world/generators/valley.md" }; + const expected = text.replace("generator: valley", "generator: dale").replace("[[world/generators/valley]]", "[[world/generators/dale]]"); + expect(retargetSave(text, from, to)).toBe(expected); + // Obsidian rewrote the link first: the name still follows. + expect(retargetSave(text.replace("[[world/generators/valley]]", "[[world/generators/dale]]"), from, to)).toBe(expected); + expect(retargetSave(text.replace("[[world/generators/valley]]", "[[dale]]"), from, to)).toBe(expected); + expect(retargetSave(text, { name: "other", path: "world/generators/other.md" }, to)).toBe(text); + }); +}); + +describe("world types: Palette column", () => { + const rows: WorldTypeRow[] = [{ world: "ocean planet", palette: "Space - Planet" }, { world: "gas giant", palette: "Gone" }]; + const links = { paletteNote: (n: string) => (n === "Space - Planet" ? "world/palettes/Space - Planet.md" : undefined) }; + const col = WORLD_TYPE_COLUMNS.indexOf("Palette"); + + it("writes links to palettes with notes, reads both forms", () => { + expect(worldTypeCellsLinked(rows[0], links)[col]).toBe("[[world/palettes/Space - Planet]]"); + expect(worldTypeCellsLinked(rows[1], links)[col]).toBe("Gone"); + expect(worldTypeCells(rows[0])[col]).toBe("Space - Planet"); + const note = buildWorldTypes("T", rows, {}, links); + expect(note).toContain("| [[world/palettes/Space - Planet]] |"); + expect(parseWorldTypes(note).rows.map((r) => r.palette)).toEqual(["Space - Planet", "Gone"]); + // Unchanged rows: the table isn't rewritten. + expect(updateWorldTypes(note, parseWorldTypes(note).rows, {}, links)).toBe(note); + }); + + it("the one-time rewrite links plain cells once", () => { + const plain = buildWorldTypes("T", rows); + expect(plain).toContain("| Space - Planet |"); + const linked = linkWorldTypePalettes(plain, links); + expect(linked).toContain("| [[world/palettes/Space - Planet]] |"); + expect(linked).toContain("| Gone |"); + expect(parseWorldTypes(linked).rows).toEqual(parseWorldTypes(plain).rows); + expect(linkWorldTypePalettes(linked, links)).toBe(linked); + expect(linkWorldTypePalettes(plain, {})).toBe(plain); + }); +}); + +// ── the one-time rewrite, on an in-memory vault ─────────────────────────── + +const gen = (meta: Record, name: string) => + modelToMarkdown({ name, terrains: [{ name: "grass", weight: 1 }], adjacency: [], meta }); + +const VAULT = () => ({ + "hexes/the-coast/_the-coast.md": "---\nhexmaker-map: 5\npalette: Default\nregion-palette: Gone\ncols: 4\nrows: 4\n---\n# The Coast\n", + "world/palettes/Default.md": "---\nhexmaker-palette: 1\nchild-palette: \"Expanded\"\n---\n\n| Terrain | Color |\n", + "world/palettes/Expanded.md": "---\nhexmaker-palette: 1\nchild-palette: Gone\n---\n\n| Terrain | Color |\n", + "world/generators/valley.md": gen({ palette: "Default", "source-maps": "the-coast + lost-map" }, "valley"), + "world/generators/coastal.md": gen({ palette: "Gone", "source-map": "the-coast" }, "coastal"), + "world/generators/blend.md": gen({ "blend-of": "valley + preset-thing" }, "blend"), + "world/generators/saves/s1.md": "---\nhexmaker-save: 1\ngenerator: valley\ngenerator-path: world/generators/valley.md\n---\n", + "world/generators/saves/s2.md": "---\nhexmaker-save: 1\ngenerator: gone\ngenerator-path: world/generators/gone.md\n---\n", + "world/world-types/Space.md": buildWorldTypes("Space", [{ world: "ocean planet", palette: "Default" }, { world: "gas giant", palette: "Gone" }]), + "world/notes/palette.md": "---\npalette: Default\n---\nMy own note.\n", +}); + +function host(files: Record) { + const vault = new MemVault(files); + let saves = 0; + const installed = new Set(["Default", "Expanded"]); + const h: NoteFormatHost = { + app: vault.app() as never, + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "hexes", worldFolder: "world", maps: [{ name: "the-coast" }], noteFormatUpgrades: ["hex-map-key", "hex-body-lines", "note-links"] }, + mapStore: { + isReady: () => true, + resolve: () => null, + notePath: (m: string) => `hexes/${m}/_${m}.md`, + }, + paletteStore: { notePathOf: (n: string) => (installed.has(n) ? `world/palettes/${n}.md` : undefined), folder: () => "world/palettes" }, + worldTypeStore: { folder: () => "world/world-types" }, + hexMapDataView: (map, x, y) => ({ map, mapLabel: map, x, y }), + saveSettings: async () => { saves++; }, + }; + return { vault, host: h, saves: () => saves }; +} + +describe("one-time rewrite of the remaining references (ref-links)", () => { + it("links every reference that names a note, once, backed up first", async () => { + const before = VAULT(); + const { vault, host: h, saves } = host(before); + const [r] = await runNoteFormatUpgrades(h); + expect(r.id).toBe("ref-links"); + expect(r.error).toBeUndefined(); + expect(h.settings.noteFormatUpgrades).toContain("ref-links"); + expect(saves()).toBe(1); + const f = (p: string) => vault.files.get(p)!; + + expect(f("hexes/the-coast/_the-coast.md")).toBe(before["hexes/the-coast/_the-coast.md"].replace("palette: Default", 'palette: "[[world/palettes/Default]]"')); + expect(f("world/palettes/Default.md")).toContain('child-palette: "[[world/palettes/Expanded]]"'); + expect(f("world/palettes/Expanded.md")).toBe(before["world/palettes/Expanded.md"]); + expect(f("world/generators/valley.md")).toContain('palette: "[[world/palettes/Default]]"'); + expect(f("world/generators/valley.md")).toContain('source-maps: ["[[_the-coast]]", "lost-map"]'); + expect(f("world/generators/coastal.md")).toContain("palette: Gone"); + expect(f("world/generators/coastal.md")).toContain('source-map: "[[_the-coast]]"'); + expect(f("world/generators/blend.md")).toContain('blend-of: ["[[world/generators/valley]]", "preset-thing"]'); + expect(f("world/generators/saves/s1.md")).toContain('generator-path: "[[world/generators/valley]]"'); + expect(f("world/generators/saves/s2.md")).toBe(before["world/generators/saves/s2.md"]); + expect(f("world/world-types/Space.md")).toContain("| [[world/palettes/Default]] |"); + expect(f("world/world-types/Space.md")).toContain("| Gone |"); + // A note that isn't the plugin's keeps its own palette: key. + expect(f("world/notes/palette.md")).toBe(before["world/notes/palette.md"]); + + // Readers see the same names as before. + expect(generatorMetaNames(parseModelMarkdown(f("world/generators/valley.md")).model.meta)).toMatchObject({ palette: "Default", "source-maps": "the-coast + lost-map" }); + expect(parseMapNote(f("hexes/the-coast/_the-coast.md"))!.settings.paletteName).toBe("Default"); + expect(parseWorldTypes(f("world/world-types/Space.md")).rows.map((x) => x.palette)).toEqual(["Default", "Gone"]); + + // The backup holds every rewritten note as it was. + const entry = [...vault.binaries].find(([p]) => p.includes("/backups/note-formats-") && p.endsWith("/ref-links.json.gz")); + const backed = (JSON.parse(gunzipSync(entry![1]).toString("utf8")) as { notes: Record }).notes; + expect(Object.keys(backed).sort()).toEqual([ + "hexes/the-coast/_the-coast.md", "world/generators/blend.md", "world/generators/coastal.md", "world/generators/saves/s1.md", + "world/generators/valley.md", "world/palettes/Default.md", "world/world-types/Space.md", + ]); + for (const [p, text] of Object.entries(backed)) expect(text).toBe(before[p as keyof typeof before]); + + // Once: recorded, and running it again changes nothing. + const writes = vault.writes.length; + expect(await runNoteFormatUpgrades(h)).toEqual([]); + const again = await runUpgrade(h, "ref-links"); + expect(again.changed).toEqual([]); + expect(vault.writes.length).toBe(writes); + }); + + it("changes nothing when the backup can't be saved, and tries again next time", async () => { + const before = VAULT(); + const { vault, host: h } = host(before); + vault.failBinary = true; + const [r] = await runNoteFormatUpgrades(h); + expect(r.error).toBeDefined(); + expect(new Map(vault.files)).toEqual(new Map(Object.entries(before))); + expect(h.settings.noteFormatUpgrades).not.toContain("ref-links"); + }); +}); diff --git a/tests/palettes.test.ts b/tests/palettes.test.ts index d6fcf627..23ab0b8c 100644 --- a/tests/palettes.test.ts +++ b/tests/palettes.test.ts @@ -557,9 +557,10 @@ describe("PaletteStore", () => { h.settings.terrainPalettes[0].childPalette = "Expanded"; await h.store.init(); const p = "world/palettes/Limited.md"; - expect(h.vault.files.get(p)).toContain('child-palette: "Expanded"'); + // An installed palette is written as a link to its note (NF3 follow-up). + expect(h.vault.files.get(p)).toContain('child-palette: "[[world/palettes/Expanded]]"'); - // In-app change → note. + // In-app change → note; a palette that isn't installed stays a plain name. h.settings.terrainPalettes[0].childPalette = "Space - System"; await h.store.sync(); expect(h.vault.files.get(p)).toContain('child-palette: "Space - System"'); @@ -569,6 +570,12 @@ describe("PaletteStore", () => { h.store.onModify(h.file(p)); await h.store.sync(); expect(h.settings.terrainPalettes[0].childPalette).toBe("Overland"); + + // A link (any folder, alias or not) reads as the palette's name. + h.vault.files.set(p, h.vault.files.get(p)!.replace(/child-palette: .*/, 'child-palette: "[[world/palettes/Expanded|Big]]"')); + h.store.onModify(h.file(p)); + await h.store.sync(); + expect(h.settings.terrainPalettes[0].childPalette).toBe("Expanded"); }); it("seeded terrain types are in the notes when init() resolves (no separately queued write)", async () => { From 2141fd7d990b7cc2bc2fcdc7c96d7695de38ba41 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 12:40:50 -0400 Subject: [PATCH 309/558] feat(space): space set as tables and roll on arrival (tables everywhere phases 3-4) Phase 3 (T1, T2, T11, SP5 data): - "Convert world types to tables" writes each World types note as random table notes under {tables}/space// (Sector/Charted sector, Unexplored sector, Mainworlds, Uncharted; System/Stars, Inner/Habitable/ Outer orbits). Same odds, rows keep their setup columns. Backed up first; the old note is kept, gets a `## Tables` role list and embeds the tables. Idempotent; never overwrites a table. - Role precedence: the map's Tables (inherited down the map tree) -> the generator setup (a converted note's role list, or the old note read as tables) -> equal odds. A missing map table falls through. - Map properties: "Generator tables" (one select per role) and "Arriving somewhere new". TableNotes keeps the tables folder in memory for the (synchronous) resolver. Phase 4 (SP4, SP5, GM4, T5, T6): - Star scatter leaves `Roll: on arrival` rows for later: the hex shows its Shown as terrain and the map note's Hexes table gets an On arrival cell. - With `on-arrival: make places`, "Go there" / Ctrl+click on a hex with no map rolls its On arrival table with the map's seed, writes the result onto the hex (discovery raised to the parent), and makes the place with no form: row attributes -> palette Submap defaults -> engine. Works in Play (new `discover` action); a plain-text `## Arrival` write-up goes in the new map's note. - Reroll in any mode until Lock (`arrival: locked`), then God only. - Build's "New map from this hex..." rolls the cell first and pre-fills the form from the same row. Tests: worldTypesConvert, tableRoles, arrivalSubmapSetup, mapNoteOnArrival, arrivalDeferred. Smoke: F13-arrival in the space setup. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 + dev/smoke/setups.mjs | 54 ++++ package.json | 4 +- src/HexmakerPlugin.ts | 59 +++- src/SetupWizardView.ts | 2 +- src/arrival/ArrivalService.ts | 327 +++++++++++++++++++++ src/arrival/arrival.ts | 266 +++++++++++++++++ src/hex-map/HexMapView.ts | 57 +++- src/hex-map/MapModal.ts | 7 + src/hex-map/help.md | 8 + src/hex-map/mapTablesForm.ts | 103 +++++++ src/hex-map/newChildMap.ts | 7 + src/maps/mapNote.ts | 53 +++- src/random-tables/TableNotes.ts | 99 +++++++ src/space/WorldTypeStore.ts | 93 +++++- src/space/WorldTypesModal.ts | 7 + src/space/spaceTables.ts | 388 +++++++++++++++++++++++++ src/space/worldTypesSource.ts | 4 +- src/types.ts | 16 + src/workMode.ts | 25 ++ src/worldgen/NewMapSetupModal.ts | 21 +- src/worldgen/procedural/common.ts | 6 + src/worldgen/procedural/starScatter.ts | 13 +- src/worldgen/registry.ts | 12 +- src/worldgen/tableRoles.ts | 22 +- src/worldgen/tableSources.ts | 144 +++++++++ styles.css | 35 +++ tests/arrivalDeferred.test.ts | 248 ++++++++++++++++ tests/arrivalSubmapSetup.test.ts | 162 +++++++++++ tests/freshEyesR5Setup.test.ts | 2 +- tests/mapNoteOnArrival.test.ts | 132 +++++++++ tests/tableRoles.test.ts | 102 +++++++ tests/worldTypesConvert.test.ts | 205 +++++++++++++ 33 files changed, 2654 insertions(+), 34 deletions(-) create mode 100644 src/arrival/ArrivalService.ts create mode 100644 src/arrival/arrival.ts create mode 100644 src/hex-map/mapTablesForm.ts create mode 100644 src/random-tables/TableNotes.ts create mode 100644 src/space/spaceTables.ts create mode 100644 src/worldgen/tableSources.ts create mode 100644 tests/arrivalDeferred.test.ts create mode 100644 tests/arrivalSubmapSetup.test.ts create mode 100644 tests/mapNoteOnArrival.test.ts create mode 100644 tests/tableRoles.test.ts create mode 100644 tests/worldTypesConvert.test.ts diff --git a/README.md b/README.md index 03844cd0..6342253a 100644 --- a/README.md +++ b/README.md @@ -115,11 +115,15 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it; a land neighbour always shows as at least a small strip or corner patch on its side (a swamp to the south-west, say). - **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one; the map draws a faint dashed tether from each moon to the world or gas giant beside it, hidden with the paths; the PNG export draws it too when it includes paths), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). - **World types** — which worlds Star scatter and Orbits place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types`. Star scatter and Orbits roll on it: their **World types** option picks the table (**Default**: Default space, or your first table if you deleted it; **None**: equal odds over the palette's worlds, stars and planets, and the generator says so). **Default space** ships with the same odds the two generators used before they read the table (the draws differ, so an old seed gives a different map); **Restore default** puts it back. Each row is a world (a terrain of your palette) with a **Weight** (decimals are fine) and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature** (the generators don't know a temperature yet, so it limits nothing there). A sector row's **Mainworld** names the body Orbits makes that system's mainworld (`ocean world` → `ocean planet`; blank: the world itself, if the system palette has it). No generator guesses anything from a terrain's name any more. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain (Default space opens its planets on the **Space - Planet** palette). The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. A row whose world isn't a terrain of the palette being generated is never placed, and the generator's warnings (and the editor's preview) name it. If no row fits the palette at all, the generator uses equal odds and says so. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows. The preview rolls for a palette, a map (sector or system), an orbit and a star exactly the way the generators do, so the odds it shows are the odds you get. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once, and notes made before the Mainworld column get the shipped sector worlds' mainworlds filled in once (after a backup; a Mainworld you typed is never changed). Changes in the editor save automatically, like the hex editor (there is no Save button): a moment after you stop typing, and when you close it. A row that isn't finished yet (no world, or a value it can't read) is marked incomplete and isn't saved; it stays in the editor until you fix or remove it, and is dropped when you close it. Edits you make to the note by hand while the editor is open are kept. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. +- **Space tables** — **Hexmap World Creator: Convert world types to tables** (or the button in a space map's properties) turns each World types note into ordinary random tables in a tidy tree under `{tables folder}/space//`: `Sector/Charted sector`, `Sector/Unexplored sector`, `Sector/Mainworlds`, `Sector/Uncharted`, `System/Stars` and `System/Inner orbits`, `Habitable orbits`, `Outer orbits`. They give the same odds the note did (different draws) and keep each row's Mainworld, Size, Generator, Options, Palette and Base as columns. The World types note is backed up first and kept: it gets a **Tables** list (role → table; edit a link to swap a table) and the tables embedded below it so they can be rolled there. Converting again changes nothing, and a table that already exists is never overwritten. An unconverted note keeps working as before. **Unexplored sector** leaves half its systems unknown: those rows have **Roll** `on arrival`, so the hex shows its **Shown as** terrain (a star system) or nothing (uncharted) and the map note's Hexes table gets an **On arrival** column naming the table to roll later. +- **Generator tables** (map properties, space maps) — one select per generator role: the table Star scatter and Orbits roll on for this map and every map under it. Unset follows the map above, then the World types option. Stored as plain keys in the map note (`sector-hexes-table: "[[…/Unexplored sector]]"`). - **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. **Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which (on space maps: a star system, planet or station is a Location). If the hex already has maps, the dialog lists them first with an **Open** button each, and the menu item reads **Add another map…**. Inside a submap, the breadcrumb ends with what its hex was on the parent map ("from: barren world"). The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. +**Arriving somewhere new** (optional; off unless you turn it on). In a map's properties, **Arriving somewhere new → Make the place, in any mode** (maps under it follow unless they set their own; stored as `on-arrival: make places` in the map note). Then right-click a hex that has no map → **Go there** (or Ctrl+click it): its On arrival table, if it has one, is rolled with the map's `seed:` (the same world gives the same result), what came up is written onto the hex (the sector learns what the system is), and the hex's map is made at once with no form and no preview: from the rolled row's Size, Generator, Options, Palette and Base, else the palette's submap settings, else the usual defaults. It works in Play, opens in the mode you were in, and the new map's note gets a plain-text **## Arrival** section (what was rolled, how the map was made). Until you lock it, the bar beside the mode switch offers **Reroll** (same setup, next seed; the map's terrain and paths are replaced) and **Lock**; after the lock (`arrival: locked`) only God mode can reroll it. Visiting again never rolls again, and a locked hex is never arrived into. **New map from this hex…** in Build still opens the form, starting from the same rolled row. + **Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and a small hex flower on the toolbar shows all six neighbours in their directions (hover a petal for its name, click to go there). An empty petal shows **+** ("New region to the north-east"): click it to walk into new land. Pick the biome that lies there, or **Roll** for one (the seed is shown, so a roll can be repeated; **Re-roll terrain** keeps the biome and tries a new seed), check the live preview of the new region blended with every region around it, and **Create and go**. A biome different from yours makes border country between the two. If that hex is past the overworld's edge, the overworld grows by a hex to fit it. The hex editor's neighbour flower offers the same walk on the hexes past a region's edge. Making a region needs Build or God; in Play the **+** is greyed out and says "Switch to Build to make a region." A new region is made from a short form: biome (the hex's terrain is its biome), blend, how wiggly the borders are, and a seed, with a live preview of the region against its neighbours. It blends with the overworld around it, and the hexes along its edges are pinned to the regions already made, so seams line up whatever order you make them in. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. **Overworlds.** **Maps → New overworld…** (or the command **Hexmap World Creator: New overworld…**) makes a map of biomes with the **World biomes** generator: rectangle or hex-shaped, a climate, water, land and which way is colder, previewed as a small map of biomes with transition hexes outlined in white and the river in blue. Pick the region size, and tick **Make every region now** to have them all made at once (the **Regions** tab's **Make the missing regions…** does the same later, with progress and a Stop button). On an overworld, the switch at the bottom right picks the view: @@ -325,6 +329,7 @@ Every command, as it appears in the command palette: | **Hexmap World Creator: Open random tables** | Opens the random tables and workflows view. | | **Hexmap World Creator: Open terrain generator** | Opens the terrain generator (learn, blend and run generators). | | **Hexmap World Creator: Open palette editor** | Opens the terrain palette editor. | +| **Hexmap World Creator: Convert world types to tables** | Writes each World types note as random tables under `{tables folder}/space//` (backed up first; the notes are kept and link to the tables). Shown while a note is left to convert. Advanced: Terrain generators. | | **Hexmap World Creator: Edit world types…** | Opens the world types table editor (which worlds the space generators place, how often, and how each world's map is made), with a preview. Advanced: Terrain generators; space maps on. | | **Hexmap World Creator: New overworld…** | Generate overworld (first pass): a map of biomes from a biome pool, laid out by climate, whose hexes open into regions that join up; can make every region at once. Advanced: Regions and overworlds. | | **Hexmap World Creator: Go up to parent map** | From a submap, back to the map it belongs to. | diff --git a/dev/smoke/setups.mjs b/dev/smoke/setups.mjs index 43c603b1..5bd270aa 100644 --- a/dev/smoke/setups.mjs +++ b/dev/smoke/setups.mjs @@ -387,6 +387,60 @@ async function spaceExtra(ctx) { out.push({ check: "F4-no-biome-notes", ok: r.biomeNotes === 0, detail: `biome notes: ${r.biomeNotes}` }); out.push({ check: "F4-default-palette", ok: r.defaultPalette === "Space - Sector", detail: `Palette for new maps: ${r.defaultPalette}; kindContent ${JSON.stringify(r.kindContent)}` }); out.push({ check: "F4-planet-palette", ok: r.planet === "Space - Planet", detail: `planet palette: ${r.planet}` }); + + // Tables everywhere phases 3-4: convert World types to tables, then arrive + // in Play at an unknown sector hex (SP4/SP5/GM4/T5). The C5 restart that + // follows checks none of it is rewritten on load. + const a = await ctx.ev(async (id) => { + const p = window.app.plugins.plugins[id]; + const steps = [], problems = []; + try { + if (!p.arrival || !p.worldTypeStore?.convertAll) return { skipped: "build has no arrival" }; + const s = p.settings.maps.find((m) => m.displayName === "Rim Sector" || m.name === "rim-sector")?.name; + if (!s) return { skipped: "no Rim Sector" }; + const sector = p.getMap(s); + if (p.arrival.canArrive(s, 6, 6)) problems.push("arrival on by default"); + await p.worldTypeStore.ensureDefault(); + const conv = await p.worldTypeStore.convertAll(); + steps.push(`converted ${conv.converted.join(", ")} (${conv.written.length} notes)`); + const again = await p.worldTypeStore.convertAll(); + if (again.converted.length || again.written.length) problems.push("converting twice wrote again"); + const mainworlds = conv.written.find((f) => f.endsWith("/Sector/Mainworlds.md")); + if (!mainworlds) return { steps, problems: [...problems, "no Mainworlds table written"] }; + const before = sector.workMode; + sector.arrivalMode = "make places"; + sector.workMode = "play"; + p.mapStore.set(s, "6_6", { terrain: "star system", onArrival: mainworlds.replace(/\.md$/, "") }); + await p.saveSettings(); + await p.mapStore.flush(); + const made = await p.arrival.arrive(s, 6, 6); + const hex = p.mapStore.get(s, "6_6") ?? {}; + if (!made) problems.push("no place made"); + else { + steps.push(`arrived: 6,6 is now ${hex.terrain}; made ${made}`); + if (hex.onArrival) problems.push("On arrival cell not cleared"); + if (!hex.terrain || hex.terrain === "star system") problems.push(`hex terrain ${hex.terrain}`); + if (!(hex.locations ?? []).includes(made)) problems.push("place not linked"); + const child = p.getMap(made); + if (child?.arrival !== "open" || child?.workMode !== "play") problems.push(`new place ${child?.arrival}/${child?.workMode}`); + const note = await p.mapStore.readNoteText(made); + if (!note?.includes("## Arrival")) problems.push("no Arrival section"); + if (!(await p.arrival.reroll(made))) problems.push("Play couldn't reroll an open place"); + await p.arrival.lock(made); + if (await p.arrival.reroll(made)) problems.push("Play rerolled a locked place"); + else steps.push("reroll then lock: Play can't reroll after the lock"); + if ((await p.arrival.arrive(s, 6, 6)) !== null) problems.push("second visit made another place"); + } + sector.workMode = before; + delete sector.arrivalMode; + await p.saveSettings(); + await p.mapStore.flush(); + } catch (e) { + problems.push(String(e?.stack ?? e).slice(0, 400)); + } + return { steps, problems }; + }, ctx.pluginId); + out.push({ check: "F13-arrival", ok: !a.skipped && a.problems.length === 0, detail: a.skipped ?? [...a.steps, ...a.problems].join("; ") }); return out; } diff --git a/package.json b/package.json index 3fb525d3..c4c11f6d 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index eb285067..caab6189 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -75,7 +75,13 @@ import { MapStore, withoutNotePaths } from "./maps/MapStore"; import { setModeMapLookup } from "./modeGate"; import { cellEdits, UndoBook } from "./undoBook"; import type { UndoItem } from "./hex-map/undoItems"; -import { workModeOf } from "./workMode"; +import { workModeOf, type ModeAction } from "./workMode"; +import { contentFolder } from "./notePickers"; +import { TableNotes } from "./random-tables/TableNotes"; +import { inheritedRoleTables, type RoleTablePick } from "./worldgen/tableSources"; +import type { RoleId } from "./worldgen/tableRoles"; +import { ArrivalService } from "./arrival/ArrivalService"; +import { effectiveArrivalMode, type ArrivalMode } from "./arrival/arrival"; import { withMapLink } from "./maps/mapNote"; import { addLocationPatch, @@ -118,6 +124,10 @@ export default class HexmakerPlugin extends Plugin { biomeStore = new BiomeStore(this); /** World types tables for the space generators (src/space). */ worldTypeStore = new WorldTypeStore(this); + /** The tables folder's notes in memory, for rolls the generators make (src/random-tables/TableNotes.ts). */ + tableNotes!: TableNotes; + /** Places made on arrival: roll, make, reroll, lock (src/arrival). */ + arrival = new ArrivalService(this); /** Per-hex map data, backed by one map note per map (src/maps). */ mapStore = new MapStore(this); /** What each hex note's Map data callout last showed (phase 2: tells a hand edit from a stale copy). */ @@ -150,6 +160,7 @@ export default class HexmakerPlugin extends Plugin { async onload() { await this.loadSettings(); + this.tableNotes = TableNotes.register(this); this.pathPins.attach(); // Terrains known now (data.json's copy of the palettes). Any a palette // note adds while Obsidian was closed get their tables once the notes @@ -171,6 +182,7 @@ export default class HexmakerPlugin extends Plugin { // Palettes first (maps reference them), then map notes — which may // migrate per-hex data out of hex notes on the first run. const biomesReady = this.biomeStore.init(); + void this.tableNotes.init(); void this.worldTypeStore.init(); const storesReady = this.paletteStore.init().then(() => this.mapStore.init()); // BC1, once per vault: every overworld hex's biome in its Biome column. @@ -319,6 +331,15 @@ export default class HexmakerPlugin extends Plugin { return true; }, }); + this.addCommand({ + id: "convert-world-types", + name: "Convert world types to tables", + checkCallback: (checking) => { + if (!hasFeature(this.settings, "generators") || !this.worldTypeStore.list().some((t) => !this.worldTypeStore.isConverted(t.name))) return false; + if (!checking) void this.convertWorldTypes(); + return true; + }, + }); this.addCommand({ id: "new-overworld", name: "New overworld…", @@ -2332,6 +2353,8 @@ export default class HexmakerPlugin extends Plugin { quiet?: boolean; /** Folder name (slug) to use instead of one made from rawName (NAV2). */ slug?: string; + /** Hexes left to roll on arrival ("x_y" → table link), for the On arrival column. */ + arrivals?: Map; } = {}, ): Promise<{ name: string } | { error: string }> { if (!rawName.trim()) return { error: "Enter a map name." }; @@ -2372,9 +2395,14 @@ export default class HexmakerPlugin extends Plugin { // Notes on use: a new map writes no hex notes — terrain goes into the // map note, and a hex note appears when the hex first gets content. - const cells = [...(terrainAt ?? new Map())] + const cells: [string, { terrain?: string; onArrival?: string }][] = [...(terrainAt ?? new Map())] .filter(([, t]) => t && t !== extra.baseTerrain) - .map(([k, t]): [string, { terrain: string }] => [k, { terrain: t }]); + .map(([k, t]): [string, { terrain?: string; onArrival?: string }] => [k, { terrain: t }]); + for (const [k, table] of extra.arrivals ?? []) { + const c = cells.find(([key]) => key === k); + if (c) c[1].onArrival = table; + else cells.push([k, { onArrival: table }]); + } this.mapStore.setMany(name, cells); onProgress?.(cols * rows, cols * rows); await this.mapStore.flush(); @@ -2635,11 +2663,11 @@ export default class HexmakerPlugin extends Plugin { * wins, so linking a shared map from a second hex doesn't move its * breadcrumb). */ - async linkSubmap(parentMap: string, x: number, y: number, childMap: string): Promise { + async linkSubmap(parentMap: string, x: number, y: number, childMap: string, action: ModeAction = "link-map"): Promise { if (childMap === parentMap) return; const key = `${x}_${y}`; const patch = addLocationPatch(this.mapStore.get(parentMap, key), childMap); - if (patch.locations && !this.mapStore.set(parentMap, key, patch, "link-map")) return; + if (patch.locations && !this.mapStore.set(parentMap, key, patch, action)) return; this.noParentMaps.clear(); const child = this.getMap(childMap); if (child && !child.parent) { @@ -2730,6 +2758,27 @@ export default class HexmakerPlugin extends Plugin { return undefined; } + /** + * Each generator role's table set on `mapName` or the nearest map above + * it (Map properties → Tables, T11), with the map that set it. + */ + roleTablesFor(mapName: string): Partial> { + return inheritedRoleTables(mapName, (m) => this.getMap(m)?.roleTables, (m) => this.parentOf(m)?.map); + } + + /** "When you arrive somewhere new" for `mapName`: its own setting, else the nearest map above it's, else off. */ + arrivalModeFor(mapName: string): { mode: ArrivalMode; from?: string } { + return effectiveArrivalMode(mapName, (m) => this.getMap(m)?.arrivalMode, (m) => this.parentOf(m)?.map); + } + + /** "Convert world types to tables": every World types note not yet converted (backed up first). */ + async convertWorldTypes(): Promise { + const r = await this.worldTypeStore.convertAll(); + if (!r.converted.length) { new Notice("All world types tables are converted already."); return; } + const kept = r.kept.length ? ` Kept ${r.kept.length} table${r.kept.length === 1 ? "" : "s"} that already existed.` : ""; + new Notice(`Converted ${r.converted.join(", ")} to tables in ${contentFolder(this.settings, "tablesFolder")}/space (${r.written.length} notes).${kept} The old notes were backed up and kept.`, 10000); + } + /** Maps whose parent scan came up empty this session (cleared on any link change). */ private noParentMaps = new Set(); diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index 4ced36dd..5acbdfdd 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -758,7 +758,7 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { plugin.settings.staggerOffset, undefined, outcome?.ok ? outcome.cells : undefined, - { baseTerrain: suggestBaseTerrain(terrains), quiet: true }, + { baseTerrain: suggestBaseTerrain(terrains), quiet: true, ...(outcome?.ok && outcome.arrivals ? { arrivals: outcome.arrivals } : {}) }, ); if ("error" in result) throw new Error(result.error); diff --git a/src/arrival/ArrivalService.ts b/src/arrival/ArrivalService.ts new file mode 100644 index 00000000..bcec1401 --- /dev/null +++ b/src/arrival/ArrivalService.ts @@ -0,0 +1,327 @@ +/** + * Arriving somewhere new (plan-tables-everywhere phase 4: SP4, SP5, GM4, T5). + * + * - resolveHex: a hex's On arrival table is rolled with a seed; what comes + * up becomes the hex's terrain on its own map (discovery is raised to the + * parent: the sector learns what the system is) and the cell is cleared, + * so a second visit never rolls again. + * - arrive: when the world is set to make places (`on-arrival: make + * places`), going into a hex with no map makes its map at once: no form + * and no preview (SP4), seeded from the parent map's seed, set up from the + * rolled row, then the palette's Submap defaults, then the engine's. It is + * linked as the hex's location and opened in the parent's mode, with a + * plain-text "## Arrival" write-up in its note. + * - reroll / lock (GM4): a place made on arrival can be made again in any + * mode until it's locked (`arrival: locked` in its note); after that only + * in God. + * + * A world that isn't set to make places never gets here: nothing changes. + */ + +import { Notice } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { randomSeed } from "../../packages/hex-wfc/src/rng"; +import { chainLabel, resolveRoll, type ResolvedOdds, type TableLookup } from "../random-tables/resolve"; +import { hexChildMaps } from "../maps/submaps"; +import { defaultSubmapLabel, uniqueMapSlug } from "../hex-map/submapNav"; +import { buildSubmapContext } from "../worldgen/submapContext"; +import { addGeneratedPaths } from "../worldgen/generators"; +import { + BLANK_ID, + kindsForPalette, + listGeneratorKinds, + optionsWithDefaults, + runGenerator, + submapStartKind, + suggestBaseTerrain, + visibleKinds, + type TerrainGeneratorKind, +} from "../worldgen/registry"; +import { attrsForTerrain } from "../worldgen/tableSources"; +import { canRerollPlace, REROLL_PLACE_LOCKED_HINT, workModeOf, type ModeAction } from "../workMode"; +import { + arrivalLines, + arrivalSeed, + arrivalSummary, + placeSetup, + restateArrival, + withArrivalSection, + type ArrivalReport, + type PlaceSetup, +} from "./arrival"; + +/** What a hex's On arrival roll gave. */ +export interface HexResolution { + /** The table rolled (as the cell had it). */ + table: string; + kind: ResolvedOdds["kind"]; + /** The terrain, text, note… ("(nothing)" for a nothing row). */ + value: string; + attrs: Record; + chain: string; +} + +/** The submap size when nothing else says (SUBMAP_SIZE_PRESETS' Medium). */ +const DEFAULT_PLACE_SIZE = { cols: 13, rows: 13 }; + +const keyOf = (x: number, y: number) => `${x}_${y}`; +const hexText = (key: string) => key.replace("_", ", "); + +export class ArrivalService { + constructor(private plugin: HexmakerPlugin) {} + + /** Why hex (x, y) of `mapName` can't be arrived at (null: it can). "off" when the world doesn't make places. */ + blocker(mapName: string, x: number, y: number): string | null { + const { plugin } = this; + if (!plugin.getMap(mapName)) return "No such map."; + if (plugin.arrivalModeFor(mapName).mode !== "make") return "off"; + const h = plugin.mapStore.get(mapName, keyOf(x, y)); + if (h?.locked) return "This hex is locked."; + if (hexChildMaps(h).some((m) => !!plugin.getMap(m))) return "This hex already has a map."; + return null; + } + + /** Whether "Go there" makes a place at hex (x, y). */ + canArrive(mapName: string, x: number, y: number): boolean { + return this.blocker(mapName, x, y) === null; + } + + /** The map's seed, given one now if it has none (saved with the next settings save). */ + private seedOf(mapName: string): number { + const map = this.plugin.getMap(mapName); + if (!map) return 0; + if (typeof map.seed !== "number" || !Number.isFinite(map.seed)) map.seed = randomSeed(); + return map.seed >>> 0; + } + + /** Tables for rolls on `mapName`: its generator tables (Map properties → Tables, World types), then any table note. */ + private lookupFor(mapName: string): { lookup: TableLookup; terrains: string[] } { + const { plugin } = this; + const terrains = plugin.getMapPalette(mapName).map((t) => t.name); + const source = plugin.worldTypeStore.sourceFor(undefined, terrains, mapName).source; + const notes = plugin.tableNotes.lookup(); + if (!source) return { lookup: notes, terrains }; + return { + terrains, + lookup: { + table: (link) => source.lookup.table(link) ?? notes.table(link), + kindOf: (link) => { + const k = source.lookup.kindOf?.(link); + return k && k !== "missing" ? k : notes.kindOf?.(link) ?? "missing"; + }, + }, + }; + } + + /** + * Roll hex (x, y)'s On arrival table (seeded by the map's seed and the + * hex) and write what came up onto the hex: a terrain replaces the shown + * one, (nothing) clears it; the cell is cleared either way. Null when the + * hex has nothing to roll or the write was refused. + */ + resolveHex(mapName: string, x: number, y: number, action: ModeAction): HexResolution | null { + const { plugin } = this; + const key = keyOf(x, y); + const cell = plugin.mapStore.get(mapName, key)?.onArrival; + if (!cell) return null; + const seed = arrivalSeed(this.seedOf(mapName), key, "arrival", 0); + const { lookup, terrains } = this.lookupFor(mapName); + const r = resolveRoll(cell, lookup, { seed, terrains }); + const patch: { onArrival: null; terrain?: string | null } = { onArrival: null }; + if (r.kind === "terrain") patch.terrain = r.value; + else if (r.kind === "nothing") patch.terrain = null; + if (!plugin.mapStore.set(mapName, key, patch, action)) return null; + return { + table: cell, + kind: r.kind, + value: r.kind === "nothing" ? "(nothing)" : r.kind === "empty" ? `nothing to roll on ${cell}` : r.value, + attrs: r.attrs, + chain: chainLabel(r), + }; + } + + /** The place's setup and the generator to run, for hex (x, y) of `mapName` (SP4's chain). */ + private async plan(mapName: string, x: number, y: number, terrain: string | undefined, attrs: Record | undefined, seed: number) { + const { plugin } = this; + const kinds = await listGeneratorKinds(plugin); + const space = plugin.isSpaceMap(mapName); + const fittingFor = (palette: string) => { + const terrains = plugin.getPaletteOrPresetTerrains(palette); + const spaceHere = space || plugin.getPaletteOrPresetKind(palette) === "space"; + return { terrains, fitting: kindsForPalette(visibleKinds(kinds, plugin.settings, spaceHere), terrains, true) }; + }; + const setup = placeSetup(attrs, plugin.submapDefaultFor(mapName, terrain), { + palette: plugin.childPaletteFor(mapName), + ...DEFAULT_PLACE_SIZE, + generatorFor: (palette) => submapStartKind(fittingFor(palette).fitting, BLANK_ID, { parentTerrain: terrain }), + baseFor: (palette) => suggestBaseTerrain(plugin.getPaletteOrPresetTerrains(palette)), + }, seed); + return { setup, ...this.kindFor(kinds, setup, fittingFor(setup.palette), terrain) }; + } + + /** The generator to run: the setup's, when it exists and fits the palette, else the engine's pick. */ + private kindFor(kinds: TerrainGeneratorKind[], setup: PlaceSetup, here: { terrains: ReturnType; fitting: TerrainGeneratorKind[] }, terrain: string | undefined) { + const wanted = kinds.find((k) => k.id === setup.generator); + if (wanted && wanted.fits(here.terrains)) return { kind: wanted, terrains: here.terrains, note: undefined as string | undefined }; + const fallback = kinds.find((k) => k.id === submapStartKind(here.fitting, BLANK_ID, { parentTerrain: terrain })) ?? kinds.find((k) => k.id === BLANK_ID)!; + return { kind: fallback, terrains: here.terrains, note: `The generator ${setup.generator} isn't there or doesn't fit ${setup.palette}, so ${fallback.label} was used.` }; + } + + /** + * Arrive at hex (x, y) of `mapName`: roll its On arrival table, make its + * map from the result (no form, no preview), link and return it. Null + * when the world doesn't make places, the hex has a map already, or + * nothing is there. + */ + async arrive(mapName: string, x: number, y: number): Promise { + const { plugin } = this; + const why = this.blocker(mapName, x, y); + if (why) { + if (why !== "off") new Notice(why); + return null; + } + const parent = plugin.getMap(mapName)!; + const key = keyOf(x, y); + const pseed = this.seedOf(mapName); + const resolution = this.resolveHex(mapName, x, y, "discover"); + if (resolution?.kind === "nothing") { + await plugin.saveSettings(); + new Notice(`Nothing at ${hexText(key)}: empty space.`); + plugin.refreshHexMap(); + return null; + } + const terrain = plugin.mapStore.get(mapName, key)?.terrain ?? parent.baseTerrain; + const source = plugin.worldTypeStore.sourceFor(undefined, plugin.getMapPalette(mapName).map((t) => t.name), mapName).source; + const attrs = resolution?.kind === "terrain" ? resolution.attrs : terrain ? attrsForTerrain(source, terrain) : undefined; + const seed = arrivalSeed(pseed, key, "submap", 0); + const { setup, kind, terrains, note } = await this.plan(mapName, x, y, terrain, attrs, seed); + + const stagger = parent.staggerOffset ?? plugin.settings.staggerOffset ?? "odd"; + const outcome = runGenerator(plugin.settings.hexOrientation, kind, { + terrains, + grid: { cols: setup.cols, rows: setup.rows, offset: { x: 0, y: 0 }, stagger }, + seed, + options: optionsWithDefaults(kind, setup.options), + context: buildSubmapContext(plugin, mapName, x, y), + pathTypes: plugin.getPathTypes(setup.palette), + tablesFrom: mapName, + }); + if (!outcome.ok) { + await plugin.saveSettings(); + new Notice(`Couldn't make the place: ${outcome.message}`); + plugin.refreshHexMap(); + return null; + } + + const label = defaultSubmapLabel(plugin.mapStore.get(mapName, key)?.name, plugin.mapLabel(mapName), x, y, { + terrain, + taken: plugin.settings.maps.map((m) => plugin.mapLabel(m.name)), + }); + const made = await plugin.createNewMap(label, setup.cols, setup.rows, setup.palette, 0, 0, stagger, undefined, outcome.cells, { + baseTerrain: setup.baseTerrain, + parent: { map: mapName, hex: key }, + quiet: true, + slug: uniqueMapSlug(label, plugin.settings.maps.map((m) => m.name)), + ...(outcome.arrivals ? { arrivals: outcome.arrivals } : {}), + }); + if ("error" in made) { + await plugin.saveSettings(); + new Notice(made.error); + return null; + } + const { paths } = kind.toPaths(outcome.paths, made.name); + if (paths.length) addGeneratedPaths(plugin, made.name, paths); + await plugin.linkSubmap(mapName, x, y, made.name, "discover"); + const child = plugin.getMap(made.name); + if (child) { + child.seed = arrivalSeed(pseed, key, "place", 0); + child.arrival = "open"; + // The new place opens in the mode the player was in. + if (parent.workMode) child.workMode = workModeOf(parent); + } + await plugin.saveSettings(); + await plugin.mapStore.flush(); + + const report: ArrivalReport = { + date: new Date().toISOString().slice(0, 10), + parentNote: `_${mapName}`, + hex: hexText(key), + ...(resolution ? { rolled: { table: resolution.table, result: resolution.value, chain: resolution.chain } } : {}), + ...(terrain ? { terrain } : {}), + made: { generator: kind.label, palette: setup.palette, cols: setup.cols, rows: setup.rows, seed }, + ...(note ? { extra: [note] } : {}), + }; + await plugin.mapStore.editNoteText(made.name, (c) => withArrivalSection(c, arrivalLines(report))); + new Notice(arrivalSummary(plugin.mapLabel(made.name), report), 8000); + return made.name; + } + + /** + * Make a place made on arrival again (GM4): same palette, size and + * generator, the next seed. Allowed in any mode until the place is + * locked; then only in God. Its terrain and paths are replaced. + */ + async reroll(mapName: string): Promise { + const { plugin } = this; + const map = plugin.getMap(mapName); + if (!map?.arrival || !map.parent || !plugin.getMap(map.parent.map)) return false; + if (!canRerollPlace(map)) { new Notice(REROLL_PLACE_LOCKED_HINT); return false; } + const { map: parentName, hex } = map.parent; + const [x, y] = hex.split("_").map(Number); + const n = (map.arrivalRerolls ?? 0) + 1; + const seed = arrivalSeed(this.seedOf(parentName), hex, "submap", n); + const terrain = plugin.mapStore.get(parentName, hex)?.terrain ?? plugin.getMap(parentName)?.baseTerrain; + const source = plugin.worldTypeStore.sourceFor(undefined, plugin.getMapPalette(parentName).map((t) => t.name), parentName).source; + const attrs = terrain ? attrsForTerrain(source, terrain) : undefined; + const planned = await this.plan(parentName, x, y, terrain, attrs, seed); + // The place keeps its palette and size; only the landscape is made again. + const kinds = await listGeneratorKinds(plugin); + const setup: PlaceSetup = { ...planned.setup, palette: map.paletteName, cols: map.gridSize.cols, rows: map.gridSize.rows }; + if (map.baseTerrain) setup.baseTerrain = map.baseTerrain; + const terrains = plugin.getPaletteOrPresetTerrains(map.paletteName); + const fitting = kindsForPalette(visibleKinds(kinds, plugin.settings, plugin.isSpaceMap(parentName)), terrains, true); + const { kind } = this.kindFor(kinds, setup, { terrains, fitting }, terrain); + const outcome = runGenerator(plugin.settings.hexOrientation, kind, { + terrains, + grid: { cols: map.gridSize.cols, rows: map.gridSize.rows, offset: { ...map.gridOffset }, stagger: map.staggerOffset ?? plugin.settings.staggerOffset ?? "odd" }, + seed, + options: optionsWithDefaults(kind, setup.options), + context: buildSubmapContext(plugin, parentName, x, y), + pathTypes: plugin.getPathTypes(map.paletteName), + tablesFrom: parentName, + }); + if (!outcome.ok) { new Notice(`Couldn't reroll: ${outcome.message}`); return false; } + + // Every hex loses its old terrain and On arrival roll, then takes the new. + const cells = new Map(); + for (const k of plugin.mapStore.all(mapName).keys()) cells.set(k, { terrain: undefined, onArrival: undefined }); + for (const [k, t] of outcome.cells) if (t && t !== map.baseTerrain) cells.set(k, { ...(cells.get(k) ?? {}), terrain: t }); + for (const [k, table] of outcome.arrivals ?? []) cells.set(k, { ...(cells.get(k) ?? {}), onArrival: table }); + plugin.mapStore.setMany(mapName, cells); + plugin.mapStore.setPaths(mapName, kind.toPaths(outcome.paths, mapName).paths); + map.arrivalRerolls = n; + await plugin.saveSettings(); + await plugin.mapStore.flush(); + await plugin.mapStore.editNoteText(mapName, (c) => restateArrival(c, { + made: { generator: kind.label, palette: map.paletteName, cols: map.gridSize.cols, rows: map.gridSize.rows, seed }, + rerolls: n, + locked: map.arrival === "locked", + })); + plugin.refreshHexMap(); + new Notice(`Rerolled ${plugin.mapLabel(mapName)}.`); + return true; + } + + /** Lock a place made on arrival (GM4): from now on only God may reroll it. */ + async lock(mapName: string): Promise { + const { plugin } = this; + const map = plugin.getMap(mapName); + if (!map?.arrival || map.arrival === "locked") return; + map.arrival = "locked"; + await plugin.saveSettings(); + await plugin.mapStore.flush(); + await plugin.mapStore.editNoteText(mapName, (c) => restateArrival(c, { rerolls: map.arrivalRerolls ?? 0, locked: true })); + plugin.refreshHexMap(); + new Notice(`Locked ${plugin.mapLabel(mapName)}. Rerolling it now needs God mode.`); + } +} diff --git a/src/arrival/arrival.ts b/src/arrival/arrival.ts new file mode 100644 index 00000000..bc771405 --- /dev/null +++ b/src/arrival/arrival.ts @@ -0,0 +1,266 @@ +/** + * Roll on arrival (plan-tables-everywhere phase 4: SP4, SP5, GM4, T5). + * + * - A world is set to make places on arrival with the map note key + * `on-arrival: make places` (Map properties), inherited down the map + * tree; unset everywhere = off, and then nothing here ever runs. + * - Seeds depend only on stored values: the parent map's `seed:`, the hex + * and a purpose (and the reroll count), never on map names. + * - A place's setup (SP4, no form) comes from, field by field: the rolled + * row's attributes (Size, Generator, Options, Palette, Base), then the + * palette's Submap defaults for the terrain, then the engine's defaults. + * - What was rolled is written as plain text in the new map's note + * (`## Arrival`), so it can be read and edited like any note. + * + * Pure: no Obsidian imports. + */ + +import { mulberry32 } from "../../packages/hex-wfc/src/rng"; +import { generatorRefId, readGenerator, readOptions, readSize } from "../space/worldTypes"; +import type { SubmapDefault } from "../types"; + +// ── the setting ────────────────────────────────────────────────────────── + +export type ArrivalMode = "off" | "make"; + +/** How the setting is written in the map note. */ +export const ARRIVAL_MODE_WORDS: Record = { off: "off", make: "make places" }; + +/** The choices as shown in Map properties. */ +export const ARRIVAL_MODE_TEXT: Record = { + off: "Do nothing (make places in Build)", + make: "Make the place, in any mode", +}; + +/** `on-arrival:` read forgivingly ("make places", "make", "generate", "yes" / "off", "no", "nothing"); unknown → undefined. */ +export function parseArrivalMode(raw: unknown): ArrivalMode | undefined { + if (typeof raw !== "string") return undefined; + const t = raw.trim().toLowerCase(); + if (/^(make|generate|create|yes|on|true)\b/.test(t)) return "make"; + if (/^(off|no|none|nothing|false|do nothing)\b/.test(t)) return "off"; + return undefined; +} + +/** The setting for a map: its own, else the nearest map above it's, else off. */ +export function effectiveArrivalMode( + mapName: string, + modeOf: (map: string) => string | undefined, + parentOf: (map: string) => string | undefined, +): { mode: ArrivalMode; from?: string } { + const seen = new Set(); + for (let m: string | undefined = mapName; m && !seen.has(m); m = parentOf(m)) { + seen.add(m); + const mode = parseArrivalMode(modeOf(m)); + if (mode) return { mode, from: m }; + } + return { mode: "off" }; +} + +// ── seeds ──────────────────────────────────────────────────────────────── + +/** A 32-bit hash of the parts (FNV-1a over their text). */ +export function hashSeed(...parts: (string | number)[]): number { + let h = 0x811c9dc5; + const text = parts.map(String).join("\u0000"); + for (let i = 0; i < text.length; i++) { + h ^= text.charCodeAt(i); + h = Math.imul(h, 0x01000193) >>> 0; + } + return h >>> 0; +} + +export type SeedPurpose = "arrival" | "submap" | "place"; + +/** + * The seed of something under hex `hex` of a map whose seed is + * `parentSeed`: "arrival" (its On arrival roll), "submap" (generating the + * place, `reroll` times rerolled), "place" (the new map's own seed). + */ +export function arrivalSeed(parentSeed: number, hex: string, purpose: SeedPurpose, reroll = 0): number { + return hashSeed(parentSeed >>> 0, hex, purpose, reroll); +} + +// ── the place's setup (SP4) ────────────────────────────────────────────── + +export interface PlaceSetup { + palette: string; + cols: number; + rows: number; + /** Generator id (registry). */ + generator: string; + options: Record; + baseTerrain?: string; + /** Where each part came from, for the write-up. */ + from: Record<"palette" | "size" | "generator" | "options" | "base", "row" | "defaults" | "engine">; +} + +/** The engine's defaults, worked out by the caller for a palette. */ +export interface EngineDefaults { + palette: string; + cols: number; + rows: number; + /** The generator for this palette and terrain (submapStartKind). */ + generatorFor: (palette: string) => string; + baseFor: (palette: string) => string | undefined; +} + +const unlinkName = (s: string) => (/\[\[([^\]|#]+)/.exec(s)?.[1] ?? s).trim().replace(/\.md$/i, "").replace(/^.*\//, ""); + +/** + * The setup for a place made on arrival, field by field: the rolled row's + * attributes, then the palette's Submap defaults, then the engine's. + * A Size range is rolled from `seed`. Options merge (the row's win). + */ +export function placeSetup( + attrs: Record | undefined, + saved: SubmapDefault | undefined, + engine: EngineDefaults, + seed: number, +): PlaceSetup { + const a = attrs ?? {}; + const from = {} as PlaceSetup["from"]; + const pick = (key: keyof PlaceSetup["from"], row: T | undefined, def: T | undefined, eng: T): T => { + if (row !== undefined) { from[key] = "row"; return row; } + if (def !== undefined) { from[key] = "defaults"; return def; } + from[key] = "engine"; + return eng; + }; + const palette = pick("palette", a.Palette?.trim() ? unlinkName(a.Palette) : undefined, saved?.palette, engine.palette); + + const sizeRange = a.Size ? readSize(a.Size) : undefined; + const rand = mulberry32(seed >>> 0); + const rolled = sizeRange + ? { cols: sizeRange.cols.lo + Math.floor(rand() * (sizeRange.cols.hi - sizeRange.cols.lo + 1)), rows: sizeRange.rows.lo + Math.floor(rand() * (sizeRange.rows.hi - sizeRange.rows.lo + 1)) } + : undefined; + const size = pick("size", rolled, saved?.cols && saved.rows ? { cols: saved.cols, rows: saved.rows } : undefined, { cols: engine.cols, rows: engine.rows }); + + const gen = a.Generator ? readGenerator(a.Generator) : undefined; + const generator = pick("generator", gen ? generatorRefId(gen) : undefined, saved?.generator, engine.generatorFor(palette)); + + const rowOptions = a.Options ? readOptions(a.Options) : undefined; + const hasRow = !!rowOptions && Object.keys(rowOptions).length > 0; + const hasSaved = !!saved?.options && Object.keys(saved.options).length > 0; + const options = pick("options", hasRow ? { ...(saved?.options ?? {}), ...rowOptions } : undefined, hasSaved ? { ...saved?.options } : undefined, {}); + + const base = pick("base", a.Base?.trim() || undefined, saved?.baseTerrain === "" ? undefined : saved?.baseTerrain, engine.baseFor(palette)); + const out: PlaceSetup = { palette, cols: size.cols, rows: size.rows, generator, options, from }; + if (base) out.baseTerrain = base; + return out; +} + +// ── the write-up ───────────────────────────────────────────────────────── + +export interface ArrivalReport { + /** The date (YYYY-MM-DD). */ + date: string; + /** The parent map's note link target (`_the-drift`), and the hex as people write it (`4, 7`). */ + parentNote: string; + hex: string; + /** The On arrival roll, when there was one: the table, what came up, and the chain ("Unexplored sector → Mainworlds → ocean world"). */ + rolled?: { table: string; result: string; chain: string }; + /** The hex's terrain once known. */ + terrain?: string; + /** "Orbits", the palette, the size and the seed. */ + made: { generator: string; palette: string; cols: number; rows: number; seed: number }; + rerolls?: number; + locked?: boolean; + /** + * More lines from arrival rules. Seam: module arrival rules (plan- + * generator-modules §4.4) add their rolls here. + */ + extra?: string[]; +} + +export const ARRIVAL_HEADING = "## Arrival"; + +/** The `## Arrival` section's lines (heading included): plain text. */ +export function arrivalLines(r: ArrivalReport): string[] { + const lines = [ + ARRIVAL_HEADING, + "", + `First visited ${r.date}, from [[${r.parentNote}]] hex ${r.hex}.`, + "", + ]; + if (r.rolled) lines.push(`- Rolled on [[${r.rolled.table.replace(/\.md$/i, "")}]]: ${r.rolled.result} (${r.rolled.chain}).`); + else if (r.terrain) lines.push(`- The hex was ${r.terrain}.`); + lines.push(`- Made with ${r.made.generator} on ${r.made.palette}, ${r.made.cols}×${r.made.rows}, seed ${r.made.seed}.`); + for (const e of r.extra ?? []) lines.push(`- ${e}`); + if (r.rerolls) lines.push(`- Rerolled ${r.rerolls === 1 ? "once" : `${r.rerolls} times`}.`); + lines.push(r.locked + ? "- Locked: rerolling it now needs God mode." + : "- Not locked yet: Reroll above the map makes it again; Lock keeps it."); + return lines; +} + +/** + * The note with its `## Arrival` section set to `lines`: an existing one + * (up to the next `## ` heading) is replaced, else the section goes at + * the end. Everything else stays as it was. + */ +export function withArrivalSection(content: string, lines: readonly string[]): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const all = content.replace(/\r\n?/g, "\n").split("\n"); + const start = all.findIndex((l) => l.trim().toLowerCase() === ARRIVAL_HEADING.toLowerCase()); + if (start >= 0) { + let end = start + 1; + while (end < all.length && !/^#{1,2}\s/.test(all[end])) end++; + // Keep one blank line before the next heading. + const next = [""]; + all.splice(start, end - start, ...lines, ...next); + return all.join(eol); + } + while (all.length && all[all.length - 1].trim() === "") all.pop(); + return [...all, "", ...lines, ""].join(eol); +} + +const STATUS_LINE = /^- (?:Made with |Rerolled |Locked|Not locked yet)/; + +/** + * The `## Arrival` section after a reroll or a lock: its "Made with", + * "Rerolled" and lock lines are written again (`made` only when given); + * every other line stays as it was. Unchanged when there's no section. + */ +export function restateArrival(content: string, s: { made?: ArrivalReport["made"]; rerolls: number; locked: boolean }): string { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const all = content.replace(/\r\n?/g, "\n").split("\n"); + const start = all.findIndex((l) => l.trim().toLowerCase() === ARRIVAL_HEADING.toLowerCase()); + if (start < 0) return content; + let end = start + 1; + while (end < all.length && !/^#{1,2}\s/.test(all[end])) end++; + const section = all.slice(start + 1, end); + const made = section.find((l) => l.startsWith("- Made with ")); + const kept = section.filter((l) => !STATUS_LINE.test(l)); + while (kept.length && kept[kept.length - 1].trim() === "") kept.pop(); + const status = arrivalLines({ date: "", parentNote: "", hex: "", made: s.made ?? { generator: "", palette: "", cols: 0, rows: 0, seed: 0 }, rerolls: s.rerolls, locked: s.locked }) + .filter((l) => STATUS_LINE.test(l)) + .map((l) => (l.startsWith("- Made with ") && !s.made ? made ?? "" : l)) + .filter((l) => l !== ""); + const next = [""]; + all.splice(start + 1, end - start - 1, ...kept, ...status, ...next); + return all.join(eol); +} + +/** One line for a notice. */ +export function arrivalSummary(place: string, r: Pick): string { + const rolled = r.rolled ? `${r.rolled.result}. ` : ""; + return `Arrived at ${place}: ${rolled}Made with ${r.made.generator}, ${r.made.cols}×${r.made.rows}.`; +} + +/** + * A row's attributes as a submap setup (the palette's Submap defaults + * shape), for Build's "New map from this hex…" form to start from. The + * smallest size of a range. + */ +export function rowSubmapDefault(attrs: Record | undefined): SubmapDefault | undefined { + if (!attrs) return undefined; + const out: SubmapDefault = {}; + if (attrs.Palette?.trim()) out.palette = unlinkName(attrs.Palette); + const size = attrs.Size ? readSize(attrs.Size) : undefined; + if (size) { out.cols = size.cols.lo; out.rows = size.rows.lo; } + const gen = attrs.Generator ? readGenerator(attrs.Generator) : undefined; + if (gen) out.generator = generatorRefId(gen); + const opts = attrs.Options ? readOptions(attrs.Options) : undefined; + if (opts && Object.keys(opts).length) out.options = opts; + if (attrs.Base?.trim()) out.baseTerrain = attrs.Base.trim(); + return Object.keys(out).length ? out : undefined; +} diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 100204b3..733a8e3c 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -36,7 +36,7 @@ import { PathTool } from "./pathTool"; import type { PinRecord } from "../paths/routePins"; import { pathListSummary } from "./pathTool"; import { flowerPetals, MapHistory, navArrows, neighbourButton, PAD_SIDES } from "../maps/mapNav"; -import { ADD_REGION_LOCKED_HINT, allows, canAdd, lockedHint, lockedSummary, TOOL_ACTIONS, WORK_MODES, WORK_MODE_TEXT, workModeOf, type ModeAction, type WorkMode } from "../workMode"; +import { ADD_REGION_LOCKED_HINT, allows, canAdd, canRerollPlace, lockedHint, lockedSummary, TOOL_ACTIONS, WORK_MODES, WORK_MODE_TEXT, workModeOf, type ModeAction, type WorkMode } from "../workMode"; import { canDo, guardWrite } from "../modeGate"; import { ModeMenu } from "./modeMenu"; import { REGION_AREAS_TOOL } from "./toolMode"; @@ -356,6 +356,8 @@ export class HexMapView extends ItemView { private navArrowsEl: HTMLElement | null = null; /** The map's work mode (Play / Build / God), always shown. */ private workModeBtn: HTMLButtonElement | null = null; + /** Reroll / Lock for a place made on arrival (refreshArrivalBar). */ + private arrivalBarEl: HTMLElement | null = null; private crumbsEl: HTMLElement | null = null; /** Sideways crumbs: the neighbouring regions of the open map. */ private sideCrumbsEl: HTMLElement | null = null; @@ -584,6 +586,45 @@ export class HexMapView extends ItemView { startNewChildMap(this.childMapHost(), this.activeMapName, x, y); } + /** + * Go into hex (x, y) where nothing exists yet (arrival, GM4/SP4): its On + * arrival table is rolled, its place made from the result with no form, + * and the view enters it. + */ + async arriveAt(x: number, y: number): Promise { + const from = this.activeMapName; + const made = await this.plugin.arrival.arrive(from, x, y); + if (made && this.activeMapName === from) this.navigateToMap(made); + else this.renderGrid(); + } + + /** + * The bar for a place made on arrival (GM4): Reroll makes it again (any + * mode until locked, then God), Lock keeps it. Hidden on other maps. + */ + private refreshArrivalBar(): void { + const el = this.arrivalBarEl; + if (!el) return; + el.empty(); + const map = this.plugin.getMap(this.activeMapName); + const state = map?.arrival?.trim().toLowerCase(); + if (!map || (state !== "open" && state !== "locked") || !map.parent) { el.hide(); return; } + const open = state === "open"; + // A locked place shows the bar only where it can still be rerolled (God). + if (!open && !canRerollPlace(map)) { el.hide(); return; } + el.show(); + el.createSpan({ cls: "duckmage-arrival-bar-label", text: open ? "New place" : "Locked place" }); + const reroll = el.createEl("button", { + text: "Reroll", + attr: { title: open ? "Make this place again (its terrain and paths are replaced)" : "Make this locked place again (God mode)" }, + }); + reroll.addEventListener("click", () => void this.plugin.arrival.reroll(map.name).then(() => { this.refreshArrivalBar(); this.renderGrid(); })); + if (open) { + const lock = el.createEl("button", { text: "Lock", attr: { title: `Keep this place as it is (rerolling it then needs ${WORK_MODE_TEXT.god.label} mode)` } }); + lock.addEventListener("click", () => void this.plugin.arrival.lock(map.name).then(() => this.refreshArrivalBar())); + } + } + /** "+ New location…" straight away (the Locations list's button). */ private openNewLocationSetup(x: number, y: number): void { startNewLocation(this.childMapHost(), this.activeMapName, x, y); @@ -748,6 +789,8 @@ export class HexMapView extends ItemView { /** The work-mode switch: names the map's mode; click to pick another. */ private refreshWorkModeBtn(): void { this.applyWorkModeUi(); + // Reroll / Lock depend on the mode too (a locked place: God only). + this.refreshArrivalBar(); const btn = this.workModeBtn; if (!btn) return; const mode = workModeOf(this.plugin.getMap(this.activeMapName)); @@ -1561,6 +1604,8 @@ export class HexMapView extends ItemView { this.workModeBtn = mapNavGroup.createEl("button", { cls: "duckmage-work-mode-btn" }); this.workModeBtn.addEventListener("click", (e) => this.openWorkModeMenu(e)); + this.arrivalBarEl = mapNavGroup.createDiv({ cls: "duckmage-arrival-bar" }); + this.arrivalBarEl.hide(); this.refreshMapNav(); this.undoBtn = controlsEl.createEl("button", { @@ -4804,6 +4849,11 @@ export class HexMapView extends ItemView { if (childPlan.listCount) { menu.add("hex.locations", `Locations (${childPlan.listCount})…`, "list", () => this.openLocationsList(x, y)); } + // Arrival (GM4): a world set to make places makes this hex's place on + // the spot, in any mode, when it has none yet. + if (!hasRegion && !childPlan.open.length && !childPlan.listCount && this.plugin.arrival.canArrive(this.activeMapName, x, y)) { + menu.add("hex.arrive", "Go there", "footprints", () => void this.arriveAt(x, y)); + } if (hasRegion || childPlan.open.length || childPlan.listCount) menu.addSeparator(); menu.add("hex.center", "Center on this hex", "crosshair", () => this.centerOnHex(x, y)); @@ -4983,6 +5033,11 @@ export class HexMapView extends ItemView { } return; } + // No map there yet: arriving makes one (when the world makes places). + if (!e.shiftKey && !ow && this.plugin.arrival.canArrive(this.activeMapName, x, y)) { + await this.arriveAt(x, y); + return; + } } // No hex editor on an overworld (#49): it's the big-picture view. diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index e3318bdf..886dad03 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -34,6 +34,7 @@ import { renderRegionSettingsForm } from "./regionSettingsForm"; import { NewMapSetupModal } from "../worldgen/NewMapSetupModal"; import { buildMapTree, filterMapTree, nodeKey, treeContains, type MapTreeNode } from "../maps/mapTree"; import { ROLLED_SECTION_TABLES, mapSectionTable, starterTablePath } from "../regionTables"; +import { renderArrivalSetting, renderRoleTables } from "./mapTablesForm"; type ModalTab = "Maps" | "Properties" | "Regions" | "Export"; @@ -537,6 +538,12 @@ export class MapModal extends HexmakerModal { // ── Region tables (E2) ───────────────────────────────────────────────── if (currentMap) this.renderRegionTables(el, currentMap); + // ── Arrival (GM4) and generator tables (T11) ────────────────────────── + if (currentMap) { + renderArrivalSetting(el, this.plugin, currentMap, () => this.render()); + renderRoleTables(el, this.plugin, currentMap, () => this.render()); + } + // ── Background image ─────────────────────────────────────────────────── el.createEl("h4", { text: "Background image" }); const bgRow = el.createDiv({ cls: "duckmage-region-row duckmage-bg-image-row" }); diff --git a/src/hex-map/help.md b/src/hex-map/help.md index ba1a7e84..98bba889 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -181,6 +181,14 @@ A road or river that ends on the edge of a region, next to where the neighbour's **More in a table** (all optional; old tables read the same). Weights can be decimals (`3.5`) or percentages. Extra columns are kept and shown in the Random Tables view. The columns **Roll** (`now` / `on arrival`), **Shown as**, **Once** (`per world` / `per map`) and **When** (`zone: outer; star: red dwarf`), and `rows:` in the frontmatter (text, note, table, generator, terrain, biome or any), are read and checked now (**Check tables**) and used by later features. +**Space tables.** The command **Convert world types to tables** (or the button under **Generator tables** in a space map's properties) turns each World types note into ordinary random tables in `{tables folder}/space//`: `Sector/` has **Charted sector** (what a star system hex is), **Unexplored sector** (the same, but only half the systems are known), **Mainworlds** and **Uncharted** (what an unknown hex turns out to be); `System/` has **Stars** and **Inner**, **Habitable** and **Outer orbits**. They give the same odds as the note did and roll like any table. The old note is backed up first and kept: it gets a **Tables** list linking each generator role to its table (change a link there to use another table) and the tables shown below it, so you can roll them from the note. Converting twice changes nothing. + +**Generator tables** (map properties, space maps). One line per generator role (Sector hexes, Star, Inner, Habitable and Outer orbits): pick the table it rolls on for this map and every map made under it. Unset lines follow the map above, then the World types picked when generating. Pick **Unexplored sector** for Sector hexes to start a sector with unknown systems. + +**Unknown hexes.** A table row whose **Roll** is `on arrival` isn't rolled when the map is made: the hex shows its **Shown as** terrain (a somewhat known system shows as a star system; an uncharted hex shows nothing) and the map note's Hexes table gets an **On arrival** cell naming the table to roll. You can type a table into any hex's On arrival cell by hand. The first time the hex is opened, the table is rolled (with the map's seed, so the same world gives the same result), the hex gets what came up and the cell is cleared: the sector learns what the system is. **New map from this hex…** rolls it first too, and the form starts from the rolled row. + +**Arriving somewhere new.** In map properties, **Arriving somewhere new** can be set to **Make the place, in any mode** (maps under it do the same unless they say otherwise; unset everywhere is off and nothing changes). Then a hex with no map gets **Go there** in its right-click menu (Ctrl+click does the same): its On arrival table is rolled and its map is made at once, with no form and no preview, from the row's Size, Generator, Options, Palette and Base, else the palette's submap settings. This works in Play. The new map opens in the mode you were in, and its note gets an **Arrival** section saying what was rolled and how the map was made. Until you lock it, the bar next to the mode switch has **Reroll** (makes the place again, in any mode) and **Lock**; once locked (`arrival: locked` in its note), only God can reroll it. A locked hex is never arrived into. + With generators on, new maps can also use the built-in **biomes and presets** (Grassland, Taiga, Swamp, Archipelago, Volcanic and more). They place terrain by type, so they work with any palette whose terrains have types. **New map…** (in Maps) is one form: generator cards with a live preview, Next to (Advanced), and **More** for starting coordinates, stagger and a background image (pick one from the vault, or drop one from your computer). A new map starts on Overland; pick Blank to paint by hand. diff --git a/src/hex-map/mapTablesForm.ts b/src/hex-map/mapTablesForm.ts new file mode 100644 index 00000000..d9980870 --- /dev/null +++ b/src/hex-map/mapTablesForm.ts @@ -0,0 +1,103 @@ +/** + * Map properties: what happens on arrival (GM4) and the generator tables + * (T11), for the open map and everything under it. One select per line, + * so a change is two clicks ("easy, modular and as low-click as + * possible"). + */ + +import type HexmakerPlugin from "../HexmakerPlugin"; +import type { MapData } from "../types"; +import { FileLinkSuggestModal } from "./FileLinkSuggestModal"; +import { contentFolder } from "../notePickers"; +import { hasFeature } from "../featureLevel"; +import { ENGINE_ROLES, type RoleId } from "../worldgen/tableRoles"; +import { fittingRoleTables } from "../worldgen/tableSources"; +import { SPACE_TABLES_FOLDER } from "../space/spaceTables"; +import { ARRIVAL_MODE_TEXT, ARRIVAL_MODE_WORDS, parseArrivalMode, type ArrivalMode } from "../arrival/arrival"; + +const noteName = (path: string) => path.replace(/\.md$/i, "").replace(/^.*\//, ""); +const withMd = (p: string) => (/\.md$/i.test(p) ? p : `${p}.md`); + +/** "Arriving somewhere new": make places, or not; blank follows the map above. */ +export function renderArrivalSetting(el: HTMLElement, plugin: HexmakerPlugin, map: MapData, rerender: () => void): void { + el.createEl("h4", { text: "Arriving somewhere new" }); + el.createDiv({ + cls: "duckmage-map-origin-desc", + text: "Going into a hex that has no map yet (Go there in the hex menu, or Ctrl+click). Making the place works in Play too; the new place can be rerolled until you lock it. Maps under this one do the same unless they set their own.", + }); + const row = el.createDiv({ cls: "duckmage-region-row" }); + const select = row.createEl("select", { attr: { "aria-label": "Arriving somewhere new" } }); + const parent = plugin.parentOf(map.name)?.map; + const inherited = parent ? plugin.arrivalModeFor(parent) : { mode: "off" as ArrivalMode }; + select.createEl("option", { + value: "", + text: parent && inherited.from ? `Same as ${plugin.mapLabel(inherited.from)} (${ARRIVAL_MODE_TEXT[inherited.mode].toLowerCase()})` : `${ARRIVAL_MODE_TEXT.off} (default)`, + }); + for (const m of ["make", "off"] as ArrivalMode[]) select.createEl("option", { value: m, text: ARRIVAL_MODE_TEXT[m] }); + select.value = parseArrivalMode(map.arrivalMode) ?? ""; + select.addEventListener("change", () => { + const v = select.value as ArrivalMode | ""; + if (v) map.arrivalMode = ARRIVAL_MODE_WORDS[v]; + else delete map.arrivalMode; + void plugin.saveSettings().then(rerender); + }); +} + +/** + * "Generator tables": the table each generator role rolls on for this map + * and the maps under it. Blank follows the map above, else the World types + * picked when generating. Shown on space maps, or wherever a table is set. + */ +export function renderRoleTables(el: HTMLElement, plugin: HexmakerPlugin, map: MapData, rerender: () => void): void { + const own = map.roleTables ?? {}; + const inherited = plugin.roleTablesFor(map.name); + const anySet = Object.keys(inherited).length > 0; + if (!anySet && (!plugin.isSpaceMap(map.name) || !hasFeature(plugin.settings, "generators"))) return; + + el.createEl("h4", { text: "Generator tables" }); + el.createDiv({ + cls: "duckmage-map-origin-desc", + text: "The random tables Star scatter and Orbits roll on, for this map and every map made under it. Unset: the map above's, else the World types picked when generating.", + }); + const tablesFolder = contentFolder(plugin.settings, "tablesFolder"); + const all = plugin.tableNotes.tables(); + const save = (role: RoleId, path: string | undefined) => { + const next = { ...(map.roleTables ?? {}) }; + if (path) next[role] = withMd(path); + else delete next[role]; + if (Object.keys(next).length) map.roleTables = next; + else delete map.roleTables; + void plugin.saveSettings().then(rerender); + }; + for (const role of ENGINE_ROLES) { + const row = el.createDiv({ cls: "duckmage-role-table-row" }); + row.createSpan({ text: role.name, attr: { title: role.help } }); + const select = row.createEl("select", { attr: { "aria-label": `${role.name} table` } }); + const above = map.parent ? plugin.roleTablesFor(map.parent.map)[role.id] : undefined; + select.createEl("option", { + value: "", + text: above ? `${noteName(above.link)} (from ${plugin.mapLabel(above.from)})` : "World types (as picked)", + }); + const choices = fittingRoleTables(all, role.id, `${tablesFolder}/${SPACE_TABLES_FOLDER}`); + const current = own[role.id]; + if (current && !choices.includes(withMd(current))) choices.unshift(withMd(current)); + for (const p of choices) { + // Name plus its set ("Unexplored sector · Default space"). + const rel = p.startsWith(`${tablesFolder}/`) ? p.slice(tablesFolder.length + 1) : p; + const parts = rel.replace(/\.md$/i, "").split("/"); + const set = parts[0] === SPACE_TABLES_FOLDER && parts.length > 2 ? ` · ${parts[1]}` : ""; + select.createEl("option", { value: p, text: `${noteName(p)}${set}` }); + } + select.createEl("option", { value: "__other", text: "Other table…" }); + select.value = current ? withMd(current) : ""; + select.addEventListener("change", () => { + if (select.value !== "__other") { save(role.id, select.value || undefined); return; } + select.value = current ? withMd(current) : ""; + new FileLinkSuggestModal(plugin.app, plugin, (file) => save(role.id, file.path), tablesFolder, ["md"]).open(); + }); + } + if (plugin.worldTypeStore.list().some((t) => !plugin.worldTypeStore.isConverted(t.name))) { + const btn = el.createEl("button", { text: "Convert world types to tables…", attr: { title: "Write each world types table as random tables under the tables folder (backed up first; the old notes are kept)" } }); + btn.addEventListener("click", () => void plugin.convertWorldTypes().then(rerender)); + } +} diff --git a/src/hex-map/newChildMap.ts b/src/hex-map/newChildMap.ts index a9642ab2..ae11ee48 100644 --- a/src/hex-map/newChildMap.ts +++ b/src/hex-map/newChildMap.ts @@ -53,6 +53,13 @@ export function startNewChildMap(host: NewChildMapHost, parentMap: string, x: nu } export function startNewLocation(host: NewChildMapHost, parentMap: string, x: number, y: number): void { + // An unknown hex (an On arrival table) is rolled first, so the form + // starts from what turned out to be there (T5). + const rolled = host.plugin.arrival.resolveHex(parentMap, x, y, "new-child-map"); + if (rolled) { + void host.plugin.saveSettings(); + new Notice(`Rolled on arrival: ${rolled.chain}.`); + } new NewMapSetupModal(host.app, host.plugin, ({ name }) => { void host.plugin.linkSubmap(parentMap, x, y, name).then(() => host.onCreated(name, "location")); }, { map: parentMap, x, y }).open(); diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index 4488780f..3e6d1fd3 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -4,6 +4,7 @@ import { formatAnchors, formatAnchor, parseAnchors } from "../paths/anchorText"; import { legacyChainsToPaths } from "../paths/legacy"; import { pathNameKey, uniquePathName } from "../paths/names"; import { HEX_MAP_KEY, isMapNoteLink, LEGACY_HEX_MAP_KEY } from "../noteFormats"; +import { ENGINE_ROLES } from "../worldgen/tableRoles"; /** * Map notes: one note per map ("hexes//_.md") holding the map's @@ -99,6 +100,13 @@ export interface HexData { /** Location maps opened from this hex (towns, dungeons…), in the user's order. */ locations?: string[]; locked?: boolean; + /** + * A table to roll when someone first arrives here (the optional "On + * arrival" column, plan-tables-everywhere §2.6): the table's link target + * as written (`world/tables/space/…/Mainworlds`, or a plain name). + * Cleared once rolled. + */ + onArrival?: string; /** * The hex's biome (an id or name of a biome note), on an overworld: set * when its terrain alone can't say it (a user's biome paints a terrain @@ -382,6 +390,11 @@ const SIMPLE_KEYS: [keyof MapSettings, string, Kind, string[]?][] = [ // "region" or "location": this map's role under its parent hex. ["submapKind", "submap-kind", "str"], ["regionSeed", "region-seed", "num"], + // Places made on arrival (plan-tables-everywhere phase 4). + ["seed", "seed", "num"], + ["arrivalMode", "on-arrival", "str"], + ["arrival", "arrival", "str"], + ["arrivalRerolls", "arrival-rerolls", "num"], ["overworldView", "overworld-view", "str"], ["showMinimap", "show-minimap", "bool"], // Work mode: play, build or god (src/workMode.ts). @@ -430,6 +443,8 @@ const REGION_KEYS = { stagger: "region-stagger", generator: "region-generator", } as const; +/** Generator tables per role (T11): `sector-hexes-table: "[[…]]"`, one key per engine role. */ +const ROLE_TABLE_KEYS: Record = Object.fromEntries(ENGINE_ROLES.map((r) => [r.id, `${r.id}-table`])); /** Prefix for MapData fields this build doesn't know (`hexmaker-origin-x`). */ const OTHER_PREFIX = "hexmaker-"; /** Format 1's one-line JSON catch-all, still read. */ @@ -442,6 +457,7 @@ function ownsKey(key: string): boolean { } const OWNED_KEYS = new Set([ MAP_NOTE_MARKER, ...SIZE_KEYS, ...PARENT_KEYS, ...WORLD_KEYS, ...BG_KEYS, BIOME_KEY, BIOME_FROM_KEY, ...Object.values(REGION_KEYS), + ...Object.values(ROLE_TABLE_KEYS), ...SIMPLE_KEYS.flatMap(([, k, , old]) => [k, ...(old ?? [])]), ]); @@ -451,6 +467,11 @@ const SKIP_FIELDS = new Set(["name", "pathChains", "paths", "savedViewport", "gr const KNOWN_FIELDS = new Set([ ...SIMPLE_KEYS.map(([f]) => f as string), "parent", "world", "backgroundImage", ]); +/** Whether a roleTables value is one the readable keys can hold (else it goes to a hexmaker- key). */ +function roleTablesReadable(v: unknown): v is Record { + return !!v && typeof v === "object" && !Array.isArray(v) + && Object.entries(v as Record).every(([k, x]) => k in ROLE_TABLE_KEYS && typeof x === "string" && x !== ""); +} /** * Optional map settings a map note owns: a key deleted by hand resets that @@ -458,7 +479,7 @@ const KNOWN_FIELDS = new Set([ */ export const RESETTABLE_FIELDS: readonly string[] = [ ...SIMPLE_KEYS.map(([f]) => f as string).filter((f) => f !== "paletteName"), - "parent", "world", "backgroundImage", "biome", "regions", + "parent", "world", "backgroundImage", "biome", "regions", "roleTables", ]; const FLOWER_CELLS = [7, 19, 37, 61, 91]; @@ -809,6 +830,16 @@ function readFrontmatter(src: string, opts: MapNoteReadOptions): FmRead { } } + // sector-hexes-table: "[[Unexplored sector]]" … (generator tables per role, T11) + const roleTables: Record = {}; + for (const [role, key] of Object.entries(ROLE_TABLE_KEYS)) { + const t = textOf(key); + const link = t ? noteLink(t, ".md") : undefined; + if (link) roleTables[role] = link; + else if (has(key) && values.get(key)!.t !== "s") bad(key, "roleTables", "should be a link to a table note"); + } + if (Object.keys(roleTables).length) out.roleTables = roleTables; + // fields this build doesn't know: hexmaker- keys, then format 1's JSON catch-all for (const [k, node] of values) { if (!k.startsWith(OTHER_PREFIX) || k === MAP_NOTE_MARKER || k === LEGACY_EXTRA_KEY) continue; @@ -881,7 +912,16 @@ function frontmatterLines(settings: Partial, keep: Set = ne put(REGION_KEYS.stagger, reg.stagger); put(REGION_KEYS.generator, reg.generator); } + const roles = s.roleTables; + const rolesReadable = roleTablesReadable(roles); + if (rolesReadable) { + for (const r of ENGINE_ROLES) { + const v = roles[r.id]; + if (v && !keep.has(ROLE_TABLE_KEYS[r.id])) lines.push(`${ROLE_TABLE_KEYS[r.id]}: ${linkTo(v.replace(/\.md$/i, ""))}`); + } + } const readable = new Set(KNOWN_FIELDS); + if (rolesReadable) readable.add("roleTables"); if (regionsReadable) readable.add("regions"); if (!parentReadable) readable.delete("parent"); if (!worldReadable) readable.delete("world"); @@ -898,11 +938,12 @@ const FRONTMATTER = /^---[ \t]*\n(?:([\s\S]*?)\n)?---[ \t]*(\n|$)/; // ── tables ─────────────────────────────────────────────────────────────── -const HEX_HEADERS = ["Hex", "Name", "Terrain", "Biome", "Icon", "GM icons", "Region", "Region map", "Locations", "Locked"]; +const HEX_HEADERS = ["Hex", "Name", "Terrain", "Biome", "Icon", "GM icons", "Region", "Region map", "Locations", "Locked", "On arrival"]; /** Known columns written only when the table has them or some row needs them (column → does a row need it). */ const OPTIONAL_HEX_HEADERS: Record boolean> = { "region map": (h) => !!h.regionMap, biome: (h) => !!h.biome, + "on arrival": (h) => !!h.onArrival, }; /** `## Paths` (format 5): what each path is. Route is derived. */ const PATH_HEADERS = ["Path", "Type", "Route", "Notes"]; @@ -926,6 +967,7 @@ const HEX_COL_ALIASES: Record = { submap: "locations", submaps: "locations", locked: "locked", biome: "biome", + onarrival: "on arrival", arrival: "on arrival", rollonarrival: "on arrival", }; const PATH_COL_ALIASES: Record = { path: "path", paths: "path", pathname: "path", @@ -1045,7 +1087,7 @@ export function compareHexKeys(a: string, b: string): number { /** Anything besides terrain set on a hex. */ function hasNonTerrainData(h: HexData): boolean { - return !!(h.name || h.icon || (h.gmIcons && h.gmIcons.length) || h.region || h.regionMap || (h.locations && h.locations.length) || h.locked || h.biome + return !!(h.name || h.icon || (h.gmIcons && h.gmIcons.length) || h.region || h.regionMap || (h.locations && h.locations.length) || h.locked || h.biome || h.onArrival || (h.extra && Object.values(h.extra).some(Boolean))); } @@ -1119,6 +1161,7 @@ const HEX_CELL: Record string | undefined> = "region map": (_k, h) => (h.regionMap ? mapLinkText(h.regionMap) : undefined), locations: (_k, h) => h.locations?.map(mapLinkText).join(", "), locked: (_k, h) => (h.locked ? "yes" : ""), + "on arrival": (_k, h) => (h.onArrival ? `[[${h.onArrival.replace(/\.md$/i, "")}]]` : undefined), }; function hexTable(hexes: Map, baseTerrain?: string, existing?: string[], keptRows: string[] = []): string { @@ -1279,7 +1322,7 @@ function readHexTable(lines: string[], t: Table | null): TableRead t.cols.indexOf(name); - const ci = { hex: col("hex"), name: col("name"), terrain: col("terrain"), icon: col("icon"), gm: col("gm icons"), region: col("region"), regionMap: col("region map"), locked: col("locked"), biome: col("biome") }; + const ci = { hex: col("hex"), name: col("name"), terrain: col("terrain"), icon: col("icon"), gm: col("gm icons"), region: col("region"), regionMap: col("region map"), locked: col("locked"), biome: col("biome"), onArrival: col("on arrival") }; // Locations may sit in more than one column (a Submap column next to a // Locations one): all are read, in column order. const locCols = t.cols.flatMap((c, i) => (c === "locations" ? [i] : [])); @@ -1316,6 +1359,8 @@ function readHexTable(lines: string[], t: Table | null): TableRead m !== h.regionMap && a.indexOf(m) === i); if (locs.length) h.locations = locs; if (TRUE_WORDS.test(lockedRaw)) h.locked = true; + const arrival = get(ci.onArrival); + if (arrival) h.onArrival = unlink(arrival) || arrival; const extra = readExtra(c, unknown); if (extra) h.extra = extra; out.set(key, h); diff --git a/src/random-tables/TableNotes.ts b/src/random-tables/TableNotes.ts new file mode 100644 index 00000000..79da1893 --- /dev/null +++ b/src/random-tables/TableNotes.ts @@ -0,0 +1,99 @@ +/** + * The text of every note under the tables folder, kept in memory so the + * table resolver (resolve.ts, which is synchronous) can roll on vault + * tables: generators and their previews, and arrival rolls. Read once at + * start, then kept up to date from vault events. Never writes. + */ + +import { TFile, type TAbstractFile } from "obsidian"; +import type HexmakerPlugin from "../HexmakerPlugin"; +import { contentFolder } from "../notePickers"; +import { notesLookup, type TableLookup } from "./resolve"; +import { parseRandomTable, type RandomTable } from "./randomTable"; + +export class TableNotes { + private contents = new Map(); + private cached: TableLookup | null = null; + private ready = false; + + constructor(private plugin: HexmakerPlugin) {} + + static register(plugin: HexmakerPlugin): TableNotes { + const notes = new TableNotes(plugin); + const { vault } = plugin.app; + plugin.registerEvent(vault.on("modify", (f) => void notes.read(f))); + plugin.registerEvent(vault.on("create", (f) => void notes.read(f))); + plugin.registerEvent(vault.on("delete", (f) => notes.drop(f.path))); + plugin.registerEvent(vault.on("rename", (f, old) => { notes.drop(old); void notes.read(f); })); + return notes; + } + + private folder(): string { + return contentFolder(this.plugin.settings, "tablesFolder"); + } + + private inScope(path: string): boolean { + const folder = this.folder(); + return path.endsWith(".md") && (!folder || path.startsWith(`${folder}/`)); + } + + /** Read every note under the tables folder (again: the folder setting changed). */ + async init(): Promise { + this.contents.clear(); + for (const f of this.plugin.app.vault.getMarkdownFiles()) { + if (this.inScope(f.path)) this.contents.set(f.path, await this.plugin.app.vault.cachedRead(f)); + } + this.cached = null; + this.ready = true; + } + + isReady(): boolean { + return this.ready; + } + + private async read(f: TAbstractFile): Promise { + if (!(f instanceof TFile) || !this.inScope(f.path)) return; + this.put(f.path, await this.plugin.app.vault.cachedRead(f)); + } + + /** Take a note's text now (the plugin just wrote it). */ + put(path: string, content: string): void { + if (this.contents.get(path) === content) return; + this.contents.set(path, content); + this.cached = null; + } + + private drop(path: string): void { + if (this.contents.delete(path)) this.cached = null; + } + + /** The tables as a lookup for the resolver (links by path or note name). */ + lookup(): TableLookup { + if (!this.cached) this.cached = notesLookup(Object.fromEntries(this.contents)); + return this.cached; + } + + /** Every note that reads as a table, with its table (for pickers). */ + tables(): { path: string; table: RandomTable }[] { + const out: { path: string; table: RandomTable }[] = []; + const lookup = this.lookup(); + for (const path of [...this.contents.keys()].sort()) { + const name = path.slice(path.lastIndexOf("/") + 1); + if (name.startsWith("_")) continue; + const t = lookup.table(path); + if (t) out.push({ path, table: t.table }); + } + return out; + } + + /** A note's text, if it's under the tables folder. */ + text(path: string): string | undefined { + return this.contents.get(path); + } + + /** Parse a note's table (undefined when it isn't one we hold). */ + table(path: string): RandomTable | undefined { + const c = this.contents.get(path); + return c === undefined ? undefined : parseRandomTable(c); + } +} diff --git a/src/space/WorldTypeStore.ts b/src/space/WorldTypeStore.ts index beb7cc71..1cb68e6b 100644 --- a/src/space/WorldTypeStore.ts +++ b/src/space/WorldTypeStore.ts @@ -13,7 +13,12 @@ * is given the shipped Stars and Sector features tables once, when read; * one from before the Mainworld column (format 1 or 2) the shipped * rows' mainworlds (backed up first). - * - source(): a table as the space generators' role tables (SP1). + * - sourceFor(): a table as the space generators' role tables (SP1). A + * converted note (its `## Tables` list, space/spaceTables.ts) gives the + * table notes it links; a map's own Tables (inherited down the map tree) + * win over both (worldgen/tableSources.ts). + * - convertAll(): the one-time Convert to tables (backed up first; the + * notes are kept and link out to the new tables). Never runs by itself. * - Every change is told to onChange listeners. */ @@ -46,6 +51,10 @@ import { import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "./worldTypePresets"; import { chosenWorldTypes, defaultWorldTypesName, worldTypesSource } from "./worldTypesSource"; import type { TableSource } from "../worldgen/tableRoles"; +import { layeredSource, notesTableSource } from "../worldgen/tableSources"; +import { convertWorldTypes, isConverted, markConverted, readRoleTables } from "./spaceTables"; +import { contentFolder } from "../notePickers"; +import { PALETTE_PRESETS } from "../palettes/presets"; interface Entry { path: string; @@ -166,11 +175,85 @@ export class WorldTypeStore { * (SP1), for a palette. `source` undefined: no table (None, or none at * all), so equal odds; `missing`: the picked table isn't there. */ - sourceFor(value: string | undefined, palette: readonly (string | { name: string })[]): { source?: TableSource; missing?: string } { + sourceFor(value: string | undefined, palette: readonly (string | { name: string })[], mapName?: string): { source?: TableSource; missing?: string } { const name = chosenWorldTypes(value, this.list().map((t) => t.name), this.defaultName()); - if (!name) return {}; - const t = this.get(name); - return t ? { source: worldTypesSource(t, palette) } : { missing: name }; + const terrains = palette.map((t) => (typeof t === "string" ? t : t.name)); + const notes = this.plugin.tableNotes.lookup(); + let base: TableSource | undefined; + let missing: string | undefined; + if (name) { + const e = this.find(name); + if (!e) missing = name; + else { + const roles = readRoleTables(this.lastContent.get(e.path) ?? ""); + base = Object.keys(roles).length ? notesTableSource(roles, notes, terrains, `Tables: ${e.name}`) : worldTypesSource(tableOf(e), palette); + } + } + // The map's own Tables (and its ancestors') win over the setup's. + const own = mapName ? this.plugin.roleTablesFor(mapName) : {}; + const overrides = Object.fromEntries(Object.entries(own).map(([r, p]) => [r, p.link])); + const source = layeredSource(base, overrides, notes, terrains); + return { ...(source ? { source } : {}), ...(missing ? { missing } : {}) }; + } + + /** Whether a table's note was converted to tables (it has a `## Tables` list). */ + isConverted(name: string): boolean { + const e = this.find(name); + return !!e && isConverted(this.lastContent.get(e.path) ?? ""); + } + + /** + * Convert every World types note not yet converted into table notes + * under `{tables}/space//` (T1, T2). The notes are backed up + * first and kept; each gets a `## Tables` list linking its tables. A + * table note that already exists is never overwritten (it's listed in + * `kept`). Running it again changes nothing. + */ + async convertAll(): Promise<{ converted: string[]; written: string[]; kept: string[] }> { + const out = { converted: [] as string[], written: [] as string[], kept: [] as string[] }; + await this.queue; // hand edits read first + await this.enqueue(async () => { + const todo = this.sorted().filter((e) => !isConverted(this.lastContent.get(e.path) ?? "")); + if (!todo.length) return; + const vault = this.plugin.app.vault; + const notes: Record = {}; + for (const e of todo) { + const f = vault.getAbstractFileByPath(e.path); + if (f instanceof TFile) notes[e.path] = await vault.read(f); + } + await this.backup("convert", notes); + const tablesFolder = contentFolder(this.plugin.settings, "tablesFolder"); + const shownAs = this.starSystemTerrain(); + for (const e of todo) { + const f = vault.getAbstractFileByPath(e.path); + const content = notes[e.path]; + if (!(f instanceof TFile) || content === undefined) continue; + const set = convertWorldTypes(tableOf(e), { tablesFolder, shownAs, unreadable: parseWorldTypes(content).unreadable }); + for (const file of set.files) { + if (vault.getAbstractFileByPath(file.path)) { out.kept.push(file.path); continue; } + await this.ensureFolder(file.path.slice(0, file.path.lastIndexOf("/"))); + await vault.create(file.path, file.content); + this.plugin.tableNotes.put(file.path, file.content); + out.written.push(file.path); + } + const next = markConverted(content, set); + if (next !== content) await vault.modify(f, next); + this.take(f.path, next); + out.converted.push(e.name); + } + this.publish(); + }); + return out; + } + + /** A terrain of type star-system (what a somewhat known hex shows), found by type: installed palettes first, then the shipped ones. */ + private starSystemTerrain(): string | undefined { + const pals = [...this.plugin.settings.terrainPalettes, ...PALETTE_PRESETS]; + for (const p of pals) { + const t = p.terrains.find((x) => x.type === "star-system"); + if (t) return t.name; + } + return undefined; } hasDefault(name: string): boolean { diff --git a/src/space/WorldTypesModal.ts b/src/space/WorldTypesModal.ts index c75c845f..b25552a1 100644 --- a/src/space/WorldTypesModal.ts +++ b/src/space/WorldTypesModal.ts @@ -274,6 +274,13 @@ export class WorldTypesModal extends HexmakerModal { text: `What the space generators place and how often. Each table is a note in ${store.folder()}.`, }); if (lock) contentEl.createEl("p", { cls: "duckmage-locked-hint", text: lock }); + // Converted (phase 3): the generators roll on the tables the note links now. + if (store.isConverted(this.tableName)) { + contentEl.createEl("p", { + cls: "duckmage-locked-hint", + text: "This table was converted to random tables: the generators roll on the tables its note links; open the note to see them. Changes here only change the old copy.", + }); + } this.problemsEl = contentEl.createDiv(); this.renderProblems(); diff --git a/src/space/spaceTables.ts b/src/space/spaceTables.ts new file mode 100644 index 00000000..8cd5d843 --- /dev/null +++ b/src/space/spaceTables.ts @@ -0,0 +1,388 @@ +/** + * The space set as random tables (plan-tables-everywhere §4, phase 3). + * + * A World types note converts, once, into ordinary random table notes in + * a tidy tree under the tables folder (T1): + * + * {tables}/space// + * Sector/Charted sector.md what a star system hex is (Star scatter) + * Sector/Unexplored sector.md the same, with some hexes left for arrival + * Sector/Mainworlds.md a system's mainworld, with its map setup + * Sector/Uncharted.md what an uncharted hex turns out to be + * System/Stars.md the star at a system's centre (Orbits) + * System/Inner orbits.md a body per orbit, by zone + * System/Habitable orbits.md + * System/Outer orbits.md + * + * The World types note is kept (T2). It gets a `## Tables` section that + * links each generator role to its table — that list is what the + * generators read from then on, so pointing Sector hexes at Unexplored + * sector is one edit — and the tables embedded below it, so they can be + * rolled from the note. + * + * The converted tables give the same odds as the note did (T4: different + * draws). Rows keep their setup columns (Mainworld, Size, Generator, + * Options, Palette, Base) as row attributes, and their limits as When. + * Weights are scaled to whole numbers where that keeps the odds exact. + * + * Nothing is special-cased by name: every set is built from the note's + * own rows. The Unexplored and Uncharted tables are built the same way + * for every note (their shares are just weights; edit them freely). + * + * Pure: no Obsidian imports. + */ + +import { rangeCellTexts, type RowType } from "../random-tables/randomTable"; +import { formatWhen } from "../random-tables/tableConditions"; +import { ENGINE_ROLES, type RoleId } from "../worldgen/tableRoles"; +import { attrsOf, conditionsOf } from "./worldTypesSource"; +import { ORBIT_ZONES, type OrbitZone, type WorldTypeRow, type WorldTypeTable } from "./worldTypes"; + +/** The subfolder of the tables folder that holds space sets. */ +export const SPACE_TABLES_FOLDER = "space"; + +/** The folder a set named `name` converts into. */ +export function spaceSetFolder(tablesFolder: string, name: string): string { + const base = tablesFolder.replace(/^\/+|\/+$/g, ""); + return `${base ? `${base}/` : ""}${SPACE_TABLES_FOLDER}/${name}`; +} + +/** A table to write. */ +export interface TableSpec { + title: string; + /** Plain text under the title. */ + description: string; + rows?: RowType; + terrainTypes?: readonly string[]; + /** Extra columns after Weight, in order (only those a row fills are written). */ + columns: readonly string[]; + entries: { result: string; link?: string; weight: number; cells?: Record }[]; +} + +const STANDARD_DICE = [2, 3, 4, 6, 8, 10, 12, 20, 100]; +const SCALES = [1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 25, 30, 40, 50, 60, 75, 100, 120, 150, 200, 300, 600, 1000]; +const near = (a: number, b: number) => Math.abs(a - b) < 1e-9; + +/** The smallest multiplier that makes every weight whole (1 when none does). */ +export function wholeScale(weights: readonly number[]): number { + return SCALES.find((n) => weights.every((w) => near(w * n, Math.round(w * n)))) ?? 1; +} + +const fmtWeight = (w: number) => (near(w, Math.round(w)) ? String(Math.round(w)) : String(Math.round(w * 1e6) / 1e6)); +const esc = (s: string) => s.replace(/\r?\n/g, " ").replace(/(? e.weight)); + const entries = spec.entries.map((e) => ({ ...e, weight: e.weight * scale })); + const total = entries.reduce((a, e) => a + e.weight, 0); + const dice = near(total, Math.round(total)) && STANDARD_DICE.includes(Math.round(total)) ? Math.round(total) : 0; + const ranges = dice ? rangeCellTexts(dice, entries.map((e) => ({ result: e.result, weight: e.weight })), "regenerate") : []; + const cols = spec.columns.filter((c) => entries.some((e) => e.cells?.[c])); + const head = [...(dice ? [`d${dice}`] : []), "Result", "Weight", ...cols]; + const lines = [ + "---", + `dice: ${dice}`, + ...(spec.rows ? [`rows: ${spec.rows}`] : []), + ...(spec.terrainTypes?.length ? [`terrain-type: ${spec.terrainTypes.join(", ")}`] : []), + "---", + "", + "```duckmage-roller", + "```", + "", + `# ${spec.title}`, + "", + spec.description, + "", + `| ${head.join(" | ")} |`, + `| ${head.map((h) => (h === "Weight" ? "---:" : "---")).join(" | ")} |`, + ...entries.map((e, i) => { + const cells = [ + ...(dice ? [ranges[i] || "—"] : []), + e.link ? linkCell(e.link) : esc(e.result), + fmtWeight(e.weight), + ...cols.map((c) => esc(e.cells?.[c] ?? "")), + ]; + return `| ${cells.join(" | ")} |`; + }), + "", + ]; + return lines.join("\n"); +} + +// ── converting a World types note ──────────────────────────────────────── + +export interface SpaceSet { + /** The set's folder. */ + folder: string; + /** Notes to write (path → text). Existing notes are never overwritten. */ + files: { path: string; content: string }[]; + /** Each role's table (vault path with .md). */ + roles: Partial>; +} + +export interface ConvertOptions { + /** The tables folder (setting). */ + tablesFolder: string; + /** + * What a "somewhat known" hex of the Unexplored sector shows until + * someone arrives: a terrain of the sector palette whose type is + * star-system (found by type by the caller). Blank: the background. + */ + shownAs?: string; + /** Rows of the note that couldn't be read, as written (copied into the set's notes). */ + unreadable?: readonly string[]; +} + +const SETUP_COLUMNS = ["When", "Mainworld", "Size", "Generator", "Options", "Palette", "Base", "Notes"] as const; +const SECTOR_TYPES = ["world", "gas-giant", "asteroids", "station", "starport", "jump-point", "anomaly"]; +const BODY_TYPES = ["world", "gas-giant", "asteroids"]; +const ZONE_FILE: Record = { inner: "Inner orbits", habitable: "Habitable orbits", outer: "Outer orbits" }; +const ZONE_ROLE: Record = { inner: "inner-orbits", habitable: "habitable-orbits", outer: "outer-orbits" }; + +function worldEntry(r: WorldTypeRow): TableSpec["entries"][number] { + const cells: Record = { ...attrsOf(r) }; + const when = conditionsOf(r); + if (when.length) cells.When = formatWhen(when); + return { result: r.world.trim(), weight: r.weight ?? 1, cells }; +} + +const lc = (s: string) => s.trim().toLowerCase(); + +/** + * A World types table as a space set: the notes to write and each role's + * table. The same odds as the note (worldTypesSource reads it the same + * way). Pure: the caller writes the files. + */ +export function convertWorldTypes(table: WorldTypeTable, opts: ConvertOptions): SpaceSet { + const folder = spaceSetFolder(opts.tablesFolder, table.name); + const path = (rel: string) => `${folder}/${rel}.md`; + const P = { + charted: path("Sector/Charted sector"), + unexplored: path("Sector/Unexplored sector"), + mainworlds: path("Sector/Mainworlds"), + uncharted: path("Sector/Uncharted"), + stars: path("System/Stars"), + }; + const files: SpaceSet["files"] = []; + const roles: SpaceSet["roles"] = {}; + const unreadable = opts.unreadable?.length + ? `\n\nRows of the World types note that couldn't be read, copied as written:\n\n${opts.unreadable.map((l) => ` ${l}`).join("\n")}` + : ""; + + // Mainworlds: the rows for a sector (Map sector or blank). + const sectorRows = table.rows.filter((r) => r.map !== "system" && r.world.trim()); + files.push({ + path: P.mainworlds, + content: tableNoteMarkdown({ + title: "Mainworlds", + description: `A star system's mainworld, and what its own map is made with. Converted from the ${table.name} world types.${unreadable}`, + rows: "terrain", + terrainTypes: BODY_TYPES, + columns: SETUP_COLUMNS, + entries: sectorRows.map(worldEntry), + }), + }); + + // Sector features by their chance, then the systems (as worldTypesSource). + const features: { name: string; weight: number }[] = []; + let left = 1; + for (const f of table.features ?? []) { + const name = f.feature.trim(); + if (!name || !(f.chance > 0)) continue; + const chance = Math.max(0, Math.min(f.chance, left)); + left -= chance; + const same = features.find((x) => lc(x.name) === lc(name)); + if (same) same.weight += chance; + else if (chance > 0) features.push({ name, weight: chance }); + } + const rest = left > 1e-12 ? left : 0; + const featureEntries = features.map((f) => ({ result: f.name, weight: f.weight, cells: { Roll: "now" } })); + + files.push({ + path: P.charted, + content: tableNoteMarkdown({ + title: "Charted sector", + description: "What each star system hex of a sector is: a special hex, or a system typed by its mainworld. Everything is known from the start.", + rows: "terrain", + terrainTypes: SECTOR_TYPES, + columns: [], + entries: [ + ...features.map((f) => ({ result: f.name, weight: f.weight })), + ...(rest ? [{ result: "Mainworlds", link: P.mainworlds, weight: rest }] : []), + ], + }), + }); + roles["sector-hexes"] = P.charted; + + // Unexplored: the systems split charted / somewhat known / uncharted, 2 : 1 : 1. + const shown = opts.shownAs?.trim() ?? ""; + files.push({ + path: P.unexplored, + content: tableNoteMarkdown({ + title: "Unexplored sector", + description: "Like Charted sector, but only half the systems are known. A somewhat known hex shows a system whose world isn't known yet; an uncharted one shows nothing. Both are rolled the first time someone goes there (Roll: on arrival). Change the weights to make the sector more or less known.", + rows: "terrain", + terrainTypes: SECTOR_TYPES, + columns: ["Roll", "Shown as", "Notes"], + entries: [ + ...featureEntries, + ...(rest ? [ + { result: "Mainworlds", link: P.mainworlds, weight: rest / 2, cells: { Roll: "now", Notes: "charted" } }, + { result: "Mainworlds", link: P.mainworlds, weight: rest / 4, cells: { Roll: "on arrival", ...(shown ? { "Shown as": shown } : {}), Notes: "somewhat known: a system is there, its world isn't known" } }, + { result: "Uncharted", link: P.uncharted, weight: rest / 4, cells: { Roll: "on arrival", Notes: "uncharted" } }, + ] : []), + ], + }), + }); + + files.push({ + path: P.uncharted, + content: tableNoteMarkdown({ + title: "Uncharted", + description: "What an uncharted hex turns out to be when someone gets there.", + rows: "terrain", + terrainTypes: SECTOR_TYPES, + columns: ["Notes"], + entries: [ + { result: "Mainworlds", link: P.mainworlds, weight: 6, cells: { Notes: "an ordinary system after all" } }, + ...features.map((f) => ({ result: f.name, weight: 1 })), + { result: "(nothing)", weight: 2, cells: { Notes: "empty space" } }, + ], + }), + }); + + if (table.stars?.length) { + files.push({ + path: P.stars, + content: tableNoteMarkdown({ + title: "Stars", + description: "The star at the centre of a system, when Orbits' Star option is Random.", + rows: "terrain", + terrainTypes: ["star"], + columns: ["Notes"], + entries: table.stars.filter((s) => s.star.trim()).map((s) => ({ result: s.star.trim(), weight: s.weight ?? 1, ...(s.notes ? { cells: { Notes: s.notes } } : {}) })), + }), + }); + roles.star = P.stars; + } + + // Orbits by zone: the rows for a system (Map system or blank) whose Orbit allows the zone. + const systemRows = table.rows.filter((r) => r.map !== "sector" && r.world.trim()); + for (const z of ORBIT_ZONES) { + const p = path(`System/${ZONE_FILE[z]}`); + files.push({ + path: p, + content: tableNoteMarkdown({ + title: ZONE_FILE[z], + description: `The body on each orbit in the ${z} zone of a system, and what its own map is made with.`, + rows: "terrain", + terrainTypes: BODY_TYPES, + columns: SETUP_COLUMNS, + entries: systemRows.filter((r) => !r.zones?.length || r.zones.includes(z)).map(worldEntry), + }), + }); + roles[ZONE_ROLE[z]] = p; + } + return { folder, files, roles }; +} + +// ── the role list in a note (`## Tables`) ─────────────────────────────── + +const TABLES_HEADING = /^##\s+tables\s*$/i; +const roleByName = new Map(ENGINE_ROLES.flatMap((r) => [[lc(r.name), r.id], [r.id, r.id]] as [string, RoleId][])); + +const splitCells = (line: string): string[] => { + const out: string[] = []; + let cur = ""; + let depth = 0; + const s = line.trim().replace(/^\|/, "").replace(/(?> { + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const out: Partial> = {}; + const start = lines.findIndex((l) => TABLES_HEADING.test(l.trim())); + if (start < 0) return out; + let i = start + 1; + while (i < lines.length && !lines[i].trim().startsWith("|") && !/^#{1,2}\s/.test(lines[i])) i++; + if (i >= lines.length || !lines[i].trim().startsWith("|")) return out; + const head = splitCells(lines[i]).map(lc); + const rc = head.indexOf("role"), tc = head.indexOf("table"); + if (rc < 0 || tc < 0) return out; + for (let j = i + 1; j < lines.length && lines[j].trim().startsWith("|"); j++) { + const c = splitCells(lines[j]); + const role = roleByName.get(lc(c[rc] ?? "")); + const target = linkTarget(c[tc] ?? ""); + if (role && target && !/^-+:?$/.test(target)) out[role] = target.replace(/\.md$/i, ""); + } + return out; +} + +/** Whether a World types note was converted (it has a role list). */ +export function isConverted(content: string): boolean { + return Object.keys(readRoleTables(content)).length > 0; +} + +/** + * The World types note after converting (T2): a short callout, the + * `## Tables` role list right under the title, the tables embedded so + * they can be rolled here, and `converted-to:` in the frontmatter. Every + * line of the old note stays. Unchanged when it was converted already. + */ +export function markConverted(content: string, set: Pick): string { + if (isConverted(content)) return content; + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + // converted-to: in the frontmatter. + if (lines[0]?.trim() === "---") { + const end = lines.indexOf("---", 1); + if (end > 0 && !lines.slice(1, end).some((l) => /^converted-to\s*:/.test(l))) lines.splice(end, 0, `converted-to: ${JSON.stringify(set.folder)}`); + } + const rows = ENGINE_ROLES.filter((r) => set.roles[r.id]).map((r) => `| ${r.name} | ${linkCell(set.roles[r.id]!)} |`); + const embeds = ENGINE_ROLES.filter((r) => set.roles[r.id]).map((r) => `![[${set.roles[r.id]!.replace(/\.md$/i, "")}]]`); + const block = [ + "> [!info] Converted to tables", + `> The space generators roll on the tables linked below (in ${set.folder}). To use another table for a role, change its link. The world types further down are the old copy, kept as they were.`, + "", + "## Tables", + "", + "| Role | Table |", + "| --- | --- |", + ...rows, + "", + ...embeds.flatMap((e) => [e, ""]), + ]; + const fmEnd = lines[0]?.trim() === "---" ? lines.indexOf("---", 1) + 1 : 0; + const h1 = lines.findIndex((l, i) => i >= fmEnd && /^#\s+\S/.test(l)); + const at = h1 >= 0 ? h1 + 1 : fmEnd; + lines.splice(at, 0, "", ...block.slice(0, -1)); + return lines.join(eol); +} diff --git a/src/space/worldTypesSource.ts b/src/space/worldTypesSource.ts index def555df..2e8be35b 100644 --- a/src/space/worldTypesSource.ts +++ b/src/space/worldTypesSource.ts @@ -54,7 +54,7 @@ const ATTR_COLUMNS = ["Mainworld", "Size", "Generator", "Options", "Palette", "B const lc = (s: string) => s.trim().toLowerCase(); -function attrsOf(r: WorldTypeRow): Record { +export function attrsOf(r: WorldTypeRow): Record { const cells = worldTypeCells(r); const out: Record = {}; for (const c of ATTR_COLUMNS) { @@ -65,7 +65,7 @@ function attrsOf(r: WorldTypeRow): Record { } /** A worlds row's limits other than map and zone, as When conditions. */ -function conditionsOf(r: WorldTypeRow): TableCondition[] { +export function conditionsOf(r: WorldTypeRow): TableCondition[] { const out: TableCondition[] = []; if (r.distance) out.push({ key: "ring", range: { ...r.distance } }); if (r.stars?.length) out.push({ key: "star", values: r.stars.map(lc) }); diff --git a/src/types.ts b/src/types.ts index 11e4cd53..8d78f831 100644 --- a/src/types.ts +++ b/src/types.ts @@ -218,6 +218,22 @@ export interface MapData { biome?: RegionBiome; /** Region maps: the seed its terrain was last generated with (Reroll picks a new one). */ regionSeed?: number; + /** The map's own seed (`seed:`): places made on arrival from its hexes + * are seeded from it, so they don't depend on the map's name. */ + seed?: number; + /** Generator tables per role (`sector-hexes-table: "[[…]]"`, T11): role + * id (worldgen/tableRoles.ts) → table note path. Inherited by every map + * under this one unless that map sets its own. */ + roleTables?: Record; + /** "When you arrive somewhere new" (`on-arrival:`), as written: "make + * places" or "off". Unset = the parent map's, else off. Read with + * arrival/arrival.ts parseArrivalMode. */ + arrivalMode?: string; + /** A place made on arrival (`arrival:`): "open" while Play may still + * reroll it, "locked" once the user locked it (then only God may). */ + arrival?: string; + /** How often a place made on arrival was rerolled (`arrival-rerolls:`). */ + arrivalRerolls?: number; /** Overworlds: "regions" shows every region's hexes stitched together on * the map (the full view); "biomes" shows the overworld's own hexes, one * biome each. Unset = regions once the map has any. */ diff --git a/src/workMode.ts b/src/workMode.ts index e629462a..cfa5eb90 100644 --- a/src/workMode.ts +++ b/src/workMode.ts @@ -13,6 +13,12 @@ * * Never locked: note text (WM2), settings and palettes (WM4). * + * Arrival (GM4, plan-tables-everywhere phase 4): when a world is set to + * make places on arrival, Play may make a place where nothing exists yet + * (`discover`): it only fills in an unknown hex and adds a new map, never + * reshapes what's there. The new place can be rerolled in any mode until + * someone locks it; after that rerolling it is God's (canRerollPlace). + * * ACTION_POLICY is the classification of every user action; * TOOL_ACTIONS / COMMAND_ACTIONS / MENU_ACTIONS map each drawing tool, * command and map-view menu item onto it. tests/workModeCoverage.test.ts @@ -55,6 +61,8 @@ export type ModeAction = | "settings" // plugin settings and palettes: never locked (WM4) | "switch-mode" // the mode switch itself | "new-top-map" // a new map that isn't made from a hex of another map + | "discover" // arrival: make a place where nothing exists yet (only when the world is set to make places) + | "lock-place" // lock a place made on arrival (after that, rerolling it needs God) // ── Build and God ── | "paint-terrain" | "paint-icon" // icon overrides and GM icons @@ -98,6 +106,8 @@ export const ACTION_POLICY: Record = { settings: { modes: ALL, verb: "change settings" }, "switch-mode": { modes: ALL, verb: "switch modes" }, "new-top-map": { modes: ALL, verb: "make a map" }, + discover: { modes: ALL, verb: "go somewhere new" }, + "lock-place": { modes: ALL, verb: "lock a new place" }, "paint-terrain": { modes: BUILD, verb: "paint terrain" }, "paint-icon": { modes: BUILD, verb: "change icons" }, "paint-region-area": { modes: BUILD, verb: "paint region areas" }, @@ -172,6 +182,7 @@ export const COMMAND_ACTIONS: Record = { "open-terrain-generator": "view", "open-palette-editor": "settings", "edit-world-types": "edit-biomes", + "convert-world-types": "edit-biomes", "new-overworld": "new-top-map", "map-go-up": "navigate", "map-go-back": "navigate", @@ -195,6 +206,7 @@ export const MENU_ACTIONS = { "hex.open-note": "open-note", "hex.enter-region": "navigate", "hex.open-location": "navigate", + "hex.arrive": "discover", "hex.locations": "navigate", "hex.new-map": "new-child-map", "hex.link-map": "link-map", @@ -259,6 +271,19 @@ export function canReshape(map: { workMode?: string } | undefined): boolean { return mapAllows(map, "reshape"); } +/** The hint when a locked place can't be rerolled. */ +export const REROLL_PLACE_LOCKED_HINT = "This place is locked. Switch to God to reroll it."; + +/** + * May a place made on arrival be rerolled? Until it's locked (`arrival: + * open`), in any mode; once locked, only in God (GM4). A map not made on + * arrival follows the usual reshape rule. + */ +export function canRerollPlace(map: { workMode?: string; arrival?: string } | undefined): boolean { + if (map?.arrival?.trim().toLowerCase() === "open") return true; + return mapAllows(map, "reshape"); +} + /** May new things be added to this map (a first biome, a new region)? Build and God; not Play. */ export function canAdd(map: { workMode?: string } | undefined): boolean { return mapAllows(map, "new-child-map"); diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index 53f3c2ad..b159ad36 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -23,6 +23,8 @@ import { IMAGE_EXTENSIONS, attachImageDropZone, getIconUrl, importBinaryFileToVa import { FileLinkSuggestModal } from "../hex-map/FileLinkSuggestModal"; import { WorldTypesModal } from "../space/WorldTypesModal"; import { WORLD_TYPES_KEY } from "../space/worldTypesSource"; +import { attrsForTerrain } from "./tableSources"; +import { rowSubmapDefault } from "../arrival/arrival"; import { STAR_SCATTER_ID } from "./procedural/starScatter"; import { ORBITS_ID } from "./procedural/orbits"; import { SIZE_PRESETS, type SizePreset } from "./sizePresets"; @@ -101,6 +103,8 @@ export class NewMapSetupModal extends HexmakerModal { private originTerrain: string | undefined; /** Saved setup for submaps of that terrain, applied as the starting values. */ private saved: SubmapDefault | undefined; + /** What the hex's row in the generator tables says (Size, Generator…): the start where nothing is saved (SP4's chain). */ + private rowStart: SubmapDefault | undefined; /** The parent hex and its neighbours, so generation fits the bigger map. */ private context: GenerationContext | undefined; /** "Next to" placement in a world of neighbouring regions (top-level maps). */ @@ -152,7 +156,11 @@ export class NewMapSetupModal extends HexmakerModal { getTerrainFromFile(app, plugin.hexPath(origin.x, origin.y, origin.map)) ?? parent?.baseTerrain ?? undefined; this.saved = plugin.submapDefaultFor(origin.map, this.originTerrain); this.context = buildSubmapContext(plugin, origin.map, origin.x, origin.y); - const d = this.saved; + if (this.originTerrain) { + const source = plugin.worldTypeStore.sourceFor(undefined, plugin.getMapPalette(origin.map).map((t) => t.name), origin.map).source; + this.rowStart = rowSubmapDefault(attrsForTerrain(source, this.originTerrain)); + } + const d: SubmapDefault | undefined = this.rowStart || this.saved ? { ...this.rowStart, ...this.saved } : undefined; if (d?.cols && d.rows) { this.cols = d.cols; this.rows = d.rows; } if (d?.generator) this.kindId = d.generator; if (d?.options) this.options = { ...d.options }; @@ -169,6 +177,7 @@ export class NewMapSetupModal extends HexmakerModal { this.rows = g.rows; // Saved submap defaults are for locations: a region uses its settings. this.saved = undefined; + this.rowStart = undefined; this.remember = { palette: false, size: false, generator: false, base: false }; } } @@ -251,7 +260,7 @@ export class NewMapSetupModal extends HexmakerModal { fillPaletteSelect( this.plugin, paletteSelect, - this.saved?.palette + this.saved?.palette ?? this.rowStart?.palette ?? (this.origin ? this.plugin.childPaletteFor(this.origin.map) : defaultPaletteFor(this.plugin.settings)), ); if (this.asRegion) { @@ -530,7 +539,7 @@ export class NewMapSetupModal extends HexmakerModal { // submap default stays visible either way. const spaceContext = isSpacePalette(terrains) || this.plugin.getPaletteOrPresetKind(paletteSelect.value) === "space" || (!!this.origin && this.plugin.isSpaceMap(this.origin.map)); - const shown = visibleKinds(this.kinds, this.plugin.settings, spaceContext, this.saved?.generator); + const shown = visibleKinds(this.kinds, this.plugin.settings, spaceContext, this.saved?.generator ?? this.rowStart?.generator); // "Zoom into the parent hex" generators only for submaps (a neighbour // has context but no parent hex); next to a neighbour, the ones that // carry on from its edge come first. @@ -542,7 +551,7 @@ export class NewMapSetupModal extends HexmakerModal { if (where.parentHex) { this.kindId = submapStartKind(fitting, this.kindId, { parentTerrain: this.originTerrain, - savedGenerator: this.saved?.generator, + savedGenerator: this.saved?.generator ?? this.rowStart?.generator, picked: this.pickedKind, }); } @@ -651,7 +660,7 @@ export class NewMapSetupModal extends HexmakerModal { baseSelect.empty(); baseSelect.createEl("option", { value: "", text: BASE_TERRAIN_NONE_LABEL }); for (const t of terrains) baseSelect.createEl("option", { value: t.name, text: t.name }); - const savedBase = this.saved?.baseTerrain; + const savedBase = this.saved?.baseTerrain ?? this.rowStart?.baseTerrain; this.baseTerrain = savedBase !== undefined && (savedBase === "" || terrains.some((t) => t.name === savedBase)) ? savedBase || undefined : suggestBaseTerrain(terrains); @@ -791,6 +800,7 @@ export class NewMapSetupModal extends HexmakerModal { return runGenerator(this.plugin.settings.hexOrientation, kind, { terrains, grid: this.grid(), seed: this.seed, options: this.resolvedOptions(kind), context: this.context, region: this.placement, pathTypes: this.plugin.getPathTypes(paletteName), + ...(this.origin ? { tablesFrom: this.origin.map } : {}), }); } @@ -875,6 +885,7 @@ export class NewMapSetupModal extends HexmakerModal { parent: this.origin ? { map: this.origin.map, hex: `${this.origin.x}_${this.origin.y}` } : undefined, quiet: true, slug: this.folderSlug(), + ...(outcome?.ok && outcome.arrivals ? { arrivals: outcome.arrivals } : {}), }, ); if ("error" in result) { diff --git a/src/worldgen/procedural/common.ts b/src/worldgen/procedural/common.ts index 554bc9a0..3c5a7f62 100644 --- a/src/worldgen/procedural/common.ts +++ b/src/worldgen/procedural/common.ts @@ -26,6 +26,12 @@ export interface ProcResult { cells: Map; paths: ProcPath[]; warnings: string[]; + /** + * Hexes left to roll when someone first arrives ("x_y" → table link): + * rows whose Roll is "on arrival" (plan-tables-everywhere §2.6). Written + * to the map note's On arrival column. + */ + arrivals?: Map; } /** Compass sides of a map, for what lies beyond each edge. */ diff --git a/src/worldgen/procedural/starScatter.ts b/src/worldgen/procedural/starScatter.ts index 15cb9361..1367da61 100644 --- a/src/worldgen/procedural/starScatter.ts +++ b/src/worldgen/procedural/starScatter.ts @@ -145,13 +145,22 @@ export function starScatter( // Systems: one roll per hex; nebulae halve the odds. const systems: [number, number][] = []; + const arrivals = new Map(); for (const [x, y] of hexes) { const k = cellKey(x, y); const odds = inCloud.has(k) ? density / 2 : density; if (rand() >= odds) continue; - const pick = rollRole(tables, "sector-hexes", { rand }, roles.worlds); + const pick = rollRole(tables, "sector-hexes", { rand, deferArrival: true }, roles.worlds); // A (nothing) row: empty space after all. if (!pick || pick.nothing) continue; + if (pick.arrival) { + // Rolled when someone arrives: until then the hex shows its Shown as + // terrain (or stays background), and hosts a system for the routes. + arrivals.set(k, pick.arrival); + if (pick.terrain) cells.set(k, pick.terrain); + systems.push([x, y]); + continue; + } cells.set(k, pick.terrain); // A world hosts a system (and so a route); of the rest, only station-like types do. if (!isFeature(pick.terrain) || hostsSystem(pick.terrain)) systems.push([x, y]); @@ -183,7 +192,7 @@ export function starScatter( } } if (systems.length === 0) warnings.push("No systems rolled — try a higher density or another seed."); - return { cells, paths, warnings }; + return arrivals.size ? { cells, paths, warnings, arrivals } : { cells, paths, warnings }; } /** diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index db9e6c5a..e5019c98 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -60,6 +60,8 @@ export type GenerateOutcome = paths: GeneratedPath[]; featureCells?: Set; warnings: string[]; + /** Hexes left to roll on arrival ("x_y" → table link): the map note's On arrival column. */ + arrivals?: Map; } | { ok: false; message: string }; @@ -76,6 +78,12 @@ export interface GenerateRequest { /** A new region placed next to existing ones: learned generators solve * against the neighbours' edges (generateConnected). */ region?: NewRegion; + /** + * The map whose generator tables apply (Map properties → Tables, T11): + * the map being made's parent, or the map itself. Its own and its + * ancestors' tables win over the World types option's. + */ + tablesFrom?: string; } export interface TerrainGeneratorKind { @@ -226,7 +234,7 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise { const orbitType = chosenPathType(req.options[ORBIT_TYPE_KEY], "orbits", req.pathTypes); - const wt = plugin.worldTypeStore.sourceFor(req.options[WORLD_TYPES_KEY], req.terrains); + const wt = plugin.worldTypeStore.sourceFor(req.options[WORLD_TYPES_KEY], req.terrains, req.tablesFrom); const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitType, req.context, wt.source); if (wt.missing) r.warnings.unshift(missingWorldTypes(wt.missing)); // No type and not None on purpose: say why there are no rings. diff --git a/src/worldgen/tableRoles.ts b/src/worldgen/tableRoles.ts index 71707a0b..630d4bdb 100644 --- a/src/worldgen/tableRoles.ts +++ b/src/worldgen/tableRoles.ts @@ -126,13 +126,21 @@ export interface TableSource { /** What the engine knows where it rolls (conditions), plus its random stream. */ export interface RoleContext extends ConditionContext { rand: () => number; + /** + * Leave rows whose Roll is "on arrival" for later (Star scatter): the pick + * then says which table to roll on arrival and what the hex shows until + * then (plan-tables-everywhere §2.6). + */ + deferArrival?: boolean; } export interface RolePick { - /** The terrain to place; "" for a (nothing) row. */ + /** The terrain to place; "" for a (nothing) row, or an on-arrival row with nothing to show. */ terrain: string; nothing?: boolean; attrs: Record; + /** An on-arrival row (deferArrival): the table to roll when someone arrives. */ + arrival?: string; } /** @@ -152,7 +160,7 @@ function withEqualOdds(lookup: TableLookup, fallback: readonly string[]): TableL const NO_SOURCE: TableLookup = { table: () => undefined }; -function resolveCtx(source: TableSource | undefined, fallback: readonly string[], ctx: ConditionContext): ResolveContext { +function resolveCtx(source: TableSource | undefined, fallback: readonly string[], ctx: ConditionContext & { deferArrival?: boolean }): ResolveContext { return { ...ctx, terrains: source?.terrains ?? fallback, onlyTerrains: true }; } @@ -171,10 +179,16 @@ function usesTable(source: TableSource | undefined, role: RoleId, fallback: read */ export function rollRole(source: TableSource | undefined, role: RoleId, ctx: RoleContext, fallback: readonly string[]): RolePick | undefined { const lookup = withEqualOdds(source?.lookup ?? NO_SOURCE, fallback); - const { rand, ...cond } = ctx; + const { rand, deferArrival, ...cond } = ctx; const link = usesTable(source, role, fallback, cond) ?? EQUAL_ODDS; - const r = resolveRoll(link, lookup, { ...resolveCtx(source, fallback, cond), rand }); + const r = resolveRoll(link, lookup, { ...resolveCtx(source, fallback, cond), rand, ...(deferArrival ? { deferArrival } : {}) }); if (r.kind === "nothing") return { terrain: "", nothing: true, attrs: r.attrs }; + if (r.kind === "deferred") { + // Shown as a palette terrain (its spelling), else nothing shown yet. + const terrains = source?.terrains ?? fallback; + const shown = r.shownAs ? terrains.find((t) => t.trim().toLowerCase() === r.shownAs!.trim().toLowerCase()) : undefined; + return { terrain: shown ?? "", attrs: r.attrs, arrival: r.value }; + } if (r.kind === "terrain") return { terrain: r.value, attrs: r.attrs }; return undefined; } diff --git a/src/worldgen/tableSources.ts b/src/worldgen/tableSources.ts new file mode 100644 index 00000000..eb7dae47 --- /dev/null +++ b/src/worldgen/tableSources.ts @@ -0,0 +1,144 @@ +/** + * Where a generator's role tables come from (plan-tables-everywhere §2.4, + * phase 3). First match wins, per role: + * + * 1. the map's own Tables (Map properties → Tables, T11), else the + * nearest map above it that sets one (inherited down the map tree); + * 2. the generator's setup: the World types option's table — a + * converted note's `## Tables` list (space/spaceTables.ts), or an + * unconverted note read as tables (space/worldTypesSource.ts). This + * is the recipe seam: a recipe's `## Tables` slots in here later; + * 3. a bound module's table (modules don't exist yet: nothing here); + * 4. none: equal odds (tableRoles.ts says so). + * + * Pure: no Obsidian imports. + */ + +import { findRow, tableFitsWant, type TableLookup } from "../random-tables/resolve"; +import type { RandomTable } from "../random-tables/randomTable"; +import { ENGINE_ROLES, engineRole, type RoleId, type TableSource } from "./tableRoles"; + +/** A role's table and where it was set. */ +export interface RoleTablePick { + /** The table note's link target (vault path, with or without .md). */ + link: string; + /** The map that set it. */ + from: string; +} + +/** + * Each role's table from the map tree: the map's own, else the nearest + * ancestor's (`parentOf` walks up; cycles stop). + */ +export function inheritedRoleTables( + mapName: string, + tablesOf: (map: string) => Record | undefined, + parentOf: (map: string) => string | undefined, +): Partial> { + const out: Partial> = {}; + const seen = new Set(); + for (let m: string | undefined = mapName; m && !seen.has(m); m = parentOf(m)) { + seen.add(m); + const own = tablesOf(m) ?? {}; + for (const r of ENGINE_ROLES) { + const link = own[r.id]; + if (link && !out[r.id]) out[r.id] = { link, from: m }; + } + } + return out; +} + +/** A role's tables straight from notes (a converted set, or a map's Tables). */ +export function notesTableSource( + links: Partial>, + lookup: TableLookup, + terrains: readonly string[], + label: string, +): TableSource { + return { + label, + lookup, + terrains, + tableFor: (role) => links[role], + rowAttrs: (role, name) => { + const link = links[role]; + return link ? findRow(link, name, lookup)?.attrs : undefined; + }, + }; +} + +/** + * The generator setup's source with some roles set elsewhere (a map's + * Tables): those roles roll on their own table from the notes, the rest + * as the base says. Links are looked up in the base first (its in-memory + * tables), then in the notes. + */ +export function layeredSource( + base: TableSource | undefined, + overrides: Partial>, + notes: TableLookup, + terrains: readonly string[], +): TableSource | undefined { + const lookup: TableLookup = { + table: (link) => base?.lookup.table(link) ?? notes.table(link), + kindOf: (link) => { + const k = base?.lookup.kindOf?.(link); + return k && k !== "missing" ? k : notes.kindOf?.(link) ?? "note"; + }, + }; + // A role whose table is gone (deleted, renamed) falls through to the base. + const own: Partial> = {}; + for (const [role, link] of Object.entries(overrides) as [RoleId, string][]) if (link && lookup.table(link)) own[role] = link; + const missing = (Object.keys(overrides) as RoleId[]).filter((r) => !own[r]); + if (!Object.keys(own).length && !missing.length) return base; + return { + label: base ? `${base.label} (with this map's tables)` : "This map's tables", + lookup, + terrains: base?.terrains ?? terrains, + tableFor: (role) => own[role] ?? base?.tableFor(role), + rowAttrs: (role, name) => { + const link = own[role]; + if (link) return findRow(link, name, lookup)?.attrs ?? base?.rowAttrs(role, name); + return base?.rowAttrs(role, name); + }, + notes: (role) => [ + ...(missing.includes(role) ? [`${engineRole(role).name}: the table set for this map (${overrides[role]}) isn't there, so the usual one is used.`] : []), + ...(own[role] ? [] : base?.notes?.(role) ?? []), + ], + }; +} + +/** + * The attributes of the row that names `terrain` in any role's table + * (Sector hexes first): what a hex of that terrain opens into (its Size, + * Generator, Palette…). Undefined when no table names it. + */ +export function attrsForTerrain(source: TableSource | undefined, terrain: string): Record | undefined { + if (!source || !terrain) return undefined; + for (const r of ENGINE_ROLES) { + const attrs = source.rowAttrs(r.id, terrain); + if (attrs) return attrs; + } + return undefined; +} + +/** + * The tables a role can roll on, for a picker (plan §2.5): those whose + * `rows:` (and terrain type) fit the role exactly, the space folder's + * first, then by path. Tables with `rows: any` (every older table) are + * left out: they'd list every table in the vault. A picker offers "Other + * table…" for those. + */ +export function fittingRoleTables( + tables: readonly { path: string; table: Pick }[], + role: RoleId, + spaceFolder: string, +): string[] { + const spec = engineRole(role); + const want = { rows: [spec.rows], terrainType: spec.terrainTypes[0] }; + const inSpace = (p: string) => (spaceFolder && p.startsWith(`${spaceFolder}/`) ? 0 : 1); + return tables + .filter((t) => tableFitsWant(t.table, want).fit === "exact") + .map((t) => t.path) + .sort((a, b) => inSpace(a) - inSpace(b) || a.localeCompare(b)); +} diff --git a/styles.css b/styles.css index 7c51ccbf..7ff8dad0 100644 --- a/styles.css +++ b/styles.css @@ -8973,3 +8973,38 @@ textarea.duckmage-edit-region-notes-input { .duckmage-world-types-rows:focus { outline: none; } + +/* A place made on arrival (GM4): Reroll / Lock next to the mode switch. */ +.duckmage-map-nav-group .duckmage-arrival-bar { + display: flex; + align-items: center; + gap: 4px; +} +.duckmage-arrival-bar .duckmage-arrival-bar-label { + font-size: 0.8em; + color: var(--text-muted); + white-space: nowrap; +} +.duckmage-map-nav-group .duckmage-arrival-bar button { + height: 26px; + padding: 0 8px; + font-size: 0.8em; +} + +/* Map properties → Tables (T11): one row per generator role. */ +.duckmage-role-table-row { + display: grid; + grid-template-columns: 9em 1fr; + align-items: center; + gap: 6px; + margin: 2px 0; +} +.duckmage-role-table-row select { + min-width: 0; + width: 100%; +} +.duckmage-role-table-from { + grid-column: 2; + font-size: 0.8em; + color: var(--text-muted); +} diff --git a/tests/arrivalDeferred.test.ts b/tests/arrivalDeferred.test.ts new file mode 100644 index 00000000..bbe67c54 --- /dev/null +++ b/tests/arrivalDeferred.test.ts @@ -0,0 +1,248 @@ +/** + * Phase 4 end to end, on an in-memory vault (SP4, SP5, GM4, T5): + * - going into an unknown sector hex in Play rolls its On arrival table + * once, with the map's seed, writes what it was onto the sector hex, + * and makes the system with no form; + * - the same seed gives the same place; a second visit rolls nothing; + * - the place can be rerolled in Play until it's locked, then only in God; + * - a world not set to make places writes nothing. + */ +import { describe, it, beforeEach } from "node:test"; +import expect from "expect"; +import { MapStore } from "../src/maps/MapStore"; +import { parseMapNote } from "../src/maps/mapNote"; +import { addLocationPatch } from "../src/maps/submaps"; +import { setHexDataSource } from "../src/frontmatter"; +import { setModeMapLookup } from "../src/modeGate"; +import { ArrivalService } from "../src/arrival/ArrivalService"; +import { effectiveArrivalMode } from "../src/arrival/arrival"; +import { convertWorldTypes } from "../src/space/spaceTables"; +import { notesLookup } from "../src/random-tables/resolve"; +import { inheritedRoleTables, layeredSource, notesTableSource } from "../src/worldgen/tableSources"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { getPreset } from "../src/palettes/presets"; +import { slugify } from "../src/utils"; +import { MemVault } from "./helpers/memVault"; +import { Notice } from "obsidian"; +import type { MapData } from "../src/types"; +import type { RoleId } from "../src/worldgen/tableRoles"; + +(globalThis as Record).window ??= globalThis; + +const SET = convertWorldTypes({ name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }, { tablesFolder: "world/tables", shownAs: "star system" }); +const TABLES = Object.fromEntries(SET.files.map((f) => [f.path, f.content])); +const MAINWORLDS = SET.files.find((f) => f.path.endsWith("Mainworlds.md"))!.path.replace(/\.md$/, ""); +const UNCHARTED = SET.files.find((f) => f.path.endsWith("Uncharted.md"))!.path.replace(/\.md$/, ""); +const SECTOR_NOTE = "world/hexes/drift/_drift.md"; + +function world(opts: { arrival?: string; seed?: number; mode?: string } = {}) { + const vault = new MemVault(); + const maps: MapData[] = [{ + name: "drift", paletteName: "Space - Sector", gridSize: { cols: 8, rows: 8 }, gridOffset: { x: 0, y: 0 }, pathChains: [], + baseTerrain: "empty space", seed: opts.seed ?? 777, workMode: opts.mode ?? "play", + ...(opts.arrival ? { arrivalMode: opts.arrival } : {}), + } as MapData]; + const lookup = notesLookup(TABLES); + const p = { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", worldFolder: "world", tablesFolder: "world/tables", maps, hexOrientation: "flat", staggerOffset: "odd", mapKinds: ["space"], featureLevel: "advanced" } as Record & { maps: MapData[] }, + mapStore: undefined as unknown as MapStore, + saves: 0, + getMap: (n: string) => maps.find((m) => m.name === n), + mapLabel: (n: string) => maps.find((m) => m.name === n)?.displayName ?? n, + parentOf: (n: string) => maps.find((m) => m.name === n)?.parent, + hexPath: (x: number, y: number, map: string) => `world/hexes/${map}/${x}_${y}.md`, + arrivalModeFor: (n: string) => effectiveArrivalMode(n, (m) => maps.find((x) => x.name === m)?.arrivalMode, (m) => maps.find((x) => x.name === m)?.parent?.map), + roleTablesFor: (n: string) => inheritedRoleTables(n, (m) => maps.find((x) => x.name === m)?.roleTables, (m) => maps.find((x) => x.name === m)?.parent?.map), + tableNotes: { lookup: () => lookup }, + worldTypeStore: { + sourceFor: (_v: string | undefined, palette: readonly (string | { name: string })[], mapName?: string) => { + const terrains = palette.map((t) => (typeof t === "string" ? t : t.name)); + const base = notesTableSource(SET.roles, lookup, terrains, "Tables: Default space"); + const own = mapName ? p.roleTablesFor(mapName) : {}; + const overrides = Object.fromEntries(Object.entries(own).map(([r, v]) => [r, v!.link])) as Partial>; + return { source: layeredSource(base, overrides, lookup, terrains) }; + }, + list: () => [], + }, + paths: { resolvedPathChains: () => [] }, + getMapPalette: (n: string) => getPreset(maps.find((m) => m.name === n)?.paletteName ?? "")?.terrains ?? [], + getPaletteOrPresetTerrains: (n: string) => getPreset(n)?.terrains ?? [], + getPaletteOrPresetKind: (n: string) => getPreset(n)?.kind, + getPaletteByName: () => undefined, + isSpaceMap: () => true, + childPaletteFor: (n: string) => getPreset(maps.find((m) => m.name === n)?.paletteName ?? "")?.childPalette ?? "Space - System", + submapDefaultFor: (n: string, t: string | undefined) => (t ? getPreset(maps.find((m) => m.name === n)?.paletteName ?? "")?.submapDefaults?.[t] : undefined), + getPathTypes: () => [], + getMapPathTypes: () => [], + saveData: async () => {}, + refreshHexMap: () => {}, + saveSettings: async () => { p.saves++; await p.mapStore.sync(); }, + async createNewMap(raw: string, cols: number, rows: number, paletteName: string, ox: number, oy: number, stagger: "odd" | "even", _prog: unknown, cells: Map | undefined, extra: { baseTerrain?: string; parent?: { map: string; hex: string }; slug?: string; arrivals?: Map }) { + const name = slugify(extra.slug || raw); + maps.push({ name, displayName: raw, paletteName, gridSize: { cols, rows }, gridOffset: { x: ox, y: oy }, pathChains: [], staggerOffset: stagger, ...(extra.baseTerrain ? { baseTerrain: extra.baseTerrain } : {}), ...(extra.parent ? { parent: extra.parent } : {}) } as MapData); + p.mapStore.setMany(name, [...(cells ?? [])].filter(([, t]) => t !== extra.baseTerrain).map(([k, t]) => [k, { terrain: t }])); + if (extra.arrivals) p.mapStore.setMany(name, [...extra.arrivals].map(([k, t]) => [k, { onArrival: t }])); + await p.mapStore.flush(); + return { name }; + }, + async linkSubmap(parent: string, x: number, y: number, child: string, action: string) { + const key = `${x}_${y}`; + p.mapStore.set(parent, key, addLocationPatch(p.mapStore.get(parent, key), child), action as never); + }, + }; + p.mapStore = new MapStore(p as never); + setHexDataSource(p.mapStore); + setModeMapLookup((n) => p.getMap(n)); + const service = new ArrivalService(p as never); + return { vault, p, maps, service }; +} + +async function sectorWith(w: ReturnType, cells: [string, { terrain?: string; onArrival?: string }][]) { + await w.p.mapStore.init(); + w.p.mapStore.setMany("drift", cells); + await w.p.mapStore.flush(); +} + +describe("arriving at an unknown sector hex (T5, SP4)", () => { + beforeEach(() => { (Notice as unknown as { shown: string[] }).shown = []; }); + + it("rolls its On arrival table once, writes the result onto the sector hex, and makes the system with no form", async () => { + const w = world({ arrival: "make places" }); + await sectorWith(w, [["4_5", { terrain: "star system", onArrival: MAINWORLDS }]]); + const made = await w.service.arrive("drift", 4, 5); + expect(made).toBeTruthy(); + const hex = w.p.mapStore.get("drift", "4_5")!; + // Discovery is raised to the parent: the sector now knows the world type. + expect(hex.onArrival).toBeUndefined(); + expect(hex.terrain).not.toBe("star system"); + expect(DEFAULT_WORLD_TYPE_ROWS.some((r) => r.map === "sector" && r.world === hex.terrain)).toBe(true); + expect(hex.locations).toEqual([made]); + // The system: made from the row (Orbits on Space - System, 13×13), in the player's mode, open for rerolls. + const sys = w.p.getMap(made!)!; + expect(sys).toMatchObject({ paletteName: "Space - System", gridSize: { cols: 13, rows: 13 }, parent: { map: "drift", hex: "4_5" }, arrival: "open", workMode: "play" }); + expect(typeof sys.seed).toBe("number"); + expect(w.p.mapStore.all(made!).size).toBeGreaterThan(3); + // The write-up, as plain text in the new map's note. + const note = w.vault.files.get(`world/hexes/${made}/_${made}.md`)!; + expect(note).toContain("## Arrival"); + expect(note).toMatch(/- Rolled on \[\[.*Mainworlds\]\]: /); + expect(note).toContain("- Made with Orbits on Space - System, 13×13"); + expect(parseMapNote(note)!.settings.arrival).toBe("open"); + // The sector's note says it too, readably. + expect(parseMapNote(w.vault.files.get(SECTOR_NOTE)!)!.hexes.get("4_5")?.terrain).toBe(hex.terrain); + }); + + it("is seeded: the same world seed gives the same result and the same place", async () => { + const run = async () => { + const w = world({ arrival: "make places", seed: 4242 }); + await sectorWith(w, [["2_3", { terrain: "star system", onArrival: UNCHARTED }], ["4_5", { terrain: "star system", onArrival: MAINWORLDS }]]); + const a = await w.service.arrive("drift", 4, 5); + return { terrain: w.p.mapStore.get("drift", "4_5")?.terrain, cells: [...w.p.mapStore.all(a!)].map(([k, h]) => `${k}=${h.terrain ?? ""}`).join(",") }; + }; + const one = await run(); + const two = await run(); + expect(two).toEqual(one); + // Another seed, (very likely) another place. + const w = world({ arrival: "make places", seed: 1 }); + await sectorWith(w, [["4_5", { terrain: "star system", onArrival: MAINWORLDS }]]); + const other = await w.service.arrive("drift", 4, 5); + expect([...w.p.mapStore.all(other!)].map(([k, h]) => `${k}=${h.terrain ?? ""}`).join(",")).not.toBe(one.cells); + }); + + it("a second visit never rolls again", async () => { + const w = world({ arrival: "make places" }); + await sectorWith(w, [["4_5", { terrain: "star system", onArrival: MAINWORLDS }]]); + const made = await w.service.arrive("drift", 4, 5); + const after = { ...w.p.mapStore.get("drift", "4_5") }; + const mapsBefore = w.maps.length; + const writes = w.vault.writes.length; + expect(w.service.canArrive("drift", 4, 5)).toBe(false); + expect(await w.service.arrive("drift", 4, 5)).toBeNull(); + expect(w.service.resolveHex("drift", 4, 5, "discover")).toBeNull(); + expect(w.p.mapStore.get("drift", "4_5")).toEqual(after); + expect(w.maps.length).toBe(mapsBefore); + expect(w.vault.writes.length).toBe(writes); + expect(w.p.getMap(made!)!.arrivalRerolls).toBeUndefined(); + }); + + it("an uncharted hex can turn out to be nothing: no place, the hex shows empty space", async () => { + // Find a seed where Uncharted rolls (nothing). + for (let seed = 1; seed < 400; seed++) { + const w = world({ arrival: "make places", seed }); + await sectorWith(w, [["1_1", { onArrival: UNCHARTED }]]); + const r = w.service.resolveHex("drift", 1, 1, "discover"); + if (r?.kind !== "nothing") continue; + expect(w.p.mapStore.get("drift", "1_1")).toBeUndefined(); + return; + } + throw new Error("no seed rolled (nothing)"); + }); + + it("a world not set to make places changes nothing (generator features stay optional)", async () => { + const w = world(); + await sectorWith(w, [["4_5", { terrain: "star system", onArrival: MAINWORLDS }]]); + const writes = w.vault.writes.length; + expect(w.service.canArrive("drift", 4, 5)).toBe(false); + expect(await w.service.arrive("drift", 4, 5)).toBeNull(); + expect(w.p.mapStore.get("drift", "4_5")).toEqual({ terrain: "star system", onArrival: MAINWORLDS }); + expect(w.maps).toHaveLength(1); + expect(w.vault.writes.length).toBe(writes); + expect(w.p.saves).toBe(0); + }); + + it("never arrives into a locked hex", async () => { + const w = world({ arrival: "make places" }); + await sectorWith(w, [["4_5", { terrain: "star system", onArrival: MAINWORLDS }]]); + w.p.mapStore.set("drift", "4_5", { locked: true }); + expect(w.service.canArrive("drift", 4, 5)).toBe(false); + expect(await w.service.arrive("drift", 4, 5)).toBeNull(); + expect(w.p.mapStore.get("drift", "4_5")?.onArrival).toBe(MAINWORLDS); + }); +}); + +describe("reroll until locked (GM4)", () => { + it("Play may reroll a new place; after Lock only God may", async () => { + const w = world({ arrival: "make places" }); + await sectorWith(w, [["4_5", { terrain: "star system", onArrival: MAINWORLDS }]]); + const made = (await w.service.arrive("drift", 4, 5))!; + const sys = w.p.getMap(made)!; + const snapshot = () => [...w.p.mapStore.all(made)].map(([k, h]) => `${k}=${h.terrain ?? ""}`).join(","); + const first = snapshot(); + const parentTerrain = w.p.mapStore.get("drift", "4_5")?.terrain; + + expect(await w.service.reroll(made)).toBe(true); + expect(sys.arrivalRerolls).toBe(1); + expect(snapshot()).not.toBe(first); + // The landscape is made again; what the hex is stays (it's known now). + expect(w.p.mapStore.get("drift", "4_5")?.terrain).toBe(parentTerrain); + expect(sys.gridSize).toEqual({ cols: 13, rows: 13 }); + const note = () => w.vault.files.get(`world/hexes/${made}/_${made}.md`)!; + expect(note()).toContain("- Rerolled once."); + + await w.service.lock(made); + expect(sys.arrival).toBe("locked"); + expect(parseMapNote(note())!.settings.arrival).toBe("locked"); + expect(note()).toContain("- Locked: rerolling it now needs God mode."); + const locked = snapshot(); + expect(await w.service.reroll(made)).toBe(false); + expect(snapshot()).toBe(locked); + + sys.workMode = "god"; + expect(await w.service.reroll(made)).toBe(true); + expect(sys.arrivalRerolls).toBe(2); + expect(sys.arrival).toBe("locked"); + }); + + it("rerolling is seeded too: the same reroll count gives the same place", async () => { + const run = async () => { + const w = world({ arrival: "make places", seed: 99 }); + await sectorWith(w, [["4_5", { terrain: "star system", onArrival: MAINWORLDS }]]); + const made = (await w.service.arrive("drift", 4, 5))!; + await w.service.reroll(made); + return [...w.p.mapStore.all(made)].map(([k, h]) => `${k}=${h.terrain ?? ""}`).join(","); + }; + expect(await run()).toBe(await run()); + }); +}); diff --git a/tests/arrivalSubmapSetup.test.ts b/tests/arrivalSubmapSetup.test.ts new file mode 100644 index 00000000..8fe3e735 --- /dev/null +++ b/tests/arrivalSubmapSetup.test.ts @@ -0,0 +1,162 @@ +/** + * Phase 4 (SP4, GM4): the arrival setting, seeds, the place's setup + * (row attributes → palette Submap defaults → engine), the write-up, and + * who may reroll a place made on arrival. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + arrivalLines, + arrivalSeed, + effectiveArrivalMode, + hashSeed, + parseArrivalMode, + placeSetup, + restateArrival, + rowSubmapDefault, + withArrivalSection, + type EngineDefaults, +} from "../src/arrival/arrival"; +import { ACTION_POLICY, allows, canRerollPlace, MENU_ACTIONS } from "../src/workMode"; + +const engine: EngineDefaults = { + palette: "Child palette", + cols: 13, + rows: 13, + generatorFor: (p) => (p === "Space - Planet" ? "procedural:planet-surface" : "procedural:region-detail"), + baseFor: (p) => (p === "Space - System" ? "void" : undefined), +}; + +describe("the arrival setting (on-arrival:)", () => { + it("reads forgivingly", () => { + for (const t of ["make places", "Make", "generate", "yes", " ON "]) expect(parseArrivalMode(t)).toBe("make"); + for (const t of ["off", "no", "Do nothing", "none"]) expect(parseArrivalMode(t)).toBe("off"); + expect(parseArrivalMode("maybe")).toBeUndefined(); + expect(parseArrivalMode(undefined)).toBeUndefined(); + }); + + it("is inherited down the map tree; unset everywhere = off", () => { + const maps: Record = { + root: { mode: "make places" }, sector: { parent: "root" }, system: { parent: "sector", mode: "off" }, planet: { parent: "system" }, alone: {}, + }; + const of = (m: string) => maps[m]?.mode; + const up = (m: string) => maps[m]?.parent; + expect(effectiveArrivalMode("sector", of, up)).toEqual({ mode: "make", from: "root" }); + expect(effectiveArrivalMode("planet", of, up)).toEqual({ mode: "off", from: "system" }); + expect(effectiveArrivalMode("alone", of, up)).toEqual({ mode: "off" }); + }); +}); + +describe("seeds", () => { + it("depend only on the parent's seed, the hex, the purpose and the reroll", () => { + expect(arrivalSeed(42, "4_7", "submap")).toBe(arrivalSeed(42, "4_7", "submap", 0)); + expect(arrivalSeed(42, "4_7", "submap", 1)).not.toBe(arrivalSeed(42, "4_7", "submap", 0)); + expect(arrivalSeed(42, "4_7", "arrival")).not.toBe(arrivalSeed(42, "4_7", "submap")); + expect(arrivalSeed(42, "4_8", "submap")).not.toBe(arrivalSeed(42, "4_7", "submap")); + expect(arrivalSeed(43, "4_7", "submap")).not.toBe(arrivalSeed(42, "4_7", "submap")); + expect(hashSeed("a", 1)).toBe(hashSeed("a", 1)); + expect(hashSeed("a", 1)).toBeGreaterThanOrEqual(0); + }); +}); + +describe("a place's setup: the rolled row, then Submap defaults, then the engine (SP4)", () => { + it("the row's attributes win, field by field", () => { + const s = placeSetup( + { Size: "20×14", Generator: "procedural:planet-surface", Options: "water=85, climate=lush", Palette: "Space - Planet", Base: "ocean" }, + { palette: "Other", cols: 9, rows: 9, generator: "procedural:orbits", options: { water: "10", relief: "rugged" }, baseTerrain: "regolith" }, + engine, 1, + ); + expect(s).toEqual({ + palette: "Space - Planet", cols: 20, rows: 14, generator: "procedural:planet-surface", + options: { water: "85", relief: "rugged", climate: "lush" }, baseTerrain: "ocean", + from: { palette: "row", size: "row", generator: "row", options: "row", base: "row" }, + }); + }); + + it("the palette's Submap defaults fill what the row doesn't say", () => { + const s = placeSetup({ Size: "16×10" }, { palette: "Space - System", generator: "procedural:orbits" }, engine, 1); + expect(s).toMatchObject({ palette: "Space - System", cols: 16, rows: 10, generator: "procedural:orbits", baseTerrain: "void" }); + expect(s.from).toEqual({ palette: "defaults", size: "row", generator: "defaults", options: "engine", base: "engine" }); + }); + + it("the engine's defaults for the chosen palette fill the rest", () => { + const s = placeSetup(undefined, undefined, engine, 1); + expect(s).toEqual({ palette: "Child palette", cols: 13, rows: 13, generator: "procedural:region-detail", options: {}, from: { palette: "engine", size: "engine", generator: "engine", options: "engine", base: "engine" } }); + // The engine's generator follows the palette the row picked. + expect(placeSetup({ Palette: "[[Space - Planet]]" }, undefined, engine, 1).generator).toBe("procedural:planet-surface"); + }); + + it("a size range is rolled from the seed: the same seed, the same size", () => { + const a = placeSetup({ Size: "16–24 × 10–14" }, undefined, engine, 99); + const b = placeSetup({ Size: "16–24 × 10–14" }, undefined, engine, 99); + expect([a.cols, a.rows]).toEqual([b.cols, b.rows]); + expect(a.cols).toBeGreaterThanOrEqual(16); + expect(a.cols).toBeLessThanOrEqual(24); + const sizes = new Set(Array.from({ length: 40 }, (_, i) => placeSetup({ Size: "16–24 × 10–14" }, undefined, engine, i).cols)); + expect(sizes.size).toBeGreaterThan(3); + }); + + it("Build's form starts from the same row (the smallest of a size range)", () => { + expect(rowSubmapDefault({ Size: "16–24 × 10–14", Generator: "preset-volcanic", Palette: "Space - Planet", Notes: "x" })).toEqual({ cols: 16, rows: 10, generator: "builtin:preset-volcanic", palette: "Space - Planet" }); + expect(rowSubmapDefault({ Notes: "x" })).toBeUndefined(); + expect(rowSubmapDefault(undefined)).toBeUndefined(); + }); +}); + +describe("the write-up in the new map's note", () => { + const report = { + date: "2026-10-11", parentNote: "_the-drift", hex: "4, 7", + rolled: { table: "world/tables/space/Default space/Sector/Mainworlds.md", result: "ocean world", chain: "Unexplored sector → Mainworlds → ocean world" }, + made: { generator: "Orbits", palette: "Space - System", cols: 13, rows: 13, seed: 1234 }, + }; + const note = "---\nhexmaker-map: 5\n---\n# Ocean world 4, 7\n\n## Hexes\n| Hex | Terrain |\n| --- | --- |\n| 0_0 | void |\n"; + + it("is plain text: what was rolled, and how the place was made", () => { + const lines = arrivalLines(report); + expect(lines[0]).toBe("## Arrival"); + expect(lines).toContain("- Rolled on [[world/tables/space/Default space/Sector/Mainworlds]]: ocean world (Unexplored sector → Mainworlds → ocean world)."); + expect(lines).toContain("- Made with Orbits on Space - System, 13×13, seed 1234."); + expect(lines.at(-1)).toMatch(/Not locked yet/); + expect(arrivalLines({ ...report, extra: ["Rare event: none"] })).toContain("- Rare event: none"); + }); + + it("goes at the end once, and is replaced (not repeated) when written again", () => { + const once = withArrivalSection(note, arrivalLines(report)); + expect(once.startsWith(note.trimEnd())).toBe(true); + const twice = withArrivalSection(once, arrivalLines(report)); + expect(twice).toBe(once); + expect(once.match(/## Arrival/g)).toHaveLength(1); + }); + + it("a reroll or a lock restates the status lines; everything else stays", () => { + const once = withArrivalSection(note, arrivalLines(report)).replace("- Made with", "My own line.\n- Made with"); + const rerolled = restateArrival(once, { made: { ...report.made, seed: 99 }, rerolls: 2, locked: false }); + expect(rerolled).toContain("My own line."); + expect(rerolled).toContain("seed 99."); + expect(rerolled).not.toContain("seed 1234."); + expect(rerolled).toContain("- Rerolled 2 times."); + const locked = restateArrival(rerolled, { rerolls: 2, locked: true }); + expect(locked).toContain("seed 99."); + expect(locked).toContain("- Locked: rerolling it now needs God mode."); + expect(locked).not.toContain("Not locked yet"); + expect(restateArrival(locked, { rerolls: 2, locked: true })).toBe(locked); + expect(restateArrival(note, { rerolls: 1, locked: true })).toBe(note); + }); +}); + +describe("who may make and reroll a place (GM4, work modes)", () => { + it("arriving somewhere new is allowed in every mode (only into places that don't exist)", () => { + expect(ACTION_POLICY.discover.modes).toEqual(["play", "build", "god"]); + expect(MENU_ACTIONS["hex.arrive"]).toBe("discover"); + expect(allows("play", "lock-place")).toBe(true); + }); + + it("reroll: any mode until locked; then only God", () => { + for (const workMode of ["play", "build", "god"]) expect(canRerollPlace({ workMode, arrival: "open" })).toBe(true); + expect(canRerollPlace({ workMode: "play", arrival: "locked" })).toBe(false); + expect(canRerollPlace({ workMode: "build", arrival: "locked" })).toBe(false); + expect(canRerollPlace({ workMode: "god", arrival: "locked" })).toBe(true); + // A map not made on arrival: the usual rule (reshape is God's). + expect(canRerollPlace({ workMode: "play" })).toBe(false); + }); +}); diff --git a/tests/freshEyesR5Setup.test.ts b/tests/freshEyesR5Setup.test.ts index 8f9ed8c5..507e2210 100644 --- a/tests/freshEyesR5Setup.test.ts +++ b/tests/freshEyesR5Setup.test.ts @@ -77,7 +77,7 @@ describe("1. New submap: starts on the generator that fits the parent hex", () = it("the setup modal applies it (and only for submaps)", () => { const src = read("src", "worldgen", "NewMapSetupModal.ts"); - expect(src).toMatch(/if \(where\.parentHex\) \{\n\s+this\.kindId = submapStartKind\(fitting, this\.kindId, \{\n\s+parentTerrain: this\.originTerrain,\n\s+savedGenerator: this\.saved\?\.generator,\n\s+picked: this\.pickedKind,/); + expect(src).toMatch(/if \(where\.parentHex\) \{\n\s+this\.kindId = submapStartKind\(fitting, this\.kindId, \{\n\s+parentTerrain: this\.originTerrain,\n\s+savedGenerator: this\.saved\?\.generator(?: \?\? this\.rowStart\?\.generator)?,\n\s+picked: this\.pickedKind,/); }); }); diff --git a/tests/mapNoteOnArrival.test.ts b/tests/mapNoteOnArrival.test.ts new file mode 100644 index 00000000..6d8cddcd --- /dev/null +++ b/tests/mapNoteOnArrival.test.ts @@ -0,0 +1,132 @@ +/** + * Phase 4, T6: the map note's optional "On arrival" column, the per-map + * generator tables (T11) and the arrival keys. Written only when needed, + * read forgivingly, kept through hand edits and a data.json reload (the + * path-loss incident class: missing ≠ empty). + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { buildMapNote, parseMapNote, updateMapNote, type HexData, type MapNoteData } from "../src/maps/mapNote"; +import { MapStore, withoutNotePaths } from "../src/maps/MapStore"; +import { MemVault } from "./helpers/memVault"; +import type { MapData } from "../src/types"; + +(globalThis as Record).window ??= globalThis; + +const data = (hexes: [string, HexData][], settings: MapNoteData["settings"] = {}): MapNoteData => ({ + settings: { paletteName: "Space - Sector", gridSize: { cols: 8, rows: 8 }, gridOffset: { x: 0, y: 0 }, ...settings }, + hexes: new Map(hexes), + paths: [], +}); + +describe("the On arrival column", () => { + it("is written only once some hex needs it, as a link", () => { + const plain = buildMapNote("drift", data([["1_1", { terrain: "garden world" }]])); + expect(plain).not.toContain("On arrival"); + const note = buildMapNote("drift", data([ + ["1_1", { terrain: "garden world" }], + ["4_7", { terrain: "star system", onArrival: "world/tables/space/Default space/Sector/Mainworlds" }], + ["5_2", { onArrival: "world/tables/space/Default space/Sector/Uncharted" }], + ])); + expect(note).toContain("| Hex | Name | Terrain | Icon | GM icons | Region | Locations | Locked | On arrival |"); + expect(note).toContain("| 4_7 | | star system | | | | | | [[world/tables/space/Default space/Sector/Mainworlds]] |"); + // A hex with nothing but an On arrival roll still gets its row. + expect(note).toContain("| 5_2 | | | | | | | | [[world/tables/space/Default space/Sector/Uncharted]] |"); + }); + + it("round-trips, and reads a hand-typed table (a plain name, a link with an alias)", () => { + const note = buildMapNote("drift", data([["4_7", { terrain: "star system", onArrival: "t/Mainworlds" }]])); + expect(parseMapNote(note)!.hexes.get("4_7")).toEqual({ terrain: "star system", onArrival: "t/Mainworlds" }); + const typed = note.replace("[[t/Mainworlds]]", "My table"); + expect(parseMapNote(typed)!.hexes.get("4_7")?.onArrival).toBe("My table"); + const header = note.replace("| On arrival |", "| Roll on arrival |"); + expect(parseMapNote(header)!.hexes.get("4_7")?.onArrival).toBe("t/Mainworlds"); + }); + + it("a cleared cell drops the column again on the next write", () => { + const note = buildMapNote("drift", data([["4_7", { terrain: "star system", onArrival: "t/Mainworlds" }]])); + const next = updateMapNote(note, "drift", data([["4_7", { terrain: "ocean world" }]])); + // The column stays while the note has it (the user's arrangement), empty. + expect(parseMapNote(next)!.hexes.get("4_7")).toEqual({ terrain: "ocean world" }); + }); +}); + +describe("map settings for arrival and generator tables", () => { + it("are plain keys, read back the same", () => { + const note = buildMapNote("drift", data([], { + seed: 1234, + arrivalMode: "make places", + arrival: "open", + arrivalRerolls: 2, + roleTables: { "sector-hexes": "world/tables/space/Default space/Sector/Unexplored sector.md", star: "t/Stars.md" }, + })); + expect(note).toContain("seed: 1234"); + expect(note).toContain("on-arrival: make places"); + expect(note).toContain("arrival: open"); + expect(note).toContain("arrival-rerolls: 2"); + expect(note).toContain('sector-hexes-table: "[[world/tables/space/Default space/Sector/Unexplored sector]]"'); + expect(note).toContain('star-table: "[[t/Stars]]"'); + const back = parseMapNote(note)!.settings; + expect(back).toMatchObject({ seed: 1234, arrivalMode: "make places", arrival: "open", arrivalRerolls: 2 }); + expect(back.roleTables).toEqual({ "sector-hexes": "world/tables/space/Default space/Sector/Unexplored sector.md", star: "t/Stars.md" }); + }); + + it("a map without them writes none of them", () => { + const note = buildMapNote("drift", data([])); + for (const k of ["seed:", "on-arrival:", "arrival:", "-table:"]) expect(note).not.toContain(k); + }); + + it("a role table key typed by hand is read (and an unknown role is the user's own key)", () => { + const note = buildMapNote("drift", data([])).replace("---\n# ", "inner-orbits-table: \"[[My orbits]]\"\nfoo-table: x\n---\n# "); + const back = parseMapNote(note)!.settings; + expect(back.roleTables).toEqual({ "inner-orbits": "My orbits.md" }); + expect(updateMapNote(note, "drift", parseMapNote(note)!)).toContain("foo-table: x"); + }); +}); + +describe("On arrival cells in the map store (missing ≠ empty)", () => { + const NOTE = "world/hexes/drift/_drift.md"; + const maps = (): MapData[] => [{ name: "drift", paletteName: "Space - Sector", gridSize: { cols: 8, rows: 8 }, gridOffset: { x: 0, y: 0 }, pathChains: [] } as MapData]; + const boot = async () => { + const v = new MemVault(); + const p = { + app: v.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", maps: maps() }, + getMap: (n: string) => p.settings.maps.find((m) => m.name === n), + saveData: async () => {}, + refreshHexMap: () => {}, + }; + const store = new MapStore(p as never); + await store.init(); + return { v, p, store }; + }; + + it("survive a data.json reload and a hand edit elsewhere in the note", async () => { + const { v, p, store } = await boot(); + store.setMany("drift", [["4_7", { terrain: "star system", onArrival: "t/Mainworlds" }], ["5_5", { onArrival: "t/Uncharted" }]]); + await store.flush(); + expect(parseMapNote(v.files.get(NOTE)!)!.hexes.get("5_5")).toEqual({ onArrival: "t/Uncharted" }); + // data.json reload: fresh map objects. + const disk = JSON.parse(JSON.stringify(withoutNotePaths(p.settings, (n) => store.holdsPaths(n)))) as { maps: MapData[] }; + p.settings = { ...p.settings, maps: disk.maps }; + store.adoptAll(); + await store.sync(); + expect(store.get("drift", "4_7")).toEqual({ terrain: "star system", onArrival: "t/Mainworlds" }); + // A hand edit to another hex. + v.files.set(NOTE, v.files.get(NOTE)!.replace("| 4_7 | | star system |", "| 4_7 | Kerrin | star system |")); + store.onModify(p.app.vault.getAbstractFileByPath(NOTE) as never); + await store.flush(); + expect(store.get("drift", "4_7")).toEqual({ name: "Kerrin", terrain: "star system", onArrival: "t/Mainworlds" }); + expect(store.get("drift", "5_5")).toEqual({ onArrival: "t/Uncharted" }); + }); + + it("clearing the cell (a roll on arrival) writes the hex without it", async () => { + const { v, store } = await boot(); + store.setMany("drift", [["4_7", { terrain: "star system", onArrival: "t/Mainworlds" }]]); + await store.flush(); + store.set("drift", "4_7", { terrain: "ocean world", onArrival: null }); + await store.flush(); + expect(parseMapNote(v.files.get(NOTE)!)!.hexes.get("4_7")).toEqual({ terrain: "ocean world" }); + }); +}); diff --git a/tests/tableRoles.test.ts b/tests/tableRoles.test.ts new file mode 100644 index 00000000..d9876be2 --- /dev/null +++ b/tests/tableRoles.test.ts @@ -0,0 +1,102 @@ +/** + * Phase 3, T11: where a role's table comes from. The map's own Tables + * win, inherited down the map tree; then the generator setup (World + * types / a converted set); a table that's gone falls through. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { inheritedRoleTables, layeredSource, notesTableSource, fittingRoleTables, attrsForTerrain } from "../src/worldgen/tableSources"; +import { notesLookup } from "../src/random-tables/resolve"; +import { roleOdds, rollRole } from "../src/worldgen/tableRoles"; +import { worldTypesSource } from "../src/space/worldTypesSource"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { SPACE_SECTOR_TERRAINS } from "../src/palettes/presets"; +import { tableNoteMarkdown } from "../src/space/spaceTables"; +import { parseRandomTable } from "../src/random-tables/randomTable"; +import { mulberry32 } from "../packages/hex-wfc/src/rng"; + +const tree: Record }> = { + root: { tables: { "sector-hexes": "t/Root sector.md", star: "t/Root stars.md" } }, + sector: { parent: "root", tables: { "sector-hexes": "t/Drift sector.md" } }, + system: { parent: "sector" }, + loopA: { parent: "loopB", tables: { star: "t/A.md" } }, + loopB: { parent: "loopA" }, +}; +const tablesOf = (m: string) => tree[m]?.tables; +const parentOf = (m: string) => tree[m]?.parent; + +describe("map tables, inherited down the map tree", () => { + it("a map's own table wins; the rest come from the nearest map above", () => { + expect(inheritedRoleTables("system", tablesOf, parentOf)).toEqual({ + "sector-hexes": { link: "t/Drift sector.md", from: "sector" }, + star: { link: "t/Root stars.md", from: "root" }, + }); + expect(inheritedRoleTables("root", tablesOf, parentOf)["sector-hexes"]).toEqual({ link: "t/Root sector.md", from: "root" }); + }); + + it("nothing set anywhere: nothing (and a parent loop stops)", () => { + expect(inheritedRoleTables("unknown", tablesOf, parentOf)).toEqual({}); + expect(inheritedRoleTables("loopB", tablesOf, parentOf)).toEqual({ star: { link: "t/A.md", from: "loopA" } }); + }); +}); + +const one = (name: string, weight = 1) => tableNoteMarkdown({ title: "x", description: "x", rows: "terrain", terrainTypes: ["world"], columns: [], entries: [{ result: name, weight }] }); + +describe("precedence: map → generator setup → equal odds", () => { + const notes = notesLookup({ "t/Only gardens.md": one("garden world"), "t/Other.md": one("ice world") }); + const terrains = SPACE_SECTOR_TERRAINS.map((t) => t.name); + const worlds = SPACE_SECTOR_TERRAINS.filter((t) => t.type === "world").map((t) => t.name); + const base = worldTypesSource({ name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }, SPACE_SECTOR_TERRAINS); + + it("the map's table replaces the setup's for that role only", () => { + const src = layeredSource(base, { "sector-hexes": "t/Only gardens.md" }, notes, terrains)!; + expect(roleOdds(src, "sector-hexes", {}, worlds).odds).toEqual([{ terrain: "garden world", odds: 1 }]); + expect(src.tableFor("star")).toBe(base.tableFor("star")); + const pick = rollRole(src, "sector-hexes", { rand: mulberry32(1) }, worlds); + expect(pick?.terrain).toBe("garden world"); + }); + + it("no map tables: the setup's source as it is", () => { + expect(layeredSource(base, {}, notes, terrains)).toBe(base); + }); + + it("a map table that's gone falls through to the setup's, and says so", () => { + const src = layeredSource(base, { "sector-hexes": "t/Deleted.md" }, notes, terrains)!; + expect(src.tableFor("sector-hexes")).toBe(base.tableFor("sector-hexes")); + expect(roleOdds(src, "sector-hexes", {}, worlds).notes.join(" ")).toMatch(/isn't there/); + }); + + it("no setup and no map table: equal odds", () => { + expect(layeredSource(undefined, {}, notes, terrains)).toBeUndefined(); + const odds = roleOdds(undefined, "sector-hexes", {}, ["a", "b"]); + expect(odds.from).toBe("equal odds"); + }); + + it("a map table with no setup under it still rolls", () => { + const src = layeredSource(undefined, { "sector-hexes": "t/Other.md" }, notes, terrains)!; + expect(roleOdds(src, "sector-hexes", {}, worlds).odds).toEqual([{ terrain: "ice world", odds: 1 }]); + }); + + it("finds a terrain's row (its map setup) in any role's table", () => { + const src = notesTableSource({ "inner-orbits": "t/Setup.md" }, notesLookup({ + "t/Setup.md": tableNoteMarkdown({ title: "x", description: "x", rows: "terrain", columns: ["Size"], entries: [{ result: "lava world", weight: 1, cells: { Size: "9×9" } }] }), + }), ["lava world"], "t"); + expect(attrsForTerrain(src, "lava world")).toEqual({ Size: "9×9" }); + expect(attrsForTerrain(src, "ice world")).toBeUndefined(); + }); +}); + +describe("the role table picker (T11, §2.5)", () => { + it("lists tables whose rows fit the role, the space folder first; rows: any tables are left out", () => { + const t = (fm: string) => parseRandomTable(`---\ndice: 0\n${fm}---\n| Result | Weight |\n| --- | --- |\n| a | 1 |\n`); + const tables = [ + { path: "w/t/zz/Gardens.md", table: t("rows: terrain\nterrain-type: world\n") }, + { path: "w/t/space/Set/Sector/Charted sector.md", table: t("rows: terrain\nterrain-type: world, station\n") }, + { path: "w/t/Encounters.md", table: t("") }, + { path: "w/t/space/Set/System/Stars.md", table: t("rows: terrain\nterrain-type: star\n") }, + { path: "w/t/Names.md", table: t("rows: text\n") }, + ]; + expect(fittingRoleTables(tables, "sector-hexes", "w/t/space")).toEqual(["w/t/space/Set/Sector/Charted sector.md", "w/t/zz/Gardens.md"]); + expect(fittingRoleTables(tables, "star", "w/t/space")).toEqual(["w/t/space/Set/System/Stars.md"]); + }); +}); diff --git a/tests/worldTypesConvert.test.ts b/tests/worldTypesConvert.test.ts new file mode 100644 index 00000000..35a4507d --- /dev/null +++ b/tests/worldTypesConvert.test.ts @@ -0,0 +1,205 @@ +/** + * Phase 3 (T1, T2, T4): a World types note converts into ordinary random + * table notes under {tables}/space// that give the same odds, the + * old note is kept (and marked, linking out), and converting is + * idempotent. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { SPACE_SECTOR_TERRAINS, SPACE_SYSTEM_TERRAINS } from "../src/palettes/presets"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { buildWorldTypes, parseWorldTypes, type WorldTypeTable } from "../src/space/worldTypes"; +import { worldTypesSource } from "../src/space/worldTypesSource"; +import { convertWorldTypes, isConverted, markConverted, readRoleTables, tableNoteMarkdown, wholeScale } from "../src/space/spaceTables"; +import { notesLookup, resolveOdds } from "../src/random-tables/resolve"; +import { parseRandomTableWithReport } from "../src/random-tables/randomTable"; +import { ENGINE_ROLES, roleOdds, rollRole, type RoleId } from "../src/worldgen/tableRoles"; +import { notesTableSource } from "../src/worldgen/tableSources"; +import { starScatter, starScatterRoles } from "../src/worldgen/procedural/starScatter"; +import { mulberry32 } from "../packages/hex-wfc/src/rng"; +import type { OrbitZone } from "../src/space/worldTypes"; + +const DEFAULT_SPACE: WorldTypeTable = { name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }; +const names = (ts: { name: string }[]) => ts.map((t) => t.name); + +function converted(table = DEFAULT_SPACE, opts: { shownAs?: string; unreadable?: string[] } = {}) { + const set = convertWorldTypes(table, { tablesFolder: "world/tables", shownAs: opts.shownAs ?? "star system", unreadable: opts.unreadable }); + const notes = Object.fromEntries(set.files.map((f) => [f.path, f.content])); + return { set, notes, lookup: notesLookup(notes) }; +} + +const sorted = (o: { terrain: string; odds: number }[]) => [...o].sort((a, b) => a.terrain.localeCompare(b.terrain)); +function expectSameOdds(a: { terrain: string; odds: number }[], b: { terrain: string; odds: number }[]) { + const A = sorted(a), B = sorted(b); + expect(A.map((x) => x.terrain)).toEqual(B.map((x) => x.terrain)); + A.forEach((x, i) => expect(Math.abs(x.odds - B[i].odds)).toBeLessThan(1e-9)); +} + +describe("converting a World types note to space tables", () => { + it("writes a tidy tree under {tables}/space// (T1)", () => { + const { set } = converted(); + expect(set.folder).toBe("world/tables/space/Default space"); + expect(set.files.map((f) => f.path.slice(set.folder.length + 1)).sort()).toEqual([ + "Sector/Charted sector.md", "Sector/Mainworlds.md", "Sector/Uncharted.md", "Sector/Unexplored sector.md", + "System/Habitable orbits.md", "System/Inner orbits.md", "System/Outer orbits.md", "System/Stars.md", + ]); + expect(Object.keys(set.roles).sort()).toEqual(ENGINE_ROLES.map((r) => r.id).sort()); + }); + + it("every table reads cleanly, with rows: terrain and roll ranges where the die fits", () => { + const { set } = converted(); + for (const f of set.files) { + const r = parseRandomTableWithReport(f.content); + expect({ path: f.path, issues: r.issues.map((i) => i.code) }).toEqual({ path: f.path, issues: [] }); + expect(r.table.rows).toBe("terrain"); + expect(r.table.entries.length).toBeGreaterThan(0); + } + // Weights made whole: 1/50, 1/75, 1/150 of a hex and the rest → 3, 2, 1, 144. + const charted = parseRandomTableWithReport(set.files.find((f) => f.path.endsWith("Charted sector.md"))!.content).table; + expect(charted.entries.map((e) => e.weight)).toEqual([3, 2, 1, 144]); + expect(charted.entries[3].isLink).toBe(true); + }); + + it("gives the same odds as the note did, for every role (T4)", () => { + const { set, lookup } = converted(); + const sector = notesTableSource(set.roles, lookup, names(SPACE_SECTOR_TERRAINS), "t"); + const system = notesTableSource(set.roles, lookup, names(SPACE_SYSTEM_TERRAINS), "t"); + const oldSector = worldTypesSource(DEFAULT_SPACE, SPACE_SECTOR_TERRAINS); + const oldSystem = worldTypesSource(DEFAULT_SPACE, SPACE_SYSTEM_TERRAINS); + const worlds = starScatterRoles(SPACE_SECTOR_TERRAINS)!.worlds; + expectSameOdds(roleOdds(sector, "sector-hexes", {}, worlds).odds, roleOdds(oldSector, "sector-hexes", {}, worlds).odds); + const stars = SPACE_SYSTEM_TERRAINS.filter((t) => t.type === "star").map((t) => t.name); + expectSameOdds(roleOdds(system, "star", {}, stars).odds, roleOdds(oldSystem, "star", {}, stars).odds); + const bodies = SPACE_SYSTEM_TERRAINS.filter((t) => ["world", "gas-giant", "asteroids"].includes(t.type ?? "")).map((t) => t.name); + const zoneRole: Record = { inner: "inner-orbits", habitable: "habitable-orbits", outer: "outer-orbits" }; + for (const zone of ["inner", "habitable", "outer"] as OrbitZone[]) { + for (const star of ["red dwarf", "yellow star"]) { + expectSameOdds(roleOdds(system, zoneRole[zone], { zone, star }, bodies).odds, roleOdds(oldSystem, zoneRole[zone], { zone, star }, bodies).odds); + } + } + }); + + it("keeps each row's setup (Mainworld, Size, Generator…) as attributes", () => { + const { set, lookup } = converted(); + const src = notesTableSource(set.roles, lookup, names(SPACE_SECTOR_TERRAINS), "t"); + expect(src.rowAttrs("sector-hexes", "ocean world")).toMatchObject({ Mainworld: "ocean planet", Size: "13×13", Generator: "procedural:orbits", Palette: "Space - System", Base: "void" }); + const sys = notesTableSource(set.roles, lookup, names(SPACE_SYSTEM_TERRAINS), "t"); + expect(sys.rowAttrs("habitable-orbits", "ocean planet")).toMatchObject({ Size: "20×14", Generator: "procedural:planet-surface", Options: "water=85, climate=lush, relief=normal" }); + }); + + it("Unexplored sector: half the systems wait for arrival, shown as the star-system terrain or not at all (T5)", () => { + const { set, lookup } = converted(); + const roles = { ...set.roles, "sector-hexes": set.files.find((f) => f.path.endsWith("Unexplored sector.md"))!.path }; + const src = notesTableSource(roles, lookup, names(SPACE_SECTOR_TERRAINS), "t"); + const worlds = starScatterRoles(SPACE_SECTOR_TERRAINS)!.worlds; + const counts = { now: 0, known: 0, uncharted: 0 }; + const rand = mulberry32(7); + for (let i = 0; i < 4000; i++) { + const p = rollRole(src, "sector-hexes", { rand, deferArrival: true }, worlds)!; + if (!p.arrival) counts.now++; + else if (p.terrain === "star system") { counts.known++; expect(p.arrival).toMatch(/Mainworlds$/); } + else { counts.uncharted++; expect(p.terrain).toBe(""); expect(p.arrival).toMatch(/Uncharted$/); } + } + expect(counts.known / 4000).toBeGreaterThan(0.2); + expect(counts.uncharted / 4000).toBeGreaterThan(0.2); + expect(counts.now / 4000).toBeGreaterThan(0.45); + // Rolled through (no deferring), the same table gives only real terrains or nothing. + const through = resolveOdds(roles["sector-hexes"], lookup, { terrains: names(SPACE_SECTOR_TERRAINS), onlyTerrains: true }); + expect(through.every((o) => o.kind === "terrain" || o.kind === "nothing")).toBe(true); + }); + + it("Star scatter leaves On arrival hexes for the unknown ones", () => { + const { set, lookup } = converted(); + const roles = { ...set.roles, "sector-hexes": set.files.find((f) => f.path.endsWith("Unexplored sector.md"))!.path }; + const src = notesTableSource(roles, lookup, names(SPACE_SECTOR_TERRAINS), "t"); + const grid = { cols: 12, rows: 12, offset: { x: 0, y: 0 }, stagger: "odd" as const, orientation: "flat" as const }; + const a = starScatter(SPACE_SECTOR_TERRAINS, grid, 3, { density: "dense", clouds: "none", routes: "none" }, undefined, src); + const b = starScatter(SPACE_SECTOR_TERRAINS, grid, 3, { density: "dense", clouds: "none", routes: "none" }, undefined, src); + expect(a.arrivals?.size).toBeGreaterThan(0); + expect([...a.arrivals!]).toEqual([...b.arrivals!]); + for (const [k, table] of a.arrivals!) { + expect(table).toMatch(/(Mainworlds|Uncharted)$/); + // Shown as "star system", or the background when uncharted. + expect(["star system", "empty space"]).toContain(a.cells.get(k)); + } + // The charted table leaves none. + const charted = notesTableSource(set.roles, lookup, names(SPACE_SECTOR_TERRAINS), "t"); + expect(starScatter(SPACE_SECTOR_TERRAINS, grid, 3, { density: "dense", clouds: "none", routes: "none" }, undefined, charted).arrivals).toBeUndefined(); + }); + + it("copies rows that couldn't be read into the Mainworlds note", () => { + const { set } = converted(DEFAULT_SPACE, { unreadable: ["| bad world | lots |"] }); + expect(set.files.find((f) => f.path.endsWith("Mainworlds.md"))!.content).toContain("| bad world | lots |"); + }); + + it("never special-cases names: a custom table converts the same way", () => { + const custom: WorldTypeTable = { name: "Drift", rows: [{ world: "glass world", weight: 2, map: "sector" }, { world: "rust world", weight: 1 }], features: [{ feature: "beacon", chance: 0.1 }] }; + const { set, lookup } = converted(custom, { shownAs: "" }); + const src = notesTableSource(set.roles, lookup, ["void", "glass world", "rust world", "beacon"], "t"); + const odds = roleOdds(src, "sector-hexes", {}, ["glass world", "rust world"]).odds; + expectSameOdds(odds, [{ terrain: "beacon", odds: 0.1 }, { terrain: "glass world", odds: 0.6 }, { terrain: "rust world", odds: 0.3 }]); + // No Stars table in the note: no Stars table written, and the role stays unset. + expect(set.roles.star).toBeUndefined(); + expect(set.files.find((f) => f.path.endsWith("Unexplored sector.md"))!.content).not.toContain("Shown as"); + }); +}); + +describe("the World types note after converting (T2)", () => { + const note = buildWorldTypes("Default space", DEFAULT_WORLD_TYPE_ROWS, DEFAULT_WORLD_TYPE_EXTRAS); + + it("links out to the tables, embeds them, and is marked converted", () => { + const { set } = converted(); + const out = markConverted(note, set); + expect(isConverted(note)).toBe(false); + expect(isConverted(out)).toBe(true); + expect(out).toContain('converted-to: "world/tables/space/Default space"'); + expect(out).toContain("## Tables"); + expect(out).toContain("![[world/tables/space/Default space/Sector/Charted sector]]"); + const roles = readRoleTables(out); + expect(roles["sector-hexes"]).toBe("world/tables/space/Default space/Sector/Charted sector"); + expect(roles["outer-orbits"]).toBe("world/tables/space/Default space/System/Outer orbits"); + }); + + it("keeps every old row readable, as before", () => { + const { set } = converted(); + const before = parseWorldTypes(note); + const after = parseWorldTypes(markConverted(note, set)); + expect(after.rows).toEqual(before.rows); + expect(after.stars).toEqual(before.stars); + expect(after.features).toEqual(before.features); + expect(after.problems).toEqual(before.problems); + }); + + it("is idempotent: converting again changes nothing", () => { + const { set } = converted(); + const once = markConverted(note, set); + expect(markConverted(once, set)).toBe(once); + // CRLF notes stay CRLF. + const crlf = markConverted(note.replace(/\n/g, "\r\n"), set); + expect(crlf.includes("\n") && !/[^\r]\n/.test(crlf)).toBe(true); + }); + + it("a hand edit of the role list is what counts", () => { + const { set } = converted(); + const out = markConverted(note, set).replace("Sector/Charted sector\\|Charted sector]]", "Sector/Unexplored sector\\|Unexplored sector]]"); + expect(readRoleTables(out)["sector-hexes"]).toBe("world/tables/space/Default space/Sector/Unexplored sector"); + }); +}); + +describe("table notes as written", () => { + it("scales weights to whole numbers only when that keeps the odds exact", () => { + expect(wholeScale([1 / 50, 1 / 75, 1 / 150, 144 / 150])).toBe(150); + expect(wholeScale([3.5, 1.5, 2])).toBe(2); + expect(wholeScale([Math.PI])).toBe(1); + }); + + it("uses a die only when the weights add up to one", () => { + const t = tableNoteMarkdown({ title: "T", description: "d", columns: [], entries: [{ result: "a", weight: 3 }, { result: "b", weight: 1 }] }); + expect(t).toContain("dice: 4"); + expect(t).toContain("| d4 | Result | Weight |"); + expect(t).toContain("| 1–3 | a | 3 |"); + const u = tableNoteMarkdown({ title: "T", description: "d", columns: [], entries: [{ result: "a", weight: 3 }, { result: "b", weight: 2 }] }); + expect(u).toContain("dice: 0"); + expect(u).toContain("| Result | Weight |"); + }); +}); From a15817285d9819656e26174c3bbf85cff866115e Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 12:43:03 -0400 Subject: [PATCH 310/558] feat: map-made tables grouped in pickers; breadcrumb never crowds the top +/- MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Table pickers (Random Tables tree, workflow step and roll dropdowns, the hex table's Encounters picker) list the user's own tables first and the terrain/region tables the map made under one collapsed "Made by the map" group. They are told apart by their table-type frontmatter (description / encounters), via tableMadeBy + tableFitsWant's mapMade option and groupTablesForPicker; never by name. The map toolbar row stops short of the centred top +/- buttons; crumbs shrink with an ellipsis, the middle ones fold into "…" (tooltip lists them, click goes one up), and when the row's own buttons don't fit the +/- move to the second row. Checked in a sandbox on a 4-deep map at several widths. README/help updated for these and the reference links. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 ++- package.json | 4 +- src/hex-map/HexMapView.ts | 64 +++++++++++++++++-- src/hex-map/help.md | 6 +- src/hex-table/LinkPickerModal.ts | 26 ++++++-- src/notePickers.ts | 24 +++++++ src/random-tables/RandomTableModal.ts | 10 ++- src/random-tables/RandomTableView.ts | 48 ++++++++++++-- src/random-tables/WorkflowEditorModal.ts | 38 +++++------ src/random-tables/resolve.ts | 43 ++++++++++++- src/random-tables/tablePickerGroups.ts | 12 ++++ styles.css | 81 +++++++++++++++++++++++- tests/tablePickerGroups.test.ts | 52 +++++++++++++++ 13 files changed, 374 insertions(+), 43 deletions(-) create mode 100644 src/random-tables/tablePickerGroups.ts create mode 100644 tests/tablePickerGroups.test.ts diff --git a/README.md b/README.md index 03844cd0..0391d5f4 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ Open via **Command palette → "Hexmap World Creator: Open random tables"** or t A two-panel view for managing and rolling on random tables. -- **Left panel** — shows all `.md` files in the configured Tables folder as a collapsible folder tree. Click a folder header to expand or collapse it. Click a table to load it. The filter input at the top narrows results and temporarily expands all folders. **+ New** creates a file from the default template. +- **Left panel** — shows all `.md` files in the configured Tables folder as a collapsible folder tree. Click a folder header to expand or collapse it. Click a table to load it. The filter input at the top narrows results and temporarily expands all folders. **+ New** creates a file from the default template. Your own tables come first; the description and encounter tables the map makes for every terrain, and the encounter table for every region, sit in one collapsed **Made by the map** section at the end (so do the workflow step and roll dropdowns, and the hex table's Encounters picker). They're told apart by their `table-type: description` / `encounters` line: delete it and the table counts as yours. - **Right panel** — shows the table's entries with their roll ranges and odds. **Roll** rolls the die, highlights the row and shows the face (e.g. `d20 → 14`) and the result. The result is editable before use. Roll history shows the last 5 results. - **Change die** dropdown — updates the `dice:` frontmatter and redoes the roll column for the new die. - **Problems** — if the ranges and weights disagree, or a range can't be read, a banner says so, with one-click fixes (**Keep ranges → set weights**, **Keep weights → redo ranges**). @@ -413,8 +413,13 @@ Older notes say `hexmaker-map: "[[_Overworld]]"` (map notes use `hexmaker-map:` | Token notes: the map a token is on | `token-map: coast` | `token-map: "[[_coast]]"` | | Second tokens for a note: the note they stand for | `token-link: world/npcs/Ana.md` | `token-link: "[[world/npcs/Ana]]"` | | Workflows: their template | `template-file: world/workflows/templates/npc.md` | `template-file: "[[world/workflows/templates/npc]]"` | +| Map notes: the palette (and region palette) | `palette: Default` | `palette: "[[world/palettes/Default]]"` | +| Palette notes: the palette for submaps | `child-palette: Space - System` | `child-palette: "[[world/palettes/Space - System]]"` | +| Generators: palette, source region(s), blended generators | `palette: Default`, `source-maps: coast + north`, `blend-of: valley + forest` | `palette: "[[world/palettes/Default]]"`, `source-maps: ["[[_coast]]", "[[_north]]"]`, `blend-of: ["[[world/generators/valley]]", "[[world/generators/forest]]"]` | +| Generator saves: their generator | `generator-path: world/generators/valley.md` | `generator-path: "[[world/generators/valley]]"` | +| World types tables: the Palette column | `Space - Planet` | `[[world/palettes/Space - Planet]]` | -Before changing anything, the full text of every note it changes is saved in the plugin folder's `backups/note-formats-/` (one gzipped file per change). Each change runs once per vault (recorded in `data.json`); a vault with nothing to change has no note written. The old forms are still read, so notes from another device on an older version keep working. Notes skipped on purpose (a `map:` key of your own, a link to a note that doesn't exist) are listed in a notice. +Before changing anything, the full text of every note it changes is saved in the plugin folder's `backups/note-formats-/` (one gzipped file per change). Each change runs once per vault (recorded in `data.json`); a vault with nothing to change has no note written. The old forms are still read, so notes from another device on an older version keep working. Notes skipped on purpose (a `map:` key of your own, a link to a note that doesn't exist) are listed in a notice. A palette, map or generator name that names no note (a palette that isn't installed, a shipped generator) stays as you wrote it. New notes and saves are written with links, so renaming a palette, map or generator note in Obsidian updates everything that names it. **Sections** (used by the editor and table view): diff --git a/package.json b/package.json index 3fb525d3..39080337 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 100204b3..d5e09ea8 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -685,16 +685,32 @@ export class HexMapView extends ItemView { if (!crumbs) return; crumbs.empty(); const ancestors = mapAncestors(this.activeMapName, (m) => this.plugin.parentOf(m)?.map); - for (const name of ancestors) { + // The crumbs between the first and the last fold into one "…" when the + // row is too narrow for them (fitTopBar); its tooltip and menu list them. + const middle = ancestors.slice(1, -1); + ancestors.forEach((name, i) => { const label = this.plugin.mapLabel(name); + const isMiddle = i > 0 && i < ancestors.length - 1; const crumb = crumbs.createEl("button", { - cls: "duckmage-map-crumb", + cls: `duckmage-map-crumb${isMiddle ? " duckmage-map-crumb-mid" : ""}`, text: label, attr: { title: `Go to ${label}` }, }); crumb.addEventListener("click", () => this.navigateToMap(name)); - crumbs.createSpan({ cls: "duckmage-map-crumb-sep", text: "›" }); - } + crumbs.createSpan({ cls: `duckmage-map-crumb-sep${isMiddle ? " duckmage-map-crumb-mid" : ""}`, text: "›" }); + if (i === 0 && middle.length) { + // Stands for the folded crumbs: the tooltip names them all, a click + // goes to the nearest of them (one up from the last crumb shown). + const nearest = middle[middle.length - 1]; + const more = crumbs.createEl("button", { + cls: "duckmage-map-crumb duckmage-map-crumb-more", + text: "…", + attr: { title: `${middle.map((m) => this.plugin.mapLabel(m)).join(" › ")}\nGo to ${this.plugin.mapLabel(nearest)}` }, + }); + more.addEventListener("click", () => this.navigateToMap(nearest)); + crumbs.createSpan({ cls: "duckmage-map-crumb-sep duckmage-map-crumb-more", text: "›" }); + } + }); // What the hex this map was made from is ("from: barren world"), read // from the parent's map data (F11: a sector's world type was nowhere // in the system map made from it). @@ -707,6 +723,46 @@ export class HexMapView extends ItemView { }); } crumbs.toggle(ancestors.length > 0); + this.fitTopBar(); + } + + /** The map's view changed size: the top toolbar row may need to fold its breadcrumb. */ + onResize(): void { + this.fitTopBar(); + } + + /** + * Keep the toolbar row clear of the top +/− buttons (the breadcrumb with + * its "from: …" crowded them on deep maps). CSS caps the row short of the + * side-panel buttons and lets the crumbs shrink (each with an ellipsis + * and its full name in the tooltip); when they don't fit whole, the + * middle ones fold into "…"; when the row still reaches the centred + * +/− buttons, those move to the second row's right side. Classes are + * reset first, then read. + */ + private fitTopBar(): void { + const crumbs = this.crumbsEl; + const nav = crumbs?.parentElement; + const controls = nav?.parentElement; + if (!crumbs || !nav || !controls) return; + const top = controls.querySelector(":scope > .duckmage-expand-group-top"); + const cut = (el: Element) => el.scrollWidth > el.clientWidth + 1; + const fold = () => { + crumbs.removeClass("is-folded"); + // Folded as soon as the crumbs don't fit whole (one is cut short or the row overflows). + if (crumbs.querySelector(".duckmage-map-crumb-mid") && (cut(crumbs) || Array.from(crumbs.children).some(cut))) crumbs.addClass("is-folded"); + }; + // First try: the row stops short of the centred +/- buttons. + nav.addClass("is-centred"); + controls.removeClass("duckmage-top-crowded"); + if (!nav.isConnected || nav.clientWidth === 0 || !top) { fold(); return; } + fold(); + const right = Math.max(...Array.from(nav.children).map((c) => c.getBoundingClientRect().right)); + if (!cut(nav) && right + 8 <= top.getBoundingClientRect().left) return; + // The row's own buttons don't fit there: it takes the width and the +/- move down. + nav.removeClass("is-centred"); + controls.addClass("duckmage-top-crowded"); + fold(); } /** diff --git a/src/hex-map/help.md b/src/hex-map/help.md index ba1a7e84..42c235e8 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -189,7 +189,11 @@ Pickers that link notes (to hexes, tokens, sections) never offer template notes On **space maps** (a palette with space terrain types, or a map under one), the hex editor, hex table, badge legend and exports call the link sections **Settlements**, **Sites**, **Points of Interest** and **Missions** instead of Towns, Dungeons, Features and Quests. Only the labels change: notes keep their usual headings, so links keep working. -Every new terrain (from the terrain tool, the palette editor, a new palette or a palette note) gets its description and encounter tables right away, empty. Renaming a terrain renames its tables. +Every new terrain (from the terrain tool, the palette editor, a new palette or a palette note) gets its description and encounter tables right away, empty. Renaming a terrain renames its tables. Table pickers (the Random Tables list, workflow steps, the roll dropdown) list your own tables first and these, with the region encounter tables, under a collapsed **Made by the map** heading. + +**Links between plugin notes.** A map note's palette, a palette's child palette, a generator's palette, source regions and blended generators, a save's generator and a world types row's Palette are links to those notes (`palette: "[[world/palettes/Default]]"`), so renaming one in Obsidian updates them. Plain names still read. Older notes were converted once, after a backup. + +**Deep maps.** When the breadcrumb doesn't fit beside the top **+** / **−** buttons, its middle maps fold into **…** (hover to see them, click to go one level up from the last one shown). **Templates**: the plugin keeps its note templates in one folder (**Settings → Templates folder**, `templates` in the world folder by default): `hex.md` for hex notes and `town.md` for new towns made from the hex editor. Edit them there and new notes follow. diff --git a/src/hex-table/LinkPickerModal.ts b/src/hex-table/LinkPickerModal.ts index 6b07ddb6..6b9dab09 100644 --- a/src/hex-table/LinkPickerModal.ts +++ b/src/hex-table/LinkPickerModal.ts @@ -5,6 +5,8 @@ import { normalizeFolder } from "../utils"; import { addLinkToSection, addBacklinkToFile } from "../sections"; import type { LinkSection } from "../types"; import { LOCATION_SECTIONS } from "../noteTemplates"; +import { groupTableFiles } from "../random-tables/tablePickerGroups"; +import { MAP_MADE_GROUP_LABEL } from "../random-tables/resolve"; export class LinkPickerModal extends HexmakerModal { constructor( @@ -32,18 +34,28 @@ export class LinkPickerModal extends HexmakerModal { .filter((f) => this.plugin.isLinkableNote(f)) .sort((a, b) => a.basename.localeCompare(b.basename)); + // Tables: the user's own first; the terrain and region tables the map + // made sit in a collapsed "Made by the map" group after them. + const { own, mapMade } = this.section === "Encounters Table" + ? groupTableFiles(this.app, files) + : { own: files, mapMade: [] as TFile[] }; + const addItems = (list: HTMLElement, items: TFile[]) => { + for (const file of items) { + const li = list.createEl("li", { cls: "duckmage-link-picker-item" }); + li.setText(file.basename); + li.addEventListener("click", () => { void this.addLink(file); }); + } + }; if (files.length > 0) { contentEl.createEl("p", { text: "Select existing:", cls: "duckmage-link-picker-heading", }); - const list = contentEl.createEl("ul", { - cls: "duckmage-link-picker-list", - }); - for (const file of files) { - const li = list.createEl("li", { cls: "duckmage-link-picker-item" }); - li.setText(file.basename); - li.addEventListener("click", () => { void this.addLink(file); }); + if (own.length) addItems(contentEl.createEl("ul", { cls: "duckmage-link-picker-list" }), own); + if (mapMade.length) { + const group = contentEl.createEl("details", { cls: "duckmage-link-picker-map-made" }); + group.createEl("summary", { text: `${MAP_MADE_GROUP_LABEL} (${mapMade.length})` }); + addItems(group.createEl("ul", { cls: "duckmage-link-picker-list" }), mapMade); } } diff --git a/src/notePickers.ts b/src/notePickers.ts index 822b68b0..9c8983a2 100644 --- a/src/notePickers.ts +++ b/src/notePickers.ts @@ -12,6 +12,9 @@ * Pure: no Obsidian imports. */ +import { tableFitsWant, type TableMaker, type TableWant } from "./random-tables/resolve"; +import type { RandomTable } from "./random-tables/randomTable"; + /** A content folder setting. */ export type ContentFolderKey = | "townsFolder" @@ -84,5 +87,26 @@ export function inAnyFolder(path: string, folders: readonly string[]): boolean { return folders.some((f) => !!f && p.startsWith(f.toLowerCase() + "/")); } +/** + * A table picker's list in two parts, order kept: the user's own tables, + * then the ones the map made (tableFitsWant's "map" group: terrain and + * region tables, marked by their frontmatter). Pickers show the user's + * first and the map's under one "Made by the map" heading, collapsed where + * the picker can collapse. Tables that don't fit the want are left out. + */ +export function groupTablesForPicker( + items: readonly T[], + tableOf: (item: T) => Pick & { madeBy?: TableMaker }, + want: TableWant = { mapMade: "group" }, +): { own: T[]; mapMade: T[] } { + const own: T[] = [], mapMade: T[] = []; + for (const item of items) { + const r = tableFitsWant(tableOf(item), want); + if (r.fit === "no") continue; + (r.group === "map" ? mapMade : own).push(item); + } + return { own, mapMade }; +} + /** Files the table editor's Import… can read: text with one entry per list item or line. */ export const IMPORT_LIST_EXTENSIONS = ["md", "txt", "csv"]; diff --git a/src/random-tables/RandomTableModal.ts b/src/random-tables/RandomTableModal.ts index 213b25c5..afb700ff 100644 --- a/src/random-tables/RandomTableModal.ts +++ b/src/random-tables/RandomTableModal.ts @@ -5,6 +5,8 @@ import { normalizeFolder } from "../utils"; import { parseRandomTable, rollTable, rollLabel, resolveTable, rowOdds, dieLabel, emptyTableMessage } from "./randomTable"; import { VIEW_TYPE_RANDOM_TABLES } from "../constants"; import { RandomTableEditorModal } from "./RandomTableEditorModal"; +import { groupTableFiles } from "./tablePickerGroups"; +import { MAP_MADE_GROUP_LABEL } from "./resolve"; /** * "Add to this hex" target for a roll made from a hex (P2): which sections @@ -117,9 +119,15 @@ export class RandomTableModal extends HexmakerModal { cls: "duckmage-roll-modal-select", }); select.createEl("option", { value: "", text: "— choose a table —" }); - for (const file of files) { + // The user's tables first; any the map made (when not filtered out) grouped after them. + const { own, mapMade } = groupTableFiles(this.app, files); + for (const file of own) { select.createEl("option", { value: file.path, text: file.basename }); } + if (mapMade.length) { + const group = select.createEl("optgroup", { attr: { label: MAP_MADE_GROUP_LABEL } }); + for (const file of mapMade) group.createEl("option", { value: file.path, text: file.basename }); + } // "Open in roller" link — hidden until a table is selected const openLink = contentEl.createEl("a", { diff --git a/src/random-tables/RandomTableView.ts b/src/random-tables/RandomTableView.ts index e90e38c1..d53dcee1 100644 --- a/src/random-tables/RandomTableView.ts +++ b/src/random-tables/RandomTableView.ts @@ -38,6 +38,8 @@ import { } from "./randomTable"; import { planTableMigration } from "./tableMigration"; import { processTableNote } from "./TableStore"; +import { groupTableFiles } from "./tablePickerGroups"; +import { MAP_MADE_GROUP_LABEL } from "./resolve"; import { parseWorkflow, generateDefaultTemplate } from "./workflow"; import { resolveWorkflowTemplate } from "./workflowFiles"; import { Frontmatter } from "../frontmatter"; @@ -48,6 +50,9 @@ import { exportRandomTableAsMarkdown, } from "../export/exporters/randomTable"; +/** Collapse key (and key prefix) of the tree's "Made by the map" section. */ +const MAP_MADE_KEY = "map-made:"; + export const DIE_OPTIONS = [ { label: "— no die —", value: 0 }, { label: "d4", value: 4 }, @@ -705,23 +710,54 @@ export class RandomTableView extends ItemView { return; } - const tree = buildTree(files, prefix, vaultFolderPaths); + // The user's own tables first; the terrain and region tables the map + // made go under one collapsed "Made by the map" section at the end. + const { own, mapMade } = groupTableFiles(this.app, files); + // A folder holding only the map's tables isn't listed among the user's. + const under = (f: TFile, folderPath: string) => f.path.startsWith(folderPath + "/"); + const ownFolders = vaultFolderPaths.filter((p) => own.some((f) => under(f, p)) || !mapMade.some((f) => under(f, p))); + const tree = buildTree(own, prefix, ownFolders); + const mapTree = buildTree(mapMade, prefix); // Collapse all folders on first load if (!this.treeInitialized) { this.treeInitialized = true; - const collectFolders = (nodes: TreeNode[]) => { + const collectFolders = (nodes: TreeNode[], keyPrefix = "") => { for (const n of nodes) if (n.type === "folder") { - this.collapsedFolders.add(n.path); - collectFolders(n.children); + this.collapsedFolders.add(keyPrefix + n.path); + collectFolders(n.children, keyPrefix); } }; collectFolders(tree); + collectFolders(mapTree, MAP_MADE_KEY); + this.collapsedFolders.add(MAP_MADE_KEY); } // When filtering, render flat (expand all) so matches aren't hidden inside collapsed folders - this.renderTreeNodes(this.listEl, tree, this.filterQuery !== ""); + const forceExpanded = this.filterQuery !== ""; + this.renderTreeNodes(this.listEl, tree, forceExpanded); + if (mapMade.length) this.renderMapMadeSection(this.listEl, mapTree, mapMade.length, forceExpanded); + } + + /** The "Made by the map" section: one collapsible folder holding the map's own tables. */ + private renderMapMadeSection(container: HTMLElement, nodes: TreeNode[], count: number, forceExpanded: boolean): void { + const section = container.createDiv({ cls: "duckmage-rt-folder duckmage-rt-map-made" }); + const header = section.createDiv({ cls: "duckmage-rt-folder-header" }); + const collapsed = !forceExpanded && this.collapsedFolders.has(MAP_MADE_KEY); + const arrow = header.createSpan({ cls: "duckmage-rt-folder-arrow", text: collapsed ? "▶" : "▼" }); + header.createSpan({ cls: "duckmage-rt-folder-name", text: `${MAP_MADE_GROUP_LABEL} (${count})` }); + header.title = "Description and encounter tables made for each terrain, and encounter tables made for each region. Delete a table's table-type line to make it your own."; + const children = section.createDiv({ cls: "duckmage-rt-folder-children" }); + if (collapsed) children.hide(); + this.renderTreeNodes(children, nodes, forceExpanded, MAP_MADE_KEY); + header.addEventListener("click", () => { + const nowCollapsed = !this.collapsedFolders.has(MAP_MADE_KEY); + if (nowCollapsed) this.collapsedFolders.add(MAP_MADE_KEY); + else this.collapsedFolders.delete(MAP_MADE_KEY); + children.toggle(!nowCollapsed); + arrow.setText(nowCollapsed ? "▶" : "▼"); + }); } private rebuildWorkflowMap(allFiles?: TFile[]): void { @@ -1070,9 +1106,11 @@ export class RandomTableView extends ItemView { container: HTMLElement, nodes: TreeNode[], forceExpanded: boolean, + keyPrefix = "", ): void { renderFolderTree(container, nodes, { collapsedFolders: this.collapsedFolders, + keyPrefix, activeFile: this.activeFile, forceExpanded, onFileClick: (file) => void this.loadTable(file), diff --git a/src/random-tables/WorkflowEditorModal.ts b/src/random-tables/WorkflowEditorModal.ts index ed558331..21997e5a 100644 --- a/src/random-tables/WorkflowEditorModal.ts +++ b/src/random-tables/WorkflowEditorModal.ts @@ -17,6 +17,8 @@ import { } from "./workflow"; import { newTemplatePath, resolveWorkflowTemplate, stepDieLabels } from "./workflowFiles"; import { noteLink } from "../noteFormats"; +import { groupTableFiles } from "./tablePickerGroups"; +import { MAP_MADE_GROUP_LABEL } from "./resolve"; import { escapeRegex, placeholderPattern } from "../textUtils"; /** Convert a table basename to a default label: spaces → underscores. */ @@ -77,6 +79,22 @@ export class WorkflowEditorModal extends HexmakerModal { .filter((f) => !tablesFolder || f.path.startsWith(tablesFolder + "/")) .filter((f) => !f.basename.startsWith("_")) .sort((a, b) => a.path.localeCompare(b.path)); + // The user's tables first; the terrain and region tables the map made + // in a "Made by the map" group at the end of each table dropdown. + const tableGroups = groupTableFiles(this.app, tableFiles); + const addTableOptions = (select: HTMLSelectElement, selected?: string) => { + const add = (parent: HTMLElement, tf: TFile) => { + const val = tf.path.slice(0, -3); + const text = tablesFolder ? tf.path.slice(tablesFolder.length + 1, -3) : val; + const opt = parent.createEl("option", { value: val, text }); + if (val === selected) opt.selected = true; + }; + for (const tf of tableGroups.own) add(select, tf); + if (tableGroups.mapMade.length) { + const group = select.createEl("optgroup", { attr: { label: MAP_MADE_GROUP_LABEL } }); + for (const tf of tableGroups.mapMade) add(group, tf); + } + }; // ── Name row ───────────────────────────────────────────────────── const nameRow = contentEl.createDiv({ @@ -382,17 +400,7 @@ export class WorkflowEditorModal extends HexmakerModal { value: "", text: "— select table —", }); - for (const tf of tableFiles) { - const val = tf.path.slice(0, -3); - const optLabel = tablesFolder - ? tf.path.slice(tablesFolder.length + 1, -3) - : val; - const opt = tableSelect.createEl("option", { - value: val, - text: optLabel, - }); - if (val === step.tablePath) opt.selected = true; - } + addTableOptions(tableSelect, step.tablePath); if ( step.tablePath && !tableFiles.some((tf) => tf.path.slice(0, -3) === step.tablePath) @@ -546,13 +554,7 @@ export class WorkflowEditorModal extends HexmakerModal { value: "", text: "— select table —", }); - for (const tf of tableFiles) { - const val = tf.path.slice(0, -3); - const optLabel = tablesFolder - ? tf.path.slice(tablesFolder.length + 1, -3) - : val; - addTableSelect.createEl("option", { value: val, text: optLabel }); - } + addTableOptions(addTableSelect); addTableSelect.addEventListener("change", () => { if (!addLabelInput.value.trim() && addTableSelect!.value) { const basename = diff --git a/src/random-tables/resolve.ts b/src/random-tables/resolve.ts index 551dcec5..a43fd630 100644 --- a/src/random-tables/resolve.ts +++ b/src/random-tables/resolve.ts @@ -342,19 +342,58 @@ export function chainLabel(r: Resolved, nameOf: (key: string) => string = (k) => // ── row types (the seam for pickers, plan §2.5) ───────────────────────────── +/** Who made a table, when it isn't the user: "map" for the tables made for every terrain and region. */ +export type TableMaker = "map"; + +/** + * The `table-type:` values of the tables the map makes for itself: two per + * terrain (`{tables}/terrain/description|encounters/.md`) and one + * per region (encounters, with `region:`). The starter tables (landmark, + * weather…) have other types and count as the user's. + */ +export const MAP_MADE_TABLE_TYPES: readonly string[] = ["description", "encounters"]; + +/** + * Who made a table, read from its frontmatter (never its name or folder): + * "map" when `table-type:` is one of MAP_MADE_TABLE_TYPES, else undefined + * (the user's). Deleting the `table-type:` line makes a table the user's. + */ +export function tableMadeBy(fm: Record | null | undefined): TableMaker | undefined { + const t = fm?.["table-type"]; + return typeof t === "string" && MAP_MADE_TABLE_TYPES.includes(lc(t)) ? "map" : undefined; +} + /** What a picker wants: tables whose rows are one of these, optionally of a terrain type. */ export interface TableWant { rows?: readonly RowType[]; terrainType?: string; + /** + * Tables the map made (tableMadeBy): "group" puts them in their own + * section after the user's tables ("Made by the map", collapsed where it + * can be), "hide" leaves them out. Unset: listed with the rest. + */ + mapMade?: "group" | "hide"; } +/** Heading of the section the map's own tables are grouped under. */ +export const MAP_MADE_GROUP_LABEL = "Made by the map"; + /** * How well a table fits a picker's want: "exact" (its `rows:` is wanted * and, for terrain rows, its terrain-type fits), "any" (`rows: any`, which * fits everything but sorts after exact matches) or "no" (with why, so a - * picker can list it disabled rather than hide it). + * picker can list it disabled rather than hide it). `group: "map"` when the + * picker groups the map's own tables apart and this is one. */ -export function tableFitsWant(table: Pick, want: TableWant): { fit: "exact" | "any" | "no"; why?: string } { +export function tableFitsWant( + table: Pick & { madeBy?: TableMaker }, + want: TableWant, +): { fit: "exact" | "any" | "no"; why?: string; group?: "map" } { + if (table.madeBy === "map" && want.mapMade) { + if (want.mapMade === "hide") return { fit: "no", why: "the map made it for its terrains and regions" }; + const r = tableFitsWant({ rows: table.rows, terrainTypes: table.terrainTypes }, want); + return { ...r, group: "map" }; + } if (!want.rows?.length) return { fit: table.rows ? "exact" : "any" }; if (!table.rows) return { fit: "any" }; if (!want.rows.includes(table.rows)) return { fit: "no", why: `its rows are ${table.rows}, not ${want.rows.join(" or ")}` }; diff --git a/src/random-tables/tablePickerGroups.ts b/src/random-tables/tablePickerGroups.ts new file mode 100644 index 00000000..2698fd89 --- /dev/null +++ b/src/random-tables/tablePickerGroups.ts @@ -0,0 +1,12 @@ +import type { App, TFile } from "obsidian"; +import { groupTablesForPicker } from "../notePickers"; +import { tableMadeBy } from "./resolve"; + +/** + * Table files for a picker: the user's own, then the ones the map made + * (terrain and region tables, told apart by their `table-type:` + * frontmatter; see tableMadeBy). Order kept within each part. + */ +export function groupTableFiles(app: App, files: readonly TFile[]): { own: TFile[]; mapMade: TFile[] } { + return groupTablesForPicker(files, (f) => ({ madeBy: tableMadeBy(app.metadataCache.getFileCache(f)?.frontmatter) })); +} diff --git a/styles.css b/styles.css index 7c51ccbf..4ef7a56d 100644 --- a/styles.css +++ b/styles.css @@ -5761,7 +5761,7 @@ tr:hover .duckmage-rt-entry-copy-btn:hover { /* Inline numeric readout shown beside a settings slider. */ .duckmage-slider-value { display: inline-block; - min-width: 2.5em; + min-width: 3em; margin-right: 8px; text-align: right; font-variant-numeric: tabular-nums; @@ -8973,3 +8973,82 @@ textarea.duckmage-edit-region-notes-input { .duckmage-world-types-rows:focus { outline: none; } + +/* Toolbar row vs the top +/- buttons (deep maps' breadcrumb crowded them): + the row stops short of the centred +/- (is-centred) and its crumbs + shrink, each with an ellipsis (full name in the tooltip). + HexMapView.fitTopBar folds the middle crumbs into "…" when they don't + fit whole; when the row's own buttons don't fit there, the row takes + the width up to the side-panel buttons and the top +/- move to the + second row (right side, clear of the mode bar). */ +.duckmage-map-nav-group { + max-width: calc(100% - 92px - 112px); +} +.duckmage-map-nav-group.is-centred { + max-width: calc(50% - 92px - 40px); +} +.duckmage-map-nav-group > .duckmage-map-crumbs { + flex: 0 1 auto; + min-width: 7em; +} +.duckmage-map-nav-group > .duckmage-map-side-crumbs { + min-width: 0; +} +.duckmage-map-nav-group > .duckmage-region-btn { + flex: 0 1 auto; + min-width: 3em; +} +.duckmage-map-nav-group > :not(.duckmage-map-crumbs):not(.duckmage-region-btn) { + flex-shrink: 0; +} +.duckmage-map-crumbs > .duckmage-map-crumb, +.duckmage-map-crumbs > .duckmage-map-crumb-from { + flex: 0 1 auto; + min-width: 2.5em; +} +.duckmage-map-crumbs > .duckmage-map-crumb-sep { + flex-shrink: 0; +} +/* Obsidian buttons centre their text (inline-flex), which cuts a long + name at both ends with no ellipsis: block, so the end gets the "…". */ +.duckmage-map-crumbs > .duckmage-map-crumb:not(.duckmage-map-crumb-more), +.duckmage-map-nav-group > .duckmage-region-btn { + display: block; + line-height: 24px; + text-align: left; +} +.duckmage-map-crumbs .duckmage-map-crumb-more { + display: none; +} +.duckmage-map-crumbs.is-folded .duckmage-map-crumb-more { + display: inline-flex; + align-items: center; + flex-shrink: 0; + min-width: 0; +} +.duckmage-map-crumbs.is-folded .duckmage-map-crumb-mid { + display: none; +} +.duckmage-top-crowded > .duckmage-expand-group-top { + top: 44px; + left: auto; + right: 112px; + transform: none; +} + +/* Table pickers: the terrain and region tables the map made, grouped + after the user's own tables (collapsed). */ +.duckmage-rt-map-made { + margin-top: 6px; + border-top: 1px solid var(--background-modifier-border); + padding-top: 4px; +} +.duckmage-rt-map-made > .duckmage-rt-folder-header .duckmage-rt-folder-name { + color: var(--text-muted); + font-style: italic; +} +.duckmage-link-picker-map-made > summary { + cursor: pointer; + color: var(--text-muted); + margin: 6px 0; +} diff --git a/tests/tablePickerGroups.test.ts b/tests/tablePickerGroups.test.ts new file mode 100644 index 00000000..f8dc6005 --- /dev/null +++ b/tests/tablePickerGroups.test.ts @@ -0,0 +1,52 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { MAP_MADE_GROUP_LABEL, tableFitsWant, tableMadeBy } from "../src/random-tables/resolve"; +import { groupTablesForPicker } from "../src/notePickers"; +import { makeTableTemplate } from "../src/utils"; +import { parseMiniYaml } from "./helpers/memVault"; + +/** + * Table pickers (inputs audit item 10 / picker focus 4): the terrain and + * region tables the map makes sit apart from the user's own tables, found + * by their frontmatter, never their name or folder. + */ + +const fmOf = (note: string) => parseMiniYaml(/^---\n([\s\S]*?)\n---/.exec(note)![1]); + +describe("tables the map made", () => { + it("are told by table-type: description or encounters", () => { + // What ensureTerrainTables / region tables write. + expect(tableMadeBy(fmOf(makeTableTemplate(20, { "table-type": "description", "roll-filter": false, "encounter-filter": false })))).toBe("map"); + expect(tableMadeBy(fmOf(makeTableTemplate(20, { region: "Basin", "table-type": "encounters" })))).toBe("map"); + expect(tableMadeBy({ "table-type": "Encounters" })).toBe("map"); + // Starter tables and the user's own tables are the user's. + expect(tableMadeBy(fmOf(makeTableTemplate(20, { "table-type": "landmark" })))).toBeUndefined(); + expect(tableMadeBy(fmOf(makeTableTemplate(20)))).toBeUndefined(); + expect(tableMadeBy(undefined)).toBeUndefined(); + // A user's table named like a terrain table is still theirs. + expect(tableMadeBy({ dice: 20 })).toBeUndefined(); + }); + + it("group after the user's, or drop out, through tableFitsWant", () => { + expect(tableFitsWant({ madeBy: "map" }, { mapMade: "group" })).toEqual({ fit: "any", group: "map" }); + expect(tableFitsWant({ madeBy: "map" }, { mapMade: "hide" }).fit).toBe("no"); + expect(tableFitsWant({ madeBy: "map" }, {})).toEqual({ fit: "any" }); + expect(tableFitsWant({}, { mapMade: "group" })).toEqual({ fit: "any" }); + // Row-type wants still apply inside the group. + expect(tableFitsWant({ madeBy: "map", rows: "text" }, { mapMade: "group", rows: ["note"] }).fit).toBe("no"); + }); + + it("pickers list the user's tables first, the map's in their own group, order kept", () => { + const items = [ + { name: "weather", madeBy: undefined }, + { name: "forest encounters", madeBy: "map" as const }, + { name: "my dragons", madeBy: undefined }, + { name: "Basin", madeBy: "map" as const }, + ]; + const g = groupTablesForPicker(items, (i) => ({ madeBy: i.madeBy })); + expect(g.own.map((i) => i.name)).toEqual(["weather", "my dragons"]); + expect(g.mapMade.map((i) => i.name)).toEqual(["forest encounters", "Basin"]); + expect(groupTablesForPicker(items, (i) => ({ madeBy: i.madeBy }), { mapMade: "hide" }).mapMade).toEqual([]); + expect(MAP_MADE_GROUP_LABEL).toBe("Made by the map"); + }); +}); From 22322af8581dad8c4ed471169c1e98cce2b71fe2 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 12:49:20 -0400 Subject: [PATCH 311/558] fix(arrival): separator after Go there in the hex menu Co-Authored-By: Claude Opus 5.5 --- src/hex-map/HexMapView.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 733a8e3c..095a17a8 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -4851,10 +4851,9 @@ export class HexMapView extends ItemView { } // Arrival (GM4): a world set to make places makes this hex's place on // the spot, in any mode, when it has none yet. - if (!hasRegion && !childPlan.open.length && !childPlan.listCount && this.plugin.arrival.canArrive(this.activeMapName, x, y)) { - menu.add("hex.arrive", "Go there", "footprints", () => void this.arriveAt(x, y)); - } - if (hasRegion || childPlan.open.length || childPlan.listCount) menu.addSeparator(); + const arrive = !hasRegion && !childPlan.open.length && !childPlan.listCount && this.plugin.arrival.canArrive(this.activeMapName, x, y); + if (arrive) menu.add("hex.arrive", "Go there", "footprints", () => void this.arriveAt(x, y)); + if (arrive || hasRegion || childPlan.open.length || childPlan.listCount) menu.addSeparator(); menu.add("hex.center", "Center on this hex", "crosshair", () => this.centerOnHex(x, y)); From 93b45894ba3512dd557476187e72d24765087528 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 13:27:43 -0400 Subject: [PATCH 312/558] feat: once-only rows + Events ledger (SP6), arrival makes overworld regions (GM4), uncharted marker - Once column (per world / per map): map rolls (arrival, Star scatter, Orbits) leave out rows held in a readable ## Events table (root map's note for per world, the map's own for per map) and write the ones they land on; deleting a ledger row frees the event. A run fires a once-only row at most once. Rerolling a place forgets its old landscape's events. - Hand rolls (Tables view, roll modal, roll blocks) say "once per world: not tracked here" (T7). - Arrival on overworlds: going to a hex with a biome and no region makes the region from that biome via createRegion, seeded, no form; same Reroll/Lock rules (Play until locked, then God). - Uncharted "?" layer for unresolved On arrival cells (Labels group, show-uncharted, default on); write-only, reuses measured placements. - Thrash bench gains a batch + uncharted variant; overworld smoke gets a GM4 arrival + marker check. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- dev/coord-label-thrash-bench.html | 19 +- dev/coord-label-thrash-bench.mjs | 3 + dev/smoke/setups.mjs | 67 +++++++ package.json | 4 +- src/HexmakerPlugin.ts | 7 + src/SetupWizardView.ts | 7 +- src/arrival/ArrivalService.ts | 148 +++++++++++++- src/arrival/EventsService.ts | 85 ++++++++ src/arrival/eventsLedger.ts | 252 ++++++++++++++++++++++++ src/hex-map/HexMapView.ts | 11 ++ src/hex-map/HexSidePanel.ts | 3 + src/hex-map/help.md | 6 +- src/hex-map/newChildMap.ts | 17 +- src/hex-map/unchartedLayer.ts | 47 +++++ src/maps/mapNote.ts | 1 + src/overworld/regionsVault.ts | 10 +- src/random-tables/RandomTableModal.ts | 5 +- src/random-tables/RandomTableView.ts | 4 +- src/random-tables/RollerBlock.ts | 5 +- src/random-tables/resolve.ts | 18 +- src/types.ts | 2 + src/workMode.ts | 1 + src/worldgen/NewMapSetupModal.ts | 9 +- src/worldgen/procedural/orbits.ts | 2 +- src/worldgen/procedural/starScatter.ts | 2 +- src/worldgen/registry.ts | 23 ++- src/worldgen/tableRoles.ts | 33 +++- styles.css | 26 +++ tests/arrivalDeferred.test.ts | 6 +- tests/arrivalRegion.test.ts | 156 +++++++++++++++ tests/eventsLedger.test.ts | 166 ++++++++++++++++ tests/tableOnce.test.ts | 259 +++++++++++++++++++++++++ tests/unchartedLayer.test.ts | 77 ++++++++ 34 files changed, 1442 insertions(+), 47 deletions(-) create mode 100644 src/arrival/EventsService.ts create mode 100644 src/arrival/eventsLedger.ts create mode 100644 src/hex-map/unchartedLayer.ts create mode 100644 tests/arrivalRegion.test.ts create mode 100644 tests/eventsLedger.test.ts create mode 100644 tests/tableOnce.test.ts create mode 100644 tests/unchartedLayer.test.ts diff --git a/README.md b/README.md index bd18ede9..1e2095d6 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,9 @@ Maps can be generated instead of painted hex by hex. When you create a map (**Ma **Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which (on space maps: a star system, planet or station is a Location). If the hex already has maps, the dialog lists them first with an **Open** button each, and the menu item reads **Add another map…**. Inside a submap, the breadcrumb ends with what its hex was on the parent map ("from: barren world"). The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. -**Arriving somewhere new** (optional; off unless you turn it on). In a map's properties, **Arriving somewhere new → Make the place, in any mode** (maps under it follow unless they set their own; stored as `on-arrival: make places` in the map note). Then right-click a hex that has no map → **Go there** (or Ctrl+click it): its On arrival table, if it has one, is rolled with the map's `seed:` (the same world gives the same result), what came up is written onto the hex (the sector learns what the system is), and the hex's map is made at once with no form and no preview: from the rolled row's Size, Generator, Options, Palette and Base, else the palette's submap settings, else the usual defaults. It works in Play, opens in the mode you were in, and the new map's note gets a plain-text **## Arrival** section (what was rolled, how the map was made). Until you lock it, the bar beside the mode switch offers **Reroll** (same setup, next seed; the map's terrain and paths are replaced) and **Lock**; after the lock (`arrival: locked`) only God mode can reroll it. Visiting again never rolls again, and a locked hex is never arrived into. **New map from this hex…** in Build still opens the form, starting from the same rolled row. +**Arriving somewhere new** (optional; off unless you turn it on). In a map's properties, **Arriving somewhere new → Make the place, in any mode** (maps under it follow unless they set their own; stored as `on-arrival: make places` in the map note). Then right-click a hex that has no map → **Go there** (or Ctrl+click it): its On arrival table, if it has one, is rolled with the map's `seed:` (the same world gives the same result), what came up is written onto the hex (the sector learns what the system is), and the hex's map is made at once with no form and no preview: from the rolled row's Size, Generator, Options, Palette and Base, else the palette's submap settings, else the usual defaults. It works in Play, opens in the mode you were in, and the new map's note gets a plain-text **## Arrival** section (what was rolled, how the map was made). Until you lock it, the bar beside the mode switch offers **Reroll** (same setup, next seed; the map's terrain and paths are replaced) and **Lock**; after the lock (`arrival: locked`) only God mode can reroll it. Visiting again never rolls again, and a locked hex is never arrived into. **New map from this hex…** in Build still opens the form, starting from the same rolled row. On an **overworld**, going to a hex that has a biome but no region yet (click it, or right-click → **Go there**) makes its region the way the Biome painter does, from the hex's biome, seeded from the overworld's seed and with no form; it gets the same **Reroll** / **Lock** bar and rules (Reroll makes it again with the next seed; locked hand-painted hexes stay). Hexes whose On arrival roll is still to come show a small **?** (layers menu → Labels → **Uncharted (?)**, on by default). + +**Once-only rows** (optional). A table row whose **Once** column says `per world` or `per map` can come up only once; leave it blank for a row that can repeat. When a roll made by the map (arriving, or a generator such as Star scatter) lands on one, it is written as a row of a plain **## Events** table (`| Event | Where | When | From |`): in the top map of the map tree for `per world`, in the map's own note for `per map`. From then on that row is left out of the roll and the other rows' odds grow to fill in (the same as "roll again if you get it" by hand). Delete a row from **## Events** to make the event possible again. Rerolling a place takes out the events its old landscape found. Rolls you make by hand in the Random Tables view or a roll block aren't tracked: a once-only result says "once per world: not tracked here". **Rectangle regions join up.** Rectangles are laid like bricks: each region sits in its own slot of one grid shared with the regions around it, so walking off a region's edge (or clicking the dimmed hexes past it) lands in the next region at the right hex, and a small hex flower on the toolbar shows all six neighbours in their directions (hover a petal for its name, click to go there). An empty petal shows **+** ("New region to the north-east"): click it to walk into new land. Pick the biome that lies there, or **Roll** for one (the seed is shown, so a roll can be repeated; **Re-roll terrain** keeps the biome and tries a new seed), check the live preview of the new region blended with every region around it, and **Create and go**. A biome different from yours makes border country between the two. If that hex is past the overworld's edge, the overworld grows by a hex to fit it. The hex editor's neighbour flower offers the same walk on the hexes past a region's edge. Making a region needs Build or God; in Play the **+** is greyed out and says "Switch to Build to make a region." A new region is made from a short form: biome (the hex's terrain is its biome), blend, how wiggly the borders are, and a seed, with a live preview of the region against its neighbours. It blends with the overworld around it, and the hexes along its edges are pinned to the regions already made, so seams line up whatever order you make them in. If the parent hex has no terrain yet, it gets the region's main terrain (painted hexes are never changed). Hex flowers can be set up but don't join their neighbours yet. @@ -208,7 +210,7 @@ More a table can say, all optional (a table without them reads exactly as before - **Weights** can be decimals (`3.5`, `0.5`) or percentages (`50%` is 0.5). - **Extra columns** are kept and shown read-only in the Random Tables view; they travel with a row when something rolls on it (a world's **Size**, **Generator**, **Mainworld**…). -- Four column names will mean the same in every table: **Roll** (`now`, or `on arrival` for a row that stays unknown until someone visits), **Shown as** (what such a hex shows until then), **Once** (`per world` or `per map`) and **When** (`zone: outer`, `star: red dwarf, white dwarf`, `ring: 2–4`, `temperature: cold`, `type: gas-giant`; separate several with `;`; a row whose When doesn't fit is rolled again). For now they are read, kept and checked (**Check tables** lists a value it can't read); rolling on arrival, the once-only record and When in the Random Tables view come later. +- Four column names will mean the same in every table: **Roll** (`now`, or `on arrival` for a row that stays unknown until someone visits), **Shown as** (what such a hex shows until then), **Once** (`per world` or `per map`) and **When** (`zone: outer`, `star: red dwarf, white dwarf`, `ring: 2–4`, `temperature: cold`, `type: gas-giant`; separate several with `;`; a row whose When doesn't fit is rolled again). They are read, kept and checked (**Check tables** lists a value it can't read). Roll and Shown as work when generating and arriving, and Once when the map rolls (see **Once-only rows**); When in the Random Tables view comes later. - `rows:` in the frontmatter says what the rows are (`text`, `note`, `table`, `generator`, `terrain`, `biome` or `any`, the default), and `terrain-type:` narrows terrain rows (`star`). It is read and checked now; table pickers will use it to offer only tables that fit. - `linked-folder:` works like `linkedFolder:`. @@ -269,7 +271,7 @@ Toggled from the **layers** panel on the right edge of the map. - **Region overlay** — paint a geographic region colour on any hex. Regions render as filled blobs with a scaled label centred on the blob. Region data is stored in the map note (see [Map notes](#map-notes)). - Both overlays can be shown simultaneously and toggled independently. - Additional toggles: **Show terrain icons**, **Show icon overrides**, **Show paths**, **Show tokens**, **GM layer**. -- **Labels** group: **Coordinates**, **Hex names** and **Token names** (all on by default). With token names off, a token's name still shows while you hover it. Hex names are always readable: never smaller than about 11px on screen, at any zoom. A long name shrinks and wraps at spaces onto up to three lines to fit inside its hex, clear of its badges and coordinates; when it still doesn't fit at a readable size (zoomed out, or a long name), it spills past the hex instead of being cut (words are never split, nothing is cut off). Their colour follows the terrain (dark text on light terrain such as snow, light text on dark terrain). **Aa** beside the Labels heading sets the hex-name font for this map: Theme / Serif / Sans / Handwritten (common system fonts, nothing bundled), size **S / M / L / XL**, **B**old and **I**talic, and ↺ back to the default. The default for every map is in **Settings → Hex name font**. Saved in the map note (`name-font`, `name-size`, `name-style`); the PNG export uses the same font. +- **Labels** group: **Coordinates**, **Hex names**, **Token names** and **Uncharted (?)** (a small ? on hexes whose On arrival roll is still to come) (all on by default). With token names off, a token's name still shows while you hover it. Hex names are always readable: never smaller than about 11px on screen, at any zoom. A long name shrinks and wraps at spaces onto up to three lines to fit inside its hex, clear of its badges and coordinates; when it still doesn't fit at a readable size (zoomed out, or a long name), it spills past the hex instead of being cut (words are never split, nothing is cut off). Their colour follows the terrain (dark text on light terrain such as snow, light text on dark terrain). **Aa** beside the Labels heading sets the hex-name font for this map: Theme / Serif / Sans / Handwritten (common system fonts, nothing bundled), size **S / M / L / XL**, **B**old and **I**talic, and ↺ back to the default. The default for every map is in **Settings → Hex name font**. Saved in the map note (`name-font`, `name-size`, `name-style`); the PNG export uses the same font. - **Show link badges** (on by default) — a coloured icon badge at a hex's right side for each kind of link in its note: towns, dungeons, features, quests, factions. **S / M / L** beside the toggle sets their size (S by default; S is small and stays inside the hex, M and L sit on the hex's right edge so they stand out). Badges sit above hex names and coordinates, and names make room for them. The legend lists the badge kinds shown on the map. Hovering the hex names the linked notes ("Gullmouth · beach · hex 6, 6 · Town: Gullmouth"). Your hex icon stays as it is. The ▸ next to the toggle picks which kinds show. Saved per map. - Opening or closing the layers panel (or the drawing tools) never moves the map; the panel may cover a few hexes at the right edge. - **Show legend** (on by default) — a small terrain legend pinned to the bottom-left of the map view, listing only the terrains used on this map by their full names (only names longer than 18 characters are cut, keeping their start; hover a row for the full name). **S / M / L** sets its size; **–** folds it to a small **Legend** button (click to open it again); **×** hides it. The new-map and generator previews show the same legend. Size and visibility are remembered. diff --git a/dev/coord-label-thrash-bench.html b/dev/coord-label-thrash-bench.html index 488b1908..aebe9895 100644 --- a/dev/coord-label-thrash-bench.html +++ b/dev/coord-label-thrash-bench.html @@ -105,6 +105,23 @@ label.style.setProperty("--duckmage-coord-x", ((p.ox / gw) * 100).toFixed(3) + "%"); label.style.setProperty("--duckmage-coord-y", ((p.oy / gh) * 100).toFixed(3) + "%"); } + return { pos, gw, gh }; + } + + // ── batched + the uncharted marker layer (renderUnchartedLayer): it + // reuses the positions just read and only writes (a third of hexes) ── + function batchedWithUncharted() { + const { pos, gw, gh } = batched(); + grid.querySelector(".uncharted-layer")?.remove(); + const layer = grid.appendChild(document.createElement("div")); + layer.className = "uncharted-layer"; + pos.forEach((p, i) => { + if (i % 3) return; + const mark = layer.appendChild(document.createElement("span")); + mark.textContent = "?"; + mark.style.setProperty("--duckmage-uncharted-x", ((p.ox / gw) * 100).toFixed(3) + "%"); + mark.style.setProperty("--duckmage-uncharted-y", ((p.oy / gh) * 100).toFixed(3) + "%"); + }); } function time(fn, withBg, iters) { @@ -124,7 +141,7 @@ // One config per call so each puppeteer evaluate stays short (the thrash // path on a bg map can take seconds per iteration). window.__measure = (which, withBg, iters) => - time(which === "thrash" ? thrashing : batched, withBg, iters); + time(which === "thrash" ? thrashing : which === "uncharted" ? batchedWithUncharted : batched, withBg, iters); document.title = "ready"; diff --git a/dev/coord-label-thrash-bench.mjs b/dev/coord-label-thrash-bench.mjs index 42dd5cf3..611a1e19 100644 --- a/dev/coord-label-thrash-bench.mjs +++ b/dev/coord-label-thrash-bench.mjs @@ -24,6 +24,8 @@ const r = await withBrowser(async ({ page }) => { batch_noBg: await m("batch", false), thrash_bg: await m("thrash", true), batch_bg: await m("batch", true), + uncharted_noBg: await m("uncharted", false), + uncharted_bg: await m("uncharted", true), }; }); @@ -32,5 +34,6 @@ console.log(`\nrenderCoordLabelsLayer cost — hexes=${r.hexCount}, median of ${ console.log(` no bg image with bg image`); console.log(`thrash (current) ${f(r.thrash_noBg)} ${f(r.thrash_bg)} ← regression`); console.log(`batch (fixed) ${f(r.batch_noBg)} ${f(r.batch_bg)}`); +console.log(`batch + uncharted ${f(r.uncharted_noBg)} ${f(r.uncharted_bg)} (the ? layer reuses the read positions)`); console.log(`\nspeedup no-bg: ${(r.thrash_noBg / r.batch_noBg).toFixed(1)}× with-bg: ${(r.thrash_bg / r.batch_bg).toFixed(1)}×`); console.log(`bg amplifies thrash by ${(r.thrash_bg / r.thrash_noBg).toFixed(1)}× (vs ${(r.batch_bg / r.batch_noBg).toFixed(1)}× when batched)\n`); diff --git a/dev/smoke/setups.mjs b/dev/smoke/setups.mjs index 5bd270aa..b38de96b 100644 --- a/dev/smoke/setups.mjs +++ b/dev/smoke/setups.mjs @@ -451,6 +451,73 @@ async function overworldExtra(ctx) { const out = [{ check: "F5-regions", ok: regions.length > 0, detail: `${ow.name}: ${regions.length} region maps` }]; const lock = await ctx.ev((id, n) => window.__smokePage.overworldPaintLock(id, n), ctx.pluginId, ow.name); out.push({ check: "C8-overworld-paint", ok: lock.ok, detail: [...lock.steps, ...lock.problems].join("; ") }); + + // GM4 on overworlds: with arrival on, going to a hex with a biome and no + // region makes the region in Play (seeded, no form); Reroll until Lock. + // The hex's unresolved On arrival cell shows the uncharted "?" first. + const a = await ctx.ev(async (id, owName) => { + const p = window.app.plugins.plugins[id]; + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const steps = [], problems = []; + const ow = p.getMap(owName); + const before = { mode: ow.workMode, cols: ow.gridSize.cols }; + try { + if (!p.arrival?.isOverworld || !p.events) return { skipped: "build has no overworld arrival" }; + if (p.arrival.canArrive(owName, ow.gridOffset.x, ow.gridOffset.y)) problems.push("arrival on by default"); + const hasRegion = (k) => p.settings.maps.some((m) => m.submapKind === "region" && m.parent?.map === owName && m.parent.hex === k); + let key; + for (let y = ow.gridOffset.y; !key && y < ow.gridOffset.y + ow.gridSize.rows; y++) + for (let x = ow.gridOffset.x; !key && x < ow.gridOffset.x + ow.gridSize.cols; x++) if (!hasRegion(`${x}_${y}`)) key = `${x}_${y}`; + if (!key) { + // Every hex has a region: take in one more column. + ow.gridSize = { ...ow.gridSize, cols: ow.gridSize.cols + 1 }; + key = `${ow.gridOffset.x + ow.gridSize.cols - 1}_${ow.gridOffset.y}`; + steps.push("grew the overworld by a column"); + } + const [x, y] = key.split("_").map(Number); + const terrain = [...p.mapStore.all(owName).values()].find((h) => h.terrain)?.terrain; + ow.arrivalMode = "make places"; + ow.workMode = "play"; + p.mapStore.set(owName, key, { terrain, onArrival: "Smoke uncharted" }); + await p.saveSettings(); + await p.mapStore.flush(); + await p.showMap(owName); + p.refreshHexMap(); + await sleep(1500); + const marks = document.querySelectorAll(".duckmage-uncharted-layer .duckmage-uncharted-mark").length; + steps.push(`uncharted marks: ${marks}`); + if (marks < 1) problems.push("no uncharted mark on the unresolved hex"); + if (!p.arrival.canArrive(owName, x, y)) problems.push(`can't arrive at ${key}: ${p.arrival.blocker(owName, x, y)}`); + const made = await p.arrival.arrive(owName, x, y); + if (!made) problems.push("no region made"); + else { + const r = p.getMap(made); + steps.push(`arrived at ${key}: made ${made}`); + if (r?.submapKind !== "region" || r?.parent?.hex !== key) problems.push(`not the hex's region: ${r?.submapKind} ${r?.parent?.hex}`); + if (r?.arrival !== "open" || r?.workMode !== "play") problems.push(`new region ${r?.arrival}/${r?.workMode}`); + if (p.mapStore.get(owName, key)?.onArrival) problems.push("On arrival cell not cleared"); + if (!p.mapStore.all(made).size) problems.push("region has no terrain"); + const note = await p.mapStore.readNoteText(made); + if (!note?.includes("## Arrival")) problems.push("no Arrival section"); + const seed = r.regionSeed; + if (!(await p.arrival.reroll(made))) problems.push("Play couldn't reroll an open region"); + else if (r.regionSeed === seed) problems.push("reroll kept the seed"); + await p.arrival.lock(made); + if (await p.arrival.reroll(made)) problems.push("Play rerolled a locked region"); + else steps.push("reroll then lock: Play can't reroll after the lock"); + if (p.arrival.canArrive(owName, x, y)) problems.push("can arrive again"); + } + } catch (e) { + problems.push(String(e?.stack ?? e).slice(0, 400)); + } finally { + ow.workMode = before.mode; + delete ow.arrivalMode; + await p.saveSettings(); + await p.mapStore.flush(); + } + return { steps, problems }; + }, ctx.pluginId, ow.name); + out.push({ check: "GM4-overworld-arrival", ok: !a.skipped && a.problems.length === 0, detail: a.skipped ?? [...a.steps, ...a.problems].join("; ") }); return out; } diff --git a/package.json b/package.json index 7321fc2f..90f1618a 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index fcf1c1a2..dbfebc48 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -81,6 +81,8 @@ import { TableNotes } from "./random-tables/TableNotes"; import { inheritedRoleTables, type RoleTablePick } from "./worldgen/tableSources"; import type { RoleId } from "./worldgen/tableRoles"; import { ArrivalService } from "./arrival/ArrivalService"; +import { EventsService } from "./arrival/EventsService"; +import type { FiredEvent } from "./arrival/eventsLedger"; import { effectiveArrivalMode, type ArrivalMode } from "./arrival/arrival"; import { withMapLink } from "./maps/mapNote"; import { @@ -128,6 +130,8 @@ export default class HexmakerPlugin extends Plugin { tableNotes!: TableNotes; /** Places made on arrival: roll, make, reroll, lock (src/arrival). */ arrival = new ArrivalService(this); + /** The Events ledgers of once-only rows in map notes (SP6). */ + events = new EventsService(this); /** Per-hex map data, backed by one map note per map (src/maps). */ mapStore = new MapStore(this); /** What each hex note's Map data callout last showed (phase 2: tells a hand edit from a stale copy). */ @@ -2356,6 +2360,8 @@ export default class HexmakerPlugin extends Plugin { slug?: string; /** Hexes left to roll on arrival ("x_y" → table link), for the On arrival column. */ arrivals?: Map; + /** Once rows the generator fired (SP6), written to the Events ledgers once the map exists. */ + events?: FiredEvent[]; } = {}, ): Promise<{ name: string } | { error: string }> { if (!rawName.trim()) return { error: "Enter a map name." }; @@ -2407,6 +2413,7 @@ export default class HexmakerPlugin extends Plugin { this.mapStore.setMany(name, cells); onProgress?.(cols * rows, cols * rows); await this.mapStore.flush(); + await this.events.record(name, extra.events); if (!extra.quiet) new Notice(`Created map "${displayName ?? name}".`); return { name }; diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index 5acbdfdd..4c0698df 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -758,7 +758,12 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { plugin.settings.staggerOffset, undefined, outcome?.ok ? outcome.cells : undefined, - { baseTerrain: suggestBaseTerrain(terrains), quiet: true, ...(outcome?.ok && outcome.arrivals ? { arrivals: outcome.arrivals } : {}) }, + { + baseTerrain: suggestBaseTerrain(terrains), + quiet: true, + ...(outcome?.ok && outcome.arrivals ? { arrivals: outcome.arrivals } : {}), + ...(outcome?.ok && outcome.events ? { events: outcome.events } : {}), + }, ); if ("error" in result) throw new Error(result.error); diff --git a/src/arrival/ArrivalService.ts b/src/arrival/ArrivalService.ts index bcec1401..1ab8f26d 100644 --- a/src/arrival/ArrivalService.ts +++ b/src/arrival/ArrivalService.ts @@ -14,6 +14,13 @@ * - reroll / lock (GM4): a place made on arrival can be made again in any * mode until it's locked (`arrival: locked` in its note); after that only * in God. + * - On an overworld (a map whose regions join up), going to a hex with no + * region makes its region, seeded and with no form, from the hex's biome + * through the same path as the Biome painter and walking into new land + * (createRegion). Same Reroll/Lock rules (GM4: "a new planet, new + * region"). + * - Once-only rows (SP6): every roll here leaves out rows the Events + * ledgers hold, and writes the ones it lands on (EventsService). * * A world that isn't set to make places never gets here: nothing changes. */ @@ -22,7 +29,10 @@ import { Notice } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import { randomSeed } from "../../packages/hex-wfc/src/rng"; import { chainLabel, resolveRoll, type ResolvedOdds, type TableLookup } from "../random-tables/resolve"; -import { hexChildMaps } from "../maps/submaps"; +import { hexChildMaps, regionMapAt } from "../maps/submaps"; +import { createRegion, hexBiomeAt, inOverworldGrid, overworldOf, regenerateRegion } from "../overworld/regionsVault"; +import { biomeNoteOf } from "../overworld/biomes"; +import { OnceTracker, type FiredEvent } from "./eventsLedger"; import { defaultSubmapLabel, uniqueMapSlug } from "../hex-map/submapNav"; import { buildSubmapContext } from "../worldgen/submapContext"; import { addGeneratedPaths } from "../worldgen/generators"; @@ -59,6 +69,13 @@ export interface HexResolution { value: string; attrs: Record; chain: string; + /** Once-only rows it landed on (written to the Events ledgers). */ + events: FiredEvent[]; +} + +/** "Found the Silent Fleet (once per world)." lines for the write-up. */ +function eventLines(events: readonly FiredEvent[]): string[] { + return events.map((e) => `Found ${e.link ? `[[${e.result.replace(/^.*\//, "")}]]` : e.result} (once per ${e.scope}; in the Events list).`); } /** The submap size when nothing else says (SUBMAP_SIZE_PRESETS' Medium). */ @@ -75,12 +92,25 @@ export class ArrivalService { const { plugin } = this; if (!plugin.getMap(mapName)) return "No such map."; if (plugin.arrivalModeFor(mapName).mode !== "make") return "off"; - const h = plugin.mapStore.get(mapName, keyOf(x, y)); + const key = keyOf(x, y); + const h = plugin.mapStore.get(mapName, key); if (h?.locked) return "This hex is locked."; + if (this.isOverworld(mapName)) { + // An overworld's hexes are regions: arriving makes the region. + if (regionMapAt(plugin.settings.maps, mapName, key)) return "This hex already has a region."; + if (!inOverworldGrid(plugin.getMap(mapName)!, x, y)) return "This hex is off the map."; + if (!h?.onArrival && !hexBiomeAt(plugin, mapName, key)) return "This hex has no biome yet."; + return null; + } if (hexChildMaps(h).some((m) => !!plugin.getMap(m))) return "This hex already has a map."; return null; } + /** A map whose regions join up (an overworld): arrival makes regions there. */ + isOverworld(mapName: string): boolean { + return !!overworldOf(this.plugin, mapName); + } + /** Whether "Go there" makes a place at hex (x, y). */ canArrive(mapName: string, x: number, y: number): boolean { return this.blocker(mapName, x, y) === null; @@ -116,27 +146,35 @@ export class ArrivalService { /** * Roll hex (x, y)'s On arrival table (seeded by the map's seed and the * hex) and write what came up onto the hex: a terrain replaces the shown - * one, (nothing) clears it; the cell is cleared either way. Null when the - * hex has nothing to roll or the write was refused. + * one, (nothing) clears it; the cell is cleared either way. Once-only + * rows in the Events ledgers are left out, and the ones it lands on are + * written there. Null when the hex has nothing to roll or the write was + * refused. */ - resolveHex(mapName: string, x: number, y: number, action: ModeAction): HexResolution | null { + async resolveHex(mapName: string, x: number, y: number, action: ModeAction): Promise { const { plugin } = this; const key = keyOf(x, y); const cell = plugin.mapStore.get(mapName, key)?.onArrival; if (!cell) return null; const seed = arrivalSeed(this.seedOf(mapName), key, "arrival", 0); const { lookup, terrains } = this.lookupFor(mapName); - const r = resolveRoll(cell, lookup, { seed, terrains }); + const once = new OnceTracker(await plugin.events.ledgersFor({ map: mapName })); + // The cell may have been resolved while the ledgers were read. + if (plugin.mapStore.get(mapName, key)?.onArrival !== cell) return null; + const r = resolveRoll(cell, lookup, { seed, terrains, isUsed: once.isUsed }); const patch: { onArrival: null; terrain?: string | null } = { onArrival: null }; if (r.kind === "terrain") patch.terrain = r.value; else if (r.kind === "nothing") patch.terrain = null; if (!plugin.mapStore.set(mapName, key, patch, action)) return null; + once.fire(r.onces, key); + await plugin.events.record(mapName, once.fired); return { table: cell, kind: r.kind, value: r.kind === "nothing" ? "(nothing)" : r.kind === "empty" ? `nothing to roll on ${cell}` : r.value, attrs: r.attrs, chain: chainLabel(r), + events: once.fired, }; } @@ -180,10 +218,11 @@ export class ArrivalService { if (why !== "off") new Notice(why); return null; } + if (this.isOverworld(mapName)) return this.arriveRegion(mapName, x, y); const parent = plugin.getMap(mapName)!; const key = keyOf(x, y); const pseed = this.seedOf(mapName); - const resolution = this.resolveHex(mapName, x, y, "discover"); + const resolution = await this.resolveHex(mapName, x, y, "discover"); if (resolution?.kind === "nothing") { await plugin.saveSettings(); new Notice(`Nothing at ${hexText(key)}: empty space.`); @@ -205,6 +244,7 @@ export class ArrivalService { context: buildSubmapContext(plugin, mapName, x, y), pathTypes: plugin.getPathTypes(setup.palette), tablesFrom: mapName, + ledgers: await plugin.events.ledgersFor({ parent: mapName }), }); if (!outcome.ok) { await plugin.saveSettings(); @@ -241,7 +281,9 @@ export class ArrivalService { } await plugin.saveSettings(); await plugin.mapStore.flush(); + await plugin.events.record(made.name, outcome.events); + const extra = [...(note ? [note] : []), ...eventLines([...(resolution?.events ?? []), ...(outcome.events ?? [])])]; const report: ArrivalReport = { date: new Date().toISOString().slice(0, 10), parentNote: `_${mapName}`, @@ -249,7 +291,7 @@ export class ArrivalService { ...(resolution ? { rolled: { table: resolution.table, result: resolution.value, chain: resolution.chain } } : {}), ...(terrain ? { terrain } : {}), made: { generator: kind.label, palette: setup.palette, cols: setup.cols, rows: setup.rows, seed }, - ...(note ? { extra: [note] } : {}), + ...(extra.length ? { extra } : {}), }; await plugin.mapStore.editNoteText(made.name, (c) => withArrivalSection(c, arrivalLines(report))); new Notice(arrivalSummary(plugin.mapLabel(made.name), report), 8000); @@ -266,10 +308,13 @@ export class ArrivalService { const map = plugin.getMap(mapName); if (!map?.arrival || !map.parent || !plugin.getMap(map.parent.map)) return false; if (!canRerollPlace(map)) { new Notice(REROLL_PLACE_LOCKED_HINT); return false; } + if (map.submapKind === "region") return this.rerollRegion(mapName); const { map: parentName, hex } = map.parent; const [x, y] = hex.split("_").map(Number); const n = (map.arrivalRerolls ?? 0) + 1; const seed = arrivalSeed(this.seedOf(parentName), hex, "submap", n); + // The old landscape's once-only events go with it. + await plugin.events.forgetMap(mapName); const terrain = plugin.mapStore.get(parentName, hex)?.terrain ?? plugin.getMap(parentName)?.baseTerrain; const source = plugin.worldTypeStore.sourceFor(undefined, plugin.getMapPalette(parentName).map((t) => t.name), parentName).source; const attrs = terrain ? attrsForTerrain(source, terrain) : undefined; @@ -289,6 +334,7 @@ export class ArrivalService { context: buildSubmapContext(plugin, parentName, x, y), pathTypes: plugin.getPathTypes(map.paletteName), tablesFrom: parentName, + ledgers: await plugin.events.ledgersFor({ map: mapName }), }); if (!outcome.ok) { new Notice(`Couldn't reroll: ${outcome.message}`); return false; } @@ -302,6 +348,7 @@ export class ArrivalService { map.arrivalRerolls = n; await plugin.saveSettings(); await plugin.mapStore.flush(); + await plugin.events.record(mapName, outcome.events); await plugin.mapStore.editNoteText(mapName, (c) => restateArrival(c, { made: { generator: kind.label, palette: map.paletteName, cols: map.gridSize.cols, rows: map.gridSize.rows, seed }, rerolls: n, @@ -312,6 +359,91 @@ export class ArrivalService { return true; } + // ── regions on an overworld (GM4: "a new region") ───────────────────── + + /** A biome's name as written. */ + private biomeText(id: string): string { + return biomeNoteOf(id)?.label ?? id; + } + + /** + * Arrive at overworld hex (x, y): roll its On arrival table if it has + * one, then make its region from the hex's biome, seeded from the + * overworld's seed, with no form (the Biome painter's path). Opens in the + * overworld's mode, open for rerolls until locked. + */ + private async arriveRegion(mapName: string, x: number, y: number): Promise { + const { plugin } = this; + const parent = plugin.getMap(mapName)!; + const key = keyOf(x, y); + const pseed = this.seedOf(mapName); + const resolution = await this.resolveHex(mapName, x, y, "discover"); + if (resolution?.kind === "nothing") { + await plugin.saveSettings(); + new Notice(`Nothing at ${hexText(key)}.`); + plugin.refreshHexMap(); + return null; + } + const biome = hexBiomeAt(plugin, mapName, key); + if (!biome) { + await plugin.saveSettings(); + new Notice(`Nothing to make at ${hexText(key)}: the hex has no biome.`); + plugin.refreshHexMap(); + return null; + } + const seed = arrivalSeed(pseed, key, "submap", 0); + const res = await createRegion(plugin, mapName, x, y, { fill: "match", biome, seed, arrival: true }); + if ("error" in res) { + await plugin.saveSettings(); + new Notice(res.error); + return null; + } + const child = plugin.getMap(res.name); + if (child) { + child.arrival = "open"; + if (parent.workMode) child.workMode = workModeOf(parent); + } + await plugin.saveSettings(); + await plugin.mapStore.flush(); + const terrain = plugin.mapStore.get(mapName, key)?.terrain; + const extra = eventLines(resolution?.events ?? []); + const report: ArrivalReport = { + date: new Date().toISOString().slice(0, 10), + parentNote: `_${mapName}`, + hex: hexText(key), + ...(resolution ? { rolled: { table: resolution.table, result: resolution.value, chain: resolution.chain } } : {}), + ...(terrain ? { terrain } : {}), + made: { generator: `the ${this.biomeText(biome)} biome`, palette: child?.paletteName ?? "", cols: child?.gridSize.cols ?? 0, rows: child?.gridSize.rows ?? 0, seed }, + ...(extra.length ? { extra } : {}), + }; + await plugin.mapStore.editNoteText(res.name, (c) => withArrivalSection(c, arrivalLines(report))); + new Notice(arrivalSummary(plugin.mapLabel(res.name), report), 8000); + return res.name; + } + + /** Make a region made on arrival again: the next seed, its biome as the overworld has it now. Locked cells stay. */ + private async rerollRegion(mapName: string): Promise { + const { plugin } = this; + const map = plugin.getMap(mapName)!; + const { map: parentName, hex } = map.parent!; + const n = (map.arrivalRerolls ?? 0) + 1; + const seed = arrivalSeed(this.seedOf(parentName), hex, "submap", n); + await plugin.events.forgetMap(mapName); + await regenerateRegion(plugin, mapName, { seed, arrival: true }); + map.arrivalRerolls = n; + await plugin.saveSettings(); + await plugin.mapStore.flush(); + const biome = hexBiomeAt(plugin, parentName, hex); + await plugin.mapStore.editNoteText(mapName, (c) => restateArrival(c, { + made: { generator: `the ${biome ? this.biomeText(biome) : "region's"} biome`, palette: map.paletteName, cols: map.gridSize.cols, rows: map.gridSize.rows, seed }, + rerolls: n, + locked: map.arrival === "locked", + })); + plugin.refreshHexMap(); + new Notice(`Rerolled ${plugin.mapLabel(mapName)}.`); + return true; + } + /** Lock a place made on arrival (GM4): from now on only God may reroll it. */ async lock(mapName: string): Promise { const { plugin } = this; diff --git a/src/arrival/EventsService.ts b/src/arrival/EventsService.ts new file mode 100644 index 00000000..acfb4c9e --- /dev/null +++ b/src/arrival/EventsService.ts @@ -0,0 +1,85 @@ +/** + * The Events ledgers in map notes (SP6; pure parts in eventsLedger.ts). + * + * - `ledgersFor` reads what a map roll must leave out: the root map's + * ledger (per world) and the map's own (per map). Read fresh from the + * notes every time, so a row deleted by hand frees its event at once. + * - `record` writes what a roll fired: `per world` rows to the root map's + * note, `per map` rows to the map's own. Nothing fired, nothing written. + * - `forgetMap` takes out the rows a map's own landscape fired (its + * Where names the map), before that landscape is rerolled. + * + * Reads and writes go through the map-note write queue (editNoteText), so + * no map write lands in between. + */ + +import type HexmakerPlugin from "../HexmakerPlugin"; +import { mapLinkText } from "../maps/mapNote"; +import { eventOnMap, eventRow, NO_LEDGERS, readEvents, withEvents, withoutEvents, type FiredEvent, type LedgerEvent, type Ledgers } from "./eventsLedger"; + +type Host = Pick; + +export class EventsService { + constructor(private plugin: Host) {} + + /** The top of `map`'s map tree (the map itself when it has no parent). */ + rootOf(map: string): string { + const seen = new Set(); + let at = map; + while (!seen.has(at)) { + seen.add(at); + const up = this.plugin.parentOf(at)?.map; + if (!up || !this.plugin.getMap(up)) break; + at = up; + } + return at; + } + + /** A map note's ledger rows (none when it has no note or no ## Events). */ + private async read(map: string): Promise { + let text = ""; + await this.plugin.mapStore.editNoteText(map, (c) => { text = c; return c; }); + return readEvents(text); + } + + /** + * The ledgers for a roll on `map`. A map that isn't made yet passes + * `parent` (where it will sit) instead: its own ledger is empty and the + * world is its parent's. + */ + async ledgersFor(where: { map?: string; parent?: string }): Promise { + const own = where.map && this.plugin.getMap(where.map) ? where.map : undefined; + const from = own ?? (where.parent && this.plugin.getMap(where.parent) ? where.parent : undefined); + if (!from) return NO_LEDGERS; + const root = this.rootOf(from); + const world = await this.read(root); + const map = !own ? [] : own === root ? world : await this.read(own); + return { world, map }; + } + + /** + * Write the events a roll on `map` fired: per world to the root map's + * note, per map to `map`'s. Returns how many rows were written. + */ + async record(map: string, fired: readonly FiredEvent[] | undefined, date = new Date().toISOString().slice(0, 10)): Promise { + if (!fired?.length || !this.plugin.getMap(map)) return 0; + const where = { mapLink: mapLinkText(map), date }; + const byNote = new Map(); + const root = this.rootOf(map); + for (const f of fired) { + const note = f.scope === "world" ? root : map; + byNote.set(note, [...(byNote.get(note) ?? []), eventRow(f, where)]); + } + let n = 0; + for (const [note, rows] of byNote) { + if (await this.plugin.mapStore.editNoteText(note, (c) => withEvents(c, rows))) n += rows.length; + } + return n; + } + + /** Take out the ledger rows whose Where is on `map` (its own and its world's). */ + async forgetMap(map: string): Promise { + const notes = new Set([map, this.rootOf(map)]); + for (const note of notes) await this.plugin.mapStore.editNoteText(note, (c) => withoutEvents(c, (e) => eventOnMap(e, map))); + } +} diff --git a/src/arrival/eventsLedger.ts b/src/arrival/eventsLedger.ts new file mode 100644 index 00000000..3862acfc --- /dev/null +++ b/src/arrival/eventsLedger.ts @@ -0,0 +1,252 @@ +/** + * Once-only rows and the Events ledger (plan-tables-everywhere §2.7, SP6, + * GM8). + * + * - A table row whose `Once` column says `per world` or `per map` can come + * up only once. Repeatable rows simply have no Once value. + * - When a map roll (arrival, generation) lands on such a row, it is written + * as a row of a readable `## Events` table: in the root map's note (the + * top of the map tree) for `per world`, in the map's own note for + * `per map`. The section is added only when the first event fires. + * - Rolling then leaves the row out and rescales the odds (the resolver's + * `isUsed`): the hand-roller's "roll again if you get it". + * - The ledger is plain text: deleting a row makes the event possible again. + * - Rolls by hand (Tables view, roll blocks) have no world, so nothing is + * tracked there; the result says so (T7). + * + * Pure: no Obsidian imports. + */ + +import { cellSpans, rollLabel, rowInfoOf, type RandomTable, type RandomTableEntry, type RollOutcome } from "../random-tables/randomTable"; + +export type OnceScope = "world" | "map"; + +export const EVENTS_HEADING = "## Events"; +export const EVENTS_HEADERS = ["Event", "Where", "When", "From"] as const; + +/** One ledger row, as written (cells keep their text: links stay links). */ +export interface LedgerEvent { + event: string; + where: string; + when: string; + from: string; +} + +/** A Once row a roll landed on (Resolved.onces). */ +export interface OnceHit { + /** The table's key (its path, or path#heading). */ + table: string; + index: number; + scope: OnceScope; + /** The row's result as the table has it (a link's target without brackets). */ + result: string; + /** The result links a note. */ + link: boolean; +} + +/** A Once row that fired during a map roll, and where (the hex, "x_y", when known). */ +export interface FiredEvent extends OnceHit { + hex?: string; +} + +// ── reading and writing the ## Events table ───────────────────────────── + +const COL_ALIASES: Record = { + event: "event", what: "event", events: "event", + where: "where", place: "where", + when: "when", date: "when", + from: "from", table: "from", source: "from", +}; + +const norm = (s: string) => s.toLowerCase().replace(/[^a-z]/g, ""); + +function cellsOf(line: string): string[] { + return cellSpans(line).map((s) => line.slice(s.start, s.end).trim().replace(/\\\|/g, "|")); +} + +const isTableLine = (l: string) => /^\s*\|/.test(l); +const isSeparator = (l: string) => /^\s*\|?[\s|:-]+\|?\s*$/.test(l) && l.includes("-"); + +interface Located { + lines: string[]; + eol: string; + /** The heading line, or -1. */ + heading: number; + /** End of the section (exclusive). */ + end: number; + /** The table: header line, first row line, end (exclusive); null when the section has none. */ + table: { header: number; first: number; end: number; cols: (keyof LedgerEvent | undefined)[] } | null; +} + +function locate(content: string): Located { + const eol = content.includes("\r\n") ? "\r\n" : "\n"; + const lines = content.replace(/\r\n?/g, "\n").split("\n"); + const heading = lines.findIndex((l) => /^##\s+events\s*$/i.test(l.trim())); + if (heading < 0) return { lines, eol, heading, end: lines.length, table: null }; + let end = heading + 1; + while (end < lines.length && !/^#{1,2}\s/.test(lines[end])) end++; + for (let i = heading + 1; i < end; i++) { + if (!isTableLine(lines[i]) || isSeparator(lines[i])) continue; + const cols = cellsOf(lines[i]).map((h) => COL_ALIASES[norm(h)]); + if (!cols.includes("event")) continue; + let first = i + 1; + if (first < end && isSeparator(lines[first])) first++; + let tEnd = first; + while (tEnd < end && isTableLine(lines[tEnd])) tEnd++; + return { lines, eol, heading, end, table: { header: i, first, end: tEnd, cols } }; + } + return { lines, eol, heading, end, table: null }; +} + +function rowOf(line: string, cols: (keyof LedgerEvent | undefined)[]): LedgerEvent { + const cells = cellsOf(line); + const out: LedgerEvent = { event: "", where: "", when: "", from: "" }; + cols.forEach((c, i) => { if (c) out[c] = cells[i] ?? ""; }); + return out; +} + +/** The rows of a note's `## Events` table (empty rows skipped). */ +export function readEvents(content: string): LedgerEvent[] { + const { lines, table } = locate(content); + if (!table) return []; + const out: LedgerEvent[] = []; + for (let i = table.first; i < table.end; i++) { + if (isSeparator(lines[i])) continue; + const r = rowOf(lines[i], table.cols); + if (r.event.trim()) out.push(r); + } + return out; +} + +const escapeCell = (s: string) => s.replace(/\|/g, "\\|").replace(/\r?\n/g, " "); + +/** + * The note with `rows` added to its `## Events` table, in the table's own + * column order (made at the end of the note when there's none yet). + * Everything else stays as it was. Unchanged when there's nothing to add. + */ +export function withEvents(content: string, rows: readonly LedgerEvent[]): string { + if (!rows.length) return content; + const loc = locate(content); + const { lines, eol } = loc; + if (loc.table) { + const cols = loc.table.cols; + const header = cellsOf(lines[loc.table.header]); + const line = (r: LedgerEvent) => `| ${header.map((_, i) => { const c = cols[i]; return escapeCell(c ? r[c] : ""); }).join(" | ")} |`; + lines.splice(loc.table.end, 0, ...rows.map(line)); + return lines.join(eol); + } + const table = [ + `| ${EVENTS_HEADERS.join(" | ")} |`, + `| ${EVENTS_HEADERS.map(() => "---").join(" | ")} |`, + ...rows.map((r) => `| ${[r.event, r.where, r.when, r.from].map(escapeCell).join(" | ")} |`), + ]; + if (loc.heading >= 0) { + // A section with no table yet: the table goes right under the heading's text. + let at = loc.end; + while (at > loc.heading + 1 && lines[at - 1].trim() === "") at--; + lines.splice(at, 0, "", ...table); + return lines.join(eol); + } + while (lines.length && lines[lines.length - 1].trim() === "") lines.pop(); + return [...lines, "", EVENTS_HEADING, "", "Once-only events that have happened. Delete a row to make the event possible again.", "", ...table, ""].join(eol); +} + +/** The note without the `## Events` rows `drop` picks. Unchanged when it picks none. */ +export function withoutEvents(content: string, drop: (e: LedgerEvent) => boolean): string { + const loc = locate(content); + if (!loc.table) return content; + const { lines, eol, table } = loc; + const keep: string[] = []; + let dropped = false; + for (let i = table.first; i < table.end; i++) { + if (!isSeparator(lines[i]) && drop(rowOf(lines[i], table.cols))) { dropped = true; continue; } + keep.push(lines[i]); + } + if (!dropped) return content; + lines.splice(table.first, table.end - table.first, ...keep); + return lines.join(eol); +} + +// ── matching ledger rows to table rows ────────────────────────────────── + +/** The name a cell or key stands for: its first link's target (or its text), without folders, `.md` or an alias; any case. */ +export function ledgerName(text: string): string { + const t = text.trim(); + const link = /\[\[([^\]]+)\]\]/.exec(t)?.[1] ?? t; + const [target, ...heading] = link.split("|")[0].split("#"); + const base = target.trim().replace(/\.md$/i, "").replace(/^.*\//, ""); + return [base, ...heading.map((h) => h.trim())].join("#").toLowerCase(); +} + +/** Whether the ledger holds the row `result` of table `tableKey` (a blank From matches any table). */ +export function ledgerHas(events: readonly LedgerEvent[], tableKey: string, result: string): boolean { + const want = ledgerName(result); + const table = ledgerName(tableKey); + return events.some((e) => ledgerName(e.event) === want && (!e.from.trim() || ledgerName(e.from) === table)); +} + +/** Whether a ledger row's Where names map `mapName` (`[[_name]] 4, 7`). */ +export function eventOnMap(e: LedgerEvent, mapName: string): boolean { + const link = /\[\[([^\]|#]+)/.exec(e.where)?.[1]?.trim().replace(/^.*\//, "").replace(/\.md$/i, ""); + return !!link && link.toLowerCase() === `_${mapName}`.toLowerCase(); +} + +// ── the tracker one map roll uses ─────────────────────────────────────── + +export interface Ledgers { + /** The root map's ledger (per world). */ + world: readonly LedgerEvent[]; + /** The map's own ledger (per map). */ + map: readonly LedgerEvent[]; +} + +export const NO_LEDGERS: Ledgers = { world: [], map: [] }; + +/** + * What one map roll knows about Once rows: the ledgers as they were when it + * started, plus what fired during it (so a generator placing a hundred + * hexes still finds a once-only row at most once). + */ +export class OnceTracker { + readonly fired: FiredEvent[] = []; + constructor(private ledgers: Ledgers = NO_LEDGERS) {} + + /** For ResolveContext.isUsed. */ + isUsed = (tableKey: string, _index: number, entry: RandomTableEntry, scope?: OnceScope): boolean => { + const name = entry.result; + if (this.fired.some((f) => (!scope || f.scope === scope) && ledgerName(f.table) === ledgerName(tableKey) && ledgerName(f.result) === ledgerName(name))) return true; + return ledgerHas(scope === "map" ? this.ledgers.map : this.ledgers.world, tableKey, name); + }; + + /** Record the Once rows a roll landed on. */ + fire(hits: readonly OnceHit[] | undefined, hex?: string): void { + for (const h of hits ?? []) this.fired.push(hex ? { ...h, hex } : { ...h }); + } +} + +/** A fired event as a ledger row: `[[The Silent Fleet]] | [[_drift]] 4, 7 | 2026-10-11 | [[Rare events]]`. */ +export function eventRow(f: FiredEvent, where: { mapLink: string; date: string }): LedgerEvent { + const name = f.result.replace(/^.*\//, ""); + const table = f.table.replace(/\.md(?=#|$)/i, "").replace(/^.*\//, ""); + return { + event: f.link ? `[[${name}]]` : f.result, + where: f.hex ? `${where.mapLink} ${f.hex.replace("_", ", ")}` : where.mapLink, + when: where.date, + from: `[[${table}]]`, + }; +} + +// ── rolls by hand (T7) ────────────────────────────────────────────────── + +/** The note for a hand roll that landed on a Once row: it isn't tracked there. Undefined for repeatable rows. */ +export function untrackedOnceLabel(table: RandomTable, index: number): string | undefined { + const once = rowInfoOf(table, index).once; + if (!once) return undefined; + return `once per ${once}: not tracked here`; +} + +/** The label under a hand roll: the die face ("d20 → 14"), and for a Once row that it isn't tracked there. */ +export function handRollLabel(table: RandomTable, outcome: RollOutcome): string { + return [rollLabel(table, outcome), untrackedOnceLabel(table, outcome.index)].filter(Boolean).join(" · "); +} diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index e7e4f261..5578d03d 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -74,6 +74,7 @@ import { FolderTreePickerModal } from "./FolderTreePickerModal"; import { FactionPickerModal } from "./FactionPickerModal"; import { GeoRegionPickerModal } from "./GeoRegionPickerModal"; import { DrawingToolPanel, OverlayPanel } from "./HexSidePanel"; +import { renderUnchartedLayer, unchartedKeys } from "./unchartedLayer"; import { BADGE_INFO, badgeNameLimit, badgeSize, hexKeyFromBasename, hiddenBadges, legendBadgeKinds, linkedNotesText, linksBySection, linkSectionsFromCache, renderLinkBadgeLayer, type BadgeSection } from "./linkBadges"; import { legendSize, MAP_LEGEND_NAME_MAX, renderTerrainLegend, usedTerrainEntries } from "./terrainLegend"; import { TokenModal } from "./TokenModal"; @@ -4648,6 +4649,8 @@ export class HexMapView extends ItemView { this.renderCoordLabelsLayer(gridContainer); // Badges reuse the hex centres the coord labels just measured. this.renderLinkBadges(gridContainer); + // So does the uncharted marker (no layout reads of its own). + renderUnchartedLayer(gridContainer, this.coordPlacements, this.coordGridSize, unchartedKeys(this.plugin.mapStore.all(this.activeMapName))); this.drawHexNames(gridContainer); if (this.bgCalibrating) { this.renderCalibrationOutlines(gridContainer); @@ -4994,6 +4997,11 @@ export class HexMapView extends ItemView { const region = regionMapAt(this.plugin.settings.maps, this.activeMapName, key)?.name; const locations = this.plugin.mapStore.get(this.activeMapName, key)?.locations?.length ?? 0; const icons: Record = { "enter-region": "log-in", "edit-region": "settings-2", "set-biome": "trees", center: "crosshair", locations: "list" }; + // Arrival (GM4): a world set to make places makes this hex's region on the spot, in any mode. + if (!region && this.plugin.arrival.canArrive(this.activeMapName, px, py)) { + menu.add("ow.arrive", "Go there", "footprints", () => void this.arriveAt(px, py)); + menu.addSeparator(); + } for (const it of overworldMenu(this.getActiveMap(), !!region, locations)) { const id = `ow.${it.id}` as const; const title = it.id === "enter-region" && region ? `Enter region: ${this.plugin.mapLabel(region)}` : it.enabled ? it.title : `${it.title} (${it.hint})`; @@ -5071,6 +5079,9 @@ export class HexMapView extends ItemView { if (act.kind === "enter" && region) { if (cell) this.enterRegionAt(region, cell.x, cell.y); else this.navigateToMap(region); + } else if (!region && this.plugin.arrival.canArrive(this.activeMapName, px, py)) { + // Arrival on: going there makes the region from its biome (GM4). + await this.arriveAt(px, py); } else if (act.kind === "place") new BiomePickerModal(this.biomeHost(), this.activeMapName, px, py).open(); else if (act.kind === "hint") new Notice(act.hint); return; diff --git a/src/hex-map/HexSidePanel.ts b/src/hex-map/HexSidePanel.ts index 4b908eee..d7726e8c 100644 --- a/src/hex-map/HexSidePanel.ts +++ b/src/hex-map/HexSidePanel.ts @@ -89,6 +89,7 @@ export type OverlayKey = | "showCoords" | "showHexNames" | "showTokenNames" + | "showUncharted" | "showTerrainIcons" | "showIconOverrides" | "showPaths"; @@ -109,6 +110,8 @@ const OVERLAY_OPTIONS: OverlayOption[] = [ { key: "showCoords", label: "Coordinates", cssClass: "duckmage-hide-coords", inLabels: true }, { key: "showHexNames", label: "Hex names", cssClass: "duckmage-hide-hex-names", inLabels: true }, { key: "showTokenNames", label: "Token names", cssClass: "duckmage-hide-token-names", inLabels: true }, + // Hexes still to roll on arrival (a ? mark). + { key: "showUncharted", label: "Uncharted (?)", cssClass: "duckmage-hide-uncharted", inLabels: true }, ]; /** Optional layers-menu rows (kept out of the positional callbacks). */ diff --git a/src/hex-map/help.md b/src/hex-map/help.md index b081306c..3f28e4dd 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -179,7 +179,7 @@ A road or river that ends on the edge of a region, next to where the neighbour's **World types** (space). Star scatter and Orbits roll on a World types table note in `{world folder}/world-types`: which worlds they place, how often, and how each world's own map is made. Their **World types** option picks the table (**Default** is Default space, which ships with the usual odds; **None** is equal odds, and the generator says so). Each row: a **World** (a terrain of the palette), a **Weight** (decimals are fine), optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**), a sector world's **Mainworld** (the body Orbits makes its mainworld) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base** (Default space opens its planets on **Space - Planet**). A row that isn't a terrain of the palette is never placed, and the warnings name it. **Edit world types…** (Advanced: Terrain generators; in the Star scatter and Orbits options, or the command) edits the rows, and its preview rolls for a palette, map, orbit and star just as the generators do, so its odds are the real odds. The same note also has a **Stars** table (the star Orbits picks when its Star choice is Random, by **Weight**) and a **Sector features** table (Star scatter's special hexes, each with a **Chance** per star system hex, like `1 in 50` or `2%`); the editor has a tab and a preview for each. Changes save automatically (no Save button); a row marked incomplete isn't saved until it's finished, and is dropped when you close the editor. Hand edits to the note made meanwhile are kept. Needs Build or God. -**More in a table** (all optional; old tables read the same). Weights can be decimals (`3.5`) or percentages. Extra columns are kept and shown in the Random Tables view. The columns **Roll** (`now` / `on arrival`), **Shown as**, **Once** (`per world` / `per map`) and **When** (`zone: outer; star: red dwarf`), and `rows:` in the frontmatter (text, note, table, generator, terrain, biome or any), are read and checked now (**Check tables**) and used by later features. +**More in a table** (all optional; old tables read the same). Weights can be decimals (`3.5`) or percentages. Extra columns are kept and shown in the Random Tables view. The columns **Roll** (`now` / `on arrival`), **Shown as**, **Once** (`per world` / `per map`) and **When** (`zone: outer; star: red dwarf`), and `rows:` in the frontmatter (text, note, table, generator, terrain, biome or any), are read and checked (**Check tables**). **Space tables.** The command **Convert world types to tables** (or the button under **Generator tables** in a space map's properties) turns each World types note into ordinary random tables in `{tables folder}/space//`: `Sector/` has **Charted sector** (what a star system hex is), **Unexplored sector** (the same, but only half the systems are known), **Mainworlds** and **Uncharted** (what an unknown hex turns out to be); `System/` has **Stars** and **Inner**, **Habitable** and **Outer orbits**. They give the same odds as the note did and roll like any table. The old note is backed up first and kept: it gets a **Tables** list linking each generator role to its table (change a link there to use another table) and the tables shown below it, so you can roll them from the note. Converting twice changes nothing. @@ -187,7 +187,9 @@ A road or river that ends on the edge of a region, next to where the neighbour's **Unknown hexes.** A table row whose **Roll** is `on arrival` isn't rolled when the map is made: the hex shows its **Shown as** terrain (a somewhat known system shows as a star system; an uncharted hex shows nothing) and the map note's Hexes table gets an **On arrival** cell naming the table to roll. You can type a table into any hex's On arrival cell by hand. The first time the hex is opened, the table is rolled (with the map's seed, so the same world gives the same result), the hex gets what came up and the cell is cleared: the sector learns what the system is. **New map from this hex…** rolls it first too, and the form starts from the rolled row. -**Arriving somewhere new.** In map properties, **Arriving somewhere new** can be set to **Make the place, in any mode** (maps under it do the same unless they say otherwise; unset everywhere is off and nothing changes). Then a hex with no map gets **Go there** in its right-click menu (Ctrl+click does the same): its On arrival table is rolled and its map is made at once, with no form and no preview, from the row's Size, Generator, Options, Palette and Base, else the palette's submap settings. This works in Play. The new map opens in the mode you were in, and its note gets an **Arrival** section saying what was rolled and how the map was made. Until you lock it, the bar next to the mode switch has **Reroll** (makes the place again, in any mode) and **Lock**; once locked (`arrival: locked` in its note), only God can reroll it. A locked hex is never arrived into. +**Arriving somewhere new.** In map properties, **Arriving somewhere new** can be set to **Make the place, in any mode** (maps under it do the same unless they say otherwise; unset everywhere is off and nothing changes). Then a hex with no map gets **Go there** in its right-click menu (Ctrl+click does the same): its On arrival table is rolled and its map is made at once, with no form and no preview, from the row's Size, Generator, Options, Palette and Base, else the palette's submap settings. This works in Play. The new map opens in the mode you were in, and its note gets an **Arrival** section saying what was rolled and how the map was made. Until you lock it, the bar next to the mode switch has **Reroll** (makes the place again, in any mode) and **Lock**; once locked (`arrival: locked` in its note), only God can reroll it. A locked hex is never arrived into. On an overworld, going to a hex with a biome and no region yet (click it, or **Go there**) makes its region from that biome, seeded, with no form, and the same Reroll/Lock rules. Hexes still waiting for their On arrival roll show a small **?** (layers menu → Labels → **Uncharted (?)**). + +**Once-only rows.** A row whose **Once** column says `per world` or `per map` comes up only once; blank means it can repeat. When the map rolls one (arriving, or a generator), it's written in an **## Events** table: in the top map's note for `per world`, in the map's own note for `per map`. After that the row is skipped and the other rows' odds grow. Delete its row in **## Events** to make it possible again. Rolls by hand in the Random Tables view aren't tracked, and say so. With generators on, new maps can also use the built-in **biomes and presets** (Grassland, Taiga, Swamp, Archipelago, Volcanic and more). They place terrain by type, so they work with any palette whose terrains have types. diff --git a/src/hex-map/newChildMap.ts b/src/hex-map/newChildMap.ts index ae11ee48..ba8d334d 100644 --- a/src/hex-map/newChildMap.ts +++ b/src/hex-map/newChildMap.ts @@ -55,14 +55,15 @@ export function startNewChildMap(host: NewChildMapHost, parentMap: string, x: nu export function startNewLocation(host: NewChildMapHost, parentMap: string, x: number, y: number): void { // An unknown hex (an On arrival table) is rolled first, so the form // starts from what turned out to be there (T5). - const rolled = host.plugin.arrival.resolveHex(parentMap, x, y, "new-child-map"); - if (rolled) { - void host.plugin.saveSettings(); - new Notice(`Rolled on arrival: ${rolled.chain}.`); - } - new NewMapSetupModal(host.app, host.plugin, ({ name }) => { - void host.plugin.linkSubmap(parentMap, x, y, name).then(() => host.onCreated(name, "location")); - }, { map: parentMap, x, y }).open(); + void host.plugin.arrival.resolveHex(parentMap, x, y, "new-child-map").then((rolled) => { + if (rolled) { + void host.plugin.saveSettings(); + new Notice(`Rolled on arrival: ${rolled.chain}.`); + } + new NewMapSetupModal(host.app, host.plugin, ({ name }) => { + void host.plugin.linkSubmap(parentMap, x, y, name).then(() => host.onCreated(name, "location")); + }, { map: parentMap, x, y }).open(); + }); } export function startNewRegion(host: NewChildMapHost, parentMap: string, x: number, y: number): void { diff --git a/src/hex-map/unchartedLayer.ts b/src/hex-map/unchartedLayer.ts new file mode 100644 index 00000000..de1a1951 --- /dev/null +++ b/src/hex-map/unchartedLayer.ts @@ -0,0 +1,47 @@ +/** + * The uncharted marker: a small "?" on every hex whose On arrival cell is + * still waiting to be rolled (plan-tables-everywhere §2.6). A layer of its + * own, shown or hidden from the layers menu (Labels → Uncharted; on by + * default) by a class on the viewport. + * + * No layout reads here (CLAUDE.md read-then-write rule): hex centres come + * from the placements the coordinate layer already measured, so this only + * writes. + */ + +import type { HexData } from "../maps/mapNote"; + +export const UNCHARTED_LAYER_CLASS = "duckmage-uncharted-layer"; + +/** Keys ("x_y") of hexes with an On arrival roll still to make. */ +export function unchartedKeys(hexes: ReadonlyMap>): Set { + const out = new Set(); + for (const [k, h] of hexes) if (h.onArrival?.trim()) out.add(k); + return out; +} + +/** + * (Re)draw the marker layer over `grid`. `placements` are hex centres in + * grid pixels, keyed "x,y" (the coordinate layer's); `gridSize` the grid's + * measured size. No layer when nothing is uncharted. + */ +export function renderUnchartedLayer( + grid: HTMLElement, + placements: readonly { key: string; ox: number; oy: number }[], + gridSize: { w: number; h: number }, + uncharted: ReadonlySet, +): void { + grid.querySelector(`.${UNCHARTED_LAYER_CLASS}`)?.remove(); + if (uncharted.size === 0) return; + const gw = gridSize.w || 1; + const gh = gridSize.h || 1; + const layer = grid.createDiv({ cls: UNCHARTED_LAYER_CLASS }); + for (const p of placements) { + if (!uncharted.has(p.key.replace(",", "_"))) continue; + const mark = layer.createSpan({ cls: "duckmage-uncharted-mark", text: "?", attr: { "aria-label": "Uncharted: rolled when someone arrives" } }); + mark.setCssProps({ + "--duckmage-uncharted-x": `${((p.ox / gw) * 100).toFixed(3)}%`, + "--duckmage-uncharted-y": `${((p.oy / gh) * 100).toFixed(3)}%`, + }); + } +} diff --git a/src/maps/mapNote.ts b/src/maps/mapNote.ts index 216eb41c..5d455cd2 100644 --- a/src/maps/mapNote.ts +++ b/src/maps/mapNote.ts @@ -422,6 +422,7 @@ const SIMPLE_KEYS: [keyof MapSettings, string, Kind, string[]?][] = [ ["linkBadgeSize", "link-badge-size", "str"], ["showHexNames", "show-hex-names", "bool"], ["showTokenNames", "show-token-names", "bool"], + ["showUncharted", "show-uncharted", "bool"], // Hex-name font (NM3): plain words, read forgivingly (hexNameFont.ts). ["hexNameFont", "name-font", "str"], ["hexNameSize", "name-size", "str"], diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index 4220bb60..cc4564eb 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -202,6 +202,12 @@ export interface RegionGenOptions { hexTerrain?: string; /** The region's own biome (a hex set to a user's biome, which its terrain can't tell); default read from the overworld. */ biome?: BiomeId; + /** + * Made or rerolled on arrival (GM4): the caller has checked the rules + * (arrival on; a new place may be rerolled until it's locked), so the + * map's work mode doesn't stop it here. + */ + arrival?: boolean; } /** @@ -348,7 +354,7 @@ export interface CreateRegionOptions extends RegionGenOptions { */ export async function createRegion(plugin: HexmakerPlugin, parentName: string, px: number, py: number, opts: CreateRegionOptions): Promise<{ name: string } | { error: string }> { const parent = plugin.getMap(parentName); - if (!canAdd(parent)) return { error: ADD_REGION_LOCKED_HINT }; + if (!opts.arrival && !canAdd(parent)) return { error: ADD_REGION_LOCKED_HINT }; if (!parent?.regions) return { error: "Set up this map's regions first." }; if (!meshes(parent.regions)) return { error: "Hex-flower regions don't join up yet: make this one from the new-map form." }; const hex = `${px}_${py}`; @@ -478,7 +484,7 @@ export function reshapeGate(plugin: HexmakerPlugin, parentName: string, px: numb export async function regenerateRegion(plugin: HexmakerPlugin, regionName: string, opts: RegionGenOptions = {}): Promise { const region = plugin.getMap(regionName); if (region?.submapKind !== "region" || !region.parent) return 0; - if (!canReshape(plugin.getMap(region.parent.map))) return 0; // see reshapeGate + if (!opts.arrival && !canReshape(plugin.getMap(region.parent.map))) return 0; // see reshapeGate const [px, py] = region.parent.hex.split("_").map(Number); const planned = await planOrError(plugin, region.parent.map, px, py, opts); if (planned && "error" in planned) { diff --git a/src/random-tables/RandomTableModal.ts b/src/random-tables/RandomTableModal.ts index afb700ff..989734bf 100644 --- a/src/random-tables/RandomTableModal.ts +++ b/src/random-tables/RandomTableModal.ts @@ -1,8 +1,9 @@ import { App, Notice, TFile } from "obsidian"; +import { handRollLabel } from "../arrival/eventsLedger"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { normalizeFolder } from "../utils"; -import { parseRandomTable, rollTable, rollLabel, resolveTable, rowOdds, dieLabel, emptyTableMessage } from "./randomTable"; +import { parseRandomTable, rollTable, resolveTable, rowOdds, dieLabel, emptyTableMessage } from "./randomTable"; import { VIEW_TYPE_RANDOM_TABLES } from "../constants"; import { RandomTableEditorModal } from "./RandomTableEditorModal"; import { groupTableFiles } from "./tablePickerGroups"; @@ -376,7 +377,7 @@ export class RandomTableModal extends HexmakerModal { tr.toggleClass("is-rolled", tr.dataset.index === String(outcome.index)); }); resultBox.el.show(); - const face = rollLabel(table, outcome); + const face = handRollLabel(table, outcome); resultBox.face.setText(face); resultBox.face.toggle(!!face); resultBox.textarea.value = outcome.entry.result; diff --git a/src/random-tables/RandomTableView.ts b/src/random-tables/RandomTableView.ts index d53dcee1..2b625ca3 100644 --- a/src/random-tables/RandomTableView.ts +++ b/src/random-tables/RandomTableView.ts @@ -1,3 +1,4 @@ +import { handRollLabel } from "../arrival/eventsLedger"; import { ItemView, MarkdownRenderer, @@ -21,7 +22,6 @@ import { parseRandomTableWithReport, emptyTableMessage, rollTable, - rollLabel, resolveTable, rowOdds, rowInfoOf, @@ -1870,7 +1870,7 @@ export class RandomTableView extends ItemView { resultBox.show(); if (faceEl) { - const face = rollLabel(table, outcome); + const face = handRollLabel(table, outcome); faceEl.setText(face); faceEl.toggle(!!face); } diff --git a/src/random-tables/RollerBlock.ts b/src/random-tables/RollerBlock.ts index 92be75e2..1e67a810 100644 --- a/src/random-tables/RollerBlock.ts +++ b/src/random-tables/RollerBlock.ts @@ -1,6 +1,7 @@ import { TFile } from "obsidian"; +import { handRollLabel } from "../arrival/eventsLedger"; import type HexmakerPlugin from "../HexmakerPlugin"; -import { dieLabel, emptyTableMessage, parseRandomTable, rollLabel, rollTable } from "./randomTable"; +import { dieLabel, emptyTableMessage, parseRandomTable, rollTable } from "./randomTable"; /** * Registers the `duckmage-roller` fenced code block processor. @@ -126,7 +127,7 @@ export function registerRollerBlock(plugin: HexmakerPlugin): void { resultTextarea.value = display; // "d20 → 14": the face rolled, so it can be checked against the note. - const face = rollLabel(table, outcome); + const face = handRollLabel(table, outcome); faceEl.setText(face); faceEl.toggle(!!face); resultBox.show(); diff --git a/src/random-tables/resolve.ts b/src/random-tables/resolve.ts index a43fd630..e7cbb491 100644 --- a/src/random-tables/resolve.ts +++ b/src/random-tables/resolve.ts @@ -26,6 +26,7 @@ import { mulberry32 } from "../../packages/hex-wfc/src/rng"; import { conditionsFit, type ConditionContext } from "./tableConditions"; +import type { OnceHit } from "../arrival/eventsLedger"; import { locateRollTable, parseRandomTable, resolveTable, rollTable, rowInfoOf, type RandomTable, type RandomTableEntry, type RowType } from "./randomTable"; /** What a cell turned out to be. */ @@ -52,8 +53,8 @@ export interface ResolveContext extends ConditionContext { onlyTerrains?: boolean; /** Stop at a row whose Roll is "on arrival" instead of rolling it through. */ deferArrival?: boolean; - /** Once rows already used (the ledger): those rows are left out. */ - isUsed?: (tableKey: string, index: number, entry: RandomTableEntry) => boolean; + /** Once rows already used (the ledger): those rows are left out. `scope` is the row's Once. */ + isUsed?: (tableKey: string, index: number, entry: RandomTableEntry, scope: "world" | "map") => boolean; /** Deepest nesting followed (default 5). */ maxDepth?: number; } @@ -78,6 +79,12 @@ export interface Resolved { chain: ResolveStep[]; /** The last Once row on the chain, for the caller's ledger. */ once?: { table: string; index: number; scope: "world" | "map" }; + /** + * Every Once row on the chain, outermost first, with what it said (for + * the Events ledger, arrival/eventsLedger.ts). Not set for a deferred + * result: nothing has happened yet. + */ + onces?: OnceHit[]; /** An on-arrival row: what the hex shows until then. */ shownAs?: string; } @@ -148,7 +155,7 @@ class Resolver { const e = table.entries[i]; const info = rowInfoOf(table, i); if (!conditionsFit(info.when, this.ctx)) { skipped.push({ table: key, index: i, result: e.result, why: "when" }); return 0; } - if (info.once && this.ctx.isUsed?.(key, i, e)) { skipped.push({ table: key, index: i, result: e.result, why: "used" }); return 0; } + if (info.once && this.ctx.isUsed?.(key, i, e, info.once)) { skipped.push({ table: key, index: i, result: e.result, why: "used" }); return 0; } if (this.ctx.onlyTerrains) { const { kind, value } = cellKind(table, e, this.lookup, this.ctx); if (kind === "table") { @@ -208,13 +215,18 @@ class Resolver { if (once) out.once = once; return out; } + const hit: OnceHit | undefined = info.once + ? { table: key, index, scope: info.once, result: entry.result, link: entryLink(table, entry) !== undefined } + : undefined; if (kind === "table") { const inner = this.roll(value, rand, [...visited, key], nextChain, nextAttrs); if (!inner.once && once) inner.once = once; + if (hit && inner.kind !== "deferred" && inner.kind !== "empty" && inner.kind !== "loop") inner.onces = [hit, ...(inner.onces ?? [])]; return inner; } const out: Resolved = { kind, value, attrs: nextAttrs, chain: nextChain }; if (once) out.once = once; + if (hit) out.onces = [hit]; return out; } diff --git a/src/types.ts b/src/types.ts index 8d78f831..9dc64b1b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -195,6 +195,8 @@ export interface MapData { showRegionOverlay?: boolean; // undefined = false (opt-in) showGmLayer?: boolean; // undefined = true (older maps); new maps are created with false showTokens?: boolean; // undefined = true (on by default) + /** The "?" on hexes with an On arrival roll still to come. undefined = true. */ + showUncharted?: boolean; /** Corner badges per link type (towns, dungeons…). undefined = true. */ showLinkBadges?: boolean; /** Badge types turned off in the layers menu (BADGE_SECTIONS names). */ diff --git a/src/workMode.ts b/src/workMode.ts index cfa5eb90..c7064531 100644 --- a/src/workMode.ts +++ b/src/workMode.ts @@ -218,6 +218,7 @@ export const MENU_ACTIONS = { "hex.remove-icon": "paint-icon", // overworld hex menu "ow.enter-region": "navigate", + "ow.arrive": "discover", "ow.edit-region": "open-editor", "ow.set-biome": "place-biome", "ow.center": "navigate", diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index b159ad36..9c29532d 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -28,6 +28,7 @@ import { rowSubmapDefault } from "../arrival/arrival"; import { STAR_SCATTER_ID } from "./procedural/starScatter"; import { ORBITS_ID } from "./procedural/orbits"; import { SIZE_PRESETS, type SizePreset } from "./sizePresets"; +import { NO_LEDGERS, type Ledgers } from "../arrival/eventsLedger"; import { LIVE_PREVIEW_DELAY_MS, sizeFromInput } from "../sizeInput"; import { BLANK_ID, @@ -95,6 +96,8 @@ export class NewMapSetupModal extends HexmakerModal { private kindId = BLANK_ID; private options: Record = {}; private seed = randomSeed(); + /** The Events ledgers where the new map will sit (SP6): once-only rows already used are left out. */ + private ledgers: Ledgers = NO_LEDGERS; private cols: number; private rows: number; private baseTerrain: string | undefined; @@ -193,7 +196,9 @@ export class NewMapSetupModal extends HexmakerModal { ? `New location — ${this.originTerrain ? `${this.originTerrain}, ` : ""}${this.plugin.mapLabel(this.origin.map)} hex ${this.origin.x}, ${this.origin.y}` : "New map", ); - void listGeneratorKinds(this.plugin).then((kinds) => { + const ledgers = this.origin ? this.plugin.events.ledgersFor({ parent: this.origin.map }) : Promise.resolve(NO_LEDGERS); + void Promise.all([listGeneratorKinds(this.plugin), ledgers]).then(([kinds, used]) => { + this.ledgers = used; this.kinds = kinds; this.render(); // A hint here can turn a feature on: show what it brings straight away. @@ -801,6 +806,7 @@ export class NewMapSetupModal extends HexmakerModal { terrains, grid: this.grid(), seed: this.seed, options: this.resolvedOptions(kind), context: this.context, region: this.placement, pathTypes: this.plugin.getPathTypes(paletteName), ...(this.origin ? { tablesFrom: this.origin.map } : {}), + ledgers: this.ledgers, }); } @@ -886,6 +892,7 @@ export class NewMapSetupModal extends HexmakerModal { quiet: true, slug: this.folderSlug(), ...(outcome?.ok && outcome.arrivals ? { arrivals: outcome.arrivals } : {}), + ...(outcome?.ok && outcome.events ? { events: outcome.events } : {}), }, ); if ("error" in result) { diff --git a/src/worldgen/procedural/orbits.ts b/src/worldgen/procedural/orbits.ts index 1e1fcce7..e38871c1 100644 --- a/src/worldgen/procedural/orbits.ts +++ b/src/worldgen/procedural/orbits.ts @@ -166,7 +166,7 @@ export function orbits( const wanted = options.star && options.star !== "random" ? roles.stars.find((s) => s.toLowerCase() === options.star) : undefined; - const star = wanted ?? rollRole(tables, "star", { rand }, roles.stars)?.terrain ?? roles.stars[0]; + const star = wanted ?? rollRole(tables, "star", { rand, where: cellKey(center[0], center[1]) }, roles.stars)?.terrain ?? roles.stars[0]; set(center, star); // The 100-diameter limit hugs the star: mark the first ring. if (roles.jumpLimit && fullRing >= 3) for (const h of ring(1)) set(h, roles.jumpLimit); diff --git a/src/worldgen/procedural/starScatter.ts b/src/worldgen/procedural/starScatter.ts index 1367da61..fc750cd8 100644 --- a/src/worldgen/procedural/starScatter.ts +++ b/src/worldgen/procedural/starScatter.ts @@ -150,7 +150,7 @@ export function starScatter( const k = cellKey(x, y); const odds = inCloud.has(k) ? density / 2 : density; if (rand() >= odds) continue; - const pick = rollRole(tables, "sector-hexes", { rand, deferArrival: true }, roles.worlds); + const pick = rollRole(tables, "sector-hexes", { rand, deferArrival: true, where: k }, roles.worlds); // A (nothing) row: empty space after all. if (!pick || pick.nothing) continue; if (pick.arrival) { diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index e5019c98..8bda0e84 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -39,6 +39,8 @@ import { generateConnected, type NewRegion } from "./neighbours"; import { WORLD_TYPES_KEY, worldTypesOption } from "../space/worldTypesSource"; import { BUILTIN_GENERATORS, BUILTIN_PREFIX, builtinModel, builtinPathType, fitBuiltinModel } from "./builtinGenerators"; import type { HexWfcModel } from "../../packages/hex-wfc/src"; +import { OnceTracker, type FiredEvent, type Ledgers } from "../arrival/eventsLedger"; +import { withOnce } from "./tableRoles"; /** * One list of terrain generators for map creation: Blank, the built-in @@ -62,6 +64,8 @@ export type GenerateOutcome = warnings: string[]; /** Hexes left to roll on arrival ("x_y" → table link): the map note's On arrival column. */ arrivals?: Map; + /** Once rows that came up (SP6): the caller writes them to the Events ledgers once the map exists. */ + events?: FiredEvent[]; } | { ok: false; message: string }; @@ -84,6 +88,12 @@ export interface GenerateRequest { * ancestors' tables win over the World types option's. */ tablesFrom?: string; + /** + * The Events ledgers (SP6) where the map sits: Once rows already used + * there are left out. Unset: none used yet (rows still fire at most once + * per run). + */ + ledgers?: Ledgers; } export interface TerrainGeneratorKind { @@ -201,6 +211,9 @@ function worldTypesChoice(plugin: HexmakerPlugin): ProcOption { return worldTypesOption(store.list().map((t) => t.name), store.defaultName()); } +/** The Once rows a run fired, for the outcome (nothing when none). */ +const firedEvents = (once: OnceTracker): { events?: FiredEvent[] } => (once.fired.length ? { events: once.fired } : {}); + const missingWorldTypes = (name: string) => `No World types table called "${name}", so equal odds.`; function procGrid(plugin: HexmakerPlugin, grid: GridSpec): ProcGrid { @@ -235,9 +248,10 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise { const orbitType = chosenPathType(req.options[ORBIT_TYPE_KEY], "orbits", req.pathTypes); const wt = plugin.worldTypeStore.sourceFor(req.options[WORLD_TYPES_KEY], req.terrains, req.tablesFrom); - const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitType, req.context, wt.source); + const once = new OnceTracker(req.ledgers); + const r = orbits(req.terrains, procGrid(plugin, req.grid), req.seed, req.options, orbitType, req.context, withOnce(wt.source, once)); if (wt.missing) r.warnings.unshift(missingWorldTypes(wt.missing)); // No type and not None on purpose: say why there are no rings. if (!orbitType && req.options[ORBIT_TYPE_KEY] !== NO_PATHS && r.cells.size) r.warnings.push("No path type for orbits, so the rings weren't drawn. Pick one under Path type for orbits (or add a path type to the palette)."); - return r.cells.size ? { ok: true, ...r } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; + return r.cells.size ? { ok: true, ...r, ...firedEvents(once) } : { ok: false, message: r.warnings[0] ?? "Nothing generated." }; }, toPaths, }, diff --git a/src/worldgen/tableRoles.ts b/src/worldgen/tableRoles.ts index 630d4bdb..985cc712 100644 --- a/src/worldgen/tableRoles.ts +++ b/src/worldgen/tableRoles.ts @@ -24,6 +24,7 @@ import type { RandomTable, RowType } from "../random-tables/randomTable"; import { resolveOdds, resolveRoll, skippedRows, type ResolveContext, type TableLookup } from "../random-tables/resolve"; import type { ConditionContext } from "../random-tables/tableConditions"; import type { OrbitZone } from "../space/worldTypes"; +import type { OnceTracker } from "../arrival/eventsLedger"; export type RoleId = "sector-hexes" | "star" | "inner-orbits" | "habitable-orbits" | "outer-orbits"; @@ -121,6 +122,25 @@ export interface TableSource { rowAttrs(role: RoleId, name: string): Record | undefined; /** Anything the source itself has to say about a role (rows it couldn't use). */ notes?(role: RoleId): string[]; + /** + * Once rows (SP6): what's used already, and where this run's fired ones + * are recorded. Set by withOnce for one generator run. + */ + readonly once?: OnceTracker; +} + +/** The source with a Once tracker for one run (the tracker's ledgers leave used rows out). */ +export function withOnce(source: TableSource | undefined, once: OnceTracker): TableSource | undefined { + if (!source) return undefined; + return { + label: source.label, + lookup: source.lookup, + terrains: source.terrains, + tableFor: (role) => source.tableFor(role), + rowAttrs: (role, name) => source.rowAttrs(role, name), + ...(source.notes ? { notes: (role: RoleId) => source.notes!(role) } : {}), + once, + }; } /** What the engine knows where it rolls (conditions), plus its random stream. */ @@ -132,6 +152,8 @@ export interface RoleContext extends ConditionContext { * then (plan-tables-everywhere §2.6). */ deferArrival?: boolean; + /** The hex the roll is for ("x_y"), written with any Once row it fires. */ + where?: string; } export interface RolePick { @@ -179,9 +201,16 @@ function usesTable(source: TableSource | undefined, role: RoleId, fallback: read */ export function rollRole(source: TableSource | undefined, role: RoleId, ctx: RoleContext, fallback: readonly string[]): RolePick | undefined { const lookup = withEqualOdds(source?.lookup ?? NO_SOURCE, fallback); - const { rand, deferArrival, ...cond } = ctx; + const { rand, deferArrival, where, ...cond } = ctx; const link = usesTable(source, role, fallback, cond) ?? EQUAL_ODDS; - const r = resolveRoll(link, lookup, { ...resolveCtx(source, fallback, cond), rand, ...(deferArrival ? { deferArrival } : {}) }); + const once = source?.once; + const r = resolveRoll(link, lookup, { + ...resolveCtx(source, fallback, cond), + rand, + ...(deferArrival ? { deferArrival } : {}), + ...(once ? { isUsed: once.isUsed } : {}), + }); + once?.fire(r.onces, where); if (r.kind === "nothing") return { terrain: "", nothing: true, attrs: r.attrs }; if (r.kind === "deferred") { // Shown as a palette terrain (its spelling), else nothing shown yet. diff --git a/styles.css b/styles.css index 6a5a61de..119e8968 100644 --- a/styles.css +++ b/styles.css @@ -9088,3 +9088,29 @@ textarea.duckmage-edit-region-notes-input { font-size: 0.8em; color: var(--text-muted); } + +/* Uncharted marker (plan-tables-everywhere §2.6): a small ? on hexes whose + On arrival roll is still to come, left of the hex centre (badges sit on + the right). Layers menu → Labels → Uncharted. */ +.duckmage-uncharted-layer { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + pointer-events: none; + z-index: 9; +} +.duckmage-hide-uncharted .duckmage-uncharted-layer { display: none; } +.duckmage-uncharted-mark { + position: absolute; + left: calc(var(--duckmage-uncharted-x, 50%) - 1.35em); + top: var(--duckmage-uncharted-y, 50%); + transform: translate(-50%, -50%); + font-size: 0.75em; + font-weight: 700; + line-height: 1; + color: #ffffff; + opacity: 0.7; + text-shadow: 0 0 2px #000000, 0 0 3px #000000; +} diff --git a/tests/arrivalDeferred.test.ts b/tests/arrivalDeferred.test.ts index bbe67c54..a70282fd 100644 --- a/tests/arrivalDeferred.test.ts +++ b/tests/arrivalDeferred.test.ts @@ -15,6 +15,7 @@ import { addLocationPatch } from "../src/maps/submaps"; import { setHexDataSource } from "../src/frontmatter"; import { setModeMapLookup } from "../src/modeGate"; import { ArrivalService } from "../src/arrival/ArrivalService"; +import { EventsService } from "../src/arrival/EventsService"; import { effectiveArrivalMode } from "../src/arrival/arrival"; import { convertWorldTypes } from "../src/space/spaceTables"; import { notesLookup } from "../src/random-tables/resolve"; @@ -93,6 +94,7 @@ function world(opts: { arrival?: string; seed?: number; mode?: string } = {}) { }, }; p.mapStore = new MapStore(p as never); + (p as Record).events = new EventsService(p as never); setHexDataSource(p.mapStore); setModeMapLookup((n) => p.getMap(n)); const service = new ArrivalService(p as never); @@ -160,7 +162,7 @@ describe("arriving at an unknown sector hex (T5, SP4)", () => { const writes = w.vault.writes.length; expect(w.service.canArrive("drift", 4, 5)).toBe(false); expect(await w.service.arrive("drift", 4, 5)).toBeNull(); - expect(w.service.resolveHex("drift", 4, 5, "discover")).toBeNull(); + expect(await w.service.resolveHex("drift", 4, 5, "discover")).toBeNull(); expect(w.p.mapStore.get("drift", "4_5")).toEqual(after); expect(w.maps.length).toBe(mapsBefore); expect(w.vault.writes.length).toBe(writes); @@ -172,7 +174,7 @@ describe("arriving at an unknown sector hex (T5, SP4)", () => { for (let seed = 1; seed < 400; seed++) { const w = world({ arrival: "make places", seed }); await sectorWith(w, [["1_1", { onArrival: UNCHARTED }]]); - const r = w.service.resolveHex("drift", 1, 1, "discover"); + const r = await w.service.resolveHex("drift", 1, 1, "discover"); if (r?.kind !== "nothing") continue; expect(w.p.mapStore.get("drift", "1_1")).toBeUndefined(); return; diff --git a/tests/arrivalRegion.test.ts b/tests/arrivalRegion.test.ts new file mode 100644 index 00000000..92cc6f60 --- /dev/null +++ b/tests/arrivalRegion.test.ts @@ -0,0 +1,156 @@ +/** + * Arrival makes regions on overworlds (GM4: "when going to a new planet, + * new region, etc"): with `on-arrival: make places`, going to an overworld + * hex with no region makes it from the hex's biome, seeded, with no form, + * through the same path as the Biome painter (createRegion). Reroll until + * Lock in any mode, then God only. Off unless the map says so. + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { ArrivalService } from "../src/arrival/ArrivalService"; +import { EventsService } from "../src/arrival/EventsService"; +import { arrivalSeed, effectiveArrivalMode } from "../src/arrival/arrival"; +import { representativeTerrain } from "../src/overworld/biomes"; +import { setModeMapLookup } from "../src/modeGate"; +import { DEFAULT_TERRAIN_PALETTE } from "../src/constants"; +import type { MapData } from "../src/types"; + +(globalThis as Record).window ??= globalThis; + +type Hex = { terrain?: string; locked?: boolean; onArrival?: string; biome?: string }; + +function world(opts: { mode?: string; arrival?: string } = {}) { + const overworld = { + name: "ow", paletteName: "Default", workMode: opts.mode ?? "play", seed: 4242, + gridSize: { cols: 4, rows: 4 }, gridOffset: { x: 0, y: 0 }, staggerOffset: "odd", + regions: { footprint: "rect", size: 4, blend: "normal", worldId: "w1", stagger: "odd" }, + pathChains: [], + ...(opts.arrival ? { arrivalMode: opts.arrival } : {}), + } as unknown as MapData; + const maps: MapData[] = [overworld]; + const store = new Map>(); + const hexes = (m: string): Map => { + let h = store.get(m); + if (!h) store.set(m, (h = new Map())); + return h; + }; + hexes("ow").set("1_1", { terrain: representativeTerrain("taiga", DEFAULT_TERRAIN_PALETTE)! }); + hexes("ow").set("2_1", { terrain: representativeTerrain("grassland", DEFAULT_TERRAIN_PALETTE)! }); + const notes = new Map(); + const made: { name: string; cells?: Map }[] = []; + const writes: string[] = []; + const plugin = { + settings: { maps, hexOrientation: "flat", staggerOffset: "odd" }, + getMap: (n: string) => maps.find((m) => m.name === n), + parentOf: (n: string) => maps.find((m) => m.name === n)?.parent, + getMapPalette: () => DEFAULT_TERRAIN_PALETTE, + getPaletteOrPresetTerrains: () => DEFAULT_TERRAIN_PALETTE, + mapLabel: (n: string) => n, + arrivalModeFor: (n: string) => effectiveArrivalMode(n, (m) => maps.find((x) => x.name === m)?.arrivalMode, (m) => maps.find((x) => x.name === m)?.parent?.map), + refreshHexMap: () => {}, + mapStore: { + get: (m: string, k: string) => store.get(m)?.get(k), + all: (m: string) => hexes(m), + set: (m: string, k: string, patch: Hex) => { + writes.push(`${m}|${k}`); + hexes(m).set(k, { ...hexes(m).get(k), ...patch }); + return true; + }, + setMany: (m: string, cells: Iterable<[string, Hex]>) => { + writes.push(m); + for (const [k, h] of cells) hexes(m).set(k, { ...hexes(m).get(k), ...h }); + }, + flush: async () => {}, + editNoteText: async (m: string, edit: (c: string) => string) => { + if (!maps.some((x) => x.name === m)) return false; + const cur = notes.get(m) ?? `# ${m}\n`; + const next = edit(cur); + if (next !== cur) { notes.set(m, next); writes.push(`note:${m}`); } + return true; + }, + }, + saveSettings: async () => {}, + createNewMap: async ( + name: string, cols: number, rows: number, _palette: string, x: number, y: number, stagger: string, + _progress: unknown, cells?: Map, extra?: { parent?: { map: string; hex: string } }, + ) => { + const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-"); + maps.push({ name: slug, paletteName: "Default", gridSize: { cols, rows }, gridOffset: { x, y }, staggerOffset: stagger, parent: extra?.parent, pathChains: [] } as unknown as MapData); + for (const [k, t] of cells ?? []) hexes(slug).set(k, { terrain: t }); + made.push({ name: slug, cells }); + return { name: slug }; + }, + linkRegion: async (_p: string, _x: number, _y: number, child: string) => { + const c = maps.find((m) => m.name === child)!; + c.submapKind = "region"; + return true; + }, + }; + (plugin as Record).events = new EventsService(plugin as never); + setModeMapLookup((n) => plugin.getMap(n)); + const service = new ArrivalService(plugin as never); + return { plugin, service, maps, overworld, store, notes, made, writes }; +} + +describe("arrival on an overworld (GM4)", () => { + it("is off unless the map makes places: nothing is made or written", async () => { + const w = world(); + expect(w.service.canArrive("ow", 2, 1)).toBe(false); + expect(await w.service.arrive("ow", 2, 1)).toBeNull(); + expect(w.made).toEqual([]); + expect(w.writes).toEqual([]); + }); + + it("going to a hex with no region makes it from the hex's biome, seeded, in Play, with no form", async () => { + const w = world({ arrival: "make places" }); + expect(w.service.canArrive("ow", 2, 1)).toBe(true); + const name = await w.service.arrive("ow", 2, 1); + expect(name).toBeTruthy(); + const region = w.maps.find((m) => m.name === name)!; + expect(region).toMatchObject({ parent: { map: "ow", hex: "2_1" }, submapKind: "region", arrival: "open", workMode: "play" }); + expect(region.regionSeed).toBe(arrivalSeed(4242, "2_1", "submap", 0)); + expect(region.world).toEqual({ id: "w1", cx: 2, cy: 1 }); + // Made from the blend field ("match"), as the Biome painter does. + expect(w.made[0].cells).toBeInstanceOf(Map); + const note = w.notes.get(name!)!; + expect(note).toContain("## Arrival"); + expect(note).toMatch(/- Made with the .+ biome on Default/); + expect(note).toContain("- Not locked yet"); + // A second visit makes nothing new. + expect(w.service.canArrive("ow", 2, 1)).toBe(false); + }); + + it("is seeded: the same overworld seed makes the same region", async () => { + const run = async () => { + const w = world({ arrival: "make places" }); + await w.service.arrive("ow", 2, 1); + return { seed: w.maps[1].regionSeed, cells: [...(w.made[0].cells ?? [])].join(",") }; + }; + expect(await run()).toEqual(await run()); + }); + + it("a hex with no biome, or with a region already, can't be arrived at", async () => { + const w = world({ arrival: "make places" }); + expect(w.service.blocker("ow", 3, 3)).toBe("This hex has no biome yet."); + await w.service.arrive("ow", 1, 1); + expect(w.service.blocker("ow", 1, 1)).toBe("This hex already has a region."); + expect(w.service.blocker("ow", 9, 9)).toBe("This hex is off the map."); + }); + + it("Play may reroll the new region until it's locked; then only God", async () => { + const w = world({ arrival: "make places" }); + const name = (await w.service.arrive("ow", 2, 1))!; + const region = w.maps.find((m) => m.name === name)!; + expect(await w.service.reroll(name)).toBe(true); + expect(region.arrivalRerolls).toBe(1); + expect(region.regionSeed).toBe(arrivalSeed(4242, "2_1", "submap", 1)); + expect(w.notes.get(name)).toContain("- Rerolled once."); + await w.service.lock(name); + expect(region.arrival).toBe("locked"); + expect(await w.service.reroll(name)).toBe(false); + expect(region.regionSeed).toBe(arrivalSeed(4242, "2_1", "submap", 1)); + region.workMode = "god"; + expect(await w.service.reroll(name)).toBe(true); + expect(region.regionSeed).toBe(arrivalSeed(4242, "2_1", "submap", 2)); + }); +}); diff --git a/tests/eventsLedger.test.ts b/tests/eventsLedger.test.ts new file mode 100644 index 00000000..00c1777d --- /dev/null +++ b/tests/eventsLedger.test.ts @@ -0,0 +1,166 @@ +/** + * The Events ledger (SP6, plan-tables-everywhere §2.7): a readable + * `## Events` table in a map note. Round trip, hand edits kept, a deleted + * row frees its event, and rolls by hand are labelled untracked (T7). + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { + eventOnMap, + eventRow, + handRollLabel, + ledgerHas, + ledgerName, + OnceTracker, + readEvents, + untrackedOnceLabel, + withEvents, + withoutEvents, + type LedgerEvent, +} from "../src/arrival/eventsLedger"; +import { parseRandomTable } from "../src/random-tables/randomTable"; +import { memoryLookup, resolveOdds, resolveRoll } from "../src/random-tables/resolve"; +import { parseMapNote } from "../src/maps/mapNote"; + +const NOTE = [ + "---", + "hexmaker-map: 5", + "palette: Space - Sector", + "---", + "# Drift", + "", + "## Hexes", + "| Hex | Terrain |", + "| --- | --- |", + "| 4, 7 | anomaly |", + "", + "## Notes", + "Kira's notes.", + "", +].join("\n"); + +const FLEET: LedgerEvent = { event: "[[The Silent Fleet]]", where: "[[_drift]] 4, 7", when: "2026-10-11", from: "[[Rare events]]" }; + +describe("the ## Events table", () => { + it("is added only when the first event fires, at the end, and reads back", () => { + expect(withEvents(NOTE, [])).toBe(NOTE); + const out = withEvents(NOTE, [FLEET]); + expect(out.startsWith(NOTE.trimEnd())).toBe(true); + expect(out).toContain("## Events"); + expect(out).toContain("| Event | Where | When | From |"); + expect(out).toContain("| [[The Silent Fleet]] | [[_drift]] 4, 7 | 2026-10-11 | [[Rare events]] |"); + expect(readEvents(out)).toEqual([FLEET]); + // The map note still reads the same. + expect(parseMapNote(out)!.hexes.get("4_7")?.terrain).toBe("anomaly"); + }); + + it("adds rows under the existing table, in the user's column order, keeping hand edits", () => { + const hand = withEvents(NOTE, [FLEET]) + .replace("| Event | Where | When | From |", "| When | Event | From | Where | Who |") + .replace("| --- | --- | --- | --- |", "| --- | --- | --- | --- | --- |") + .replace("| [[The Silent Fleet]] | [[_drift]] 4, 7 | 2026-10-11 | [[Rare events]] |", "| 2026-10-11 | [[The Silent Fleet]] | [[Rare events]] | [[_drift]] 4, 7 | Kira |"); + const more = withEvents(hand, [{ event: "a sun going out", where: "[[_drift]]", when: "2026-10-12", from: "[[Rare events]]" }]); + expect(more).toContain("| 2026-10-11 | [[The Silent Fleet]] | [[Rare events]] | [[_drift]] 4, 7 | Kira |"); + expect(more).toContain("| 2026-10-12 | a sun going out | [[Rare events]] | [[_drift]] | |"); + expect(readEvents(more).map((e) => e.event)).toEqual(["[[The Silent Fleet]]", "a sun going out"]); + expect(more).toContain("Kira's notes."); + }); + + it("keeps CRLF notes CRLF", () => { + const crlf = NOTE.replace(/\n/g, "\r\n"); + const out = withEvents(crlf, [FLEET]); + expect(out.replace(/\r\n/g, "")).not.toContain("\n"); + expect(readEvents(out)).toEqual([FLEET]); + }); + + it("an Events section with no table yet gets one under its text", () => { + const note = `${NOTE}\n## Events\nWhat has happened.\n\n## Later\nx\n`; + const out = withEvents(note, [FLEET]); + expect(readEvents(out)).toEqual([FLEET]); + expect(out.indexOf("[[The Silent Fleet]]")).toBeLessThan(out.indexOf("## Later")); + expect(out).toContain("What has happened."); + }); + + it("withoutEvents takes out only the rows asked for", () => { + const two = withEvents(NOTE, [FLEET, { event: "x", where: "[[_other]] 1, 1", when: "", from: "" }]); + const out = withoutEvents(two, (e) => eventOnMap(e, "other")); + expect(readEvents(out)).toEqual([FLEET]); + expect(withoutEvents(out, () => false)).toBe(out); + }); +}); + +describe("matching ledger rows to table rows", () => { + it("by the row's result and the table's name, any case, links or not", () => { + expect(ledgerName("[[world/tables/Rare events|Rare]]")).toBe("rare events"); + expect(ledgerName("world/tables/Rare events.md")).toBe("rare events"); + expect(ledgerName("[[Tundra#Mix]]")).toBe("tundra#mix"); + expect(ledgerHas([FLEET], "world/tables/Rare events.md", "The Silent Fleet")).toBe(true); + expect(ledgerHas([FLEET], "world/tables/Other.md", "The Silent Fleet")).toBe(false); + // A row typed by hand with no From counts for any table. + expect(ledgerHas([{ ...FLEET, from: "" }], "world/tables/Other.md", "the silent fleet")).toBe(true); + // Extra words after the link are fine. + expect(ledgerHas([{ ...FLEET, event: "[[The Silent Fleet]] (Kira found it)" }], "Rare events", "The Silent Fleet")).toBe(true); + }); + + it("a fired event becomes a readable row", () => { + expect(eventRow({ table: "world/tables/Rare events.md", index: 0, scope: "world", result: "The Silent Fleet", link: true, hex: "4_7" }, { mapLink: "[[_drift]]", date: "2026-10-11" })) + .toEqual(FLEET); + expect(eventRow({ table: "Sector hexes", index: 2, scope: "map", result: "silent fleet", link: false }, { mapLink: "[[_drift]]", date: "2026-10-11" })) + .toEqual({ event: "silent fleet", where: "[[_drift]]", when: "2026-10-11", from: "[[Sector hexes]]" }); + }); +}); + +const RARE = parseRandomTable([ + "---", + "dice: 100", + "---", + "| d100 | Result | Weight | Once |", + "| --- | --- | ---: | --- |", + "| 01–50 | [[The Silent Fleet]] | 50 | per world |", + "| 51–75 | a sun going out | 25 | per map |", + "| 76–100 | [[Derelicts]] | 25 | |", +].join("\n")); + +describe("rolling with a ledger (the resolver's isUsed)", () => { + const lookup = memoryLookup({ "Rare events": RARE }); + + it("a ledgered row is left out and the rest rescaled", () => { + const used = new OnceTracker({ world: [{ ...FLEET, from: "[[Rare events]]" }], map: [] }); + const odds = resolveOdds("Rare events", lookup, { isUsed: used.isUsed }); + expect(odds.map((o) => [o.value, o.odds]).sort()).toEqual([["Derelicts", 0.5], ["a sun going out", 0.5]]); + }); + + it("per world rows check the world's ledger, per map rows the map's", () => { + const sun = { event: "a sun going out", where: "", when: "", from: "[[Rare events]]" }; + // In the world's ledger only: the per-map row may still come up here. + const t = new OnceTracker({ world: [sun], map: [] }); + expect(resolveOdds("Rare events", lookup, { isUsed: t.isUsed }).some((o) => o.value === "a sun going out")).toBe(true); + const m = new OnceTracker({ world: [], map: [sun] }); + expect(resolveOdds("Rare events", lookup, { isUsed: m.isUsed }).some((o) => o.value === "a sun going out")).toBe(false); + }); + + it("the roll says which Once rows it landed on, and one run fires each at most once", () => { + const t = new OnceTracker(); + const got: string[] = []; + for (let seed = 1; seed < 200; seed++) { + const r = resolveRoll("Rare events", lookup, { seed, isUsed: t.isUsed }); + if (r.onces) expect(r.onces.map((o) => o.result)).toEqual([r.value]); + t.fire(r.onces, `${seed}_0`); + got.push(r.value); + } + expect(got.filter((g) => g === "The Silent Fleet")).toHaveLength(1); + expect(got.filter((g) => g === "a sun going out")).toHaveLength(1); + expect(t.fired.map((f) => [f.result, f.scope, f.link])).toEqual(expect.arrayContaining([["The Silent Fleet", "world", true], ["a sun going out", "map", false]])); + expect(t.fired).toHaveLength(2); + }); +}); + +describe("rolls by hand are not tracked (T7)", () => { + it("a Once row says so; a repeatable row says nothing", () => { + expect(untrackedOnceLabel(RARE, 0)).toBe("once per world: not tracked here"); + expect(untrackedOnceLabel(RARE, 1)).toBe("once per map: not tracked here"); + expect(untrackedOnceLabel(RARE, 2)).toBeUndefined(); + expect(handRollLabel(RARE, { entry: RARE.entries[0], index: 0, face: 7 })).toBe("d100 → 7 · once per world: not tracked here"); + expect(handRollLabel(RARE, { entry: RARE.entries[2], index: 2, face: 90 })).toBe("d100 → 90"); + }); +}); diff --git a/tests/tableOnce.test.ts b/tests/tableOnce.test.ts new file mode 100644 index 00000000..c2a31296 --- /dev/null +++ b/tests/tableOnce.test.ts @@ -0,0 +1,259 @@ +/** + * Phase 5 (SP6, GM8): once-only rows end to end on an in-memory vault. + * - per world: recorded in the root map's `## Events`, never again anywhere + * in that map tree (the Silent Fleet scenario); + * - per map: recorded in the map's own note, again possible on another map; + * - deleting a ledger row by hand makes the event possible again; + * - generation (Star scatter) fires a once-only row at most once, and never + * when the ledger holds it; + * - rerolling a place forgets the events its old landscape fired; + * - nothing is written when nothing once-only came up (smoke C5). + */ +import { describe, it, beforeEach } from "node:test"; +import expect from "expect"; +import { MapStore } from "../src/maps/MapStore"; +import { setHexDataSource } from "../src/frontmatter"; +import { setModeMapLookup } from "../src/modeGate"; +import { ArrivalService } from "../src/arrival/ArrivalService"; +import { EventsService } from "../src/arrival/EventsService"; +import { OnceTracker, readEvents } from "../src/arrival/eventsLedger"; +import { effectiveArrivalMode } from "../src/arrival/arrival"; +import { convertWorldTypes } from "../src/space/spaceTables"; +import { notesLookup } from "../src/random-tables/resolve"; +import { notesTableSource } from "../src/worldgen/tableSources"; +import { withOnce } from "../src/worldgen/tableRoles"; +import { starScatter } from "../src/worldgen/procedural/starScatter"; +import { DEFAULT_WORLD_TYPE_EXTRAS, DEFAULT_WORLD_TYPE_ROWS } from "../src/space/worldTypePresets"; +import { getPreset } from "../src/palettes/presets"; +import { slugify } from "../src/utils"; +import { MemVault } from "./helpers/memVault"; +import { Notice } from "obsidian"; +import type { MapData, TerrainColor } from "../src/types"; + +(globalThis as Record).window ??= globalThis; + +const SET = convertWorldTypes({ name: "Default space", rows: [...DEFAULT_WORLD_TYPE_ROWS], ...DEFAULT_WORLD_TYPE_EXTRAS }, { tablesFolder: "world/tables", shownAs: "star system" }); +const MAINWORLDS = SET.files.find((f) => f.path.endsWith("Mainworlds.md"))!.path.replace(/\.md$/, ""); + +/** Rare finds on arrival: the fleet is almost certain until it's been found. */ +const FRONTIER = [ + "---", + "dice: 0", + "---", + "# Frontier", + "", + "| Result | Weight | Once |", + "| --- | ---: | --- |", + "| [[The Silent Fleet]] | 1000 | per world |", + "| a sun going out | 1000 | per map |", + `| [[${MAINWORLDS}]] | 1 | |`, +].join("\n"); +const FLEET = ["---", "dice: 0", "---", "# Fleet", "", "| Result | Weight | Once |", "| --- | ---: | --- |", "| [[The Silent Fleet]] | 1000 | per world |", `| [[${MAINWORLDS}]] | 1 | |`].join("\n"); +const PLAIN = ["---", "dice: 0", "---", "# Plain", "", "| Result | Weight |", "| --- | ---: |", `| [[${MAINWORLDS}]] | 1 |`].join("\n"); + +const TABLES: Record = { + ...Object.fromEntries(SET.files.map((f) => [f.path, f.content])), + "world/tables/Frontier.md": FRONTIER, + "world/tables/Plain.md": PLAIN, + "world/tables/Fleet.md": FLEET, +}; + +const noteOf = (map: string) => `world/hexes/${map}/_${map}.md`; + +/** A galaxy (the root) with two sectors under it, all set to make places. */ +function world() { + const vault = new MemVault(); + const base = { paletteName: "Space - Sector", gridSize: { cols: 8, rows: 8 }, gridOffset: { x: 0, y: 0 }, pathChains: [], baseTerrain: "empty space", workMode: "play" }; + const maps: MapData[] = [ + { ...base, name: "galaxy", seed: 1, arrivalMode: "make places" } as MapData, + { ...base, name: "drift", seed: 2, parent: { map: "galaxy", hex: "1_1" }, submapKind: "location" } as MapData, + { ...base, name: "rim", seed: 3, parent: { map: "galaxy", hex: "2_2" }, submapKind: "location" } as MapData, + ]; + const lookup = notesLookup(TABLES); + const p = { + app: vault.app(), + manifest: { dir: ".obsidian/plugins/hexmaker" }, + settings: { hexFolder: "world/hexes", worldFolder: "world", tablesFolder: "world/tables", maps, hexOrientation: "flat", staggerOffset: "odd", mapKinds: ["space"], featureLevel: "advanced" } as Record & { maps: MapData[] }, + mapStore: undefined as unknown as MapStore, + events: undefined as unknown as EventsService, + saves: 0, + getMap: (n: string) => maps.find((m) => m.name === n), + mapLabel: (n: string) => maps.find((m) => m.name === n)?.displayName ?? n, + parentOf: (n: string) => maps.find((m) => m.name === n)?.parent, + hexPath: (x: number, y: number, map: string) => `world/hexes/${map}/${x}_${y}.md`, + arrivalModeFor: (n: string) => effectiveArrivalMode(n, (m) => maps.find((x) => x.name === m)?.arrivalMode, (m) => maps.find((x) => x.name === m)?.parent?.map), + tableNotes: { lookup: () => lookup }, + worldTypeStore: { + sourceFor: (_v: string | undefined, palette: readonly (string | { name: string })[]) => { + const terrains = palette.map((t) => (typeof t === "string" ? t : t.name)); + return { source: notesTableSource(SET.roles, lookup, terrains, "Tables: Default space") }; + }, + list: () => [], + }, + paths: { resolvedPathChains: () => [] }, + getMapPalette: (n: string) => getPreset(maps.find((m) => m.name === n)?.paletteName ?? "")?.terrains ?? [], + getPaletteOrPresetTerrains: (n: string) => getPreset(n)?.terrains ?? [], + getPaletteOrPresetKind: (n: string) => getPreset(n)?.kind, + getPaletteByName: () => undefined, + isSpaceMap: () => true, + childPaletteFor: (n: string) => getPreset(maps.find((m) => m.name === n)?.paletteName ?? "")?.childPalette ?? "Space - System", + submapDefaultFor: (n: string, t: string | undefined) => (t ? getPreset(maps.find((m) => m.name === n)?.paletteName ?? "")?.submapDefaults?.[t] : undefined), + getPathTypes: () => [], + getMapPathTypes: () => [], + saveData: async () => {}, + refreshHexMap: () => {}, + saveSettings: async () => { p.saves++; await p.mapStore.sync(); }, + async createNewMap(raw: string, cols: number, rows: number, paletteName: string, ox: number, oy: number, stagger: "odd" | "even", _prog: unknown, cells: Map | undefined, extra: { baseTerrain?: string; parent?: { map: string; hex: string }; slug?: string; arrivals?: Map }) { + const name = slugify(extra.slug || raw); + maps.push({ name, displayName: raw, paletteName, gridSize: { cols, rows }, gridOffset: { x: ox, y: oy }, pathChains: [], staggerOffset: stagger, ...(extra.baseTerrain ? { baseTerrain: extra.baseTerrain } : {}), ...(extra.parent ? { parent: extra.parent } : {}) } as MapData); + p.mapStore.setMany(name, [...(cells ?? [])].filter(([, t]) => t !== extra.baseTerrain).map(([k, t]) => [k, { terrain: t }])); + await p.mapStore.flush(); + return { name }; + }, + async linkSubmap() {}, + }; + p.mapStore = new MapStore(p as never); + p.events = new EventsService(p as never); + setHexDataSource(p.mapStore); + setModeMapLookup((n) => p.getMap(n)); + const service = new ArrivalService(p as never); + return { vault, p, maps, service }; +} + +async function ready(w: ReturnType, cells: Record) { + await w.p.mapStore.init(); + for (const [map, c] of Object.entries(cells)) w.p.mapStore.setMany(map, c); + // Every map gets its note (the root's too, for the per-world ledger). + for (const m of ["galaxy", "drift", "rim"]) w.p.mapStore.setMany(m, [["7_7", { terrain: "nebula" }]]); + await w.p.mapStore.flush(); +} + +const events = (w: ReturnType, map: string) => readEvents(w.vault.files.get(noteOf(map)) ?? ""); + +describe("once per world (the Silent Fleet)", () => { + beforeEach(() => { (Notice as unknown as { shown: string[] }).shown = []; }); + + it("is found once, written in the root map's Events, and never again anywhere in that world", async () => { + const w = world(); + await w.p.mapStore.init(); + await ready(w, { + drift: [["1_1", { onArrival: "Fleet" }], ["2_1", { onArrival: "Fleet" }], ["3_1", { onArrival: "Fleet" }]], + rim: [["1_1", { onArrival: "Fleet" }]], + }); + const first = await w.service.resolveHex("drift", 1, 1, "discover"); + const second = await w.service.resolveHex("drift", 2, 1, "discover"); + const third = await w.service.resolveHex("drift", 3, 1, "discover"); + const elsewhere = await w.service.resolveHex("rim", 1, 1, "discover"); + const found = [first, second, third, elsewhere].filter((r) => r?.value === "The Silent Fleet"); + expect(found).toHaveLength(1); + expect(first?.value).toBe("The Silent Fleet"); + // In the root's note, readably; not in the sector's. + expect(events(w, "galaxy")).toEqual([{ event: "[[The Silent Fleet]]", where: "[[_drift]] 1, 1", when: expect.any(String), from: "[[Fleet]]" }]); + expect(events(w, "drift").map((e) => e.event)).not.toContain("[[The Silent Fleet]]"); + expect(w.vault.files.get(noteOf("galaxy"))).toContain("## Events"); + }); + + it("deleting the ledger row by hand makes it possible again", async () => { + const w = world(); + await ready(w, { drift: [["1_1", { onArrival: "Fleet" }], ["2_1", { onArrival: "Fleet" }], ["3_1", { onArrival: "Fleet" }]] }); + expect((await w.service.resolveHex("drift", 1, 1, "discover"))?.value).toBe("The Silent Fleet"); + expect((await w.service.resolveHex("drift", 2, 1, "discover"))?.value).not.toBe("The Silent Fleet"); + const path = noteOf("galaxy"); + w.vault.files.set(path, w.vault.files.get(path)!.split("\n").filter((l) => !l.includes("[[The Silent Fleet]]")).join("\n")); + expect((await w.service.resolveHex("drift", 3, 1, "discover"))?.value).toBe("The Silent Fleet"); + expect(events(w, "galaxy").filter((e) => e.event === "[[The Silent Fleet]]")).toHaveLength(1); + }); +}); + +describe("once per map", () => { + it("is written in the map's own note and can happen again on another map", async () => { + const w = world(); + await ready(w, { + drift: [["1_1", { onArrival: "Frontier" }], ["2_1", { onArrival: "Frontier" }], ["3_1", { onArrival: "Frontier" }]], + rim: [["1_1", { onArrival: "Frontier" }], ["2_1", { onArrival: "Frontier" }]], + }); + const drift = []; + for (const x of [1, 2, 3]) drift.push((await w.service.resolveHex("drift", x, 1, "discover"))?.value); + expect(drift.filter((v) => v === "a sun going out")).toHaveLength(1); + expect(events(w, "drift").map((e) => e.event)).toEqual(["a sun going out"]); + const rim = []; + for (const x of [1, 2]) rim.push((await w.service.resolveHex("rim", x, 1, "discover"))?.value); + expect(rim).toContain("a sun going out"); + expect(events(w, "rim").map((e) => e.event)).toEqual(["a sun going out"]); + // Per map never reaches the root's ledger. + expect(events(w, "galaxy").map((e) => e.event)).toEqual(["[[The Silent Fleet]]"]); + }); +}); + +describe("nothing once-only, nothing written (smoke C5)", () => { + it("a roll with no Once row adds no Events section; reading the ledgers writes nothing", async () => { + const w = world(); + await ready(w, { drift: [["1_1", { onArrival: "Plain" }]] }); + const writes = w.vault.writes.length; + await w.p.events.ledgersFor({ map: "drift" }); + await w.p.events.ledgersFor({ parent: "drift" }); + expect(w.vault.writes.length).toBe(writes); + expect(await w.p.events.record("drift", [])).toBe(0); + expect(w.vault.writes.length).toBe(writes); + const r = await w.service.resolveHex("drift", 1, 1, "discover"); + expect(r?.events).toEqual([]); + for (const m of ["galaxy", "drift"]) expect(w.vault.files.get(noteOf(m))).not.toContain("## Events"); + }); +}); + +describe("arriving makes the place and lists what it found", () => { + it("the place's write-up names the once-only find; the root holds the ledger row", async () => { + const w = world(); + await ready(w, { drift: [["4_5", { terrain: "star system", onArrival: "Frontier" }]] }); + const made = await w.service.arrive("drift", 4, 5); + expect(made).toBeTruthy(); + expect(w.vault.files.get(noteOf(made!))).toContain("- Found [[The Silent Fleet]] (once per world; in the Events list)."); + expect(events(w, "galaxy").map((e) => e.event)).toEqual(["[[The Silent Fleet]]"]); + }); +}); + +describe("rerolling a place", () => { + it("forgets the events its old landscape fired (Where on that map), and only those", async () => { + const w = world(); + await ready(w, {}); + const hit = { table: "world/tables/Fleet.md", index: 0, result: "The Silent Fleet", link: true }; + expect(await w.p.events.record("drift", [{ ...hit, scope: "world", hex: "3_3" }, { ...hit, scope: "map", result: "a sun going out", link: false }])).toBe(2); + expect(await w.p.events.record("rim", [{ ...hit, scope: "world", result: "a comet", link: false }])).toBe(1); + await w.p.events.forgetMap("drift"); + expect(events(w, "galaxy").map((e) => e.event)).toEqual(["a comet"]); + expect(events(w, "drift")).toEqual([]); + }); +}); + +describe("generation (Star scatter's Sector hexes)", () => { + const fleet: TerrainColor = { name: "silent fleet", type: "anomaly", color: "#222222" }; + const terrains: TerrainColor[] = [...(getPreset("Space - Sector")?.terrains ?? []), fleet]; + const sector = [ + "---", "dice: 0", "rows: terrain", "---", "# Fleet sector", "", + "| Result | Weight | Once |", "| --- | ---: | --- |", + "| silent fleet | 1000 | per world |", + "| garden world | 1 | |", + ].join("\n"); + const lookup = notesLookup({ "world/tables/Fleet sector.md": sector }); + const source = () => notesTableSource({ "sector-hexes": "Fleet sector" }, lookup, terrains.map((t) => t.name), "Fleet"); + const grid = { cols: 12, rows: 12, offset: { x: 0, y: 0 }, stagger: "odd" as const, orientation: "flat" as const }; + const count = (cells: Map) => [...cells.values()].filter((t) => t === "silent fleet").length; + + it("places a once-only row at most once per run, and says where", () => { + const once = new OnceTracker(); + const r = starScatter(terrains, grid, 42, { density: "dense" }, undefined, withOnce(source(), once)); + expect(count(r.cells)).toBe(1); + expect(once.fired).toHaveLength(1); + expect(r.cells.get(once.fired[0].hex!)).toBe("silent fleet"); + expect(once.fired[0]).toMatchObject({ scope: "world", result: "silent fleet", link: false }); + }); + + it("never places it when the world's ledger holds it", () => { + const once = new OnceTracker({ world: [{ event: "silent fleet", where: "[[_drift]] 3, 4", when: "2026-10-11", from: "[[Fleet sector]]" }], map: [] }); + for (const seed of [1, 2, 3, 42]) { + const r = starScatter(terrains, grid, seed, { density: "dense" }, undefined, withOnce(source(), once)); + expect(count(r.cells)).toBe(0); + } + expect(once.fired).toHaveLength(0); + }); +}); diff --git a/tests/unchartedLayer.test.ts b/tests/unchartedLayer.test.ts new file mode 100644 index 00000000..2be994b0 --- /dev/null +++ b/tests/unchartedLayer.test.ts @@ -0,0 +1,77 @@ +/** + * The uncharted marker: a "?" only on hexes whose On arrival cell is still + * unresolved, drawn without layout reads (CLAUDE.md read-then-write rule), + * toggled from the layers menu (Labels → Uncharted, on by default). + */ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import * as path from "node:path"; +import { renderUnchartedLayer, unchartedKeys, UNCHARTED_LAYER_CLASS } from "../src/hex-map/unchartedLayer"; +import { parseMapNote, buildMapNote } from "../src/maps/mapNote"; + +/** Just enough of an element for the layer: children, classes, text, css props. */ +class FakeEl { + children: FakeEl[] = []; + props: Record = {}; + constructor(public cls = "", public text = "", public parent?: FakeEl) {} + createDiv(o: { cls?: string } = {}) { const c = new FakeEl(o.cls, "", this); this.children.push(c); return c; } + createSpan(o: { cls?: string; text?: string } = {}) { const c = new FakeEl(o.cls, o.text, this); this.children.push(c); return c; } + setCssProps(p: Record) { Object.assign(this.props, p); } + querySelector(sel: string) { return this.children.find((c) => `.${c.cls}` === sel) ?? null; } + remove() { if (this.parent) this.parent.children = this.parent.children.filter((c) => c !== this); } +} + +const placements = [ + { key: "0,0", ox: 10, oy: 10 }, + { key: "1,0", ox: 30, oy: 10 }, + { key: "2,0", ox: 50, oy: 10 }, +]; + +describe("the uncharted marker", () => { + it("marks only hexes with an On arrival roll still to make", () => { + const keys = unchartedKeys(new Map([ + ["0_0", { onArrival: "Uncharted" }], + ["1_0", {}], + ["2_0", { onArrival: " " }], + ])); + expect([...keys]).toEqual(["0_0"]); + const grid = new FakeEl(); + renderUnchartedLayer(grid as never, placements, { w: 100, h: 20 }, keys); + const layer = grid.querySelector(`.${UNCHARTED_LAYER_CLASS}`)!; + expect(layer.children.map((c) => c.text)).toEqual(["?"]); + expect(layer.children[0].props).toEqual({ "--duckmage-uncharted-x": "10.000%", "--duckmage-uncharted-y": "50.000%" }); + }); + + it("redraws in place, and leaves no layer once every cell is resolved", () => { + const grid = new FakeEl(); + renderUnchartedLayer(grid as never, placements, { w: 100, h: 20 }, new Set(["0_0", "2_0"])); + renderUnchartedLayer(grid as never, placements, { w: 100, h: 20 }, new Set(["2_0"])); + expect(grid.children).toHaveLength(1); + expect(grid.children[0].children).toHaveLength(1); + renderUnchartedLayer(grid as never, placements, { w: 100, h: 20 }, new Set()); + expect(grid.children).toHaveLength(0); + }); + + it("never reads layout: it uses the coordinate layer's measured placements", () => { + const src = readFileSync(path.join(__dirname, "../src/hex-map/unchartedLayer.ts"), "utf8"); + for (const read of ["offsetWidth", "offsetHeight", "offsetLeft", "offsetTop", "getBoundingClientRect", "getComputedStyle"]) { + expect(src.includes(`.${read}`) || src.includes(`${read}(`)).toBe(false); + } + // The view draws it right after the coordinate layer measured the hexes. + const view = readFileSync(path.join(__dirname, "../src/hex-map/HexMapView.ts"), "utf8"); + const body = view.slice(view.indexOf("private renderMeasuredLayers")); + expect(body.indexOf("this.renderCoordLabelsLayer(gridContainer)")).toBeLessThan(body.indexOf("renderUnchartedLayer(")); + expect(body.indexOf("renderUnchartedLayer(gridContainer, this.coordPlacements")).toBeGreaterThan(0); + }); + + it("its layers-menu toggle is kept per map in the map note (show-uncharted)", () => { + const note = buildMapNote("drift", { settings: { paletteName: "Space - Sector", gridSize: { cols: 2, rows: 2 }, gridOffset: { x: 0, y: 0 }, showUncharted: false } as never, hexes: new Map(), paths: [] }); + expect(note).toContain("show-uncharted: false"); + expect(parseMapNote(note)!.settings.showUncharted).toBe(false); + const panel = readFileSync(path.join(__dirname, "../src/hex-map/HexSidePanel.ts"), "utf8"); + expect(panel).toMatch(/key: "showUncharted",\s+label: "Uncharted \(\?\)", cssClass: "duckmage-hide-uncharted",\s+inLabels: true/); + const css = readFileSync(path.join(__dirname, "../styles.css"), "utf8"); + expect(css).toContain(".duckmage-hide-uncharted .duckmage-uncharted-layer { display: none; }"); + }); +}); From ee28ebd8c1be60728434faab35676d217d28bfd7 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 16:26:49 -0400 Subject: [PATCH 313/558] feat: drop the feature level; Advanced dropdowns, Debug mode and one placement map Owner round 8 (self-paced discovery). Never released (master 1.5.6 has none of it), so removed outright with no migration: - Simple/Advanced level, the per-feature switches (generators, workflows, custom palettes, regions), every "turn on X?" hint, EnableFeatureModal, MoreFeaturesModal, AdvancedNudgeModal/shouldNudge and the wizard's level step. src/featureLevel.ts and src/advancedHints.ts deleted; featureLevel, advancedFeatures, dismissedHints, installedAt, advancedNudgeAt and advancedNudgeOff are no longer read, written or defaulted (the installedAt/level save triggers in loadSettings went with them). - Every hasFeature/isAdvanced/withFeature site is ungated; visibleKinds drops STARTER_IDS; the wizard offers every generator. - DJ-Q4: shipped biome notes are written when the first overworld or region is made (New overworld, first region settings, createRegion: plugin.ensureOverworldBiomes), not on start-up. mapKinds stays (DJ-Q7). Shared disclosure infrastructure: - src/ui/placement.ts: one declarative map, UI id -> main / more / advanced / debug / hidden (unlisted = main). - src/ui/disclosure.ts: per-surface collapsed Advanced dropdown (open state per surface in local storage) with a Debug subsection only in debug mode; place(id, el) / target(id, here). HexmakerModal exposes section("advanced"|"debug") and place(). - src/ui/debugMode.ts: per device in app local storage (DJ-Q1), never data.json; status-bar "Debug" while on (click turns it off); turned on only from the last row of settings, with a one-time confirm. - Proof placements: Settings folders -> Advanced, Generate folders and Generate terrain tables & hex links -> Debug (both settings paths); generator page engine sliders -> Debug, Symmetry / Edge style / guarantees -> Advanced. Tests: tests/disclosure.test.ts (placement, debug storage, open state, no feature-level reads, settings definitions end with the debug toggle); feature-level tests removed or rewritten; smoke simple-mid setup, F10 and the C2/C5 level checks removed. README and help updated. Co-Authored-By: Claude Opus 5.5 --- README.md | 27 +- dev/smoke/lib/compare.mjs | 8 +- dev/smoke/lib/page.mjs | 3 - dev/smoke/run.mjs | 9 +- dev/smoke/setups.mjs | 63 +-- package.json | 4 +- src/HexmakerModal.ts | 33 ++ src/HexmakerPlugin.ts | 140 ++--- src/HexmakerSettingTab.ts | 503 ++++++++++-------- src/SetupWizardView.ts | 39 +- src/advancedHints.ts | 210 -------- src/constants.ts | 5 - src/featureLevel.ts | 124 ----- src/hex-map/HexEditorModal.ts | 40 +- src/hex-map/HexMapView.ts | 6 +- src/hex-map/MakeGeneratorModal.ts | 8 +- src/hex-map/MapModal.ts | 31 +- src/hex-map/help.md | 14 +- src/hex-map/mapTablesForm.ts | 3 +- src/hex-map/newChildMap.ts | 14 - src/hex-table/LinkPickerModal.ts | 14 +- src/kindContent.ts | 16 +- src/overworld/demoWorld.ts | 7 +- src/overworld/regionsVault.ts | 2 + src/random-tables/RandomTableView.ts | 20 +- src/types.ts | 12 - src/ui/debugMode.ts | 58 ++ src/ui/disclosure.ts | 119 +++++ src/ui/placement.ts | 102 ++++ src/worldgen/GeneratorPanel.ts | 91 ++-- src/worldgen/NewMapSetupModal.ts | 20 +- src/worldgen/registry.ts | 23 +- styles.css | 121 ++--- tests/__mocks__/obsidian.ts | 2 + tests/arrivalDeferred.test.ts | 2 +- tests/arrivalRegion.test.ts | 2 + tests/biomeGenerators.test.ts | 4 + tests/biomeNotes.test.ts | 21 +- tests/builtinGenerators.test.ts | 6 +- tests/disclosure.test.ts | 225 ++++++++ tests/featureLevel.test.ts | 63 --- .../integration/pathLossReload.integration.ts | 14 +- tests/mapKinds.test.ts | 8 +- tests/noteTemplates.test.ts | 2 +- tests/overworldTools.test.ts | 2 + tests/regionTables.test.ts | 5 +- tests/smokeSuite.test.ts | 3 +- tests/spaceSetup.test.ts | 15 +- tests/tableOnce.test.ts | 2 +- tests/walkNewRegion.test.ts | 2 + 50 files changed, 1122 insertions(+), 1145 deletions(-) delete mode 100644 src/advancedHints.ts delete mode 100644 src/featureLevel.ts create mode 100644 src/ui/debugMode.ts create mode 100644 src/ui/disclosure.ts create mode 100644 src/ui/placement.ts create mode 100644 tests/disclosure.test.ts delete mode 100644 tests/featureLevel.test.ts diff --git a/README.md b/README.md index 1e2095d6..b62d23c6 100644 --- a/README.md +++ b/README.md @@ -66,16 +66,16 @@ After enabling the plugin, a **setup wizard** opens. It asks what you'll map (a To set things up by hand instead (or later): ### 1. Set your world folder -Open **Settings → Hexmap World Creator** and enter a root folder name in **World folder** (e.g. `RPG/world`). This is the base for all other folders. +Open **Settings → Hexmap World Creator**, open the **Advanced** dropdown near the bottom, and enter a root folder name in **World notes folder** (e.g. `RPG/world`). This is the base for all other folders. ### 2. Generate folders -Click **Generate folders**. This fills in the hex, towns, dungeons, tables, and other folder settings with sensible defaults under your world folder and creates them in your vault. Any field you've already filled in is left untouched. +Turn on **Debug mode** (the last setting) and click **Generate folders** in the Debug section of the Advanced dropdown. This fills in the hex, towns, dungeons, tables, and other folder settings with sensible defaults under your world folder and creates them in your vault. Any field you've already filled in is left untouched. ### 3. Open the Hex Map Click the map icon in the left ribbon (or use the command palette: **Hexmap World Creator: Open hex map**). You'll be prompted to create your first map — give it a name, choose its size, and pick a terrain palette. ### 4. Generate terrain tables -Once your folders are set, go back to **Settings → Hexmap World Creator** and click **Generate terrain tables & hex links**. This creates a description and encounters table file for every terrain type and links them into any existing hex notes. It's safe to run again at any time. +Once your folders are set, click **Generate terrain tables & hex links** (in the same Debug section). This creates a description and encounters table file for every terrain type and links them into any existing hex notes. It's safe to run again at any time. You're ready to start mapping. @@ -110,17 +110,17 @@ Organise your world into multiple named hex maps, each stored as a subfolder und ### Generators Maps can be generated instead of painted hex by hex. When you create a map (**Maps → New map…**, or the setup wizard's first map) or a submap (right-click a hex → **New map from this hex…**), pick a generator and preview it before creating. A new map starts on Overland (Star scatter for space-only setups); pick Blank to paint it all yourself. **More** under the form sets the starting coordinates, stagger and a background image (picked from the vault or dropped from your computer), and the **folder name** (made from the name; you can change it later in Map properties). A new submap is named after its hex, or its terrain and coordinates ("Barren world 12, 5") if the hex has no name, with " (2)" added if another map already has that name; click the name once to select it all and type your own. A palette a new map installs, and generated paths with no matching path type on the new map's palette (an orbit crossing a planet), are handled quietly, with no notice. -- **World biomes** (Advanced) — an overworld: one biome per hex, laid out by temperature, moisture and height, with transition biomes (taiga between tundra and forest, savanna between jungle and badlands) where two shouldn't touch. Its hexes open into regions that blend with each other. +- **World biomes** — an overworld: one biome per hex, laid out by temperature, moisture and height, with transition biomes (taiga between tundra and forest, savanna between jungle and badlands) where two shouldn't touch. Its hexes open into regions that blend with each other. - **Overland** — a region from noise: seas, coasts, plains, forests, hills, mountains. Set water %, climate, and which side the sea is on. - **Region detail** (submaps) — zooms into the parent hex: its terrain fills the map and each neighbouring hex shapes the matching edge, with that neighbour's own terrain (evergreen next to evergreen) along it; a land neighbour always shows as at least a small strip or corner patch on its side (a swamp to the south-west, say). - **Star scatter**, **Orbits**, **Planet surface** (space maps) — a star sector, a star system around its star, and a planet's surface. They place terrain by type only: Orbits puts the star-type terrain in the middle, world / gas giant / asteroid belt types on the rings, moon-type terrain beside planets (a system with a planet always has at least one; the map draws a faint dashed tether from each moon to the world or gas giant beside it, hidden with the paths; the PNG export draws it too when it includes paths), a starport and station beside the main world, and a jump point and comet past the last orbit; the Star choice lists your palette's own stars. Space palettes made before these types existed are retyped once on load ("moon" typed world becomes moon, "jump limit" typed void becomes jump limit, and so on). - **World types** — which worlds Star scatter and Orbits place and how often, and what each world's own map is made with, as an editable table note in `{world folder}/world-types`. Star scatter and Orbits roll on it: their **World types** option picks the table (**Default**: Default space, or your first table if you deleted it; **None**: equal odds over the palette's worlds, stars and planets, and the generator says so). **Default space** ships with the same odds the two generators used before they read the table (the draws differ, so an old seed gives a different map); **Restore default** puts it back. Each row is a world (a terrain of your palette) with a **Weight** (decimals are fine) and optional limits: **Map** (sector for Star scatter's systems, system for Orbits), **Orbit** (inner, habitable, outer, or rings like `2–4`), **Stars** and **Temperature** (the generators don't know a temperature yet, so it limits nothing there). A sector row's **Mainworld** names the body Orbits makes that system's mainworld (`ocean world` → `ocean planet`; blank: the world itself, if the system palette has it). No generator guesses anything from a terrain's name any more. A row can also say how that world's map is made: **Size** (`20×14`, or a range like `16–24 × 10–14` rolled per world), **Generator**, **Options** (`water=85, climate=lush`), **Palette** and **Base** terrain (Default space opens its planets on the **Space - Planet** palette). The same world can have several rows, so an ocean planet can be likelier and bigger around a yellow star. A row whose world isn't a terrain of the palette being generated is never placed, and the generator's warnings (and the editor's preview) name it. If no row fits the palette at all, the generator uses equal odds and says so. Edit it as text, or with **Edit world types…** (in the Star scatter and Orbits options, or the command): add, remove and reorder rows. The preview rolls for a palette, a map (sector or system), an orbit and a star exactly the way the generators do, so the odds it shows are the odds you get. The same note has two more tables, each under its own heading: **Stars** (which star Orbits puts in the middle when its Star choice is Random, with a **Weight** each; red dwarfs are the most common) and **Sector features** (Star scatter's special hexes, each with a **Chance** per star system hex such as `1 in 50`, `2%` or `never`; Default space has a deep-space station 1 in 50, an anomaly 1 in 75 and a black hole 1 in 150, the 4% Star scatter has always used). The editor has a tab for each table, each with its own preview. Notes made before these tables existed get the shipped ones added once, and notes made before the Mainworld column get the shipped sector worlds' mainworlds filled in once (after a backup; a Mainworld you typed is never changed). Changes in the editor save automatically, like the hex editor (there is no Save button): a moment after you stop typing, and when you close it. A row that isn't finished yet (no world, or a value it can't read) is marked incomplete and isn't saved; it stays in the editor until you fix or remove it, and is dropped when you close it. Edits you make to the note by hand while the editor is open are kept. Rows that can't be read are reported and left in the note as written. Editing needs Build or God. - **Space tables** — **Hexmap World Creator: Convert world types to tables** (or the button in a space map's properties) turns each World types note into ordinary random tables in a tidy tree under `{tables folder}/space//`: `Sector/Charted sector`, `Sector/Unexplored sector`, `Sector/Mainworlds`, `Sector/Uncharted`, `System/Stars` and `System/Inner orbits`, `Habitable orbits`, `Outer orbits`. They give the same odds the note did (different draws) and keep each row's Mainworld, Size, Generator, Options, Palette and Base as columns. The World types note is backed up first and kept: it gets a **Tables** list (role → table; edit a link to swap a table) and the tables embedded below it so they can be rolled there. Converting again changes nothing, and a table that already exists is never overwritten. An unconverted note keeps working as before. **Unexplored sector** leaves half its systems unknown: those rows have **Roll** `on arrival`, so the hex shows its **Shown as** terrain (a star system) or nothing (uncharted) and the map note's Hexes table gets an **On arrival** column naming the table to roll later. - **Generator tables** (map properties, space maps) — one select per generator role: the table Star scatter and Orbits roll on for this map and every map under it. Unset follows the map above, then the World types option. Stored as plain keys in the map note (`sector-hexes-table: "[[…/Unexplored sector]]"`). -- **Biomes and presets** (Advanced) — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. +- **Biomes and presets** — Grassland, Temperate forest, Taiga, Tundra, Alpine, Badlands, Savanna, Jungle, Swamp, Karst, River delta, Coastal fjord, Archipelago, Deep forest, Valley and Volcanic. They place terrain by terrain *type*, so they work with Limited, Expanded, or your own palette (as long as its terrains have types). On Limited, terrain kinds it lacks fold into the nearest one (marsh becomes grass, peaks become mountain). Streams and trails are drawn as your River and Road path types if you have no stream or trail type. - **Learned generators** — made in the **Terrain generator** view (command palette: **Hexmap World Creator: Open terrain generator**) by learning from maps you've already painted, or by blending several. -**Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and, with the Advanced *Regions and overworlds* feature, one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which (on space maps: a star system, planet or station is a Location). If the hex already has maps, the dialog lists them first with an **Open** button each, and the menu item reads **Add another map…**. Inside a submap, the breadcrumb ends with what its hex was on the parent map ("from: barren world"). The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. +**Regions and locations.** A hex can open into maps of its own: any number of **locations** (a town, a dungeon, a ship: each with its own size and palette) and one **region** (the hex itself, up close). Right-click a hex → **New map from this hex…** and pick Region or Location; a short line under each says which is which (on space maps: a star system, planet or station is a Location). If the hex already has maps, the dialog lists them first with an **Open** button each, and the menu item reads **Add another map…**. Inside a submap, the breadcrumb ends with what its hex was on the parent map ("from: barren world"). The first region of a map asks once for its **region settings**: hex flower (7, 19, 37, 61 or 91 hexes) or rectangle (6×6, 8×8, 10×10 or custom), palette and blend width. Every region of that map uses them, so they line up; they are fixed once a region exists (the map menu's **Regions** tab shows them, with the list of regions; blend stays editable). The right-click menu shows the region and up to two locations by name; from three on, **Locations (n)…** opens a list to search, open, unlink and reorder. Every submap made before this is a location; nothing about it changes. **Arriving somewhere new** (optional; off unless you turn it on). In a map's properties, **Arriving somewhere new → Make the place, in any mode** (maps under it follow unless they set their own; stored as `on-arrival: make places` in the map note). Then right-click a hex that has no map → **Go there** (or Ctrl+click it): its On arrival table, if it has one, is rolled with the map's `seed:` (the same world gives the same result), what came up is written onto the hex (the sector learns what the system is), and the hex's map is made at once with no form and no preview: from the rolled row's Size, Generator, Options, Palette and Base, else the palette's submap settings, else the usual defaults. It works in Play, opens in the mode you were in, and the new map's note gets a plain-text **## Arrival** section (what was rolled, how the map was made). Until you lock it, the bar beside the mode switch offers **Reroll** (same setup, next seed; the map's terrain and paths are replaced) and **Lock**; after the lock (`arrival: locked`) only God mode can reroll it. Visiting again never rolls again, and a locked hex is never arrived into. **New map from this hex…** in Build still opens the form, starting from the same rolled row. On an **overworld**, going to a hex that has a biome but no region yet (click it, or right-click → **Go there**) makes its region the way the Biome painter does, from the hex's biome, seeded from the overworld's seed and with no form; it gets the same **Reroll** / **Lock** bar and rules (Reroll makes it again with the next seed; locked hand-painted hexes stay). Hexes whose On arrival roll is still to come show a small **?** (layers menu → Labels → **Uncharted (?)**, on by default). @@ -181,7 +181,7 @@ A modal for editing a hex note without leaving the map. - **Notes sections** — Description, Landmark, Hidden, Secret — inline text areas; a 📖 button rolls the section's table where one exists. - **Weather and Hooks & Rumors** — folded under Notes. 🎲 rolls the map's weather or rumours table (set in **Maps → Properties → Weather and rumours**); ⋯ picks a different table for one hex. With neither set, the starter `weather.md` / `rumors.md` in your tables folder is used. - **Add to this hex** — any roll made from the editor (encounter tables, section tables) can be added to a section of this hex's note, chosen from a list (the section you rolled from comes first). The note is created if the hex has none. **Copy** is always there too. -- **Run workflow** (Advanced: workflows) — the link beside the hex title picks a workflow and runs it for this hex; **Add to this hex** puts the filled-in result into a section (its headings become bold lines so the section stays whole). +- **Run workflow** — the link beside the hex title picks a workflow and runs it for this hex; **Add to this hex** puts the filled-in result into a section (its headings become bold lines so the section stays whole). - **Open note** link next to the hex coordinates opens the full note in a new tab. ### Random Tables view @@ -331,9 +331,9 @@ Every command, as it appears in the command palette: | **Hexmap World Creator: Open random tables** | Opens the random tables and workflows view. | | **Hexmap World Creator: Open terrain generator** | Opens the terrain generator (learn, blend and run generators). | | **Hexmap World Creator: Open palette editor** | Opens the terrain palette editor. | -| **Hexmap World Creator: Convert world types to tables** | Writes each World types note as random tables under `{tables folder}/space//` (backed up first; the notes are kept and link to the tables). Shown while a note is left to convert. Advanced: Terrain generators. | -| **Hexmap World Creator: Edit world types…** | Opens the world types table editor (which worlds the space generators place, how often, and how each world's map is made), with a preview. Advanced: Terrain generators; space maps on. | -| **Hexmap World Creator: New overworld…** | Generate overworld (first pass): a map of biomes from a biome pool, laid out by climate, whose hexes open into regions that join up; can make every region at once. Advanced: Regions and overworlds. | +| **Hexmap World Creator: Convert world types to tables** | Writes each World types note as random tables under `{tables folder}/space//` (backed up first; the notes are kept and link to the tables). Shown while a note is left to convert. | +| **Hexmap World Creator: Edit world types…** | Opens the world types table editor (which worlds the space generators place, how often, and how each world's map is made), with a preview. Space maps on. | +| **Hexmap World Creator: New overworld…** | Generate overworld (first pass): a map of biomes from a biome pool, laid out by climate, whose hexes open into regions that join up; can make every region at once. | | **Hexmap World Creator: Go up to parent map** | From a submap, back to the map it belongs to. | | **Hexmap World Creator: Go back to previous map** | Returns to the map you were on before. | | **Hexmap World Creator: Go forward to the next map** | After going back, forward again (like a browser). | @@ -351,7 +351,7 @@ Every command, as it appears in the command palette: ## Settings -Open **Settings → Hexmap World Creator** to configure: +Open **Settings → Hexmap World Creator** to configure the settings below. Everyday ones are at the top. The folder layout is in the collapsed **Advanced** dropdown near the bottom (it stays open or closed as you left it, on this device). The maintenance buttons (**Generate folders**, **Generate**) are in its **Debug** section, which shows only while **Debug mode** is on. There's no Simple or Advanced level: every feature is always there. | Setting | Description | |---------|-------------| @@ -377,7 +377,8 @@ Open **Settings → Hexmap World Creator** to configure: | **Palette for new maps** | The palette a new map starts on. *First palette* = the first one listed (overland before space). New installs start on Expanded; any palette can be picked, and renaming it keeps the setting. | | **Add default palettes** | Shown when Expanded or Limited isn't in the list: puts them back. Palettes you delete (in settings, or by deleting a palette note the plugin wrote) stay deleted, with a copy in the plugin folder's `backups/`; an empty palette list stays empty until you add one. A palette whose note isn't there yet for another reason (an upgrade, a new palettes folder, a note sync hasn't delivered) is kept: its note is written, or the palette comes back when the note arrives. | | **Terrain palettes** | Named palettes of terrain types. Each palette has a name and a list of terrain entries (name, colour, optional icon and icon tint). Palettes are assigned to maps at creation time. Edit palette contents from the terrain tool on the hex map, or as a table in the palette's note — copy a palette note into another vault's palettes folder to share it. **Add palette** offers built-in presets: *Expanded* (the default fantasy overland palette on new installs; installs from before it keep their first palette as the new-map default: coasts, wetlands, forest and mountain kinds; matches the generators) and *Limited* (fewer, simpler terrains; quicker to paint), plus *Space - Sector* (star charts, one hex per parsec; adds Jump route and Trade route path types), *Space - System* (stars, planets, belts, stations) and *Space - Planet* (a planet's surface: seas, plains, regolith, dunes, ice, craters, lava fields, toxic marsh, crystal fields, ruins, colonies; typed for the Planet surface generator, and what planets and moons open on) for sci-fi games such as Traveller. A palette note's `map-kind:` line (`world` or `space`) says which map type it belongs to; without it, a palette with space terrain types counts as space. New-map palette menus list uninstalled presets too, and show the picked palette's terrains as a row of colour swatches (names on hover) under the menu. | -| **Generate** | ⚠️ Configure all folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | +| **Generate** | Debug section. Set the folders first. Creates missing terrain table files and links each hex's terrain encounters table into the hex note. | +| **Debug mode** | The very last setting. Shows backend controls (the terrain generator's engine tuning sliders, maintenance buttons) in a **Debug** section inside each page's Advanced dropdown. The first time it asks to make sure. While it's on, **Debug** shows in the status bar; click it to turn it off. Kept per device (Obsidian's local storage), never in `data.json`, never synced. | --- @@ -464,7 +465,7 @@ npm run smoke # smoke vault matrix in sandboxed Obsidian (Windows; see belo npm run premerge # build + lint + tests + integration + smoke: run before merging or deploying ``` -**Before merging into the integration branch or deploying a build into a real vault, run `npm run premerge`** and wait for `PREMERGE PASSED`. The smoke matrix (`dev/smoke/run.mjs`) starts a throwaway, separately profiled Obsidian per vault setup (fresh install, an old 1.5.5 vault, space only, an overworld with regions, neighbour maps, a custom palette, a vault with its folders deleted, 80 maps, Simple level…), up to 4 at once (fewer when free memory is low or the CPU is busy; `--jobs N` sets it), and checks the plugin loads without errors, every map opens, untouched notes stay byte-identical, a restart rewrites nothing, paint and undo round-trip, and Play mode refuses edits. It needs Windows Obsidian and the fresh-eyes tester's `sandbox.mjs` (set `UX_TOOLS_DIR` if it isn't in the default place); `npm run smoke -- --list` shows the setups and `--only ` runs some of them. Results go to `dev/smoke/last-run.json` (and `last-pass.json` on a full pass). It only counts and stops its own sandboxes' processes, so your Obsidian or another smoke run can start or stop while it runs; a sandbox slow to exit gets about 30 seconds more before the stop counts as failed. +**Before merging into the integration branch or deploying a build into a real vault, run `npm run premerge`** and wait for `PREMERGE PASSED`. The smoke matrix (`dev/smoke/run.mjs`) starts a throwaway, separately profiled Obsidian per vault setup (fresh install, an old 1.5.5 vault, space only, an overworld with regions, neighbour maps, a custom palette, a vault with its folders deleted, 80 maps…), up to 4 at once (fewer when free memory is low or the CPU is busy; `--jobs N` sets it), and checks the plugin loads without errors, every map opens, untouched notes stay byte-identical, a restart rewrites nothing, paint and undo round-trip, and Play mode refuses edits. It needs Windows Obsidian and the fresh-eyes tester's `sandbox.mjs` (set `UX_TOOLS_DIR` if it isn't in the default place); `npm run smoke -- --list` shows the setups and `--only ` runs some of them. Results go to `dev/smoke/last-run.json` (and `last-pass.json` on a full pass). It only counts and stops its own sandboxes' processes, so your Obsidian or another smoke run can start or stop while it runs; a sandbox slow to exit gets about 30 seconds more before the stop counts as failed. The built output is `main.js` in the repo root. Obsidian loads this file directly from the plugin folder. diff --git a/dev/smoke/lib/compare.mjs b/dev/smoke/lib/compare.mjs index 4be95db6..d5847a32 100644 --- a/dev/smoke/lib/compare.mjs +++ b/dev/smoke/lib/compare.mjs @@ -20,11 +20,11 @@ export function canon(v) { } /** - * Settings the plugin sets once, on some later start (the "ready for - * more?" check-in, the one-time table-ranges survey): a restart may write - * these to data.json. Anything else it writes is a rewrite. + * Settings the plugin sets once, on some later start (the one-time + * table-ranges survey, note format upgrades): a restart may write these + * to data.json. Anything else it writes is a rewrite. */ -export const ONE_TIME_KEYS = new Set(["tableRangesPrompt", "advancedNudgeAt", "noteFormatUpgrades"]); +export const ONE_TIME_KEYS = new Set(["tableRangesPrompt", "noteFormatUpgrades"]); /** data.json changed only in ONE_TIME_KEYS (top level). */ diff --git a/dev/smoke/lib/page.mjs b/dev/smoke/lib/page.mjs index 1729af42..f6e986ca 100644 --- a/dev/smoke/lib/page.mjs +++ b/dev/smoke/lib/page.mjs @@ -83,9 +83,6 @@ export function state(id) { })); return { version: p.manifest.version, - featureLevel: s.featureLevel, - advancedFeatures: s.advancedFeatures ?? [], - dismissedHints: s.dismissedHints ?? [], mapKinds: s.mapKinds, palettes: s.terrainPalettes.map((x) => x.name), pathTypes: (s.pathTypes ?? []).length, diff --git a/dev/smoke/run.mjs b/dev/smoke/run.mjs index 98a62ac2..f4cd64e8 100644 --- a/dev/smoke/run.mjs +++ b/dev/smoke/run.mjs @@ -200,9 +200,6 @@ async function runSetup(setup) { const probs = []; if (!disk) probs.push("no data.json written"); else { - if (disk.featureLevel === undefined) probs.push("featureLevel not saved"); - if (setup.expect.level && state.featureLevel !== setup.expect.level) probs.push(`level ${state.featureLevel}, expected ${setup.expect.level}`); - if (setup.expect.level && disk.featureLevel !== setup.expect.level) probs.push(`saved level ${disk.featureLevel}, expected ${setup.expect.level}`); const renamed = { regions: "maps", defaultRegion: "defaultMap" }; const lost = Object.keys(dataIn ?? {}).filter((k) => !(k in disk) && !(renamed[k] && renamed[k] in disk)); if (lost.length) probs.push(`keys lost from data.json: ${lost.join(", ")}`); @@ -211,7 +208,7 @@ async function runSetup(setup) { const goneMaps = [...inMaps].filter((m) => !outMaps.has(m)); if (goneMaps.length) probs.push(`maps lost from data.json: ${goneMaps.join(", ")}`); } - rec("C2-settings", probs.length === 0, probs.join("; ") || `level ${state.featureLevel}, ${state.maps.length} maps, palettes ${state.palettes.length}, kinds ${state.mapKinds}`); + rec("C2-settings", probs.length === 0, probs.join("; ") || `${state.maps.length} maps, palettes ${state.palettes.length}, kinds ${state.mapKinds}`); } // C3: every map opens and renders. @@ -349,7 +346,6 @@ async function runSetup(setup) { // ── C5: restart rewrites nothing ── const storeBefore = canon(await ev(P.dumpStore, pluginId)); - const levelBefore = state.featureLevel; await ev(P.settle, pluginId, 3000, 60_000); await stop(); const snapA = snapshot(vault, pluginId); @@ -377,9 +373,8 @@ async function runSetup(setup) { if (d.added.length) probs.push(`new: ${d.added.slice(0, 12).join(", ")}`); if (d.removed.length) probs.push(`removed: ${d.removed.slice(0, 12).join(", ")}`); if (storeAfter !== storeBefore) probs.push(`map data differs after restart: ${jsonDiff(JSON.parse(storeBefore), JSON.parse(storeAfter)).join("; ")}`); - if (state2.featureLevel !== levelBefore) probs.push(`level ${levelBefore} → ${state2.featureLevel}`); if (errs2.length) probs.push(`plugin errors: ${errs2.slice(0, 3).map((e) => e.text.split("\n")[0]).join(" || ")}`); - rec("C5-restart", probs.length === 0, probs.join("; ") || `0 files rewritten, map data and level the same (ready ${r2.ms} ms)`); + rec("C5-restart", probs.length === 0, probs.join("; ") || `0 files rewritten, map data the same (ready ${r2.ms} ms)`); } } catch (e) { rec("crash", false, e.stack ?? String(e)); diff --git a/dev/smoke/setups.mjs b/dev/smoke/setups.mjs index b38de96b..add7ec48 100644 --- a/dev/smoke/setups.mjs +++ b/dev/smoke/setups.mjs @@ -1,5 +1,5 @@ /** - * The vault setups of the smoke matrix (plan-work-modes §3.1, F1–F10). + * The vault setups of the smoke matrix (plan-work-modes §3.1, F1–F9; F10, the Simple-level setup, went with the feature level). * Every fixture is built from code into a temp folder, or copied; never the * main vault. A setup can: * build(dir) write seed notes / a data.json into `dir` → { seed?, pluginData? } @@ -162,7 +162,6 @@ function recipeOverworld(id) { const p = window.app.plugins.plugins[id]; p.settings.setupComplete = true; window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); - await p.setFeatureLevel("advanced"); const t0 = Date.now(); while (!p.devTools && Date.now() - t0 < 30000) await new Promise((r) => setTimeout(r, 300)); if (!p.devTools) throw new Error("devTools missing (sandbox marker?)"); @@ -178,7 +177,6 @@ function recipeNeighbours(id) { const p = window.app.plugins.plugins[id]; p.settings.setupComplete = true; window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); - await p.setFeatureLevel("advanced"); const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; const wid = "wsmoke1"; const names = []; @@ -248,7 +246,6 @@ function recipeDeleted(id) { const p = window.app.plugins.plugins[id]; p.settings.setupComplete = true; window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); - await p.setFeatureLevel("advanced"); const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; const made = []; for (const n of ["Gone One", "Gone Two"]) { @@ -274,7 +271,6 @@ function recipeManyMaps(id) { const p = window.app.plugins.plugins[id]; p.settings.setupComplete = true; window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); - await p.setFeatureLevel("advanced"); const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; const made = []; const errors = []; @@ -305,28 +301,6 @@ function recipeManyMaps(id) { })(); } -function recipeSimpleMid(id) { - return (async () => { - const p = window.app.plugins.plugins[id]; - p.settings.setupComplete = true; - window.app.workspace.getLeavesOfType("duckmage-setup-wizard").forEach((l) => l.detach()); - await p.setFeatureLevel("simple"); - await p.enableAdvancedFeature("workflows"); - p.settings.dismissedHints = [...new Set([...(p.settings.dismissedHints ?? []), "generators-toolbar", "regions-map-menu"])]; - const pal = p.settings.defaultPalette ?? p.settings.terrainPalettes[0].name; - const r = await p.createNewMap("Starter Isle", 10, 8, pal, 0, 0, undefined, undefined, undefined, { quiet: true }); - if ("error" in r) throw new Error(r.error); - const terr = p.getMapPalette(r.name).map((t) => t.name); - const cells = []; - for (let x = 0; x < 10; x++) for (let y = 0; y < 8; y++) if ((x + 2 * y) % 4 === 0) cells.push([`${x}_${y}`, { terrain: terr[(x + y) % terr.length] }]); - p.mapStore.setMany(r.name, cells); - p.settings.defaultMap = r.name; - await p.saveSettings(); - await p.mapStore.flush(); - return { map: r.name, level: p.settings.featureLevel, advancedFeatures: p.settings.advancedFeatures }; - })(); -} - // ── setup-specific checks (Node side; ctx.ev(fn, ...args) evaluates in page) ── async function freshExtra(ctx) { @@ -569,26 +543,6 @@ async function manyMapsExtra(ctx) { return [{ check: "F9-count", ok: n >= 80, detail: `${n} maps, ${deep} at depth 4, store ready in ${ctx.readyMs} ms` }]; } -async function simpleMidExtra(ctx) { - const st = ctx.state; - const out = []; - out.push({ check: "F10-level", ok: st.featureLevel === "simple" && st.advancedFeatures.includes("workflows"), detail: `level ${st.featureLevel}, advanced ${JSON.stringify(st.advancedFeatures)}` }); - out.push({ check: "F10-hints", ok: st.dismissedHints.includes("generators-toolbar"), detail: `dismissed ${JSON.stringify(st.dismissedHints)}` }); - // The generator page is Advanced: in Simple the command offers to turn it on instead. - const r = await ctx.ev((id) => (async () => { - const app = window.app; - app.commands.executeCommandById(`${id}:open-terrain-generator`); - await new Promise((res) => setTimeout(res, 800)); - const modal = document.querySelectorAll(".modal-container").length; - const gen = app.workspace.getLeavesOfType("duckmage-terrain-generator").length; - document.querySelectorAll(".modal-container .modal-close-button").forEach((b) => b.click()); - return { modal, gen }; - })(), ctx.pluginId); - out.push({ check: "F10-gate", ok: r.modal > 0 && r.gen === 0, detail: `generator command: modal ${r.modal}, generator view ${r.gen}` }); - out.push({ check: "F10-mode-switch", ok: !!ctx.firstOpen?.workModeBtn, detail: `work mode button on the map: ${!!ctx.firstOpen?.workModeBtn}` }); - return out; -} - // ── the matrix ──────────────────────────────────────────────────────────── export const SETUPS = [ @@ -604,13 +558,13 @@ export const SETUPS = [ return { seed: REAL_SEED, pluginData }; }, migration: true, - expect: { level: "advanced", readyMs: 600_000, openMs: 60_000 }, + expect: { readyMs: 600_000, openMs: 60_000 }, }, - { id: "fresh", title: "Fresh install", build: (dir) => ({ seed: seedDir(dir) }), expect: { level: "simple", wizard: true }, extra: freshExtra, skipPaint: true }, - { id: "v155", title: "Synthetic 1.5.5 vault (hex-note frontmatter + data.json maps), migrates", build: buildV155, migration: true, expect: { level: "advanced" } }, + { id: "fresh", title: "Fresh install", build: (dir) => ({ seed: seedDir(dir) }), expect: { wizard: true }, extra: freshExtra, skipPaint: true }, + { id: "v155", title: "Synthetic 1.5.5 vault (hex-note frontmatter + data.json maps), migrates", build: buildV155, migration: true, expect: {} }, { id: "space", title: "Space only (sector → system → planet)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeSpace, expect: {}, extra: spaceExtra }, - { id: "overworld", title: "Overworld + regions (demo world, seed 7)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeOverworld, expect: { level: "advanced", openMs: 60_000 }, extra: overworldExtra }, - { id: "neighbours", title: "Neighbours world (legacy 2×2, own coordinates)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeNeighbours, expect: { level: "advanced" }, extra: neighboursExtra }, + { id: "overworld", title: "Overworld + regions (demo world, seed 7)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeOverworld, expect: { openMs: 60_000 }, extra: overworldExtra }, + { id: "neighbours", title: "Neighbours world (legacy 2×2, own coordinates)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeNeighbours, expect: {}, extra: neighboursExtra }, { id: "custom-palette", title: "One custom palette, no default names", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeCustomPalette, expect: {}, extra: customPaletteExtra }, { id: "deleted", title: "Everything deleted (no palettes, path types or map folders)", @@ -626,9 +580,8 @@ export const SETUPS = [ data.pathTypes = []; fs.writeFileSync(dataFile, JSON.stringify(data, null, 2)); }, - expect: { level: "advanced" }, extra: deletedExtra, skipModeLocks: true, + expect: {}, extra: deletedExtra, skipModeLocks: true, }, - { id: "many-maps", title: "Many maps (80, nested 4 deep, look-alike names)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeManyMaps, expect: { level: "advanced" }, extra: manyMapsExtra }, - { id: "simple-mid", title: "Simple level, mid-ramp (workflows on, hints dismissed)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeSimpleMid, expect: { level: "simple" }, extra: simpleMidExtra }, + { id: "many-maps", title: "Many maps (80, nested 4 deep, look-alike names)", build: (dir) => ({ seed: seedDir(dir) }), recipe: recipeManyMaps, expect: {}, extra: manyMapsExtra }, ]; diff --git a/package.json b/package.json index 90f1618a..67f37715 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/featureLevel.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/disclosure.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/disclosure.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerModal.ts b/src/HexmakerModal.ts index e6fa87ac..13ccc79d 100644 --- a/src/HexmakerModal.ts +++ b/src/HexmakerModal.ts @@ -1,6 +1,7 @@ import { App, Modal } from "obsidian"; import { iconLabel, iconPack, iconPackTabs, placeIconKind, PLACE_ICON_KINDS, type IconPack } from "./utils"; import { wheelDeltaPx, wheelTarget } from "./wheelChain"; +import { Disclosure } from "./ui/disclosure"; /** Last pack tab picked in any icon filter — remembered for the session. */ let lastIconPack: IconPack | "all" | undefined; @@ -26,6 +27,38 @@ export class HexmakerModal extends Modal { super(app); } + /** + * Stable id of this surface (the UI inventory's screen id, e.g. + * "MapModal"): keys the Advanced dropdown's remembered open state. + * Subclasses that use section/place set it; else the title is used. + */ + protected surfaceId = ""; + private disclosureState?: Disclosure; + + /** This modal's Advanced dropdown and Debug subsection (src/ui/disclosure.ts). */ + protected get disclosure(): Disclosure { + this.disclosureState ??= new Disclosure(this.app, this.surfaceId || this.titleEl.getText() || "modal", () => this.contentEl); + return this.disclosureState; + } + + /** + * The collapsed "Advanced" dropdown at the current end of the modal + * (made on first use), or the "Debug" subsection inside it: null while + * debug mode is off. + */ + protected section(layer: "advanced" | "debug"): HTMLElement | null { + return this.disclosure.section(layer); + } + + /** + * Put a built control where the placement map (src/ui/placement.ts) + * says: left in place, moved into Advanced or Debug, or removed. Returns + * whether it is shown. + */ + protected place(id: string, el: HTMLElement): boolean { + return this.disclosure.place(id, el); + } + /** * Put a search box + pack tabs (All / Terrain / Places / Space / Custom, * with Settlements / Castles / … chips on Places) above an diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index dbfebc48..3eeeadf3 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -45,10 +45,9 @@ import { RoutePins } from "./paths/routePins"; import { setPathEditMapLookup } from "./paths/editGate"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; import { enabledKinds, isIconHiddenByKind, newTerrains, paletteKind, resolveMapKinds, sectionKindFor, sectionWordsFor, terrainsForTables, type MapKind, type SectionWordsFn } from "./mapKinds"; -import { enableFeature, hasFeature, resolveFeatureLevel, shouldNudge, type AdvancedFeature, type FeatureLevel } from "./featureLevel"; import { defaultPaletteFor, resolveDefaultPalette, resolveExpandedDefault, setPaletteTerrainSource } from "./palettes/paletteOptions"; -import { AdvancedNudgeModal, EnableFeatureModal } from "./advancedHints"; import { mapAncestors } from "./hex-map/submapNav"; +import { isDebugMode, onDebugModeChange, setDebugMode } from "./ui/debugMode"; import { getPreset, presetToPalette, @@ -209,14 +208,6 @@ export default class HexmakerPlugin extends Plugin { TableStore.register(this); if (!this.settings.setupComplete && !this.settings.setupDismissed) { this.openSetupWizard(); - } else if (shouldNudge(this.settings, this.settings.maps.length)) { - // A Simple user who's been at it a while: offer Advanced, once. - this.settings.advancedNudgeAt = new Date().toISOString().slice(0, 10); - // Saved once the map notes are loaded: a save before that writes - // every map's (empty) path list back into data.json, though the - // paths live in the map notes (smoke suite C5). - void storesReady.then(() => this.saveSettings()); - new AdvancedNudgeModal(this.app, this).open(); } else { // Once after updating: offer roll ranges for older tables (asks // first). After the stores load, for the same reason. @@ -328,7 +319,7 @@ export default class HexmakerPlugin extends Plugin { id: "edit-world-types", name: "Edit world types…", checkCallback: (checking) => { - if (!hasFeature(this.settings, "generators") || !enabledKinds(this.settings).has("space")) return false; + if (!enabledKinds(this.settings).has("space")) return false; if (!checking) { const open = this.app.workspace.getActiveViewOfType(HexMapView); new WorldTypesModal(this.app, this, open?.activeMapName).open(); @@ -340,7 +331,7 @@ export default class HexmakerPlugin extends Plugin { id: "convert-world-types", name: "Convert world types to tables", checkCallback: (checking) => { - if (!hasFeature(this.settings, "generators") || !this.worldTypeStore.list().some((t) => !this.worldTypeStore.isConverted(t.name))) return false; + if (!this.worldTypeStore.list().some((t) => !this.worldTypeStore.isConverted(t.name))) return false; if (!checking) void this.convertWorldTypes(); return true; }, @@ -348,11 +339,7 @@ export default class HexmakerPlugin extends Plugin { this.addCommand({ id: "new-overworld", name: "New overworld…", - checkCallback: (checking) => { - if (!hasFeature(this.settings, "regions")) return false; - if (!checking) this.openNewOverworld(); - return true; - }, + callback: () => this.openNewOverworld(), }); this.addCommand({ id: "map-go-up", @@ -519,6 +506,16 @@ export default class HexmakerPlugin extends Plugin { }), ); this.addSettingTab(new HexmakerSettingTab(this.app, this)); + // Debug mode (per device, src/ui/debugMode.ts): "Debug" in the status + // bar while it's on; clicking it turns it off. Pages with a Debug + // subsection re-render when it changes. + this.syncDebugStatus(isDebugMode(this.app)); + this.register(onDebugModeChange((on) => { + this.syncDebugStatus(on); + for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_GENERATOR)) { + if (leaf.view instanceof GeneratorView) leaf.view.refresh(); + } + })); // Register the embedded roller code block processor registerRollerBlock(this); @@ -724,11 +721,6 @@ export default class HexmakerPlugin extends Plugin { * generator (the page says which biomes use it). */ async openTerrainGenerator(select: { mapName?: string; generatorPath?: string; paletteName?: string; biome?: string } = {}): Promise { - // An Advanced feature: in Simple, offer to turn it on first. - if (!hasFeature(this.settings, "generators")) { - new EnableFeatureModal(this.app, this, "generators", () => void this.openTerrainGenerator(select)).open(); - return; - } if (select.mapName) GeneratorPanel.mapName = select.mapName; if (select.paletteName) GeneratorPanel.paletteName = select.paletteName; if (select.generatorPath) { @@ -754,7 +746,18 @@ export default class HexmakerPlugin extends Plugin { /** "New overworld…": a World biomes map with its region settings (and its regions). */ openNewOverworld(): void { - new NewOverworldModal(this.app, this, (name) => void this.showMap(name)).open(); + // The form picks biomes from the notes: the shipped ones go in first (DJ-Q4). + void this.ensureOverworldBiomes().then(() => new NewOverworldModal(this.app, this, (name) => void this.showMap(name)).open()); + } + + /** + * DJ-Q4: the shipped biome notes are written when the first overworld or + * region is made (New overworld, a map given region settings, a region + * created), not on start-up. Each is written once and never over a note, + * so a deleted one stays deleted; later calls only top up new shipped ones. + */ + async ensureOverworldBiomes(): Promise { + await this.biomeStore.seedShipped(true); } /** @@ -860,24 +863,15 @@ export default class HexmakerPlugin extends Plugin { // already; a fresh install writes none until its setup picks the types. // Setup over without a pick: inferred, nothing installed (saved with the next save). this.settings.kindContent = inferKindContent({ ...this.settings, kindContent: resolveKindContent(rawData, this.settings.mapKinds) }); - // Feature level, also from the raw data: an install that already had - // settings (an update) gets Advanced so nothing it used disappears; a - // fresh one starts Simple. Saved right away, so the next load doesn't - // mistake a fresh install's first save for an update. - this.settings.featureLevel = resolveFeatureLevel(rawData); - this.settings.advancedFeatures = Array.isArray(data["advancedFeatures"]) ? (data["advancedFeatures"] as unknown[]).filter((f): f is string => typeof f === "string") : []; - this.settings.dismissedHints = Array.isArray(data["dismissedHints"]) ? (data["dismissedHints"] as unknown[]).filter((f): f is string => typeof f === "string") : []; - const firstLevel = rawData?.["featureLevel"] === undefined; - if (!this.settings.installedAt) this.settings.installedAt = new Date().toISOString().slice(0, 10); // New maps default to Expanded on fresh installs only (GEN1): decided - // once from the raw data, like the level, and saved with it. + // once from the raw data, and saved with it. this.settings.expandedByDefault = resolveExpandedDefault(rawData); const firstExpanded = typeof rawData?.["expandedByDefault"] !== "boolean"; // "Palette for new maps": seeded once from the above, then the user's. this.settings.defaultPalette = resolveDefaultPalette(rawData); const firstDefaultPalette = typeof rawData?.["defaultPalette"] !== "string"; const firstKindContent = rawData?.["kindContent"] === undefined; - if (firstKindContent || firstLevel || firstExpanded || firstDefaultPalette || !rawData?.["installedAt"]) await this.saveData(this.settings); + if (firstKindContent || firstExpanded || firstDefaultPalette) await this.saveData(this.settings); } /** @@ -992,11 +986,6 @@ export default class HexmakerPlugin extends Plugin { /** Open (or focus) the palette editor page, optionally on one palette. */ async openPaletteEditor(paletteName?: string): Promise { - // An Advanced feature: in Simple, offer to turn it on first. - if (!hasFeature(this.settings, "palettes")) { - new EnableFeatureModal(this.app, this, "palettes", () => void this.openPaletteEditor(paletteName)).open(); - return; - } if (paletteName) PaletteEditorView.paletteName = paletteName; const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_PALETTE_EDITOR)[0]; if (existing) { @@ -1014,63 +1003,29 @@ export default class HexmakerPlugin extends Plugin { } } - /** - * Map types turned on/off (settings, setup wizard): reload the icon - * pickers and re-render open pages that list palettes or generators so - * the change shows at once. Modals read the setting when they open. - */ - /** Switch between Simple and Advanced (settings, wizard, hints). */ - async setFeatureLevel(level: FeatureLevel): Promise { - this.settings.featureLevel = level; - await this.saveSettings(); - await this.biomesForOverworlds(); - this.onFeaturesChanged(); - } - - /** Turn on one Advanced feature while in Simple (see enableFeature). */ - async enableAdvancedFeature(f: AdvancedFeature): Promise { - enableFeature(this.settings, f); - await this.saveSettings(); - await this.biomesForOverworlds(); - this.onFeaturesChanged(); - } - - /** Overworlds need biomes: the shipped ones (of map types that are on) once Regions and overworlds is on. */ - private async biomesForOverworlds(): Promise { - if (hasFeature(this.settings, "regions")) await this.biomeStore.seedShipped(); - } - - /** Turn off one Advanced feature that was turned on by itself (Simple only). */ - async disableAdvancedFeature(f: AdvancedFeature): Promise { - this.settings.advancedFeatures = this.settings.advancedFeatures.filter((x) => x !== f); - await this.saveSettings(); - this.onFeaturesChanged(); - } + /** The status-bar "Debug" item, while debug mode is on. */ + private debugStatusEl: HTMLElement | null = null; - /** Open modals that show or hide features (see onFeatureChange). */ - private featureListeners = new Set<() => void>(); - - /** - * Re-render when the feature level or an Advanced feature changes, e.g. a - * modal whose hint turned one on. Returns the unsubscribe; call it on close. - */ - onFeatureChange(fn: () => void): () => void { - this.featureListeners.add(fn); - return () => this.featureListeners.delete(fn); + private syncDebugStatus(on: boolean): void { + if (on && !this.debugStatusEl) { + const el = this.addStatusBarItem(); + el.addClass("mod-clickable", "duckmage-debug-status"); + el.setText("Debug"); + el.setAttr("aria-label", "Hexmaker debug mode is on. Click to turn it off."); + el.setAttr("data-tooltip-position", "top"); + el.addEventListener("click", () => setDebugMode(this.app, false)); + this.debugStatusEl = el; + } else if (!on && this.debugStatusEl) { + this.debugStatusEl.remove(); + this.debugStatusEl = null; + } } /** - * Feature level or an Advanced feature changed: re-render open pages and - * modals that show or hide features. + * Map types turned on/off (settings, setup wizard): reload the icon + * pickers and re-render open pages that list palettes or generators so + * the change shows at once. Modals read the setting when they open. */ - onFeaturesChanged(): void { - this.onMapKindsChanged(); - for (const fn of [...this.featureListeners]) fn(); - for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_RANDOM_TABLES)) { - if (leaf.view instanceof RandomTableView) leaf.view.refreshFeatures(); - } - } - onMapKindsChanged(): void { this.loadAvailableIcons(); this.refreshPaletteEditors(); @@ -2738,8 +2693,11 @@ export default class HexmakerPlugin extends Plugin { const map = this.getMap(mapName); if (!map) return; const locked = regionsLocked(this.settings.maps, mapName); + const first = !map.regions; map.regions = map.regions ? applyRegionSettingsEdit(map.regions, next, locked) : next; await this.saveSettings(); + // The first overworld: its biomes need the shipped biome notes (DJ-Q4). + if (first) await this.ensureOverworldBiomes(); } /** diff --git a/src/HexmakerSettingTab.ts b/src/HexmakerSettingTab.ts index 15c04593..04f2c5b8 100644 --- a/src/HexmakerSettingTab.ts +++ b/src/HexmakerSettingTab.ts @@ -5,7 +5,27 @@ import { normalizeFolder } from "./utils"; import { AddPaletteModal } from "./palettes/AddPaletteModal"; import { repointPaletteName } from "./palettes/paletteOptions"; import { MAP_KINDS, enabledKinds, type MapKind } from "./mapKinds"; -import { ADVANCED_FEATURES, hasFeature, isAdvanced } from "./featureLevel"; +import { ConfirmModal } from "./worldgen/ConfirmModal"; +import { Disclosure, disclosureOpen, setDisclosureOpen } from "./ui/disclosure"; +import { partition } from "./ui/placement"; +import { + DEBUG_CONFIRM_TEXT, + debugModeConfirmed, + isDebugMode, + markDebugModeConfirmed, + onDebugModeChange, + setDebugMode, +} from "./ui/debugMode"; + +/** The settings tab's surface id (placement ids are `Settings.`). */ +const SURFACE = "Settings"; + +/** The Advanced dropdown row's description (both settings paths). */ +const ADVANCED_DESC = "Folder layout and other options most people never change."; + +/** The debug-mode switch's description (both settings paths). */ +const DEBUG_MODE_DESC = + "Show backend controls (engine tuning, maintenance) in a Debug section inside each Advanced dropdown. On this device only."; /** Size names in the settings dropdowns. */ const NAME_SIZE_TEXT: Record = { small: "Small", medium: "Medium", large: "Large", huge: "Huge" }; @@ -242,8 +262,9 @@ export class HexmakerSettingTab extends PluginSettingTab { }; }); - return [ - { + const T = (id: string, item: LocalSettingDefinitionItem) => ({ id, item }); + const tagged: { id: string; item: LocalSettingDefinitionItem }[] = [ + T("Settings.rerunSetupWizard", { name: "Setup wizard", desc: "Re-open the setup wizard to reconfigure folders or create a new map.", render: (setting: Setting) => { @@ -256,13 +277,8 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); }, - }, - { - type: "group", - heading: "Features", - items: this.featureItems(), - }, - { + }), + T("Settings.defaultTableDice", { name: "Default die for new tables", desc: "Die size used when creating new random table notes (d6, d20, d100, etc.).", aliases: ["dice"], @@ -283,20 +299,20 @@ export class HexmakerSettingTab extends PluginSettingTab { }, defaultValue: "100", }, - }, - { + }), + T("Settings.collapseSections", { name: "Hex editor sections start collapsed", desc: "Choose which sections open collapsed by default in the right-click hex editor.", aliases: ["terrain", "features", "notes", "collapse"], render: (setting: Setting) => this.buildCollapseTogglesRow(setting), - }, - folderText( + }), + T("Settings.templatePath", folderText( "Template path", "templatePath", "templates/hex.md", "Vault-relative path to a hex note template. Supports {{x}}, {{y}}, {{title}}. Include ### Towns, ### Dungeons, and ### Features headings for the link sections. Blank = hex.md in the templates folder.", - ), - { + )), + T("Settings.defaultMap", { name: "Default map", desc: "The map opened when the hex map is launched.", control: { @@ -305,8 +321,8 @@ export class HexmakerSettingTab extends PluginSettingTab { options: mapOptions, defaultValue: this.plugin.settings.maps[0]?.name ?? "", }, - }, - { + }), + T("Settings.hexOrientation", { name: "Hex orientation", desc: "Pointy-top: points face north/south, flat sides east/west. Flat-top: flat sides face north/south, points east/west.", control: { @@ -315,8 +331,8 @@ export class HexmakerSettingTab extends PluginSettingTab { options: { pointy: "Pointy-top", flat: "Flat-top" }, defaultValue: "pointy", }, - }, - { + }), + T("Settings.staggerOffset", { name: "Stagger offset", desc: "Which set of columns (flat-top) or rows (pointy-top) is offset by half a hex. Affects how new maps render unless overridden per-map.", render: (setting: Setting) => { @@ -334,8 +350,8 @@ export class HexmakerSettingTab extends PluginSettingTab { void this.plugin.saveSettings(); }); }, - }, - { + }), + T("Settings.coordPlacement", { name: "Coordinate placement", desc: "Where the coordinate label sits inside each hex. Move to top or bottom to keep it from clashing with a centered terrain icon.", control: { @@ -344,8 +360,8 @@ export class HexmakerSettingTab extends PluginSettingTab { options: { top: "Top", middle: "Middle", bottom: "Bottom" }, defaultValue: "bottom", }, - }, - { + }), + T("Settings.coordFontSize", { name: "Coordinate label size", desc: "Size of the coordinate label, relative to the hex.", control: { @@ -357,8 +373,8 @@ export class HexmakerSettingTab extends PluginSettingTab { displayFormat: (value) => value.toFixed(2), defaultValue: 0.8, }, - }, - { + }), + T("Settings.coordFontFamily", { name: "Coordinate label font", desc: "Font used for the coordinate label.", control: { @@ -371,8 +387,8 @@ export class HexmakerSettingTab extends PluginSettingTab { }, defaultValue: "interface", }, - }, - { + }), + T("Settings.coordFontColor", { name: "Coordinate label color", desc: "Color of the coordinate label.", control: { @@ -380,8 +396,8 @@ export class HexmakerSettingTab extends PluginSettingTab { key: "coordFontColor", defaultValue: "#ffffff", }, - }, - { + }), + T("Settings.hexNameFont", { name: "Hex name font", desc: "Default font for hex names on maps and in PNG exports. Each map can pick its own in the layers menu.", control: { @@ -390,8 +406,8 @@ export class HexmakerSettingTab extends PluginSettingTab { options: Object.fromEntries(NAME_FAMILIES.map((f) => [f.id, f.label])), defaultValue: DEFAULT_NAME_FONT.family, }, - }, - { + }), + T("Settings.hexNameSize", { name: "Hex name size", desc: "Default size for hex names. Names never get smaller than readable on screen.", control: { @@ -400,8 +416,8 @@ export class HexmakerSettingTab extends PluginSettingTab { options: Object.fromEntries(NAME_SIZES.map((s) => [s.id, NAME_SIZE_TEXT[s.id]])), defaultValue: "medium", }, - }, - { + }), + T("Settings.hexNameStyle", { name: "Hex name style", desc: "Default weight and slant for hex names.", control: { @@ -410,8 +426,8 @@ export class HexmakerSettingTab extends PluginSettingTab { options: Object.fromEntries(NAME_STYLES.map((s) => [s.id, s.label])), defaultValue: "bold", }, - }, - { + }), + T("Settings.hexGap", { name: "Hex cell spacing", desc: "Gap between hex cells (0 – 0.5 em).", control: { @@ -423,8 +439,8 @@ export class HexmakerSettingTab extends PluginSettingTab { displayFormat: (value) => value.toFixed(2), defaultValue: 0.15, }, - }, - { + }), + T("Settings.defaultNewMapCols", { name: "Default new map columns", desc: "Default number of columns when creating a new top-level map.", control: { @@ -435,8 +451,8 @@ export class HexmakerSettingTab extends PluginSettingTab { step: 1, defaultValue: 20, }, - }, - { + }), + T("Settings.defaultNewMapRows", { name: "Default new map rows", desc: "Default number of rows when creating a new top-level map.", control: { @@ -447,8 +463,8 @@ export class HexmakerSettingTab extends PluginSettingTab { step: 1, defaultValue: 16, }, - }, - { + }), + T("Settings.defaultSubmapCols", { name: "Default submap columns", desc: "Default number of columns when creating a new submap.", control: { @@ -459,8 +475,8 @@ export class HexmakerSettingTab extends PluginSettingTab { step: 1, defaultValue: 10, }, - }, - { + }), + T("Settings.defaultSubmapRows", { name: "Default submap rows", desc: "Default number of rows when creating a new submap.", control: { @@ -471,49 +487,38 @@ export class HexmakerSettingTab extends PluginSettingTab { step: 1, defaultValue: 10, }, - }, - folderText( + }), + T("Settings.iconsFolder", folderText( "Custom icons folder", "iconsFolder", "Icons", "Vault-relative folder containing additional icon images (PNG, JPG, SVG, etc.) for the terrain palette and hex icon override. These are merged with the built-in icons.", - ), - { - type: "group", - heading: "Generate world data", - items: [ - { - name: "", - desc: "⚠️ configure all folder settings before selecting generate. This will create terrain table notes, add roller links to all table notes, and link each hex note to its terrain's encounters table. Safe to run multiple times — existing notes and links are not overwritten.", - searchable: false, - }, - { - name: "Generate terrain tables & hex links", - desc: "Creates missing terrain table notes, adds roller links to all table notes (so they can be opened in the hexmaker roller from within Obsidian), and links each hex note's terrain encounters table into its encounters table section.", - render: (setting: Setting) => { - setting.addButton((btn) => - btn - .setButtonText("Generate") - .setCta() - .onClick(async () => { - btn.setDisabled(true); - btn.setButtonText("Generating…"); - try { - await this.plugin.ensureTerrainTables(); - await this.plugin.ensureAllRollerLinks(); - await this.plugin.backfillTerrainLinks(); - await this.plugin.backfillRegionLinks(); - } finally { - btn.setDisabled(false); - btn.setButtonText("Generate"); - } - }), - ); - }, - }, - ], - }, - { + )), + T("Settings.generateWorldData", { + name: "Generate terrain tables & hex links", + desc: "Creates missing terrain table notes, adds roller links to all table notes (so they can be opened in the hexmaker roller from within Obsidian), and links each hex note's terrain encounters table into its encounters table section. Set the folders first. Safe to run more than once: existing notes and links are not overwritten.", + render: (setting: Setting) => { + setting.addButton((btn) => + btn + .setButtonText("Generate") + .setCta() + .onClick(async () => { + btn.setDisabled(true); + btn.setButtonText("Generating…"); + try { + await this.plugin.ensureTerrainTables(); + await this.plugin.ensureAllRollerLinks(); + await this.plugin.backfillTerrainLinks(); + await this.plugin.backfillRegionLinks(); + } finally { + btn.setDisabled(false); + btn.setButtonText("Generate"); + } + }), + ); + }, + }), + T("Settings.pathTypesNote", { type: "group", heading: "Path types", items: [ @@ -523,14 +528,14 @@ export class HexmakerSettingTab extends PluginSettingTab { searchable: false, }, ], - }, - folderText( + }), + T("Settings.worldFolder", folderText( "World notes folder", "worldFolder", "World.", "Vault-relative path. Scopes the file search when adding links to hexes.", - ), - { + )), + T("Settings.generateFolders", { name: "Set up folders", desc: "Populates any blank folder settings below with defaults under the world folder, then creates those folders in your vault. Only blank fields are affected — manually set values are left untouched.", render: (setting: Setting) => { @@ -604,92 +609,92 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); }, - }, - folderText( + }), + T("Settings.hexFolder", folderText( "Hex notes folder", "hexFolder", "World/hexes", "Vault-relative path where hex notes (X_y.md) are stored.", - ), - folderText( + )), + T("Settings.townsFolder", folderText( "Towns folder", "townsFolder", "World/towns", "Vault-relative folder to populate the towns dropdown in the hex editor. Files starting with _ are excluded.", - ), - folderText( + )), + T("Settings.dungeonsFolder", folderText( "Dungeons folder", "dungeonsFolder", "World/dungeons", "Vault-relative folder to populate the dungeons dropdown in the hex editor. Files starting with _ are excluded.", - ), - folderText( + )), + T("Settings.questsFolder", folderText( "Quests folder", "questsFolder", "World/quests", "Vault-relative folder to populate the quests dropdown in the hex editor. Files starting with _ are excluded.", - ), - folderText( + )), + T("Settings.featuresFolder", folderText( "Features folder", "featuresFolder", "World/features", "Vault-relative folder to populate the features dropdown in the hex editor. Files starting with _ are excluded.", - ), - folderText( + )), + T("Settings.factionsFolder", folderText( "Factions folder", "factionsFolder", "World/factions", "Vault-relative folder to populate the factions dropdown in the hex editor. Files starting with _ are excluded.", - ), - folderText( + )), + T("Settings.regionsFolder", folderText( "Regions folder", "regionsFolder", "World/regions", "Vault-relative folder for geographic region notes (used by the region overlay paint tool). Files starting with _ are excluded.", - ), - folderText( + )), + T("Settings.tablesFolder", folderText( "Tables folder", "tablesFolder", "World/tables", "Vault-relative folder for random table notes. Used by the encounters table section and the random tables view.", - ), - folderText( + )), + T("Settings.workflowsFolder", folderText( "Workflows folder", "workflowsFolder", "World/workflows", "Vault-relative folder for workflow notes. Browsable from the random tables view via the workflows tab.", - ), - folderText( + )), + T("Settings.templatesFolder", folderText( "Templates folder", "templatesFolder", "World/templates", TEMPLATES_FOLDER_DESC, - ), - folderText( + )), + T("Settings.palettesFolder", folderText( "Palettes folder", "palettesFolder", "World/palettes", PALETTES_FOLDER_DESC, - ), - folderText( + )), + T("Settings.biomesFolder", folderText( "Biomes folder", "biomesFolder", "World/biomes", BIOMES_FOLDER_DESC, - ), - folderText( + )), + T("Settings.biomePoolsFolder", folderText( "Biome pools folder", "biomePoolsFolder", "World/biome-pools", BIOME_POOLS_FOLDER_DESC, - ), - folderText( + )), + T("Settings.worldTypesFolder", folderText( "World types folder", "worldTypesFolder", "World/world-types", WORLD_TYPES_FOLDER_DESC, - ), - { + )), + T("Settings.mapKinds", { type: "group", heading: "Map types", items: MAP_KINDS.map((k): LocalSettingDefinition => ({ @@ -702,7 +707,11 @@ export class HexmakerSettingTab extends PluginSettingTab { ); }, })), - }, + }), + ]; + // Terrain palettes LAST among the regular settings (see the comment on + // them); the Advanced dropdown and the debug-mode switch go after them. + const palettesSection: LocalSettingDefinitionItem[] = [ // Terrain palettes LAST, deliberately: on update() the declarative // renderer reuses unchanged rows but re-creates a changed list and // appends it at the END of the page — a mid-page list visibly "drops @@ -774,6 +783,8 @@ export class HexmakerSettingTab extends PluginSettingTab { }, }, ]; + this.watchDebugMode(() => this.requestDeclarativeRerender()); + return this.layoutDefinitions(tagged, palettesSection); } /** @@ -881,55 +892,117 @@ export class HexmakerSettingTab extends PluginSettingTab { } /** - * Feature level (src/featureLevel.ts): Simple or Advanced, each Advanced - * feature on its own while in Simple, and a way to bring closed hints back. + * The declarative page: the regular settings above the fold (`main`, then + * `more`), Terrain palettes, then the collapsed Advanced dropdown with its + * Debug subsection (only in debug mode), then the debug-mode switch at the + * very bottom. Each setting's layer comes from the placement map + * (src/ui/placement.ts), keyed by its `Settings.` id. */ - private featureItems(): LocalSettingDefinition[] { - const s = this.plugin.settings; - const refresh = () => { - if (typeof (this as unknown as { update?: () => void }).update === "function") this.requestDeclarativeRerender(); - else this.renderSettings(); - }; - const items: LocalSettingDefinition[] = [ - { - name: "Feature level", - desc: "Simple: paint maps, write hex notes, roll on encounter tables, export. Advanced: also terrain generators, workflows, custom palettes and neighbouring regions. Nothing you've made is touched either way.", - aliases: ["simple", "advanced", "mode"], - render: (setting: Setting) => { - setting.addDropdown((d) => - d.addOption("simple", "Simple").addOption("advanced", "Advanced") - .setValue(s.featureLevel) - .onChange((v) => void this.plugin.setFeatureLevel(v === "simple" ? "simple" : "advanced").then(refresh)), - ); - }, - }, - ]; - for (const f of ADVANCED_FEATURES) { - items.push({ - name: f.label, - desc: isAdvanced(s) ? `${f.pitch} (On with Advanced.)` : f.pitch, - render: (setting: Setting) => { - setting.addToggle((t) => { - t.setValue(hasFeature(s, f.id)).setDisabled(isAdvanced(s)); - t.onChange((on) => void (on ? this.plugin.enableAdvancedFeature(f.id) : this.plugin.disableAdvancedFeature(f.id)).then(refresh)); - }); - }, + private layoutDefinitions( + tagged: { id: string; item: LocalSettingDefinitionItem }[], + palettesSection: LocalSettingDefinitionItem[], + ): LocalSettingDefinitionItem[] { + // Every layer is laid out; Debug shows only while debug mode is on. + const { main, more, advanced, debug } = partition(tagged, true); + const open = () => disclosureOpen(this.app, SURFACE); + const debugOn = () => isDebugMode(this.app); + // Settings in a dropdown are flat rows: a group's rows go in without its heading. + const flat = (items: LocalSettingDefinitionItem[]): LocalSettingDefinition[] => + items.flatMap((i) => ("type" in i && (i.type === "group" || i.type === "list") ? (i.items ?? []) : [i as LocalSettingDefinition])); + const shownWhen = (items: LocalSettingDefinition[], when: () => boolean): LocalSettingDefinition[] => + items.map((i) => { + const own = i.visible; + return { ...i, visible: () => when() && (own === undefined || (typeof own === "function" ? own() : own)) }; }); - } - if (s.dismissedHints.length) - items.push({ - name: "Hints", - desc: `${s.dismissedHints.length} hint${s.dismissedHints.length === 1 ? "" : "s"} about Advanced features hidden.`, - render: (setting: Setting) => { - setting.addButton((b) => - b.setButtonText("Show hints again").onClick(() => { - s.dismissedHints = []; - void this.plugin.saveSettings().then(refresh); - }), - ); - }, + const out: LocalSettingDefinitionItem[] = [...main, ...more, ...palettesSection]; + if (advanced.length || debug.length) { + out.push({ + type: "group", + cls: "duckmage-settings-advanced", + items: [ + { + name: "Advanced", + desc: ADVANCED_DESC, + aliases: ["folders"], + render: (setting: Setting) => this.renderAdvancedRow(setting, () => this.requestDeclarativeRerender()), + }, + ...shownWhen(flat(advanced), open), + ], }); - return items; + if (debug.length) + out.push({ + type: "group", + heading: "Debug", + cls: "duckmage-settings-debug", + visible: () => open() && debugOn(), + items: shownWhen(flat(debug), () => open() && debugOn()), + }); + } + out.push({ + type: "group", + cls: "duckmage-settings-debug-mode", + items: [this.debugModeDefinition()], + }); + return out; + } + + /** The Advanced dropdown's header row: click to open or close it (remembered on this device). */ + private renderAdvancedRow(setting: Setting, refresh: () => void): void { + const open = disclosureOpen(this.app, SURFACE); + setting.settingEl.addClass("duckmage-settings-advanced-row"); + setting.settingEl.toggleClass("is-open", open); + setting.settingEl.setAttr("role", "button"); + setting.settingEl.setAttr("aria-expanded", String(open)); + setting.addExtraButton((b) => + b.setIcon(open ? "chevron-down" : "chevron-right").setTooltip(open ? "Hide advanced settings" : "Show advanced settings"), + ); + setting.settingEl.addEventListener("click", () => { + setDisclosureOpen(this.app, SURFACE, !open); + refresh(); + }); + } + + /** + * The debug-mode switch (both settings paths): the only way to turn debug + * mode on. The first time on this device it asks first. The page redraws + * through watchDebugMode. + */ + private debugModeDefinition(): LocalSettingDefinition { + return { + name: "Debug mode", + desc: DEBUG_MODE_DESC, + aliases: ["debug", "developer", "maintenance"], + render: (setting: Setting) => { + setting.addToggle((t) => + t.setValue(isDebugMode(this.app)).onChange((on) => { + if (!on || debugModeConfirmed(this.app)) { + setDebugMode(this.app, on); + return; + } + // Not on until the user confirms. + t.setValue(false); + new ConfirmModal(this.app, DEBUG_CONFIRM_TEXT.title, DEBUG_CONFIRM_TEXT.body, DEBUG_CONFIRM_TEXT.confirm, () => { + markDebugModeConfirmed(this.app); + setDebugMode(this.app, true); + }).open(); + }), + ); + }, + }; + } + + /** Redraws the tab when debug mode changes (this switch, or the status bar). */ + private stopDebugWatch?: () => void; + + hide(): void { + this.stopDebugWatch?.(); + this.stopDebugWatch = undefined; + super.hide(); + } + + private watchDebugMode(refresh: () => void): void { + this.stopDebugWatch?.(); + this.stopDebugWatch = onDebugModeChange(() => refresh()); } private requestDeclarativeRerender(): void { @@ -1013,8 +1086,14 @@ export class HexmakerSettingTab extends PluginSettingTab { private renderSettings(): void { const { containerEl } = this; containerEl.empty(); - - new Setting(containerEl) + this.watchDebugMode(() => this.renderSettings()); + // Each row's layer comes from the placement map (Settings. ids): + // built above the fold, in the Advanced dropdown, in Debug, or nowhere + // (a detached element) when it isn't shown. + const disclosure = new Disclosure(this.app, SURFACE, () => containerEl); + const at = (id: string): HTMLElement => disclosure.target(id, containerEl) ?? createDiv(); + + new Setting(at("Settings.rerunSetupWizard")) .setName("Setup wizard") .setDesc("Re-open the setup wizard to reconfigure folders or create a new map.") .addButton((btn) => @@ -1026,14 +1105,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl).setName("Features").setHeading(); - for (const item of this.featureItems()) { - const s = new Setting(containerEl).setName(item.name ?? ""); - if (typeof item.desc === "string") s.setDesc(item.desc); - item.render?.(s); - } - - new Setting(containerEl) + new Setting(at("Settings.defaultTableDice")) .setName("Default die for new tables") .setDesc( "Die size used when creating new random table notes (d6, d20, d100, etc.).", @@ -1057,14 +1129,14 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.collapseSections")) .setName("Hex editor sections start collapsed") .setDesc( "Choose which sections open collapsed by default in the right-click hex editor.", ) .then((setting) => this.buildCollapseTogglesRow(setting)); - new Setting(containerEl) + new Setting(at("Settings.templatePath")) .setName("Template path") .setDesc( "Vault-relative path to a hex note template. Supports {{x}}, {{y}}, {{title}}. Include ### Towns, ### Dungeons, and ### Features headings for the link sections. Blank = hex.md in the templates folder.", @@ -1079,7 +1151,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.defaultMap")) .setName("Default map") .setDesc("The map opened when the hex map is launched.") .addDropdown((dropdown) => { @@ -1098,7 +1170,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }); }); - new Setting(containerEl) + new Setting(at("Settings.hexOrientation")) .setName("Hex orientation") .setDesc( "Pointy-top: points face north/south, flat sides east/west. Flat-top: flat sides face north/south, points east/west.", @@ -1114,7 +1186,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.staggerOffset")) .setName("Stagger offset") .setDesc( "Which set of columns (flat-top) or rows (pointy-top) is offset by half a hex. Affects how new maps render unless overridden per-map.", @@ -1133,7 +1205,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }); }); - new Setting(containerEl) + new Setting(at("Settings.coordPlacement")) .setName("Coordinate placement") .setDesc( "Where the coordinate label sits inside each hex. Move to top or bottom to keep it from clashing with a centered terrain icon.", @@ -1155,7 +1227,7 @@ export class HexmakerSettingTab extends PluginSettingTab { ); { - const coordSetting = new Setting(containerEl) + const coordSetting = new Setting(at("Settings.coordFontSize")) .setName("Coordinate label") .setDesc( "Size (relative to the hex) and font for the coordinate label.", @@ -1209,7 +1281,7 @@ export class HexmakerSettingTab extends PluginSettingTab { await this.plugin.saveSettings(); this.plugin.refreshHexMap(); }; - new Setting(containerEl) + new Setting(at("Settings.hexNameFont")) .setName("Hex name font") .setDesc("Default font, size and style for hex names on maps and in PNG exports. Each map can pick its own in the layers menu.") .addDropdown((dropdown) => { @@ -1236,7 +1308,7 @@ export class HexmakerSettingTab extends PluginSettingTab { } { - const gapSetting = new Setting(containerEl) + const gapSetting = new Setting(at("Settings.hexGap")) .setName("Hex cell spacing") .setDesc("Gap between hex cells (0 – 0.5 em)."); const currentGap = @@ -1258,7 +1330,7 @@ export class HexmakerSettingTab extends PluginSettingTab { ); } - new Setting(containerEl) + new Setting(at("Settings.defaultNewMapCols")) .setName("Default new map size") .setDesc("Default columns and rows when creating a new top-level map.") .addText((text) => @@ -1280,7 +1352,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.defaultSubmapCols")) .setName("Default submap size") .setDesc("Default columns and rows when creating a new submap.") .addText((text) => @@ -1302,7 +1374,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.iconsFolder")) .setName("Custom icons folder") .setDesc( "Vault-relative folder containing additional icon images (PNG, JPG, SVG, etc.) for the terrain palette and hex icon override. These are merged with the built-in icons.", @@ -1318,15 +1390,10 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl).setName("Generate world data").setHeading(); - containerEl.createEl("p", { - cls: "setting-item-description duckmage-generate-warning", - text: "⚠️ configure all folder settings above before selecting generate. This will create terrain table notes, add roller links to all table notes, and link each hex note to its terrain's encounters table. Safe to run multiple times — existing notes and links are not overwritten.", - }); - new Setting(containerEl) + new Setting(at("Settings.generateWorldData")) .setName("Generate terrain tables & hex links") .setDesc( - "Creates missing terrain table notes, adds roller links to all table notes (so they can be opened in the hexmaker roller from within Obsidian), and links each hex note's terrain encounters table into its encounters table section.", + "Creates missing terrain table notes, adds roller links to all table notes (so they can be opened in the hexmaker roller from within Obsidian), and links each hex note's terrain encounters table into its encounters table section. Set the folders first. Safe to run more than once: existing notes and links are not overwritten.", ) .addButton((btn) => btn @@ -1353,7 +1420,7 @@ export class HexmakerSettingTab extends PluginSettingTab { cls: "setting-item-description", }); - new Setting(containerEl) + new Setting(at("Settings.worldFolder")) .setName("World notes folder") .setDesc( "Vault-relative path. Scopes the file search when adding links to hexes.", @@ -1368,7 +1435,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.generateFolders")) .setName("Set up folders") .setDesc( "Populates any blank folder settings below with defaults under the world folder, then creates those folders in your vault. Only blank fields are affected — manually set values are left untouched.", @@ -1442,7 +1509,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.hexFolder")) .setName("Hex notes folder") .setDesc("Vault-relative path where hex notes (X_y.md) are stored.") .addText((text) => @@ -1455,7 +1522,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.townsFolder")) .setName("Towns folder") .setDesc( "Vault-relative folder to populate the towns dropdown in the hex editor. Files starting with _ are excluded.", @@ -1470,7 +1537,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.dungeonsFolder")) .setName("Dungeons folder") .setDesc( "Vault-relative folder to populate the dungeons dropdown in the hex editor. Files starting with _ are excluded.", @@ -1485,7 +1552,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.questsFolder")) .setName("Quests folder") .setDesc( "Vault-relative folder to populate the quests dropdown in the hex editor. Files starting with _ are excluded.", @@ -1500,7 +1567,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.featuresFolder")) .setName("Features folder") .setDesc( "Vault-relative folder to populate the features dropdown in the hex editor. Files starting with _ are excluded.", @@ -1515,7 +1582,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.factionsFolder")) .setName("Factions folder") .setDesc( "Vault-relative folder to populate the factions dropdown in the hex editor. Files starting with _ are excluded.", @@ -1530,7 +1597,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.regionsFolder")) .setName("Regions folder") .setDesc( "Vault-relative folder for geographic region notes (used by the region overlay paint tool). Files starting with _ are excluded.", @@ -1545,7 +1612,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.tablesFolder")) .setName("Tables folder") .setDesc( "Vault-relative folder for random table notes. Used by the encounters table section and the random tables view.", @@ -1560,7 +1627,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.workflowsFolder")) .setName("Workflows folder") .setDesc( "Vault-relative folder for workflow notes. Browsable from the random tables view via the workflows tab.", @@ -1575,7 +1642,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.templatesFolder")) .setName("Templates folder") .setDesc(TEMPLATES_FOLDER_DESC) .addText((text) => @@ -1588,7 +1655,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.palettesFolder")) .setName("Palettes folder") .setDesc(PALETTES_FOLDER_DESC) .addText((text) => @@ -1601,7 +1668,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.biomesFolder")) .setName("Biomes folder") .setDesc(BIOMES_FOLDER_DESC) .addText((text) => @@ -1615,7 +1682,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.biomePoolsFolder")) .setName("Biome pools folder") .setDesc(BIOME_POOLS_FOLDER_DESC) .addText((text) => @@ -1628,7 +1695,7 @@ export class HexmakerSettingTab extends PluginSettingTab { }), ); - new Setting(containerEl) + new Setting(at("Settings.worldTypesFolder")) .setName("World types folder") .setDesc(WORLD_TYPES_FOLDER_DESC) .addText((text) => @@ -1688,13 +1755,11 @@ export class HexmakerSettingTab extends PluginSettingTab { const palettes = this.plugin.settings.terrainPalettes; + // The list redraws inside its own host, so what's below it stays below. + const listHost = containerEl.createDiv(); const renderPaletteList = () => { - const existingList = containerEl.querySelector( - ".duckmage-palette-mgmt-list", - ); - if (existingList) existingList.remove(); - - const listEl = containerEl.createDiv({ + listHost.empty(); + const listEl = listHost.createDiv({ cls: "duckmage-palette-mgmt-list", }); @@ -1765,5 +1830,13 @@ export class HexmakerSettingTab extends PluginSettingTab { }; renderPaletteList(); + + // The Advanced dropdown (with Debug inside) below everything else, then + // the debug-mode switch at the very bottom. + disclosure.toEnd(); + const debugRow = new Setting(containerEl).setName("Debug mode"); + const debugDef = this.debugModeDefinition(); + if (typeof debugDef.desc === "string") debugRow.setDesc(debugDef.desc); + debugDef.render?.(debugRow); } } diff --git a/src/SetupWizardView.ts b/src/SetupWizardView.ts index 4c0698df..5fb3da0f 100644 --- a/src/SetupWizardView.ts +++ b/src/SetupWizardView.ts @@ -6,7 +6,6 @@ import { linkLabel, normalizeFolder, slugify } from "./utils"; import { VIEW_TYPE_SETUP_WIZARD, VIEW_TYPE_HEX_MAP } from "./constants"; import { attachPaletteHint, defaultPaletteFor, fillPaletteSelect } from "./palettes/paletteOptions"; import { MAP_KINDS, enabledKinds, isSpacePalette, terrainsForTables, type MapKind } from "./mapKinds"; -import { FEATURE_LEVEL_CHOICES, type FeatureLevel } from "./featureLevel"; import { randomSeed } from "../packages/hex-wfc/src"; import { drawPreview, PREVIEW_AUTO_LIMIT } from "./worldgen/preview"; import { addGeneratedPaths, pathColors } from "./worldgen/generators"; @@ -54,8 +53,6 @@ interface WizardContext { hexOrientation: "flat" | "pointy"; /** Map types to enable (src/mapKinds.ts). */ mapKinds: MapKind[]; - /** Simple or Advanced (src/featureLevel.ts). */ - featureLevel: FeatureLevel; /** Generator for the first map (registry id); undefined = pick the * default for the map types and palette (firstMapGenerator). */ generatorId?: string; @@ -172,14 +169,9 @@ function wizardKinds( ctx: WizardContext, terrains: TerrainColor[], ): { fitting: TerrainGeneratorKind[]; selected: string } { - // Choose among every generator the map types allow, then (in Simple) keep - // just Blank and the default starter, so a Simple first map still gets - // terrain without a wall of choices. - const all = kindsForPalette(visibleKinds(kinds, { mapKinds: ctx.mapKinds, featureLevel: "advanced" }, isSpacePalette(terrains), ctx.generatorId), terrains); - const starter = firstMapGenerator(all, ctx.mapKinds); - const fitting = ctx.featureLevel === "simple" - ? all.filter((k) => k.id === BLANK_ID || k.id === starter || k.mapKind === "space") - : all; + // Every generator the map types allow; the default starter is selected. + const fitting = kindsForPalette(visibleKinds(kinds, { mapKinds: ctx.mapKinds }, isSpacePalette(terrains), ctx.generatorId), terrains); + const starter = firstMapGenerator(fitting, ctx.mapKinds); const selected = ctx.generatorId && fitting.some((k) => k.id === ctx.generatorId) ? ctx.generatorId : starter; @@ -254,27 +246,10 @@ function makeWelcomeStep(): WizardStep { }); } - // How much to start with. Changeable any time in settings, and - // any one Advanced feature can be turned on from where it would appear. - const level = container.createDiv({ cls: "duckmage-wizard-field duckmage-wizard-kinds" }); - level.createEl("label", { text: "How much do you want to start with?", cls: "duckmage-wizard-label" }); - for (const opt of FEATURE_LEVEL_CHOICES) { - const row = level.createEl("label", { cls: "duckmage-wizard-kind" }); - const radio = row.createEl("input", { type: "radio", attr: { name: "duckmage-feature-level" } }); - radio.checked = ctx.featureLevel === opt.id; - const text = row.createDiv(); - text.createDiv({ text: opt.label, cls: "duckmage-wizard-kind-title" }); - text.createDiv({ text: opt.description, cls: "duckmage-wizard-kind-desc" }); - radio.addEventListener("change", () => { - if (radio.checked) ctx.featureLevel = opt.id; - cbs.onUpdate(); - }); - } }, canProceed: (ctx) => ctx.mapKinds.length > 0, async onNext(ctx, plugin) { plugin.settings.mapKinds = [...ctx.mapKinds]; - plugin.settings.featureLevel = ctx.featureLevel; // What the setup installs follows the map types picked (SP3): // space only → space palettes, no biome notes or fantasy // palettes, "Palette for new maps" on Space - Sector. @@ -594,13 +569,6 @@ function makeMapStep(plugin: HexmakerPlugin): WizardStep { const genBody = genField.createDiv({ cls: "duckmage-wizard-generator-body" }); const genSide = genBody.createDiv({ cls: "duckmage-wizard-generator-choices" }); const genList = genSide.createDiv({ cls: "duckmage-setup-generators", text: "Loading generators…" }); - // Simple offers just the starter generator; say there's more. - if (ctx.featureLevel === "simple") { - genSide.createDiv({ - text: "More generators (learned from your own maps, biome presets, blends) come with the advanced features; turn them on any time.", - cls: "duckmage-wizard-kind-desc", - }); - } const optsBox = genSide.createDiv({ cls: "duckmage-wizard-generator-options" }); const previewBox = genBody.createDiv({ cls: "duckmage-wizard-generator-preview" }); const canvas = previewBox.createEl("canvas", { cls: "duckmage-setup-canvas" }); @@ -881,7 +849,6 @@ export class SetupWizardView extends ItemView { paletteName: defaultPaletteFor(plugin.settings), hexOrientation: plugin.settings.hexOrientation ?? "flat", mapKinds: [...enabledKinds(plugin.settings)], - featureLevel: plugin.settings.featureLevel, generatorOptions: {}, seed: randomSeed(), }; diff --git a/src/advancedHints.ts b/src/advancedHints.ts deleted file mode 100644 index 630aa971..00000000 --- a/src/advancedHints.ts +++ /dev/null @@ -1,210 +0,0 @@ -/** - * The ways a Simple user finds Advanced features (see src/featureLevel.ts): - * a small "More" line where a hidden feature would sit, a "Turn on …?" box - * when they reach for one, and a one-time "Ready for more?" check-in. Every - * hint turns on just that feature or all of Advanced, and can be closed. - */ - -import { App } from "obsidian"; -import type HexmakerPlugin from "./HexmakerPlugin"; -import { HexmakerModal } from "./HexmakerModal"; -import { ADVANCED_FEATURES, hasFeature, type AdvancedFeature } from "./featureLevel"; - -const info = (f: AdvancedFeature) => ADVANCED_FEATURES.find((x) => x.id === f)!; - -/** - * A one-line "More: …" hint in `parent` for a feature that's off, unless - * it's on or this spot's hint was closed. `spot` names the place (one id per - * screen), so closing it there doesn't hide it elsewhere. `text` overrides - * the feature's own pitch with one that fits the spot. - */ -export function renderAdvancedHint( - parent: HTMLElement, - plugin: HexmakerPlugin, - feature: AdvancedFeature, - spot: string, - text?: string, -): HTMLElement | null { - const s = plugin.settings; - if (hasFeature(s, feature) || s.dismissedHints.includes(spot)) return null; - const f = info(feature); - const el = parent.createDiv({ cls: "duckmage-advanced-hint" }); - el.createSpan({ text: "✦", cls: "duckmage-advanced-hint-mark" }); - el.createSpan({ text: text ?? f.pitch, cls: "duckmage-advanced-hint-text" }); - const on = el.createEl("button", { text: `Turn on ${f.label.toLowerCase()}`, cls: "duckmage-advanced-hint-on" }); - on.addEventListener("click", () => void plugin.enableAdvancedFeature(feature)); - const close = el.createEl("button", { text: "✕", cls: "duckmage-advanced-hint-close", attr: { "aria-label": "Hide this hint", title: "Hide this hint (the features section of settings can show it again)" } }); - close.addEventListener("click", () => { - s.dismissedHints = [...new Set([...s.dismissedHints, spot])]; - void plugin.saveSettings(); - el.remove(); - }); - return el; -} - -/** - * One "More options" line for a screen where several Advanced features would - * sit, instead of a stack of single hints. Lists whichever of `features` are - * still off; "Show" opens MoreFeaturesModal to turn them on one by one. With - * only one left it's an ordinary single hint. - */ -export function renderAdvancedHints( - parent: HTMLElement, - plugin: HexmakerPlugin, - features: { feature: AdvancedFeature; text: string }[], - spot: string, -): HTMLElement | null { - const s = plugin.settings; - const off = features.filter((f) => !hasFeature(s, f.feature)); - if (!off.length || s.dismissedHints.includes(spot)) return null; - if (off.length === 1) return renderAdvancedHint(parent, plugin, off[0].feature, spot, off[0].text); - const el = parent.createDiv({ cls: "duckmage-advanced-hint" }); - el.createSpan({ text: "✦", cls: "duckmage-advanced-hint-mark" }); - el.createSpan({ - text: `More options: ${off.map((f) => info(f.feature).label.toLowerCase()).join(", ")}.`, - cls: "duckmage-advanced-hint-text", - }); - el.createEl("button", { text: "Show", cls: "duckmage-advanced-hint-on" }) - .addEventListener("click", () => new MoreFeaturesModal(plugin.app, plugin, off).open()); - const close = el.createEl("button", { text: "✕", cls: "duckmage-advanced-hint-close", attr: { "aria-label": "Hide this hint", title: "Hide this hint (the features section of settings can show it again)" } }); - close.addEventListener("click", () => { - s.dismissedHints = [...new Set([...s.dismissedHints, spot])]; - void plugin.saveSettings(); - el.remove(); - }); - return el; -} - -/** The features behind a "More options" hint, each with its own Turn on. */ -export class MoreFeaturesModal extends HexmakerModal { - constructor( - app: App, - private plugin: HexmakerPlugin, - private features: { feature: AdvancedFeature; text: string }[], - ) { - super(app); - } - - onOpen(): void { - this.makeDraggable(); - this.modalEl.addClass("duckmage-more-features-modal"); - this.titleEl.setText("More options"); - this.render(); - } - - private render(): void { - const { contentEl } = this; - contentEl.empty(); - contentEl.createEl("p", { - text: "These are advanced features. Turn on the ones you want; they can be turned off again in settings, and nothing you've made is touched.", - cls: "duckmage-map-origin-desc", - }); - const list = contentEl.createDiv({ cls: "duckmage-more-features" }); - for (const f of this.features) { - const row = list.createDiv({ cls: "duckmage-more-features-row" }); - const text = row.createDiv({ cls: "duckmage-more-features-text" }); - text.createEl("strong", { text: info(f.feature).label }); - text.createDiv({ text: f.text }); - if (hasFeature(this.plugin.settings, f.feature)) { - row.createSpan({ text: "On", cls: "duckmage-more-features-on" }); - } else { - row.createEl("button", { text: "Turn on" }).addEventListener("click", () => { - void this.plugin.enableAdvancedFeature(f.feature).then(() => this.render()); - }); - } - } - const row = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); - row.createEl("button", { text: "Turn on all advanced features" }).addEventListener("click", () => { - void this.plugin.setFeatureLevel("advanced").then(() => this.close()); - }); - row.createEl("button", { text: "Done", cls: "mod-cta" }).addEventListener("click", () => this.close()); - } - - onClose(): void { - this.contentEl.empty(); - } -} - -/** "Turn on ?": shown when a Simple user reaches for an Advanced feature. */ -export class EnableFeatureModal extends HexmakerModal { - constructor( - app: App, - private plugin: HexmakerPlugin, - private feature: AdvancedFeature, - private onEnabled: () => void, - ) { - super(app); - } - - onOpen(): void { - this.makeDraggable(); - const f = info(this.feature); - this.titleEl.setText(`Turn on ${f.label.toLowerCase()}?`); - const { contentEl } = this; - contentEl.createEl("p", { text: f.pitch }); - contentEl.createEl("p", { - text: "It's one of the advanced features. Turn on just this, or all of them; either can be turned off again in settings, and nothing you've made is touched.", - cls: "duckmage-map-origin-desc", - }); - const row = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); - const one = row.createEl("button", { text: `Turn on ${f.label.toLowerCase()}`, cls: "mod-cta" }); - one.addEventListener("click", () => void this.enable(false)); - row.createEl("button", { text: "Turn on all advanced features" }).addEventListener("click", () => void this.enable(true)); - row.createEl("button", { text: "Not now" }).addEventListener("click", () => this.close()); - } - - private async enable(all: boolean): Promise { - if (all) await this.plugin.setFeatureLevel("advanced"); - else await this.plugin.enableAdvancedFeature(this.feature); - this.close(); - this.onEnabled(); - } - - onClose(): void { - this.contentEl.empty(); - } -} - -/** Run `then` now if the feature is on, else after the user turns it on. */ -export function withFeature(plugin: HexmakerPlugin, feature: AdvancedFeature, then: () => void): void { - if (hasFeature(plugin.settings, feature)) then(); - else new EnableFeatureModal(plugin.app, plugin, feature, then).open(); -} - -/** The one-time "Ready for more?" check-in (see shouldNudge). */ -export class AdvancedNudgeModal extends HexmakerModal { - constructor(app: App, private plugin: HexmakerPlugin) { - super(app); - } - - onOpen(): void { - this.makeDraggable(); - this.titleEl.setText("Ready for more?"); - const { contentEl } = this; - contentEl.createEl("p", { text: "You've got the hang of the basics. Advanced adds:" }); - const list = contentEl.createEl("ul"); - for (const f of ADVANCED_FEATURES) { - if (hasFeature(this.plugin.settings, f.id)) continue; - const li = list.createEl("li"); - li.createEl("strong", { text: `${f.label}: ` }); - li.appendText(f.pitch); - } - contentEl.createEl("p", { text: "You can switch back any time in settings; nothing you've made is touched.", cls: "duckmage-map-origin-desc" }); - const row = contentEl.createDiv({ cls: "duckmage-confirm-btn-row" }); - const on = row.createEl("button", { text: "Turn on advanced features", cls: "mod-cta" }); - on.addEventListener("click", () => { - void this.plugin.setFeatureLevel("advanced"); - this.close(); - }); - row.createEl("button", { text: "Not now" }).addEventListener("click", () => this.close()); - row.createEl("button", { text: "Don't ask again" }).addEventListener("click", () => { - this.plugin.settings.advancedNudgeOff = true; - void this.plugin.saveSettings(); - this.close(); - }); - } - - onClose(): void { - this.contentEl.empty(); - } -} diff --git a/src/constants.ts b/src/constants.ts index fd468a2b..7d31b59a 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -414,11 +414,6 @@ export const DEFAULT_SETTINGS: HexmakerPluginSettings = { // the setting get space too if they already have space palettes // (resolveMapKinds in src/mapKinds.ts). mapKinds: ["world"], - // Resolved at load from the raw data (resolveFeatureLevel): updates from - // before feature levels get Advanced, fresh installs start Simple. - featureLevel: "simple", - advancedFeatures: [], - dismissedHints: [], terrainTypesSeeded: false, presetTerrainsAdded: [], presetPathFieldsAdded: [], diff --git a/src/featureLevel.ts b/src/featureLevel.ts deleted file mode 100644 index 59ce66b9..00000000 --- a/src/featureLevel.ts +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Feature level: Simple or Advanced. Simple is everything needed to run a - * hexcrawl (paint maps, write hex notes, roll on tables, export); Advanced - * adds the power tools below. Simple users can turn on any one of them from - * the screen where it would appear (see renderAdvancedHint), so they ramp up - * at their own pace; turning on all of them is the same as Advanced. - * - * Hiding a feature never touches its data: generators, workflows, palettes - * and linked regions all stay on disk and come back when it's turned on. - * Space (src/mapKinds.ts) is a separate switch and brings all its content, - * generators included, at either level. - */ - -export type FeatureLevel = "simple" | "advanced"; - -export type AdvancedFeature = "generators" | "workflows" | "palettes" | "regions"; - -export interface AdvancedFeatureInfo { - id: AdvancedFeature; - label: string; - /** One line on what it adds, for hints, settings and the wizard. */ - pitch: string; -} - -export const ADVANCED_FEATURES: AdvancedFeatureInfo[] = [ - { - id: "generators", - label: "Terrain generators", - pitch: "Generate terrain for you: learned from maps you've painted, or from biome presets, blended between biomes.", - }, - { - id: "workflows", - label: "Workflows", - pitch: "Chain several table rolls into one filled-in note (a settlement, an NPC, a dungeon room).", - }, - { - id: "palettes", - label: "Custom palettes", - pitch: "Design your own palettes: terrains, colours, icons, path types and submap defaults.", - }, - { - id: "regions", - label: "Regions and overworlds", - pitch: "Give each hex its own region map at one shared scale, join maps edge to edge into one big world, and walk from one into the next.", - }, -]; - -export const ALL_ADVANCED_FEATURES: AdvancedFeature[] = ADVANCED_FEATURES.map((f) => f.id); - -export interface FeatureSettings { - featureLevel?: FeatureLevel; - /** Advanced features turned on one by one while in Simple. */ - advancedFeatures?: string[]; -} - -export const isAdvanced = (s: FeatureSettings): boolean => s.featureLevel !== "simple"; - -/** Is this Advanced feature on: Advanced level, or turned on by itself. */ -export function hasFeature(s: FeatureSettings, f: AdvancedFeature): boolean { - return isAdvanced(s) || (s.advancedFeatures ?? []).includes(f); -} - -/** - * Turn one feature on (in place). Once every feature is on, the level - * becomes Advanced, so features added later come on too. - */ -export function enableFeature(s: FeatureSettings, f: AdvancedFeature): void { - const on = new Set(s.advancedFeatures ?? []); - on.add(f); - s.advancedFeatures = [...on]; - if (ALL_ADVANCED_FEATURES.every((x) => on.has(x))) s.featureLevel = "advanced"; -} - -/** - * The level for settings as loaded. A saved level always wins. Without one, - * an install that already has data (any saved settings: an update from a - * version before feature levels) gets Advanced so nothing it used - * disappears; a fresh install starts Simple until the setup wizard asks. - */ -export function resolveFeatureLevel(raw: Record | null | undefined): FeatureLevel { - const saved = raw?.["featureLevel"]; - if (saved === "simple" || saved === "advanced") return saved; - return raw && Object.keys(raw).length > 0 ? "advanced" : "simple"; -} - -/** Settings for the one-time "ready for more?" check-in. */ -export interface NudgeSettings extends FeatureSettings { - /** When the plugin first ran (ISO date). */ - installedAt?: string; - /** Last time the check-in was shown (ISO date). */ - advancedNudgeAt?: string; - /** "Don't ask again". */ - advancedNudgeOff?: boolean; -} - -/** Days after install, or maps made, before the check-in; and days between asks. */ -export const NUDGE = { afterDays: 14, afterMaps: 2, againDays: 14 }; - -const days = (from: string | undefined, now: Date): number => - from ? (now.getTime() - new Date(from).getTime()) / 86_400_000 : 0; - -/** - * Time to ask a Simple user whether they want Advanced: they've been at it a - * while (two weeks, or a couple of maps made) and weren't asked recently. - */ -export function shouldNudge(s: NudgeSettings, mapCount: number, now = new Date()): boolean { - if (isAdvanced(s) || s.advancedNudgeOff) return false; - if (s.advancedNudgeAt && days(s.advancedNudgeAt, now) < NUDGE.againDays) return false; - return mapCount >= NUDGE.afterMaps || days(s.installedAt, now) >= NUDGE.afterDays; -} - -/** The setup wizard's "How much do you want to start with?" choices. */ -export const FEATURE_LEVEL_CHOICES: { id: FeatureLevel; label: string; description: string }[] = [ - { - id: "simple", - label: "Simple", - description: "Paint maps, write hex notes, roll on encounter tables: everything you need to run a hexcrawl. You can turn on more later from any screen.", - }, - { - id: "advanced", - label: "Advanced", - description: "Also generates terrain for you (learned from your own maps, or from presets), chains tables into workflows, lets you design your own palettes, and joins maps into one big world.", - }, -]; diff --git a/src/hex-map/HexEditorModal.ts b/src/hex-map/HexEditorModal.ts index 23937f97..0bd7aec7 100644 --- a/src/hex-map/HexEditorModal.ts +++ b/src/hex-map/HexEditorModal.ts @@ -53,8 +53,6 @@ import { WalkRegionModal } from "../worldgen/WalkRegionModal"; import { regionHome, walkLock } from "../overworld/regionsVault"; import { parentOf } from "../overworld/layout"; import { flowerPetals, neighbourButton } from "../maps/mapNav"; -import { hasFeature } from "../featureLevel"; -import { withFeature } from "../advancedHints"; import type { MapData } from "../types"; import { RegionNavigateModal } from "./RegionNavigateModal"; import { displayedEncounterLinks, linkDisplayName } from "../encounterLinks"; @@ -223,15 +221,13 @@ export class HexEditorModal extends HexmakerModal { }); } // Run a workflow for this hex (PA2): its result can be added to a - // section here. Workflows are an Advanced feature. - if (hasFeature(this.plugin.settings, "workflows")) { - const wfLink = titleLeft.createEl("a", { - text: "Run workflow", - cls: "duckmage-editor-open-link", - attr: { title: "Roll a workflow and add the result to this hex" }, - }); - wfLink.addEventListener("click", () => this.pickWorkflow()); - } + // section here. + const wfLink = titleLeft.createEl("a", { + text: "Run workflow", + cls: "duckmage-editor-open-link", + attr: { title: "Roll a workflow and add the result to this hex" }, + }); + wfLink.addEventListener("click", () => this.pickWorkflow()); this.renderNeighborWidget(titleRow, this.x, this.y); this.renderNameField(contentEl, path); this.renderMapsStrip(contentEl); @@ -621,21 +617,15 @@ export class HexEditorModal extends HexmakerModal { const side = offMapSide(here, nx, ny); tile.addClass("duckmage-neighbor-tile-new"); tile.removeClass("duckmage-neighbor-tile-offmap"); - tile.title = hasFeature(this.plugin.settings, "regions") - ? `New land to the ${side}…` - : `Join a new map to the ${side} (neighbouring regions)…`; + tile.title = `New land to the ${side}…`; tile.addEventListener("click", () => { - // Needs neighbouring regions, and generators to pick a biome; - // in Simple each asks to be turned on first. - withFeature(this.plugin, "regions", () => withFeature(this.plugin, "generators", () => { - new WalkRegionModal(this.app, this.plugin, this.mapName, side, () => { - const now = this.plugin.getMap(this.mapName); - const arrived = now ? resolveHex(this.plugin.settings.maps, now, nx, ny) : null; - if (!arrived || arrived.map.name === this.mapName) return; - this.close(); - this.options.onCrossToRegion?.(arrived.map.name, arrived.x, arrived.y); - }).open(); - })); + new WalkRegionModal(this.app, this.plugin, this.mapName, side, () => { + const now = this.plugin.getMap(this.mapName); + const arrived = now ? resolveHex(this.plugin.settings.maps, now, nx, ny) : null; + if (!arrived || arrived.map.name === this.mapName) return; + this.close(); + this.options.onCrossToRegion?.(arrived.map.name, arrived.x, arrived.y); + }).open(); }); } else { tile.title = "Off map"; diff --git a/src/hex-map/HexMapView.ts b/src/hex-map/HexMapView.ts index 5578d03d..80ba9ca6 100644 --- a/src/hex-map/HexMapView.ts +++ b/src/hex-map/HexMapView.ts @@ -95,7 +95,6 @@ import { draftsAfterEdit, isApplied } from "../overworld/pathProjection"; import { brushCells, FrameThrottle, terrainDiff, overworldLeftClick, overworldMenu, PAINT_LOCKED_HINT, PAINT_NO_REGION_HINT, paintTargets, TERRAIN_IN_BIOMES_HINT } from "../overworld/overworldInput"; import { WalkRegionModal, type OverworldWalk } from "../worldgen/WalkRegionModal"; import type { Side } from "../worldgen/world"; -import { withFeature } from "../advancedHints"; import { overworldRefreshFor } from "../overworld/overworldChanges"; import { RegionNavigateModal } from "./RegionNavigateModal"; import { neighbourShadow, neighbourSpec } from "../worldgen/neighbours"; @@ -1053,13 +1052,10 @@ export class HexMapView extends ItemView { */ private openWalk(to: Side | OverworldWalk): void { const from = this.activeMapName; - const open = () => new WalkRegionModal(this.app, this.plugin, from, to, (name) => { + new WalkRegionModal(this.app, this.plugin, from, to, (name) => { if (this.activeMapName === from) this.navigateToMap(name); else this.refreshSideCrumbs(); }).open(); - // A side-by-side world picks a terrain generator; an overworld needs neither feature. - if (typeof to === "string") withFeature(this.plugin, "regions", () => withFeature(this.plugin, "generators", open)); - else open(); } public switchMapFromModal(name: string): void { diff --git a/src/hex-map/MakeGeneratorModal.ts b/src/hex-map/MakeGeneratorModal.ts index 538c2a20..509680b9 100644 --- a/src/hex-map/MakeGeneratorModal.ts +++ b/src/hex-map/MakeGeneratorModal.ts @@ -11,16 +11,10 @@ import { App, Notice } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import { makeRegionGenerator, overwriteTargets, type OverwriteCandidate } from "../worldgen/regionGenerator"; -import { hasFeature } from "../featureLevel"; -import { withFeature } from "../advancedHints"; import { slugify } from "../utils"; -/** Open the dialog (an Advanced feature: in Simple, offers to turn Generators on first). */ +/** Open the "Make generator from this map" dialog. */ export function openMakeGenerator(app: App, plugin: HexmakerPlugin, mapName: string): void { - if (!hasFeature(plugin.settings, "generators")) { - withFeature(plugin, "generators", () => openMakeGenerator(app, plugin, mapName)); - return; - } new MakeGeneratorModal(app, plugin, mapName).open(); } diff --git a/src/hex-map/MapModal.ts b/src/hex-map/MapModal.ts index 886dad03..3d26a5d6 100644 --- a/src/hex-map/MapModal.ts +++ b/src/hex-map/MapModal.ts @@ -19,8 +19,6 @@ import { linkRegions, regionNeighbours, } from "../worldgen/neighbours"; -import { hasFeature } from "../featureLevel"; -import { renderAdvancedHint, withFeature } from "../advancedHints"; import { regionsOf, removeMapPatch } from "../maps/submaps"; import { RegionSettingsModal } from "./newChildMap"; import { openMakeGenerator } from "./MakeGeneratorModal"; @@ -72,7 +70,6 @@ export function renderMissingActions(el: HTMLElement, plugin: HexmakerPlugin, na export class MapModal extends HexmakerModal { private confirmingDelete: string | null = null; private stopKeepInViewport?: () => void; - private stopFeatureChange?: () => void; private activeTab: ModalTab = "Maps"; constructor( @@ -91,8 +88,6 @@ export class MapModal extends HexmakerModal { // moves up as a tab grows (fresh-eyes r4: Export ran off the bottom). this.modalEl.addClass("duckmage-map-modal"); this.stopKeepInViewport = this.keepInViewport(); - // A hint here can turn a feature on: show what it brings straight away. - this.stopFeatureChange = this.plugin.onFeatureChange(() => this.render()); this.render(); } @@ -103,9 +98,8 @@ export class MapModal extends HexmakerModal { // Tab bar const tabBar = contentEl.createDiv({ cls: "duckmage-rt-mode-tabs duckmage-map-modal-tabs" }); - // Regions: shown once the map has region settings, or Regions are on. const active = this.plugin.getMap(this.view.activeMapName); - const showRegions = !!active && (!!active.regions || hasFeature(this.plugin.settings, "regions")); + const showRegions = !!active; const tabNames: ModalTab[] = showRegions ? ["Maps", "Properties", "Regions", "Export"] : ["Maps", "Properties", "Export"]; if (!tabNames.includes(this.activeTab)) this.activeTab = "Maps"; @@ -128,13 +122,11 @@ export class MapModal extends HexmakerModal { if (tab === "Properties") { tabBar.createEl("button", { text: "New map…", cls: "duckmage-rt-mode-tab duckmage-map-new-btn" }) .addEventListener("click", () => this.openNewMap()); - if (hasFeature(this.plugin.settings, "regions")) { - tabBar.createEl("button", { text: "New overworld…", cls: "duckmage-rt-mode-tab duckmage-map-new-btn", attr: { title: "A map of biomes whose hexes open into regions that join up" } }) - .addEventListener("click", () => { - this.close(); - this.plugin.openNewOverworld(); - }); - } + tabBar.createEl("button", { text: "New overworld…", cls: "duckmage-rt-mode-tab duckmage-map-new-btn", attr: { title: "A map of biomes whose hexes open into regions that join up" } }) + .addEventListener("click", () => { + this.close(); + this.plugin.openNewOverworld(); + }); } btn.addEventListener("click", () => { this.activeTab = tab; @@ -169,9 +161,9 @@ export class MapModal extends HexmakerModal { }); if (!map.regions) { const btn = el.createEl("button", { text: "Set up regions…" }); - btn.addEventListener("click", () => withFeature(this.plugin, "regions", () => { + btn.addEventListener("click", () => { new RegionSettingsModal(this.app, this.plugin, map.name, () => this.render()).open(); - })); + }); return; } const regions = regionsOf(this.plugin.settings.maps, map.name); @@ -699,12 +691,6 @@ export class MapModal extends HexmakerModal { }); return; } - // An Advanced feature; a map that's already linked keeps showing its links. - if (!hasFeature(this.plugin.settings, "regions") && !map.world) { - renderAdvancedHint(el, this.plugin, "regions", "map-properties", - "Join this map edge to edge with others into one big world, and walk from one into the next: neighbouring regions."); - return; - } el.createEl("h4", { text: "Neighbouring regions" }); el.createEl("p", { text: "Regions next to each other share one grid: walking off this map's edge (or the hex flower) leads into them. They must be the same size and use the same palette.", @@ -924,7 +910,6 @@ export class MapModal extends HexmakerModal { onClose(): void { this.stopKeepInViewport?.(); - this.stopFeatureChange?.(); this.contentEl.empty(); } } diff --git a/src/hex-map/help.md b/src/hex-map/help.md index 3f28e4dd..43192fc2 100644 --- a/src/hex-map/help.md +++ b/src/hex-map/help.md @@ -15,7 +15,7 @@ A hex can open into maps of its own. There are two kinds: - **Location**: a separate place in the hex, like a town, a dungeon or a ship, with its own size and palette. A hex can have any number. Every submap made before regions is a location. -- **Region** (Advanced): the hex itself, up close. Every region of a map uses the same shape and size, so regions line up with each other. A hex has at most one. +- **Region**: the hex itself, up close. Every region of a map uses the same shape and size, so regions line up with each other. A hex has at most one. Hexes with locations show a small ring at the top, with a count once there are two or more. A hex with a region has a thin outline inside it. @@ -139,15 +139,15 @@ Tokens show their name underneath. The layers panel's **Labels** group turns coo --- -## Simple and Advanced +## Advanced dropdowns and Debug mode -**Simple** has everything you need to run a hexcrawl: paint maps, write hex notes, roll on encounter tables, export. **Advanced** adds terrain generators, workflows (chained table rolls), custom palettes, and regions and overworlds (a region map per hex at one scale, and maps joined into one world). Locations (towns, dungeons… inside a hex) are in Simple too. +Every feature is always there: there's no Simple or Advanced level to switch. Each page keeps the everyday options on top; options most people never change sit in a collapsed **Advanced** dropdown at the bottom of that page (in Settings: the folder layout; on the terrain generator page: Symmetry, Edge style and the guarantees). Open it when you want it; it stays open or closed on that page next time (on this device). -Turn on any one of them from the hint (✦) where it would appear, or all of them in **Settings → Features**. Switching back hides them again; nothing you made is deleted. +**Debug mode** shows backend controls, such as the generator's engine tuning sliders and maintenance buttons (Generate folders, Generate terrain tables & hex links), in a **Debug** section inside each Advanced dropdown. Turn it on with **Settings → Debug mode**, at the very bottom; the first time, it asks to make sure. While it's on, **Debug** shows in the status bar: click it to turn debug mode off. It's kept per device and never synced. **Map types.** What the setup installs follows the map types you pick: World gets the Expanded and Limited palettes and the biome notes; Space alone gets Space - Sector, Space - System and Space - Planet and nothing fantasy. Turning a type on later in **Settings → Map types** installs its content then. Planets and moons open on **Space - Planet**, a land palette for surfaces. Note pickers list only what they're for: the token form's Note list shows the tokens, towns, dungeons, features, quests, factions and regions folders, never biomes, palettes, tables or other plugin notes. -**Overworlds** (Advanced: Regions and overworlds). **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). Right-click a region → **Edit region…** for its name, the hex it's on, **Enter region**, **Open map note**, its biome, facts (size, palette, terrain counts, neighbouring regions, locations) and notes (kept in its map note under `## Notes`, editable in every mode). The biome can only be changed in God mode: there it's a picker with **Reroll** and **Settings…**; in Build and Play it's shown with "Switch to God to change it." The overworld has no hex editor: right-click shows only region-level items. The **Biome** tool sets biomes (see Drawing tools). The terrain tool paints the regions and only works in the Regions view (the Biomes view shows biomes only, so the terrain tool is off there): the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. +**Overworlds**. **Maps → New overworld…** makes a map of biomes whose hexes each open into a rectangle region; regions next to each other share one grid, so they join hex for hex. The switch at the bottom right picks the view (the one showing is highlighted): **Regions** shows every region's hexes stitched together, with blank bricks where there's no region yet (hover for a region's name, click to go in at that spot; the terrain tool paints the regions' own hexes, across seams), **Biomes** shows one biome per hex (hover for its region's name). In both views a click on a hex or brick that has a region goes into it, in every mode; a click on an empty one sets its biome and makes its region (Build and God). Right-click a region → **Edit region…** for its name, the hex it's on, **Enter region**, **Open map note**, its biome, facts (size, palette, terrain counts, neighbouring regions, locations) and notes (kept in its map note under `## Notes`, editable in every mode). The biome can only be changed in God mode: there it's a picker with **Reroll** and **Settings…**; in Build and Play it's shown with "Switch to God to change it." The overworld has no hex editor: right-click shows only region-level items. The **Biome** tool sets biomes (see Drawing tools). The terrain tool paints the regions and only works in the Regions view (the Biomes view shows biomes only, so the terrain tool is off there): the brush (any size) paints the regions' own hexes across seams and they update as you draw, on the overworld and in any open view of those regions. A stroke is one undo step. Where there's no region yet the brush does nothing ("No region here yet; place a biome first"); in Play it says "Switch to Build to paint the regions." The minimap at the bottom right shows the overworld from any of its regions. Hand-painted region hexes are locked, so remaking a region keeps them. **Work modes: Play, Build, God.** Each map has a mode, shown on the toolbar next to the map button; click it to switch. The map keeps its mode (the `mode:` line in its map note) and opens in it next time; new maps are in **Build**. @@ -177,7 +177,7 @@ Neighbouring regions share one set of hex numbers: a new region carries on from A road or river that ends on the edge of a region, next to where the neighbour's road of the same type ends, is drawn on to the shared edge on both maps, so the two join up. -**World types** (space). Star scatter and Orbits roll on a World types table note in `{world folder}/world-types`: which worlds they place, how often, and how each world's own map is made. Their **World types** option picks the table (**Default** is Default space, which ships with the usual odds; **None** is equal odds, and the generator says so). Each row: a **World** (a terrain of the palette), a **Weight** (decimals are fine), optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**), a sector world's **Mainworld** (the body Orbits makes its mainworld) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base** (Default space opens its planets on **Space - Planet**). A row that isn't a terrain of the palette is never placed, and the warnings name it. **Edit world types…** (Advanced: Terrain generators; in the Star scatter and Orbits options, or the command) edits the rows, and its preview rolls for a palette, map, orbit and star just as the generators do, so its odds are the real odds. The same note also has a **Stars** table (the star Orbits picks when its Star choice is Random, by **Weight**) and a **Sector features** table (Star scatter's special hexes, each with a **Chance** per star system hex, like `1 in 50` or `2%`); the editor has a tab and a preview for each. Changes save automatically (no Save button); a row marked incomplete isn't saved until it's finished, and is dropped when you close the editor. Hand edits to the note made meanwhile are kept. Needs Build or God. +**World types** (space). Star scatter and Orbits roll on a World types table note in `{world folder}/world-types`: which worlds they place, how often, and how each world's own map is made. Their **World types** option picks the table (**Default** is Default space, which ships with the usual odds; **None** is equal odds, and the generator says so). Each row: a **World** (a terrain of the palette), a **Weight** (decimals are fine), optional limits (**Map** sector or system, **Orbit** inner / habitable / outer or rings like `2–4`, **Stars**, **Temperature**), a sector world's **Mainworld** (the body Orbits makes its mainworld) and, for the world's map, **Size** (`20×14` or `16–24 × 10–14`), **Generator**, **Options**, **Palette** and **Base** (Default space opens its planets on **Space - Planet**). A row that isn't a terrain of the palette is never placed, and the warnings name it. **Edit world types…** (in the Star scatter and Orbits options, or the command) edits the rows, and its preview rolls for a palette, map, orbit and star just as the generators do, so its odds are the real odds. The same note also has a **Stars** table (the star Orbits picks when its Star choice is Random, by **Weight**) and a **Sector features** table (Star scatter's special hexes, each with a **Chance** per star system hex, like `1 in 50` or `2%`); the editor has a tab and a preview for each. Changes save automatically (no Save button); a row marked incomplete isn't saved until it's finished, and is dropped when you close the editor. Hand edits to the note made meanwhile are kept. Needs Build or God. **More in a table** (all optional; old tables read the same). Weights can be decimals (`3.5`) or percentages. Extra columns are kept and shown in the Random Tables view. The columns **Roll** (`now` / `on arrival`), **Shown as**, **Once** (`per world` / `per map`) and **When** (`zone: outer; star: red dwarf`), and `rows:` in the frontmatter (text, note, table, generator, terrain, biome or any), are read and checked (**Check tables**). @@ -193,7 +193,7 @@ A road or river that ends on the edge of a region, next to where the neighbour's With generators on, new maps can also use the built-in **biomes and presets** (Grassland, Taiga, Swamp, Archipelago, Volcanic and more). They place terrain by type, so they work with any palette whose terrains have types. -**New map…** (in Maps) is one form: generator cards with a live preview, Next to (Advanced), and **More** for starting coordinates, stagger and a background image (pick one from the vault, or drop one from your computer). A new map starts on Overland; pick Blank to paint by hand. +**New map…** (in Maps) is one form: generator cards with a live preview, Next to, and **More** for starting coordinates, stagger and a background image (pick one from the vault, or drop one from your computer). A new map starts on Overland; pick Blank to paint by hand. Pickers that link notes (to hexes, tokens, sections) never offer template notes (the hex template, workflow templates, a Templates folder); pickers for choosing a template do. Notes starting with `_` are never offered. diff --git a/src/hex-map/mapTablesForm.ts b/src/hex-map/mapTablesForm.ts index d9980870..0a9c14cf 100644 --- a/src/hex-map/mapTablesForm.ts +++ b/src/hex-map/mapTablesForm.ts @@ -9,7 +9,6 @@ import type HexmakerPlugin from "../HexmakerPlugin"; import type { MapData } from "../types"; import { FileLinkSuggestModal } from "./FileLinkSuggestModal"; import { contentFolder } from "../notePickers"; -import { hasFeature } from "../featureLevel"; import { ENGINE_ROLES, type RoleId } from "../worldgen/tableRoles"; import { fittingRoleTables } from "../worldgen/tableSources"; import { SPACE_TABLES_FOLDER } from "../space/spaceTables"; @@ -52,7 +51,7 @@ export function renderRoleTables(el: HTMLElement, plugin: HexmakerPlugin, map: M const own = map.roleTables ?? {}; const inherited = plugin.roleTablesFor(map.name); const anySet = Object.keys(inherited).length > 0; - if (!anySet && (!plugin.isSpaceMap(map.name) || !hasFeature(plugin.settings, "generators"))) return; + if (!anySet && !plugin.isSpaceMap(map.name)) return; el.createEl("h4", { text: "Generator tables" }); el.createDiv({ diff --git a/src/hex-map/newChildMap.ts b/src/hex-map/newChildMap.ts index ba8d334d..f4acc5bd 100644 --- a/src/hex-map/newChildMap.ts +++ b/src/hex-map/newChildMap.ts @@ -2,8 +2,6 @@ import { App, Notice } from "obsidian"; import { HexmakerModal } from "../HexmakerModal"; import type HexmakerPlugin from "../HexmakerPlugin"; import type { RegionSettings, SubmapKind } from "../types"; -import { hasFeature } from "../featureLevel"; -import { renderAdvancedHint } from "../advancedHints"; import { NewMapSetupModal } from "../worldgen/NewMapSetupModal"; import { DEFAULT_REGION_SETTINGS, regionMapAt } from "../maps/submaps"; import { renderRegionSettingsForm } from "./regionSettingsForm"; @@ -113,7 +111,6 @@ export class ChildKindModal extends HexmakerModal { contentEl.empty(); const { plugin } = this.host; const existing = regionMapAt(plugin.settings.maps, this.parentMap, `${this.x}_${this.y}`); - const regionsOn = hasFeature(plugin.settings, "regions"); const text = childKindText(plugin.isSpaceMap(this.parentMap)); // The hex's maps first (C11): opening what's there is the usual pick; @@ -148,27 +145,16 @@ export class ChildKindModal extends HexmakerModal { const why = existing ? `This hex's region is ${plugin.mapLabel(existing.name)}.` - : !regionsOn ? "Advanced: needs Regions and overworlds." : !canAdd(plugin.getMap(this.parentMap)) ? ADD_REGION_LOCKED_HINT : undefined; card("region", why); if (existing && this.host.onEnter) { const enter = contentEl.createEl("button", { cls: "duckmage-child-kind-enter", text: `Enter ${plugin.mapLabel(existing.name)}` }); enter.addEventListener("click", () => { this.close(); this.host.onEnter?.(existing.name); }); } - if (!regionsOn && !existing) { - renderAdvancedHint(contentEl, plugin, "regions", "child-kind-region", "Regions: a map of each hex that lines up with its neighbours."); - } card("location"); - // Turning Regions on from the hint enables the card at once. - const stop = plugin.onFeatureChange(() => this.render()); - this.stopFeatureChange?.(); - this.stopFeatureChange = stop; } - private stopFeatureChange?: () => void; - onClose(): void { - this.stopFeatureChange?.(); this.contentEl.empty(); } } diff --git a/src/hex-table/LinkPickerModal.ts b/src/hex-table/LinkPickerModal.ts index 6b9dab09..977f6eff 100644 --- a/src/hex-table/LinkPickerModal.ts +++ b/src/hex-table/LinkPickerModal.ts @@ -13,7 +13,7 @@ export class LinkPickerModal extends HexmakerModal { app: App, private plugin: HexmakerPlugin, private hexPath: string, - private section: LinkSection, + private linkSection: LinkSection, private sourceFolder: string, private onLinked: () => void, private createTemplate = "", @@ -24,7 +24,7 @@ export class LinkPickerModal extends HexmakerModal { onOpen(): void { this.makeDraggable(); const { contentEl } = this; - this.titleEl.setText(`Add ${this.section}`); + this.titleEl.setText(`Add ${this.linkSection}`); contentEl.addClass("duckmage-link-picker-modal"); const normalized = normalizeFolder(this.sourceFolder); @@ -36,7 +36,7 @@ export class LinkPickerModal extends HexmakerModal { // Tables: the user's own first; the terrain and region tables the map // made sit in a collapsed "Made by the map" group after them. - const { own, mapMade } = this.section === "Encounters Table" + const { own, mapMade } = this.linkSection === "Encounters Table" ? groupTableFiles(this.app, files) : { own: files, mapMade: [] as TFile[] }; const addItems = (list: HTMLElement, items: TFile[]) => { @@ -68,7 +68,7 @@ export class LinkPickerModal extends HexmakerModal { type: "text", cls: "duckmage-link-picker-input", }); - input.placeholder = `${this.section.slice(0, -1)} name…`; + input.placeholder = `${this.linkSection.slice(0, -1)} name…`; const createBtn = row.createEl("button", { text: "Create", cls: "mod-cta", @@ -85,7 +85,7 @@ export class LinkPickerModal extends HexmakerModal { private async addLink(file: TFile): Promise { await this.ensureHexNote(); const linkText = `[[${this.app.metadataCache.fileToLinktext(file, this.hexPath)}]]`; - await addLinkToSection(this.app, this.hexPath, this.section, linkText); + await addLinkToSection(this.app, this.hexPath, this.linkSection, linkText); await addBacklinkToFile(this.app, file.path, this.hexPath, this.plugin.hexLinkAlias(this.hexPath)); this.onLinked(); this.close(); @@ -104,8 +104,8 @@ export class LinkPickerModal extends HexmakerModal { // Towns start from the town template (PA3) unless the caller gave one. // Places made from a hex say where they are (a Location line, R3). const content = this.createTemplate - ? (LOCATION_SECTIONS.includes(this.section) ? this.plugin.withHexLocation(this.createTemplate, this.hexPath) : this.createTemplate) - : await this.plugin.newLinkedNoteContent(this.section, name, this.hexPath); + ? (LOCATION_SECTIONS.includes(this.linkSection) ? this.plugin.withHexLocation(this.createTemplate, this.hexPath) : this.createTemplate) + : await this.plugin.newLinkedNoteContent(this.linkSection, name, this.hexPath); file = await this.app.vault.create(newPath, content); } catch (err) { new Notice(`Could not create ${newPath}: ${String(err)}`); diff --git a/src/kindContent.ts b/src/kindContent.ts index 8fdeac78..d1baba9c 100644 --- a/src/kindContent.ts +++ b/src/kindContent.ts @@ -25,7 +25,6 @@ import { ALL_MAP_KINDS, paletteKind, type MapKind } from "./mapKinds"; import type { TerrainColor } from "./types"; import { PALETTE_PRESETS, type PalettePreset } from "./palettes/presets"; import { terrainsEqual } from "./palettes/paletteNote"; -import { hasFeature, type FeatureSettings } from "./featureLevel"; export interface KindContentInput { /** Map types on now. */ @@ -107,21 +106,20 @@ export function planKindContent(input: KindContentInput): KindContentPlan { /** * May the shipped biome notes of map type `kind` be written? Never while the * type is off (a space-only setup gets none). Otherwise when it's asked for - * (`explicit`: the setup picked the type, or it was turned on in - * Settings), when the overworld tools are on (Regions and overworlds: they - * need biomes, however the vault was made), or when the vault already has - * shipped biome notes (later shipped biomes top them up, once each). - * A vault that never had biome notes and doesn't use overworlds gets none - * written on its own (no content into a vault that didn't ask for it). + * (`explicit`: the setup picked the type, it was turned on in Settings, or + * the first overworld or region was made, DJ-Q4), or when the vault + * already has shipped biome notes (later shipped biomes top them up, once + * each). A vault that never had biome notes and makes no overworld gets + * none written on its own (no content into a vault that didn't ask for it). */ export function biomeSeedingOn( - settings: FeatureSettings & { mapKinds?: string[]; biomesSeeded?: string[] }, + settings: { mapKinds?: string[]; biomesSeeded?: string[] }, kind: MapKind, explicit = false, ): boolean { const kinds = Array.isArray(settings.mapKinds) ? settings.mapKinds : ALL_MAP_KINDS; if (!kinds.includes(kind)) return false; - return explicit || hasFeature(settings, "regions") || (settings.biomesSeeded?.length ?? 0) > 0; + return explicit || (settings.biomesSeeded?.length ?? 0) > 0; } /** diff --git a/src/overworld/demoWorld.ts b/src/overworld/demoWorld.ts index 9b690a99..8cf255cd 100644 --- a/src/overworld/demoWorld.ts +++ b/src/overworld/demoWorld.ts @@ -74,14 +74,13 @@ export function overworldSeams(plugin: HexmakerPlugin, overworld: string): DemoW } /** - * The owner's playtest world: Advanced on, a 19-hex hex-shaped overworld + * The owner's playtest world: a 19-hex hex-shaped overworld * (World biomes) with 8×8 brick regions, all generated, plus a few * location stubs (three on one hex to exercise the Locations list). */ export async function buildDemoWorld(plugin: HexmakerPlugin, opts: { seed?: number } = {}): Promise { const t0 = performance.now(); - await plugin.enableAdvancedFeature("regions"); - await plugin.enableAdvancedFeature("generators"); + await plugin.ensureOverworldBiomes(); plugin.settings.setupComplete = true; await plugin.ensurePaletteInstalled(EXPANDED_PALETTE_NAME); const seed = opts.seed ?? 7; @@ -121,7 +120,7 @@ export async function buildDemoWorld(plugin: HexmakerPlugin, opts: { seed?: numb /** The bench world: a 10×10 overworld with 8×8 regions (100 regions, 6,400 hexes). */ export async function buildBenchWorld(plugin: HexmakerPlugin, opts: { seed?: number; side?: number } = {}): Promise<{ name: string; regions: number; hexes: number; msOverworld: number; msRegions: number }> { - await plugin.enableAdvancedFeature("regions"); + await plugin.ensureOverworldBiomes(); const side = opts.side ?? 10; const cells: [number, number][] = []; for (let y = 0; y < side; y++) for (let x = 0; x < side; x++) cells.push([x, y]); diff --git a/src/overworld/regionsVault.ts b/src/overworld/regionsVault.ts index cc4564eb..44465054 100644 --- a/src/overworld/regionsVault.ts +++ b/src/overworld/regionsVault.ts @@ -390,6 +390,8 @@ export async function createRegion(plugin: HexmakerPlugin, parentName: string, p recordHexBiome(plugin, parentName, hex, biome); await plugin.mapStore.flush(); } + // The first region made: the shipped biome notes go in (DJ-Q4; once each). + await plugin.ensureOverworldBiomes(); return res; } diff --git a/src/random-tables/RandomTableView.ts b/src/random-tables/RandomTableView.ts index 2b625ca3..82967217 100644 --- a/src/random-tables/RandomTableView.ts +++ b/src/random-tables/RandomTableView.ts @@ -11,8 +11,6 @@ import { } from "obsidian"; import type HexmakerPlugin from "../HexmakerPlugin"; import { VIEW_TYPE_RANDOM_TABLES } from "../constants"; -import { hasFeature } from "../featureLevel"; -import { renderAdvancedHint } from "../advancedHints"; import { normalizeFolder, makeTableTemplate } from "../utils"; import { RandomTableEditorModal } from "./RandomTableEditorModal"; import { WorkflowEditorModal } from "./WorkflowEditorModal"; @@ -83,19 +81,6 @@ export class RandomTableView extends ItemView { private viewMode: "tables" | "workflows" = "tables"; private tablesBtn: HTMLButtonElement | null = null; private workflowsBtn: HTMLButtonElement | null = null; - /** Holds the "workflows" hint while that Advanced feature is off. */ - private workflowHintBox: HTMLElement | null = null; - - /** Show or hide workflows to match the feature level (see src/featureLevel.ts). */ - refreshFeatures(): void { - const on = hasFeature(this.plugin.settings, "workflows"); - this.workflowsBtn?.toggle(on); - this.workflowHintBox?.empty(); - if (!on && this.workflowHintBox) - renderAdvancedHint(this.workflowHintBox, this.plugin, "workflows", "random-tables", - "Chain several of these tables into one filled-in note (a settlement, an NPC): workflows."); - if (!on && this.viewMode === "workflows") this.setViewMode("tables"); - } private tableFooterEl: HTMLElement | null = null; private workflowFooterEl: HTMLElement | null = null; @@ -178,9 +163,6 @@ export class RandomTableView extends ItemView { this.workflowsBtn.addEventListener("click", () => this.setViewMode("workflows"), ); - // Workflows are an Advanced feature: in Simple, a hint sits here instead. - this.workflowHintBox = leftCol.createDiv(); - this.refreshFeatures(); // Middle-click mode tabs → open view in new tab at that mode this.tablesBtn.addEventListener("auxclick", (e: MouseEvent) => { @@ -1804,7 +1786,7 @@ export class RandomTableView extends ItemView { // ── Used by workflows ─────────────────────────────────────────────── const tableKey = file.path.slice(0, -3); // remove .md const usingWorkflows = this.workflowMap.get(tableKey) ?? []; - if (hasFeature(this.plugin.settings, "workflows") && (usingWorkflows.length > 0 || this.plugin.settings.workflowsFolder)) { + if (usingWorkflows.length > 0 || this.plugin.settings.workflowsFolder) { const usedBySection = this.detailEl.createDiv({ cls: "duckmage-rt-used-by", }); diff --git a/src/types.ts b/src/types.ts index 9dc64b1b..b1bd3fe7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -428,20 +428,8 @@ export interface HexmakerPluginSettings { * are written until it does (saved as null so a restart still knows). */ kindContent?: string[] | null; - /** Simple or Advanced (see src/featureLevel.ts). */ - featureLevel: "simple" | "advanced"; - /** Advanced features turned on one by one while in Simple. */ - advancedFeatures: string[]; - /** Advanced hints the user closed, by spot id. */ - dismissedHints: string[]; /** The one-time "Add roll ranges to tables?" offer: answered ("done") or turned off ("never"). Unset = not asked yet. */ tableRangesPrompt?: "done" | "never"; - /** When the plugin first ran (ISO date), for the "ready for more?" check-in. */ - installedAt?: string; - /** Last time the check-in was shown (ISO date). */ - advancedNudgeAt?: string; - /** "Don't ask again" on the check-in. */ - advancedNudgeOff?: boolean; /** True once existing palettes got terrain types (one-time seeding). */ terrainTypesSeeded: boolean; /** Default hex-name font for maps without their own (NM3; see hexNameFont.ts). Unset = theme font, medium, bold. */ diff --git a/src/ui/debugMode.ts b/src/ui/debugMode.ts new file mode 100644 index 00000000..30eb2aa5 --- /dev/null +++ b/src/ui/debugMode.ts @@ -0,0 +1,58 @@ +/** + * Debug mode: shows the Debug subsection inside each surface's Advanced + * dropdown (backend controls: engine knobs, maintenance and repair). + * + * - Per device (DJ-Q1): kept in Obsidian's local storage for this vault + * (`app.saveLocalStorage`), never in data.json, so it never syncs. + * - Turned on only from the bottom of the plugin's settings, with a + * one-time confirmation (settings tab). No command, ribbon or menu item + * turns it on. + * - While on, a "Debug" status-bar item shows; clicking it turns debug + * mode off (HexmakerPlugin). + */ + +/** The bit of Obsidian's App this needs (local storage), so tests can fake it. */ +export interface LocalStore { + loadLocalStorage(key: string): unknown; + saveLocalStorage(key: string, data: unknown): void; +} + +/** Local-storage key: debug mode is on. */ +export const DEBUG_MODE_KEY = "hexmaker-debug-mode"; +/** Local-storage key: the user has seen and accepted the debug-mode confirmation once. */ +export const DEBUG_CONFIRMED_KEY = "hexmaker-debug-mode-confirmed"; + +const listeners = new Set<(on: boolean) => void>(); + +export function isDebugMode(store: LocalStore): boolean { + return store.loadLocalStorage(DEBUG_MODE_KEY) === true; +} + +/** Turn debug mode on or off on this device and tell every listener. Off removes the key. */ +export function setDebugMode(store: LocalStore, on: boolean): void { + if (on === isDebugMode(store)) return; + store.saveLocalStorage(DEBUG_MODE_KEY, on ? true : null); + for (const fn of [...listeners]) fn(on); +} + +/** Has the one-time "this is a debug mode" confirmation been accepted on this device? */ +export function debugModeConfirmed(store: LocalStore): boolean { + return store.loadLocalStorage(DEBUG_CONFIRMED_KEY) === true; +} + +export function markDebugModeConfirmed(store: LocalStore): void { + store.saveLocalStorage(DEBUG_CONFIRMED_KEY, true); +} + +/** Call `fn` whenever debug mode changes. Returns the unsubscribe. */ +export function onDebugModeChange(fn: (on: boolean) => void): () => void { + listeners.add(fn); + return () => listeners.delete(fn); +} + +/** The confirmation shown the first time debug mode is turned on. */ +export const DEBUG_CONFIRM_TEXT = { + title: "Turn on debug mode?", + body: "This is a debug mode. It shows backend controls, such as engine tuning and maintenance tools, that most people never need. They appear in a Debug section inside each page's Advanced dropdown. While it's on, \"Debug\" shows in the status bar; click it to turn debug mode off.", + confirm: "Turn on debug mode", +}; diff --git a/src/ui/disclosure.ts b/src/ui/disclosure.ts new file mode 100644 index 00000000..255f6291 --- /dev/null +++ b/src/ui/disclosure.ts @@ -0,0 +1,119 @@ +/** + * Local disclosure for one surface (a modal, page or the settings tab): the + * collapsed "Advanced" dropdown and the "Debug" subsection inside it. + * + * - The Advanced dropdown is made the first time something goes in it, so + * a surface with nothing advanced shows none. It starts collapsed; its + * open state is remembered per surface on this device (local storage). + * - Debug exists only while debug mode is on (src/ui/debugMode.ts); it sits + * at the end of Advanced, after the advanced controls. + * - Where a control goes comes from the placement map (src/ui/placement.ts): + * `place(id, el)` moves a built control into its layer; `target(id, here)` + * gives the parent to build it in (null: don't build it). + * + * If the host is emptied and rebuilt (a re-render), the next call makes a + * fresh dropdown in it. + */ + +import { isDebugMode, type LocalStore } from "./debugMode"; +import { layerOf, type Layer } from "./placement"; + +/** Local-storage key: surfaces whose Advanced dropdown was left open. */ +export const DISCLOSURE_OPEN_KEY = "hexmaker-disclosure-open"; + +export function disclosureOpen(store: LocalStore, surface: string): boolean { + const v = store.loadLocalStorage(DISCLOSURE_OPEN_KEY); + return Array.isArray(v) && v.includes(surface); +} + +export function setDisclosureOpen(store: LocalStore, surface: string, open: boolean): void { + const v = store.loadLocalStorage(DISCLOSURE_OPEN_KEY); + const list = new Set(Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []); + if (open) list.add(surface); + else list.delete(surface); + store.saveLocalStorage(DISCLOSURE_OPEN_KEY, list.size ? [...list] : null); +} + +export class Disclosure { + private details: HTMLDetailsElement | null = null; + private items: HTMLElement | null = null; + private debug: HTMLElement | null = null; + + /** + * @param store local storage (the App) + * @param surface stable id of the surface, e.g. "Settings", "GenPage" + * @param host where the dropdown goes (read at creation, so a + * re-rendered surface can hand over its new container) + */ + constructor( + private store: LocalStore, + readonly surface: string, + private host: () => HTMLElement, + ) {} + + get debugMode(): boolean { + return isDebugMode(this.store); + } + + /** The Advanced dropdown's container, or Debug's inside it (null while debug mode is off). */ + section(layer: "advanced" | "debug"): HTMLElement | null { + if (layer === "debug" && !this.debugMode) return null; + if (!this.details?.isConnected) this.build(); + if (layer === "advanced") return this.items; + if (!this.debug?.isConnected) { + this.debug = this.details!.createDiv({ cls: "duckmage-disclosure-debug" }); + this.debug.createDiv({ cls: "duckmage-disclosure-debug-title", text: "Debug" }); + } + return this.debug; + } + + /** + * The parent control `id` should be built in: `here` for main and more, + * the Advanced or Debug container, or null when it isn't shown (hidden, + * or Debug while debug mode is off). + */ + target(id: string, here: HTMLElement): HTMLElement | null { + const layer: Layer = layerOf(id); + if (layer === "main" || layer === "more") return here; + if (layer === "hidden") return null; + return this.section(layer); + } + + /** + * Put a built control where the placement map says: left where it is for + * main and more, moved into Advanced or Debug, or removed when it isn't + * shown. Returns whether it is shown. + */ + place(id: string, el: HTMLElement): boolean { + const layer: Layer = layerOf(id); + if (layer === "main" || layer === "more") return true; + const to = layer === "hidden" ? null : this.section(layer); + if (!to) { + el.remove(); + return false; + } + // Advanced controls stay above Debug: they have their own container before it. + to.appendChild(el); + return true; + } + + /** Move the dropdown (if there is one) to the end of the host, e.g. below content built after it. */ + toEnd(): void { + if (this.details?.isConnected) this.host().appendChild(this.details); + } + + /** Is there an Advanced dropdown on the surface now. */ + get exists(): boolean { + return !!this.details?.isConnected; + } + + private build(): void { + const details = this.host().createEl("details", { cls: "duckmage-disclosure" }); + details.createEl("summary", { cls: "duckmage-disclosure-summary", text: "Advanced" }); + details.open = disclosureOpen(this.store, this.surface); + details.addEventListener("toggle", () => setDisclosureOpen(this.store, this.surface, details.open)); + this.details = details; + this.items = details.createDiv({ cls: "duckmage-disclosure-body" }); + this.debug = null; + } +} diff --git a/src/ui/placement.ts b/src/ui/placement.ts new file mode 100644 index 00000000..9ec8b95c --- /dev/null +++ b/src/ui/placement.ts @@ -0,0 +1,102 @@ +/** + * Where each control sits: the one declarative placement map (design rule 7, + * "built to retool", in the self-paced-discovery UX notes). + * + * Every surface (settings tab, page, modal) is layered: + * + * - `main` above the fold: the simple view that does the common job. + * - `more` below the fold: more specific options, still always shown. + * - `advanced` inside the surface's collapsed "Advanced" dropdown. + * - `debug` in the "Debug" subsection inside Advanced, shown only while + * debug mode is on (src/ui/debugMode.ts). + * - `hidden` dropped: not rendered at all. + * + * Keys are UI item ids from the owner's UI inventory worksheet + * (`.`, e.g. `Settings.hexGap`, `GenPage.clumping`). An id + * that isn't listed is `main`, so this map only names the exceptions. + * + * Moving a control between layers is a one-line change here; no view code + * changes. Views ask through Disclosure.place / Disclosure.target + * (src/ui/disclosure.ts) or, in the settings tab, layoutSettings. + */ + +export type Layer = "main" | "more" | "advanced" | "debug" | "hidden"; + +export const LAYERS: readonly Layer[] = ["main", "more", "advanced", "debug", "hidden"]; + +export const PLACEMENT: Readonly> = { + // ── Settings: folder layout is Advanced (the custom icons folder stays + // main: customisation is not "advanced", rule 5); maintenance is Debug ── + "Settings.worldFolder": "advanced", + "Settings.hexFolder": "advanced", + "Settings.townsFolder": "advanced", + "Settings.dungeonsFolder": "advanced", + "Settings.questsFolder": "advanced", + "Settings.featuresFolder": "advanced", + "Settings.factionsFolder": "advanced", + "Settings.regionsFolder": "advanced", + "Settings.tablesFolder": "advanced", + "Settings.workflowsFolder": "advanced", + "Settings.templatesFolder": "advanced", + "Settings.palettesFolder": "advanced", + "Settings.biomesFolder": "advanced", + "Settings.biomePoolsFolder": "advanced", + "Settings.worldTypesFolder": "advanced", + "Settings.generateFolders": "debug", + "Settings.generateWorldData": "debug", + + // ── Generator page: recipe extras are Advanced ── + "GenPage.symmetry": "advanced", + "GenPage.edgeStyle": "advanced", + "GenPage.guaranteedFeatures": "advanced", + "GenPage.connectedLand": "advanced", + + // ── Generator page: engine tuning is Debug ── + "GenPage.clumping": "debug", + "GenPage.edgeSmoothing": "debug", + "GenPage.removeSmallPatches": "debug", + "GenPage.keepRare": "debug", + "GenPage.edgeStrength": "debug", + "GenPage.directionalBias": "debug", + "GenPage.scatter": "debug", + "GenPage.spacing": "debug", + "GenPage.randomness": "debug", + "GenPage.mixStrength": "debug", +}; + +/** The layer of control `id` (unlisted = `main`). */ +export function layerOf(id: string, map: Readonly> = PLACEMENT): Layer { + const layer = Object.prototype.hasOwnProperty.call(map, id) ? map[id] : undefined; + return layer && LAYERS.includes(layer) ? layer : "main"; +} + +/** Is control `id` shown at all right now (hidden never; debug only in debug mode). */ +export function isShown(id: string, debugMode: boolean, map: Readonly> = PLACEMENT): boolean { + const layer = layerOf(id, map); + return layer !== "hidden" && (layer !== "debug" || debugMode); +} + +/** Every listed id on `layer`, in map order (for tests and inventories). */ +export function idsOn(layer: Layer, map: Readonly> = PLACEMENT): string[] { + return Object.keys(map).filter((id) => map[id] === layer); +} + +/** + * Group tagged items by layer, keeping their order within each: what a + * surface draws above the fold (`main` then `more`), in its Advanced + * dropdown, and in Debug. Hidden items, and Debug ones while debug mode + * is off, are left out. + */ +export function partition( + items: { id: string; item: T }[], + debugMode: boolean, + map: Readonly> = PLACEMENT, +): { main: T[]; more: T[]; advanced: T[]; debug: T[] } { + const out = { main: [] as T[], more: [] as T[], advanced: [] as T[], debug: [] as T[] }; + for (const { id, item } of items) { + const layer = layerOf(id, map); + if (layer === "hidden" || (layer === "debug" && !debugMode)) continue; + out[layer].push(item); + } + return out; +} diff --git a/src/worldgen/GeneratorPanel.ts b/src/worldgen/GeneratorPanel.ts index 68581911..7846dd80 100644 --- a/src/worldgen/GeneratorPanel.ts +++ b/src/worldgen/GeneratorPanel.ts @@ -44,9 +44,8 @@ import { SIDES, hexRangeText, type Side } from "./world"; import { blendFromNeighbours, regionBiome, generateConnected, neighbourSpec, NEIGHBOUR_SHARE, occupiedSides, placeNewRegion, regionNameAt, regionNeighbourNames, type NewRegion } from "./neighbours"; import { GeneratorLibrary } from "./GeneratorLibrary"; import { BiomePanel } from "./BiomePanel"; -import { hasFeature } from "../featureLevel"; -import { renderAdvancedHint } from "../advancedHints"; import { generatorMapKind, isGeneratorShown } from "../mapKinds"; +import { Disclosure } from "../ui/disclosure"; import { sizePresets } from "./sizePresets"; import { listSaves, writeSave, readSave, applySave, renameGenerator } from "./saves"; import { ConfirmModal } from "./ConfirmModal"; @@ -281,6 +280,15 @@ export class GeneratorPanel { const saved = file ? { ...g, file } : null; // Controls go into the current section; each section() call starts a new one. let el = main; + // Recipe extras go in the page's Advanced dropdown, engine tuning in its + // Debug subsection (debug mode only): the placement map (src/ui/placement.ts) + // says which, by GenPage. id. + const disclosure = new Disclosure(this.plugin.app, "GenPage", () => main); + const place = (id: string, control: HTMLElement) => disclosure.place(id, control); + /** A section whose controls all moved to Advanced or Debug goes. */ + const dropIfEmpty = (body: HTMLElement) => { + if (!body.childElementCount) body.parentElement?.remove(); + }; const colors = paletteColors(this.plugin, GeneratorPanel.paletteName); // One short line; the per-shape breakdown is on hover. const byShape = (shape: string) => model.terrains.filter((t) => (t.shape ?? "none") === shape).map((t) => t.name); @@ -624,13 +632,6 @@ export class GeneratorPanel { anchorSelect.value = GeneratorPanel.connect?.anchor ?? ""; sideSelect.value = GeneratorPanel.connect?.side ?? "east"; sideSelect.disabled = !anchorSelect.value; - // Neighbouring regions are an Advanced feature: a hint instead in Simple. - if (!hasFeature(this.plugin.settings, "regions")) { - connectRow.hide(); - GeneratorPanel.connect = null; - renderAdvancedHint(el, this.plugin, "regions", "generator-connect", - "Make the new map a neighbour of an existing one, its terrain carrying on across the border: neighbouring regions."); - } const connectNote = el.createEl("p", { cls: "duckmage-map-origin-desc" }); let connected: NewRegion | null = null; if (GeneratorPanel.connect) { @@ -1010,7 +1011,7 @@ export class GeneratorPanel { // Shape el = this.section(main, "Shape"); this.slider(el, "Feature size", "Size of each terrain's patches relative to the map. 1 = like the example; lower = more, smaller patches; 0 = no growth.", 0, 3, 0.25, s().featureSize, (v) => save({ featureSize: v })); - this.slider(el, "Clumping", "How strongly each hex follows its neighbours. 0 gives speckled noise.", 0, 6, 0.5, s().neighbourInfluence, (v) => save({ neighbourInfluence: v })); + place("GenPage.clumping", this.slider(el, "Clumping", "How strongly each hex follows its neighbours. 0 gives speckled noise.", 0, 6, 0.5, s().neighbourInfluence, (v) => save({ neighbourInfluence: v }))); if (model.terrains.some((t) => t.shape === "line")) { const learnedWidth = Math.max(1, Math.round(Math.max(...model.terrains.filter((t) => t.shape === "line").map((t) => t.width ?? 1)))); this.slider(el, "Line width", "Thickness of line-shaped terrain, in hexes.", 1, 3, 1, s().lineWidth > 0 ? s().lineWidth : learnedWidth, (v) => save({ lineWidth: v })); @@ -1018,34 +1019,36 @@ export class GeneratorPanel { // Clean-up after generating. Older generators only have one "smoothing" // value; the sliders start from what it meant, and any change replaces it. const cleanup = cleanupStrengths(s()); - this.slider(el, "Edge smoothing", "Trim one-hex bumps and notches along the edges of patches. Lone hexes are left alone.", 0, 1, 0.1, cleanup.edges, - (v) => save({ edgeSmoothing: v, speckSize: cleanupStrengths(s()).speckSize, smoothing: undefined })); - this.slider(el, "Remove small patches", "Fill in patches of this many hexes or fewer with the terrain around them. 0 = keep all.", 0, 6, 1, cleanup.speckSize, - (v) => save({ speckSize: v, edgeSmoothing: cleanupStrengths(s()).edges, smoothing: undefined })); - this.slider(el, "Keep rare terrain", "Terrains under this share of the example (%) are never smoothed or removed, so the odd rare hex survives.", 0, 20, 1, - Math.round(s().keepRare * 100), (v) => save({ keepRare: v / 100 })); - this.select(el, "Symmetry", "Mirror the map. Symmetric wherever the rules allow.", - SYMMETRIES.map((v) => [v, SYMMETRY_LABELS[v]]), s().symmetry, (v) => save({ symmetry: v })); - this.select(el, "Edge style", "What the map border prefers: a terrain of your choice, or the example's border.", + place("GenPage.edgeSmoothing", this.slider(el, "Edge smoothing", "Trim one-hex bumps and notches along the edges of patches. Lone hexes are left alone.", 0, 1, 0.1, cleanup.edges, + (v) => save({ edgeSmoothing: v, speckSize: cleanupStrengths(s()).speckSize, smoothing: undefined }))); + place("GenPage.removeSmallPatches", this.slider(el, "Remove small patches", "Fill in patches of this many hexes or fewer with the terrain around them. 0 = keep all.", 0, 6, 1, cleanup.speckSize, + (v) => save({ speckSize: v, edgeSmoothing: cleanupStrengths(s()).edges, smoothing: undefined }))); + place("GenPage.keepRare", this.slider(el, "Keep rare terrain", "Terrains under this share of the example (%) are never smoothed or removed, so the odd rare hex survives.", 0, 20, 1, + Math.round(s().keepRare * 100), (v) => save({ keepRare: v / 100 }))); + place("GenPage.symmetry", this.select(el, "Symmetry", "Mirror the map. Symmetric wherever the rules allow.", + SYMMETRIES.map((v) => [v, SYMMETRY_LABELS[v]]), s().symmetry, (v) => save({ symmetry: v }))); + place("GenPage.edgeStyle", this.select(el, "Edge style", "What the map border prefers: a terrain of your choice, or the example's border.", [["", "As in the example"], ...model.terrains.map((t): [string, string] => [t.name, t.name])], - s().edgeTerrain, (v) => save({ edgeTerrain: v || undefined })); - this.slider(el, "Edge strength", "How strongly the border follows the edge style. 0 = off.", 0, 1, 0.05, s().edgeStrength, (v) => save({ edgeStrength: v })); + s().edgeTerrain, (v) => save({ edgeTerrain: v || undefined }))); + place("GenPage.edgeStrength", this.slider(el, "Edge strength", "How strongly the border follows the edge style. 0 = off.", 0, 1, 0.05, s().edgeStrength, (v) => save({ edgeStrength: v }))); + dropIfEmpty(el); // Placement el = this.section(main, "Placement"); - this.slider(el, "Directional bias", "0 = terrain goes anywhere. 1 = it keeps to where it was in the example.", 0, 1, 0.05, s().directionalBias, (v) => save({ directionalBias: v })); - this.slider(el, "Scatter", "Randomness in where patches start. Too low and one terrain can take over the map.", 0, 6, 0.5, s().scatter, (v) => save({ scatter: v })); + place("GenPage.directionalBias", this.slider(el, "Directional bias", "0 = terrain goes anywhere. 1 = it keeps to where it was in the example.", 0, 1, 0.05, s().directionalBias, (v) => save({ directionalBias: v }))); + place("GenPage.scatter", this.slider(el, "Scatter", "Randomness in where patches start. Too low and one terrain can take over the map.", 0, 6, 0.5, s().scatter, (v) => save({ scatter: v }))); if (model.terrains.some((t) => t.shape === "scatter")) { - this.slider(el, "Spacing", "How far apart single-hex terrain stays, relative to the example. 0 = no spacing.", 0, 3, 0.25, s().spacing, (v) => save({ spacing: v })); + place("GenPage.spacing", this.slider(el, "Spacing", "How far apart single-hex terrain stays, relative to the example. 0 = no spacing.", 0, 3, 0.25, s().spacing, (v) => save({ spacing: v }))); } - this.slider(el, "Randomness", "Share of hexes chosen by chance, ignoring neighbours, so rare terrain turns up here and there.", 0, 1, 0.05, s().randomness, (v) => save({ randomness: v })); + place("GenPage.randomness", this.slider(el, "Randomness", "Share of hexes chosen by chance, ignoring neighbours, so rare terrain turns up here and there.", 0, 1, 0.05, s().randomness, (v) => save({ randomness: v }))); + dropIfEmpty(el); // Guarantees el = this.section(main, "Guarantees"); if (model.features?.length) { - this.toggle(el, "Guaranteed features", "Always place the example's anchored terrain lines (such as a river painted as terrain). Drawn paths have their own section below.", s().features, (v) => save({ features: v })); + place("GenPage.guaranteedFeatures", this.toggle(el, "Guaranteed features", "Always place the example's anchored terrain lines (such as a river painted as terrain). Drawn paths have their own section below.", s().features, (v) => save({ features: v }))); } - this.toggle(el, "Connected land", "Fill cut-off pockets so every passable hex connects.", s().connected, (v) => save({ connected: v })); + place("GenPage.connectedLand", this.toggle(el, "Connected land", "Fill cut-off pockets so every passable hex connects.", s().connected, (v) => save({ connected: v }))); const impassableBox = el.createDiv(); const hintBox = el.createDiv({ cls: "duckmage-wfc-hint" }); // Terrain the learned paths go around, offered to add (never added for you). @@ -1173,7 +1176,7 @@ export class GeneratorPanel { }); } - this.slider(el, "Mix strength", "How closely the overall terrain mix follows the example.", 0, 4, 0.5, s().frequencyFeedback, (v) => save({ frequencyFeedback: v })); + place("GenPage.mixStrength", this.slider(el, "Mix strength", "How closely the overall terrain mix follows the example.", 0, 4, 0.5, s().frequencyFeedback, (v) => save({ frequencyFeedback: v }))); // Paths: one row per learned route (type + what its ends connect to) if (model.paths?.length) { @@ -1400,7 +1403,8 @@ export class GeneratorPanel { refreshGroups(); } - + // The Advanced dropdown (if anything went in it) after every section. + disclosure.toEnd(); schedulePreview(); } @@ -1444,9 +1448,11 @@ export class GeneratorPanel { step: number, value: number, onChange: (v: number) => void, - ): void { - const labelEl = el.createEl("label", { text: label, cls: "duckmage-map-field-label" }); - const row = el.createDiv({ cls: "duckmage-region-row" }); + ): HTMLElement { + // One box per control, so the placement map can move it as a whole. + const box = el.createDiv({ cls: "duckmage-wfc-control" }); + const labelEl = box.createEl("label", { text: label, cls: "duckmage-map-field-label" }); + const row = box.createDiv({ cls: "duckmage-region-row" }); const input = row.createEl("input", { type: "range" }); linkLabel(labelEl, input); input.min = String(min); @@ -1454,9 +1460,10 @@ export class GeneratorPanel { input.step = String(step); input.value = String(value); const valueEl = row.createSpan({ text: String(value) }); - el.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); + box.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); input.addEventListener("input", () => valueEl.setText(input.value)); input.addEventListener("change", () => onChange(Number(input.value))); + return box; } private select( @@ -1466,23 +1473,27 @@ export class GeneratorPanel { options: [T, string][], value: T, onChange: (v: T) => void, - ): void { - const labelEl = el.createEl("label", { text: label, cls: "duckmage-map-field-label" }); - const sel = el.createDiv({ cls: "duckmage-region-row" }).createEl("select"); + ): HTMLElement { + const box = el.createDiv({ cls: "duckmage-wfc-control" }); + const labelEl = box.createEl("label", { text: label, cls: "duckmage-map-field-label" }); + const sel = box.createDiv({ cls: "duckmage-region-row" }).createEl("select"); linkLabel(labelEl, sel); for (const [v, text] of options) sel.createEl("option", { value: v, text }); sel.value = value; - el.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); + box.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); sel.addEventListener("change", () => onChange(sel.value as T)); + return box; } - private toggle(el: HTMLElement, label: string, hint: string, value: boolean, onChange: (v: boolean) => void): void { - const row = el.createEl("label", { cls: "duckmage-region-row duckmage-wfc-toggle" }); + private toggle(el: HTMLElement, label: string, hint: string, value: boolean, onChange: (v: boolean) => void): HTMLElement { + const box = el.createDiv({ cls: "duckmage-wfc-control" }); + const row = box.createEl("label", { cls: "duckmage-region-row duckmage-wfc-toggle" }); const cb = row.createEl("input", { type: "checkbox" }); cb.checked = value; row.createSpan({ text: label }); - if (hint) el.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); + if (hint) box.createEl("p", { text: hint, cls: "duckmage-map-origin-desc" }); cb.addEventListener("change", () => onChange(cb.checked)); + return box; } /** * Searchable terrain list: type to filter, click a match to add it; added diff --git a/src/worldgen/NewMapSetupModal.ts b/src/worldgen/NewMapSetupModal.ts index 9c29532d..49c6ce85 100644 --- a/src/worldgen/NewMapSetupModal.ts +++ b/src/worldgen/NewMapSetupModal.ts @@ -7,8 +7,6 @@ import { getTerrainFromFile } from "../frontmatter"; import { buildSubmapContext } from "./submapContext"; import { buildRegionContext } from "./regionContext"; import { neighbourShadow, neighbourSpec, occupiedSides, placeNewRegion, regionNameAt, type NewRegion } from "./neighbours"; -import { hasFeature } from "../featureLevel"; -import { renderAdvancedHints } from "../advancedHints"; import { hexRangeText, type Side as WorldSide } from "./world"; import { OVERLAND_ID, REGION_DETAIL_ID, seaSideFromNeighbours, type NeighbourSea } from "./procedural/planetSurface"; import type { GenerationContext, Side } from "./procedural/common"; @@ -115,7 +113,6 @@ export class NewMapSetupModal extends HexmakerModal { /** "Use for new submaps of hexes" checkboxes, one per option row. */ private remember = { palette: false, size: false, generator: false, base: false }; private stopKeepInViewport?: () => void; - private stopFeatureChange?: () => void; /** The neighbours' terrain just past the new map's edges (faded in the preview). */ private shadow: Map | undefined; /** Set once the user clicks a generator card: placement then stops re-picking one. */ @@ -201,15 +198,12 @@ export class NewMapSetupModal extends HexmakerModal { this.ledgers = used; this.kinds = kinds; this.render(); - // A hint here can turn a feature on: show what it brings straight away. - this.stopFeatureChange = this.plugin.onFeatureChange(() => this.render()); }); this.contentEl.createDiv({ cls: "duckmage-setup-loading", text: "Loading generators…" }); } onClose(): void { this.stopKeepInViewport?.(); - this.stopFeatureChange?.(); this.contentEl.empty(); } @@ -332,11 +326,10 @@ export class NewMapSetupModal extends HexmakerModal { // ── Next to (new top-level maps): join a world of neighbouring regions. // Size, palette, offset and stagger then follow the neighbour; terrain // and roads continue across the borders. - // An Advanced feature (the More options hint under Generator offers it in Simple). let applyPrefill: (() => void) | undefined; /** Set by the "More" section below: placement locks its fields. */ let lockMore: ((locked: boolean) => void) | undefined; - if (!this.origin && this.plugin.settings.maps.length > 0 && hasFeature(this.plugin.settings, "regions")) { + if (!this.origin && this.plugin.settings.maps.length > 0) { const nextRow = this.row(form, "Next to"); const anchorSel = this.labelled(nextRow, nextRow.createEl("select", { attr: { "aria-label": "Neighbouring map" } })); anchorSel.createEl("option", { value: "", text: "— none (stand-alone) —" }); @@ -413,14 +406,6 @@ export class NewMapSetupModal extends HexmakerModal { genRow.parentElement?.querySelector(":scope > .duckmage-setup-label")?.setAttr("id", genLabelId); const genList = genRow.createDiv({ cls: "duckmage-setup-generators", attr: { role: "radiogroup", "aria-labelledby": genLabelId } }); this.rememberBox(genRow, "generator", "generator and its options"); - // Simple shows Blank, the starter generators and Space ones; one hint - // offers the rest, and placing the map next to another. - renderAdvancedHints(form, this.plugin, [ - { feature: "generators", text: "Generate terrain for you: learned from maps you've painted, or from biome presets." }, - ...(!this.origin && this.plugin.settings.maps.length > 0 - ? [{ feature: "regions" as const, text: "Place this map next to an existing one so they join into one world." }] - : []), - ], "new-map-setup-more"); const optsBox = form.createDiv({ cls: "duckmage-setup-options" }); // ── Base terrain ── @@ -534,7 +519,6 @@ export class NewMapSetupModal extends HexmakerModal { const actions = contentEl.createDiv({ cls: "duckmage-setup-actions" }); const goBtn = actions.createEl("button", { cls: "mod-cta" }); const genBtn = actions.createEl("button", { text: "Open in generator", attr: { title: "Create the map blank and open the generator view on it to tune generation by hand" } }); - if (!hasFeature(this.plugin.settings, "generators")) genBtn.hide(); actions.createEl("button", { text: "Cancel" }).addEventListener("click", () => this.close()); const renderGenerators = () => { @@ -650,7 +634,7 @@ export class NewMapSetupModal extends HexmakerModal { } // Space generators: the worlds they place come from a world types table // (the World types option picks it; this edits it). - if (kind && (kind.id === STAR_SCATTER_ID || kind.id === ORBITS_ID) && hasFeature(this.plugin.settings, "generators")) { + if (kind && (kind.id === STAR_SCATTER_ID || kind.id === ORBITS_ID)) { const r = worldTypesRow ?? this.row(optsBox, "World types"); const btn = r.createEl("button", { text: "Edit world types…" }); btn.addEventListener("click", () => { diff --git a/src/worldgen/registry.ts b/src/worldgen/registry.ts index 8bda0e84..01248f7b 100644 --- a/src/worldgen/registry.ts +++ b/src/worldgen/registry.ts @@ -34,7 +34,6 @@ import { } from "./procedural/planetSurface"; import { generatorMapKind, isGeneratorShown, isSpacePalette, type MapKind } from "../mapKinds"; import { routeContextPaths } from "./procedural/contextPaths"; -import { hasFeature, type FeatureSettings } from "../featureLevel"; import { generateConnected, type NewRegion } from "./neighbours"; import { WORLD_TYPES_KEY, worldTypesOption } from "../space/worldTypesSource"; import { BUILTIN_GENERATORS, BUILTIN_PREFIX, builtinModel, builtinPathType, fitBuiltinModel } from "./builtinGenerators"; @@ -387,8 +386,7 @@ export async function listGeneratorKinds(plugin: HexmakerPlugin): Promise, * Generators to offer: those whose map type is on, space ones on a space * map (`spaceContext`), and the current/saved choice (`selectedId`). */ -/** - * Generators Simple offers without the generators feature: Blank, the ones - * a first map starts with, and Region detail, which a submap of a painted - * hex starts on (submaps are Simple). - */ -const STARTER_IDS = new Set([BLANK_ID, OVERLAND_ID, STAR_SCATTER_ID, REGION_DETAIL_ID]); - export function visibleKinds( kinds: TerrainGeneratorKind[], - settings: { mapKinds?: string[] } & FeatureSettings, + settings: { mapKinds?: string[] }, spaceContext: boolean, selectedId?: string, ): TerrainGeneratorKind[] { - return kinds.filter( - (k) => - isGeneratorShown(settings, k.mapKind, { spaceContext, selected: k.id === selectedId }) - // Generators are an Advanced feature. Simple still gets the starter - // ones (STARTER_IDS), and Space brings its own at either level. - && (STARTER_IDS.has(k.id) || k.id === selectedId || k.mapKind === "space" || hasFeature(settings, "generators")), - ); + return kinds.filter((k) => isGeneratorShown(settings, k.mapKind, { spaceContext, selected: k.id === selectedId })); } /** @@ -496,7 +481,7 @@ export function visibleKinds( */ export function newMapGeneratorChoices( kinds: TerrainGeneratorKind[], - settings: { mapKinds?: string[] } & FeatureSettings, + settings: { mapKinds?: string[] }, terrains: TerrainColor[], currentId: string | undefined, neighbour: boolean, diff --git a/styles.css b/styles.css index 119e8968..4083e05c 100644 --- a/styles.css +++ b/styles.css @@ -6551,67 +6551,6 @@ button.duckmage-wfc-library-tab.is-active { min-width: 0; } -/* Advanced-feature hint (src/advancedHints.ts): a quiet one-liner where a - hidden Advanced feature would sit, with "Turn on" and close buttons. */ -.duckmage-advanced-hint { - display: flex; - align-items: center; - gap: 0.5em; - margin: 0.5em 0; - padding: 0.35em 0.6em; - border: 1px dashed var(--background-modifier-border); - border-radius: var(--radius-s); - color: var(--text-muted); - font-size: var(--font-ui-smaller); -} - -.duckmage-advanced-hint-mark { - color: var(--interactive-accent); -} - -.duckmage-advanced-hint-text { - flex: 1; -} - -.duckmage-advanced-hint button { - font-size: var(--font-ui-smaller); - padding: 0.15em 0.6em; - height: auto; -} - -.duckmage-advanced-hint-close { - box-shadow: none; - background: transparent; - color: var(--text-faint); -} - -/* "More options" (MoreFeaturesModal): one row per hidden feature. */ -.duckmage-more-features { - display: flex; - flex-direction: column; - gap: 0.6em; - margin: 0.6em 0 1em; -} - -.duckmage-more-features-row { - display: flex; - align-items: center; - gap: 1em; -} - -.duckmage-more-features-text { - flex: 1; - color: var(--text-muted); -} - -.duckmage-more-features-text strong { - color: var(--text-normal); -} - -.duckmage-more-features-on { - color: var(--text-success); -} - /* ── Fresh-eyes fixes: hex editor (#38), path tool & navigation (#39) ───── */ /* Hex editor: the link fields sit in a "Linked notes" group, each in its own @@ -7137,11 +7076,6 @@ button.duckmage-wfc-library-tab.is-active { margin-top: 0.25em; } -/* The More options box is short: no draggable-modal minimum height. */ -.modal.duckmage-editor-modal-drag.duckmage-more-features-modal { - min-height: 0; -} - /* Map list as a tree (N4): submaps under their parent, neighbouring regions grouped; collapsible, with a search box on long lists. */ .duckmage-map-tree-search { @@ -9114,3 +9048,58 @@ textarea.duckmage-edit-region-notes-input { opacity: 0.7; text-shadow: 0 0 2px #000000, 0 0 3px #000000; } + +/* ── Local disclosure (src/ui/disclosure.ts, src/ui/placement.ts) ───────── + Each surface's collapsed "Advanced" dropdown, with the "Debug" + subsection inside it (debug mode only), and the settings tab's rows. */ +.duckmage-disclosure { + margin: 0.75em 0; + border-top: 1px solid var(--background-modifier-border); + padding-top: 0.4em; +} + +.duckmage-disclosure-summary { + cursor: pointer; + user-select: none; + color: var(--text-muted); + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + padding: 0.2em 0; +} + +.duckmage-disclosure-summary:hover { + color: var(--text-normal); +} + +.duckmage-disclosure-body { + padding-top: 0.25em; +} + +.duckmage-disclosure-debug { + margin-top: 0.6em; + padding: 0.4em 0.6em; + border: 1px dashed var(--background-modifier-border); + border-radius: var(--radius-s); +} + +.duckmage-disclosure-debug-title { + color: var(--text-faint); + font-size: var(--font-ui-smaller); + text-transform: uppercase; + letter-spacing: 0.05em; + margin-bottom: 0.25em; +} + +/* Settings tab: the Advanced row opens and closes the dropdown. */ +.duckmage-settings-advanced-row { + cursor: pointer; +} + +.duckmage-settings-advanced-row:hover .setting-item-name { + color: var(--text-accent); +} + +/* Status bar: "Debug" while debug mode is on (click to turn it off). */ +.duckmage-debug-status { + color: var(--text-warning); +} diff --git a/tests/__mocks__/obsidian.ts b/tests/__mocks__/obsidian.ts index b11b4d40..980dbae3 100644 --- a/tests/__mocks__/obsidian.ts +++ b/tests/__mocks__/obsidian.ts @@ -32,6 +32,8 @@ export class Notice { hide() { this.rec.hidden = true; } } export class Plugin { constructor(_app: App, _manifest: any) {} } +export class PluginSettingTab { app: App; containerEl: any = {}; constructor(app: App, _plugin: unknown) { this.app = app; } display(): void {} hide(): void {} } +export class Setting { constructor(_el: unknown) {} } export function setIcon(_el: HTMLElement, _icon: string): void {} export function getIcon(_icon: string): SVGSVGElement | null { return null; } diff --git a/tests/arrivalDeferred.test.ts b/tests/arrivalDeferred.test.ts index a70282fd..d557a3b1 100644 --- a/tests/arrivalDeferred.test.ts +++ b/tests/arrivalDeferred.test.ts @@ -47,7 +47,7 @@ function world(opts: { arrival?: string; seed?: number; mode?: string } = {}) { const p = { app: vault.app(), manifest: { dir: ".obsidian/plugins/hexmaker" }, - settings: { hexFolder: "world/hexes", worldFolder: "world", tablesFolder: "world/tables", maps, hexOrientation: "flat", staggerOffset: "odd", mapKinds: ["space"], featureLevel: "advanced" } as Record & { maps: MapData[] }, + settings: { hexFolder: "world/hexes", worldFolder: "world", tablesFolder: "world/tables", maps, hexOrientation: "flat", staggerOffset: "odd", mapKinds: ["space"] } as Record & { maps: MapData[] }, mapStore: undefined as unknown as MapStore, saves: 0, getMap: (n: string) => maps.find((m) => m.name === n), diff --git a/tests/arrivalRegion.test.ts b/tests/arrivalRegion.test.ts index 92cc6f60..7da9a954 100644 --- a/tests/arrivalRegion.test.ts +++ b/tests/arrivalRegion.test.ts @@ -80,6 +80,8 @@ function world(opts: { mode?: string; arrival?: string } = {}) { made.push({ name: slug, cells }); return { name: slug }; }, + // The first region writes the shipped biome notes (DJ-Q4); nothing to write here. + ensureOverworldBiomes: async () => {}, linkRegion: async (_p: string, _x: number, _y: number, child: string) => { const c = maps.find((m) => m.name === child)!; c.submapKind = "region"; diff --git a/tests/biomeGenerators.test.ts b/tests/biomeGenerators.test.ts index e81dcfa9..05e7ccb2 100644 --- a/tests/biomeGenerators.test.ts +++ b/tests/biomeGenerators.test.ts @@ -179,6 +179,8 @@ describe("biome page edits round-trip through the store", () => { const v = new MemVault(); const store = new BiomeStore(storePlugin(v) as never); await store.init(); + // The shipped notes come with the first overworld or region (DJ-Q4). + await store.seedShipped(true); const path = "world/biomes/Alpine.md"; v.files.set(path, v.files.get(path)! + "\nMy notes about the peaks.\n"); store.onModify(v.app().vault.getAbstractFileByPath(path)!); @@ -218,6 +220,8 @@ describe("biome page edits round-trip through the store", () => { const v = new MemVault(); const store = new BiomeStore(storePlugin(v) as never); await store.init(); + // The shipped notes come with the first overworld or region (DJ-Q4). + await store.seedShipped(true); expect(store.get("coast")?.shore).toBe(true); expect(v.files.get("world/biomes/Coast.md")).toContain("shore: yes"); await store.update("coast", { shore: undefined }); diff --git a/tests/biomeNotes.test.ts b/tests/biomeNotes.test.ts index c68edb31..146a687f 100644 --- a/tests/biomeNotes.test.ts +++ b/tests/biomeNotes.test.ts @@ -267,10 +267,16 @@ function plugin(vault: MemVault, settings: Record = {}) { const FOLDER = "world/biomes"; const tick = () => new Promise((r) => setTimeout(r, 0)); -async function boot(vault: MemVault, settings: Record = {}) { +/** + * Start a store. `overworld`: the vault has made an overworld or region, + * which is when the shipped biome notes are written (DJ-Q4, + * HexmakerPlugin.ensureOverworldBiomes); off = a plain start-up. + */ +async function boot(vault: MemVault, settings: Record = {}, overworld = true) { const p = plugin(vault, settings); const store = new BiomeStore(p as never); await store.init(); + if (overworld) await store.seedShipped(true); return { p, store }; } @@ -290,17 +296,16 @@ describe("BiomeStore", () => { expect([...v.files.keys()].filter((f) => f.startsWith(FOLDER))).toEqual([]); expect(store.list()).toEqual([]); expect(p.settings.biomesSeeded).toBeUndefined(); - // A fresh Simple install before its setup picks the types: none either. + // A fresh install before its setup picks the types: none at start-up. const v2 = new MemVault(); - const fresh = await boot(v2, { kindContent: null, featureLevel: "simple" }); + const fresh = await boot(v2, { kindContent: null }, false); expect([...v2.files.keys()].filter((f) => f.startsWith(FOLDER))).toEqual([]); - // ...until it asks: Regions and overworlds turned on (smoke "overworld": a recipe vault). - fresh.p.settings.advancedFeatures = ["regions"]; - await fresh.store.seedShipped(); + // ...until the first overworld or region is made (DJ-Q4). + await fresh.store.seedShipped(true); expect(v2.files.has(`${FOLDER}/Tundra.md`)).toBe(true); - // A Simple vault that never had biomes and doesn't use overworlds: none at startup. + // A world vault that never had biomes and makes no overworld: none at start-up. const v3 = new MemVault(); - await boot(v3, { kindContent: ["world"], featureLevel: "simple" }); + await boot(v3, { kindContent: ["world"] }, false); expect([...v3.files.keys()].filter((f) => f.startsWith(FOLDER))).toEqual([]); // World turned on later (an explicit pick). p.settings.mapKinds = ["space", "world"]; diff --git a/tests/builtinGenerators.test.ts b/tests/builtinGenerators.test.ts index 0b673a28..e3eb1be1 100644 --- a/tests/builtinGenerators.test.ts +++ b/tests/builtinGenerators.test.ts @@ -140,12 +140,12 @@ describe("shipped biome / preset generators", () => { for (const model of models.values()) expect(fitBuiltinModel(model, SPACE_SYSTEM_TERRAINS)).toBeUndefined(); }); - it("are world generators, hidden in Simple", () => { + it("are world generators, shown where world maps are", () => { const kind = builtinKind(plugin, "biome-taiga", "Taiga", "", models.get("biome-taiga")!); expect(kind.id).toBe("builtin:biome-taiga"); expect(kind.mapKind).toBe("world"); - expect(visibleKinds([kind], { mapKinds: ["world"], featureLevel: "simple" }, false)).toEqual([]); - expect(visibleKinds([kind], { mapKinds: ["world"], featureLevel: "advanced" }, false)).toEqual([kind]); + expect(visibleKinds([kind], { mapKinds: ["world"] }, false)).toEqual([kind]); + expect(visibleKinds([kind], { mapKinds: ["space"] }, false)).toEqual([]); }); }); diff --git a/tests/disclosure.test.ts b/tests/disclosure.test.ts new file mode 100644 index 00000000..f7b413c2 --- /dev/null +++ b/tests/disclosure.test.ts @@ -0,0 +1,225 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync, readdirSync, statSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { LAYERS, PLACEMENT, idsOn, isShown, layerOf, partition, type Layer } from "../src/ui/placement"; +import { + DEBUG_CONFIRMED_KEY, + DEBUG_MODE_KEY, + debugModeConfirmed, + isDebugMode, + markDebugModeConfirmed, + onDebugModeChange, + setDebugMode, + type LocalStore, +} from "../src/ui/debugMode"; +import { DISCLOSURE_OPEN_KEY, disclosureOpen, setDisclosureOpen } from "../src/ui/disclosure"; +import { DEFAULT_SETTINGS } from "../src/constants"; +import { HexmakerSettingTab } from "../src/HexmakerSettingTab"; + +/** Obsidian's per-vault local storage, in memory. */ +class FakeStore implements LocalStore { + data = new Map(); + loadLocalStorage(key: string): unknown { + return this.data.has(key) ? JSON.parse(JSON.stringify(this.data.get(key))) : null; + } + saveLocalStorage(key: string, value: unknown): void { + if (value === null || value === undefined) this.data.delete(key); + else this.data.set(key, value); + } +} + +describe("placement map", () => { + it("unlisted ids are main; listed ones keep their layer", () => { + expect(layerOf("Settings.hexGap")).toBe("main"); + expect(layerOf("Nowhere.atAll")).toBe("main"); + expect(layerOf("Settings.hexFolder")).toBe("advanced"); + expect(layerOf("Settings.generateWorldData")).toBe("debug"); + expect(layerOf("GenPage.clumping")).toBe("debug"); + expect(layerOf("GenPage.symmetry")).toBe("advanced"); + // Not a prototype key or a bad value. + expect(layerOf("toString")).toBe("main"); + expect(layerOf("X.y", { "X.y": "sideways" as Layer })).toBe("main"); + }); + + it("every listed layer is a real one, and ids look like .", () => { + for (const [id, layer] of Object.entries(PLACEMENT)) { + expect(LAYERS).toContain(layer); + expect(id).toMatch(/^[A-Z][A-Za-z]+\.[a-z][A-Za-z0-9]*$/); + } + }); + + it("moving a control is one entry: a custom map overrides the default", () => { + expect(layerOf("Settings.hexGap", { "Settings.hexGap": "advanced" })).toBe("advanced"); + expect(layerOf("Settings.hexFolder", {})).toBe("main"); + }); + + it("the proof placements: folders Advanced, maintenance and engine tuning Debug", () => { + expect(idsOn("advanced").filter((id) => id.startsWith("Settings."))).toContain("Settings.worldFolder"); + expect(idsOn("debug")).toEqual(expect.arrayContaining(["Settings.generateFolders", "Settings.generateWorldData", "GenPage.scatter", "GenPage.mixStrength"])); + // Customisation is not "advanced" (rule 5): the custom icons folder stays main. + expect(layerOf("Settings.iconsFolder")).toBe("main"); + }); + + it("isShown: hidden never, debug only in debug mode", () => { + const map = { "A.hid": "hidden", "A.dbg": "debug", "A.adv": "advanced" } as Record; + expect(isShown("A.hid", true, map)).toBe(false); + expect(isShown("A.dbg", false, map)).toBe(false); + expect(isShown("A.dbg", true, map)).toBe(true); + expect(isShown("A.adv", false, map)).toBe(true); + expect(isShown("A.other", false, map)).toBe(true); + }); + + it("partition keeps order within each layer and drops hidden (and debug when off)", () => { + const map = { "S.b": "advanced", "S.c": "debug", "S.d": "hidden", "S.e": "more", "S.f": "advanced" } as Record; + const items = ["a", "b", "c", "d", "e", "f"].map((x) => ({ id: `S.${x}`, item: x })); + expect(partition(items, true, map)).toEqual({ main: ["a"], more: ["e"], advanced: ["b", "f"], debug: ["c"] }); + expect(partition(items, false, map).debug).toEqual([]); + }); +}); + +describe("debug mode", () => { + it("lives in local storage only, off by default, and off removes the key", () => { + const store = new FakeStore(); + expect(isDebugMode(store)).toBe(false); + setDebugMode(store, true); + expect(isDebugMode(store)).toBe(true); + expect([...store.data.keys()]).toEqual([DEBUG_MODE_KEY]); + setDebugMode(store, false); + expect(isDebugMode(store)).toBe(false); + expect(store.data.size).toBe(0); + }); + + it("is never a data.json setting", () => { + const keys = Object.keys(DEFAULT_SETTINGS).map((k) => k.toLowerCase()); + expect(keys.filter((k) => k.includes("debug"))).toEqual([]); + const types = readFileSync(join("src", "types.ts"), "utf8"); + expect(types).not.toMatch(/debug/i); + }); + + it("tells listeners when it changes (not when it's set to what it is)", () => { + const store = new FakeStore(); + const seen: boolean[] = []; + const stop = onDebugModeChange((on) => seen.push(on)); + setDebugMode(store, true); + setDebugMode(store, true); + setDebugMode(store, false); + stop(); + setDebugMode(store, true); + expect(seen).toEqual([true, false]); + }); + + it("the one-time confirmation is remembered per device", () => { + const store = new FakeStore(); + expect(debugModeConfirmed(store)).toBe(false); + markDebugModeConfirmed(store); + expect(debugModeConfirmed(store)).toBe(true); + expect(store.data.has(DEBUG_CONFIRMED_KEY)).toBe(true); + }); + + it("no command, ribbon or menu turns it on: only the settings tab calls setDebugMode(…, true)", () => { + const hits: string[] = []; + const walk = (dir: string) => { + for (const name of readdirSync(dir)) { + const p = join(dir, name); + if (statSync(p).isDirectory()) walk(p); + else if (p.endsWith(".ts") && /setDebugMode\([^)]*,\s*(true|on)\)/.test(readFileSync(p, "utf8"))) hits.push(p.replace(/\\/g, "/")); + } + }; + walk("src"); + expect(hits.sort()).toEqual(["src/HexmakerSettingTab.ts"]); + }); +}); + +describe("Advanced dropdown open state", () => { + it("is remembered per surface", () => { + const store = new FakeStore(); + expect(disclosureOpen(store, "Settings")).toBe(false); + setDisclosureOpen(store, "Settings", true); + setDisclosureOpen(store, "GenPage", true); + expect(disclosureOpen(store, "Settings")).toBe(true); + setDisclosureOpen(store, "Settings", false); + expect(disclosureOpen(store, "Settings")).toBe(false); + expect(disclosureOpen(store, "GenPage")).toBe(true); + setDisclosureOpen(store, "GenPage", false); + expect(store.data.has(DISCLOSURE_OPEN_KEY)).toBe(false); + }); +}); + +describe("feature level is gone", () => { + const RETIRED = ["featureLevel", "advancedFeatures", "dismissedHints", "installedAt", "advancedNudgeAt", "advancedNudgeOff"]; + + it("no default, and the modules are deleted", () => { + for (const k of RETIRED) expect(Object.keys(DEFAULT_SETTINGS)).not.toContain(k); + expect(existsSync(join("src", "featureLevel.ts"))).toBe(false); + expect(existsSync(join("src", "advancedHints.ts"))).toBe(false); + }); + + it("nothing in src reads or writes the level, the switches or the hints", () => { + const pattern = new RegExp(`\\b(${[...RETIRED, "hasFeature", "isAdvanced", "withFeature", "EnableFeatureModal", "AdvancedNudgeModal", "shouldNudge"].join("|")})\\b`); + const hits: string[] = []; + const walk = (dir: string) => { + for (const name of readdirSync(dir)) { + const p = join(dir, name); + if (statSync(p).isDirectory()) walk(p); + else if (/\.(ts|md)$/.test(p)) { + readFileSync(p, "utf8").split(/\r?\n/).forEach((line, i) => { + // HexTableView's "Has Feature" filter is a local variable, not the gate. + if (pattern.test(line) && !/const hasFeature =|filterHasFeature|dataset\.hasFeature/.test(line)) hits.push(`${p}:${i + 1}`); + }); + } + } + }; + walk("src"); + expect(hits).toEqual([]); + }); +}); + +describe("settings definitions (Obsidian 1.13+)", () => { + type Item = { name?: string; type?: string; heading?: string; items?: Item[]; visible?: boolean | (() => boolean) }; + + function tabWith(store: FakeStore) { + const plugin = { + settings: { ...DEFAULT_SETTINGS, maps: [], terrainPalettes: [] }, + missingDefaultPalettes: () => [], + }; + const app = store as unknown; + return new HexmakerSettingTab(app as never, plugin as never); + } + + const names = (items: Item[]): string[] => items.flatMap((i) => (i.items ? names(i.items) : [i.name ?? ""])); + const shown = (v: Item["visible"]) => (v === undefined ? true : typeof v === "function" ? v() : v); + + it("end with the debug-mode switch, after the Advanced dropdown", () => { + const defs = tabWith(new FakeStore()).getSettingDefinitions() as Item[]; + const last = defs[defs.length - 1]; + expect(last.items?.map((i) => i.name)).toEqual(["Debug mode"]); + const all = names(defs); + expect(all[all.length - 1]).toBe("Debug mode"); + expect(all.indexOf("Advanced")).toBeGreaterThan(all.indexOf("Palette for new maps")); + expect(all).not.toContain("Feature level"); + }); + + it("put folders in Advanced (collapsed) and maintenance in Debug (debug mode only)", () => { + const store = new FakeStore(); + let defs = tabWith(store).getSettingDefinitions() as Item[]; + const advanced = defs.find((d) => d.items?.[0]?.name === "Advanced")!; + const folders = advanced.items!.find((i) => i.name === "Hex notes folder")!; + expect(folders).toBeDefined(); + // Main settings stay above the fold. + expect(defs.some((d) => d.name === "Hex cell spacing")).toBe(true); + expect(defs.some((d) => d.name === "Hex notes folder")).toBe(false); + // Collapsed until opened. + expect(shown(folders.visible)).toBe(false); + setDisclosureOpen(store, "Settings", true); + expect(shown(folders.visible)).toBe(true); + // Debug: only while debug mode is on (and Advanced is open). + defs = tabWith(store).getSettingDefinitions() as Item[]; + const debug = defs.find((d) => d.heading === "Debug")!; + expect(names(debug.items!)).toEqual(expect.arrayContaining(["Generate terrain tables & hex links", "Set up folders"])); + expect(shown(debug.visible)).toBe(false); + setDebugMode(store, true); + expect(shown(debug.visible)).toBe(true); + setDebugMode(store, false); + }); +}); diff --git a/tests/featureLevel.test.ts b/tests/featureLevel.test.ts deleted file mode 100644 index 91675108..00000000 --- a/tests/featureLevel.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, it } from "node:test"; -import expect from "expect"; -import { - ALL_ADVANCED_FEATURES, - enableFeature, - hasFeature, - isAdvanced, - NUDGE, - resolveFeatureLevel, - shouldNudge, - type FeatureSettings, -} from "../src/featureLevel"; - -describe("feature level", () => { - it("keeps a saved level", () => { - expect(resolveFeatureLevel({ featureLevel: "simple", maps: [] })).toBe("simple"); - expect(resolveFeatureLevel({ featureLevel: "advanced" })).toBe("advanced"); - }); - - it("gives an update from before feature levels Advanced, so nothing disappears", () => { - expect(resolveFeatureLevel({ maps: [{ name: "the-coast" }], setupComplete: true })).toBe("advanced"); - expect(resolveFeatureLevel({ hexOrientation: "flat" })).toBe("advanced"); - }); - - it("starts a fresh install Simple", () => { - expect(resolveFeatureLevel(null)).toBe("simple"); - expect(resolveFeatureLevel({})).toBe("simple"); - }); - - it("turns features on one at a time, and all of them means Advanced", () => { - const s: FeatureSettings = { featureLevel: "simple", advancedFeatures: [] }; - expect(hasFeature(s, "workflows")).toBe(false); - enableFeature(s, "workflows"); - expect(hasFeature(s, "workflows")).toBe(true); - expect(hasFeature(s, "generators")).toBe(false); - expect(isAdvanced(s)).toBe(false); - for (const f of ALL_ADVANCED_FEATURES) enableFeature(s, f); - expect(isAdvanced(s)).toBe(true); - }); - - it("has everything on in Advanced", () => { - for (const f of ALL_ADVANCED_FEATURES) expect(hasFeature({ featureLevel: "advanced" }, f)).toBe(true); - }); -}); - -describe("the ready-for-more check-in", () => { - const now = new Date("2026-11-01"); - const daysAgo = (n: number) => new Date(now.getTime() - n * 86_400_000).toISOString().slice(0, 10); - const simple = { featureLevel: "simple" as const, installedAt: daysAgo(1) }; - - it("waits until a couple of maps or a couple of weeks", () => { - expect(shouldNudge(simple, 1, now)).toBe(false); - expect(shouldNudge(simple, NUDGE.afterMaps, now)).toBe(true); - expect(shouldNudge({ ...simple, installedAt: daysAgo(NUDGE.afterDays) }, 1, now)).toBe(true); - }); - - it("doesn't ask again soon, ever after Don't ask again, or in Advanced", () => { - expect(shouldNudge({ ...simple, advancedNudgeAt: daysAgo(3) }, 5, now)).toBe(false); - expect(shouldNudge({ ...simple, advancedNudgeAt: daysAgo(NUDGE.againDays + 1) }, 5, now)).toBe(true); - expect(shouldNudge({ ...simple, advancedNudgeOff: true }, 5, now)).toBe(false); - expect(shouldNudge({ featureLevel: "advanced" }, 5, now)).toBe(false); - }); -}); diff --git a/tests/integration/pathLossReload.integration.ts b/tests/integration/pathLossReload.integration.ts index 9fc8c158..65100663 100644 --- a/tests/integration/pathLossReload.integration.ts +++ b/tests/integration/pathLossReload.integration.ts @@ -52,8 +52,6 @@ function initialData() { return { hexFolder: "world/hexes", hexOrientation: "flat", - featureLevel: "advanced", - installedAt: "2026-01-01", expandedByDefault: false, defaultPalette: "Default", maps: [ @@ -66,7 +64,7 @@ function initialData() { interface Booted { v: MemVault; plugin: { - settings: { maps: MapData[]; dismissedHints?: string[] }; + settings: { maps: MapData[]; hiddenIcons?: string[] }; getMap(name: string): MapData | undefined; loadSettings(): Promise; saveSettings(): Promise; @@ -137,8 +135,8 @@ describe("#47: a data.json reload mid-save-burst keeps every map's paths (real p plugin.loadSettings = async () => { loads++; await load(); }; const burst: Promise[] = [plugin.saveSettings(), plugin.saveSettings()]; // Another device (or a hand edit) changes data.json: not one of our own writes. - const disk = JSON.parse(v.files.get(DATA)!) as { dismissedHints?: string[] }; - disk.dismissedHints = [...(disk.dismissedHints ?? []), "from-elsewhere"]; + const disk = JSON.parse(v.files.get(DATA)!) as { hiddenIcons?: string[] }; + disk.hiddenIcons = [...(disk.hiddenIcons ?? []), "from-elsewhere"]; v.files.set(DATA, JSON.stringify(disk, null, 2)); burst.push(plugin.onExternalSettingsChange()); // The burst goes on while the reload is in flight. @@ -193,8 +191,8 @@ describe("#47: a data.json reload mid-save-burst keeps every map's paths (real p const b = await boot(); const { v, plugin } = b; plugin.getMap("coast")!.world = { id: "w3", cx: 0, cy: 0 }; - const disk = JSON.parse(v.files.get(DATA)!) as { dismissedHints?: string[] }; - disk.dismissedHints = ["x"]; + const disk = JSON.parse(v.files.get(DATA)!) as { hiddenIcons?: string[] }; + disk.hiddenIcons = ["x"]; v.files.set(DATA, JSON.stringify(disk, null, 2)); await Promise.all([plugin.saveSettings(), plugin.onExternalSettingsChange(), plugin.saveSettings()]); await settle(b); @@ -236,7 +234,7 @@ describe("#47: a data.json reload mid-save-burst keeps every map's paths (real p expect(dataWrites).toBe(0); expect(v.files.get(DATA)).toBe(text); // A real change is still written. - again.settings.dismissedHints = ["changed"]; + again.settings.hiddenIcons = ["changed"]; await again.saveSettings(); expect(dataWrites).toBe(1); }); diff --git a/tests/mapKinds.test.ts b/tests/mapKinds.test.ts index 84f36afb..17fe679e 100644 --- a/tests/mapKinds.test.ts +++ b/tests/mapKinds.test.ts @@ -161,19 +161,15 @@ describe("generator registry visibility", () => { expect(shown).toContain("wfc:world/generators/planet-ocean.md"); }); - it("Simple shows the starter generators and Space ones, not learned or preset ones", async () => { + it("every generator of the map types that are on is offered (no feature level)", async () => { const plugin = pluginWith(learned, ["world", "space"]); - (plugin.settings as { featureLevel?: string }).featureLevel = "simple"; const all = await listGeneratorKinds(plugin); const world = ids(visibleKinds(all, plugin.settings, false)); for (const id of [BLANK_ID, OVERLAND_ID, REGION_DETAIL_ID]) expect(world).toContain(id); - expect(world).not.toContain("wfc:world/generators/my-coast.md"); + expect(world).toContain("wfc:world/generators/my-coast.md"); const space = ids(visibleKinds(all, plugin.settings, true)); expect(space).toContain(STAR_SCATTER_ID); expect(space).toContain("wfc:world/generators/planet-ocean.md"); - // Turning on just the generators feature brings the rest back. - (plugin.settings as { advancedFeatures?: string[] }).advancedFeatures = ["generators"]; - expect(ids(visibleKinds(all, plugin.settings, false))).toContain("wfc:world/generators/my-coast.md"); }); it("keeps a saved choice visible", async () => { diff --git a/tests/noteTemplates.test.ts b/tests/noteTemplates.test.ts index 7c8559f6..37ffb574 100644 --- a/tests/noteTemplates.test.ts +++ b/tests/noteTemplates.test.ts @@ -58,7 +58,7 @@ describe("templates folder (PA3)", () => { // …and say which hex they're in (a Location line, R3). expect(editor).toContain("this.plugin.newLinkedNoteContent(section, name, path)"); const picker = readFileSync("src/hex-table/LinkPickerModal.ts", "utf8"); - expect(picker).toContain("this.plugin.newLinkedNoteContent(this.section, name, this.hexPath)"); + expect(picker).toContain("this.plugin.newLinkedNoteContent(this.linkSection, name, this.hexPath)"); }); it("the Templates folder setting is in both settings paths", () => { diff --git a/tests/overworldTools.test.ts b/tests/overworldTools.test.ts index cf55fde6..d1aed281 100644 --- a/tests/overworldTools.test.ts +++ b/tests/overworldTools.test.ts @@ -101,6 +101,8 @@ function world(mode?: string) { made.push({ name: slug, cells }); return { name: slug }; }, + // The first region writes the shipped biome notes (DJ-Q4); nothing to write here. + ensureOverworldBiomes: async () => {}, linkRegion: async () => true, }; /** A region already made on hex (x, y), painted with `terrain`. */ diff --git a/tests/regionTables.test.ts b/tests/regionTables.test.ts index 438194e3..c712e0ff 100644 --- a/tests/regionTables.test.ts +++ b/tests/regionTables.test.ts @@ -123,9 +123,10 @@ describe("Run workflow from a hex (PA2)", () => { expect(sectionText(out, "landmark")).toBe(""); }); - it("the hex editor offers it only with workflows on, and passes this hex as the target", () => { + it("the hex editor always offers it (no feature switch), and passes this hex as the target", () => { const src = readFileSync("src/hex-map/HexEditorModal.ts", "utf8"); - expect(src).toMatch(/hasFeature\(this\.plugin\.settings, "workflows"\)[\s\S]{0,200}Run workflow/); + expect(src).toContain('text: "Run workflow"'); + expect(src).not.toMatch(/hasFeature|withFeature/); expect(src).toContain("new WorkflowWizardModal(this.app, this.plugin, file, this.rollTarget("); const wizard = readFileSync("src/random-tables/WorkflowWizardModal.ts", "utf8"); expect(wizard).toContain("renderAddToHex(resultBtns, this.hexTarget"); diff --git a/tests/smokeSuite.test.ts b/tests/smokeSuite.test.ts index d43cf4d7..e4613d70 100644 --- a/tests/smokeSuite.test.ts +++ b/tests/smokeSuite.test.ts @@ -23,7 +23,7 @@ describe("smoke suite: comparison helpers", () => { it("a restart may only write the one-time settings", () => { expect(oneTimeOnly({ a: 1 }, { a: 1, tableRangesPrompt: "done" })).toBe(true); - expect(oneTimeOnly({ a: 1 }, { a: 1, advancedNudgeAt: "2026-10-11", tableRangesPrompt: "done" })).toBe(true); + expect(oneTimeOnly({ a: 1 }, { a: 1, noteFormatUpgrades: ["NF1"], tableRangesPrompt: "done" })).toBe(true); // The churn the suite found: maps' path lists written back on a later start. expect(oneTimeOnly({ maps: [{ name: "a" }] }, { maps: [{ name: "a", pathChains: [] }], tableRangesPrompt: "done" })).toBe(false); expect(oneTimeOnly({ a: 1 }, { a: 1 })).toBe(false); @@ -101,7 +101,6 @@ describe("smoke suite findings stay fixed", () => { it("C5: startup saves wait for the map notes to load", () => { const src = read("src", "HexmakerPlugin.ts"); expect(src).toMatch(/void storesReady\.then\(\(\) => maybePromptTableRanges\(this\)\);/); - expect(src).toMatch(/void storesReady\.then\(\(\) => this\.saveSettings\(\)\);/); }); }); diff --git a/tests/spaceSetup.test.ts b/tests/spaceSetup.test.ts index 1569c3aa..171a03a2 100644 --- a/tests/spaceSetup.test.ts +++ b/tests/spaceSetup.test.ts @@ -82,13 +82,12 @@ describe("what a setup installs follows the map types picked (SP3)", () => { expect(plan.remove).toEqual([]); }); - it("biome notes: never for a type that's off; else when asked, for overworlds, or to top up", () => { - expect(biomeSeedingOn({ mapKinds: ["space"], featureLevel: "advanced" }, "world", true)).toBe(false); - expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "simple" }, "world")).toBe(false); - expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "simple" }, "world", true)).toBe(true); - expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "advanced" }, "world")).toBe(true); - expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "simple", advancedFeatures: ["regions"] }, "world")).toBe(true); - expect(biomeSeedingOn({ mapKinds: ["world"], featureLevel: "simple", biomesSeeded: ["tundra"] }, "world")).toBe(true); + it("biome notes: never for a type that's off; else when asked (first overworld or region, DJ-Q4) or to top up", () => { + expect(biomeSeedingOn({ mapKinds: ["space"] }, "world", true)).toBe(false); + // Not on start-up by themselves: a world vault gets none until it asks. + expect(biomeSeedingOn({ mapKinds: ["world"] }, "world")).toBe(false); + expect(biomeSeedingOn({ mapKinds: ["world"] }, "world", true)).toBe(true); + expect(biomeSeedingOn({ mapKinds: ["world"], biomesSeeded: ["tundra"] }, "world")).toBe(true); }); it("a vault set up without a pick (recipe, Don't show again, custom or deleted palettes) is recorded, nothing installed", () => { @@ -111,7 +110,7 @@ describe("what a setup installs follows the map types picked (SP3)", () => { expect(resolveKindContent(null, ["world"])).toBeNull(); expect(resolveKindContent({}, ["world"])).toBeNull(); // A fresh install's first save keeps it undecided across a restart. - expect(resolveKindContent({ featureLevel: "simple", kindContent: null }, ["world"])).toBeNull(); + expect(resolveKindContent({ setupComplete: false, kindContent: null }, ["world"])).toBeNull(); expect(resolveKindContent({ maps: [] }, ["world", "space"])).toEqual(["world", "space"]); expect(resolveKindContent({ kindContent: ["space"] }, ["world"])).toEqual(["space"]); }); diff --git a/tests/tableOnce.test.ts b/tests/tableOnce.test.ts index c2a31296..91e3ec2b 100644 --- a/tests/tableOnce.test.ts +++ b/tests/tableOnce.test.ts @@ -73,7 +73,7 @@ function world() { const p = { app: vault.app(), manifest: { dir: ".obsidian/plugins/hexmaker" }, - settings: { hexFolder: "world/hexes", worldFolder: "world", tablesFolder: "world/tables", maps, hexOrientation: "flat", staggerOffset: "odd", mapKinds: ["space"], featureLevel: "advanced" } as Record & { maps: MapData[] }, + settings: { hexFolder: "world/hexes", worldFolder: "world", tablesFolder: "world/tables", maps, hexOrientation: "flat", staggerOffset: "odd", mapKinds: ["space"] } as Record & { maps: MapData[] }, mapStore: undefined as unknown as MapStore, events: undefined as unknown as EventsService, saves: 0, diff --git a/tests/walkNewRegion.test.ts b/tests/walkNewRegion.test.ts index 7a28a941..c380ee87 100644 --- a/tests/walkNewRegion.test.ts +++ b/tests/walkNewRegion.test.ts @@ -144,6 +144,8 @@ describe("walkIntoHex: making the next region", () => { made.push({ name: slug, cols, rows, cells }); return { name: slug }; }, + // The first region writes the shipped biome notes (DJ-Q4); nothing to write here. + ensureOverworldBiomes: async () => {}, linkRegion: async () => true, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any From ae5b5124790463a39181b22c2d3536b8e1a1645b Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 16:35:32 -0400 Subject: [PATCH 314/558] fix(placement): setup tools in Advanced, storage plumbing folders in Debug "Generate folders" and "Generate terrain tables & hex links" are in the README's manual setup steps, so they belong in Advanced, not Debug. The Biomes / Biome pools / World types folder settings follow the owner's worksheet tags (overkill = Debug). CLAUDE.md: the smoke matrix is 9 setups now that the Simple mid-ramp setup is gone. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 520 +++++++++++++++++++-------------------- src/ui/placement.ts | 10 +- tests/disclosure.test.ts | 14 +- 3 files changed, 274 insertions(+), 270 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e8de8526..4d0c1b3f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,260 +1,260 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Commands - -```bash -# Development (watch mode with inline sourcemaps) — use with Hot Reload (see below) -npm run dev - -# Production build (type-checks then bundles) -npm run build - -# Run tests (vitest) -npm test - -# Bump version (updates manifest.json and versions.json, stages both) -npm run version -``` - -Slash commands (invoke inside Claude Code): -- `/dev` — starts esbuild in watch mode (long-running; pairs with Hot Reload) -- `/rebuild` — one-off production build + test run; reports errors if either fails - -**Always run `/rebuild` after making code changes.** The TypeScript type-check and test suite are the only automated verification — catch errors before the user does. - -## Dev loop - -Each coding session: -1. Run `npm run dev` in a terminal (or `/dev` from Claude Code) — esbuild watches for changes and rebuilds `main.js` on every save -2. After a rebuild, reload the plugin in Obsidian: - ```bash - powershell.exe -Command "obsidian eval code=\"(async()=>{await app.plugins.disablePlugin('hexmaker'); await app.plugins.enablePlugin('hexmaker'); return 'ok'})()\"" - ``` - The plugin **id is `hexmaker`** (the folder is `duckmage-plugin`). On this machine's Obsidian installer the CLI's `plugin:reload` / `plugin:disable` / `plugin:enable` and `dev:*` commands silently do nothing (exit 255, "installer out of date"); `obsidian eval` works. To check what's loaded: `obsidian eval code="Object.keys(app.commands.commands).filter(c=>c.startsWith('hexmaker:'))"`. Screenshot: `require('@electron/remote').getCurrentWebContents().capturePage()` inside `eval`. `app.plugins.plugins.hexmaker.manifest.version` is cached from startup — don't use it to tell builds apart. - **Before copying a build into this folder**, check which branch the current vault build came from — other sessions deploy from their own branches, and a deploy reverts theirs. -3. Use `/rebuild` for a final production build before committing (runs the TypeScript type-check and tests too) - -## Before merging or deploying: `npm run premerge` - -**Before merging into `feat/region-notes` (or master) or deploying a build into the live vault, run `npm run premerge`** (from WSL, like every npm script here) and only go ahead when it ends with `PREMERGE PASSED`. It runs build → lint → unit tests → integration tests → the **smoke vault matrix**, stopping loudly at the first failure (owner decision WM5: the matrix runs locally, not in CI; CI keeps the Obsidian-free tests). - -- The matrix (`dev/smoke/run.mjs`, plan [[plan-work-modes]] §3) builds 10 vault setups (fresh install, a synthetic 1.5.5 vault, a copy of the owner's real data `C:/Users/markr/work/tmp/migtest/seedF` + a copy of the live `data.json`, space only, overworld + regions, neighbours world, a custom palette with no default names, everything deleted, 80 maps, Simple mid-ramp), each in its own sandboxed Obsidian (fresh-eyes `sandbox.mjs`, up to 4 at once), and checks: no plugin console errors; settings saved; every map opens and renders; untouched files unchanged on disk (migrations verified separately: map notes, backups, hex data vs the old frontmatter, paths resolve, palette upgrades keep every terrain); a restart rewrites nothing; paint → undo round trip; registered commands; Play refuses a path edit. ~5 minutes, mostly the real-data migration. -- Run parts of it: `npm run smoke -- --only fresh,v155 --jobs 2` (`--list` for the setup ids, `--keep` to keep run folders, `--build ` to test another build). A failed setup keeps its run folder (path in `dev/smoke/last-run.json`); a full pass writes `dev/smoke/last-pass.json` (commit, build hash, per-check results). -- It only stops the sandboxes it started and checks every other Obsidian process is still there (`otherObsidianBefore == otherObsidianAfter`). Never point it at the main vault. -- A new feature with a user-visible write path (paint, paths, a new note type, a migration) should get a smoke check in `dev/smoke/lib/page.mjs` / `setups.mjs` as well as unit tests. - -## Architecture - -The plugin source is split across `main.ts` (entry point re-export) and modules under `src/`. esbuild bundles everything into `main.js`, which Obsidian loads directly. - -See `ARCHITECTURE.md` for a full overview of the system. - -### Source layout - -``` -main.ts ← thin re-export: export { default } from "./src/DuckmagePlugin" -src/ - DuckmagePlugin.ts ← Plugin class (entry point, default export) - HexMapView.ts ← ItemView — hex grid, all drawing tools, inline modals - HexEditorModal.ts ← Modal — right-click per-hex editor (terrain, links, notes, icon override) - HexTableView.ts ← ItemView — spreadsheet view of all hex notes with filters/sort - TerrainPickerModal.ts ← Modal — full terrain palette picker for the terrain paint tool - TerrainEntryEditorModal.ts ← Modal — edit a single terrain palette entry (name, color, icon) - IconPickerModal.ts ← Modal — icon picker for the icon paint tool - RegionModal.ts ← Modal — switch active region, create/rename/delete regions - FileLinkSuggestModal.ts ← SuggestModal — file picker scoped to worldFolder - RandomTableView.ts ← ItemView — random table + workflow browser (tabbed: Tables / Workflows) - RandomTableModal.ts ← Modal — inline roll modal used from HexEditorModal - RandomTableEditorModal.ts ← Modal — edit entries of a random table file - WorkflowEditorModal.ts ← Modal — edit workflow definition (steps, template, results folder) - WorkflowWizardModal.ts ← Modal — execute a workflow (roll steps, fill template, save as note) - randomTable.ts ← Pure logic: parse, roll, weight, die-range helpers - workflow.ts ← Pure logic: parse/serialize workflows, generate templates, placeholder helpers - DuckmageSettingTab.ts ← PluginSettingTab — settings UI - types.ts ← Interfaces & type constants (TerrainColor, DuckmagePluginSettings, LINK_SECTIONS, TEXT_SECTIONS) - constants.ts ← Runtime constants (VIEW_TYPE_*, DEFAULT_TERRAIN_PALETTE, DEFAULT_SETTINGS) - defaultHexTemplate.md ← Built-in hex note template (imported as text via esbuild loader) - frontmatter.ts ← YAML frontmatter helpers (terrain + icon override read/write) - sections.ts ← Markdown section helpers (addLinkToSection, getLinksInSection, getAllSectionData, …) - utils.ts ← Shared utilities (normalizeFolder, getIconUrl, makeTableTemplate) - md.d.ts ← TypeScript declaration for "*.md" text imports -``` - -The `.md` loader is configured in `esbuild.config.mjs` (`loader: { '.md': 'text' }`), allowing `defaultHexTemplate.md` to be imported as a plain string. - -### Plugin purpose - -Renders an interactive hex-grid map for tabletop RPG world-building inside Obsidian. Each hex cell corresponds to a Markdown note on disk. The map supports terrain painting, icon painting, road/river chain drawing, link-to-hex tools (random tables, factions), panning, and zooming. A spreadsheet view summarises all hex notes with filtering. A random tables view lets users browse, roll, and edit weighted random tables, and execute multi-step workflows that chain table rolls into a filled template note. - -### Key classes - -- **`DuckmagePlugin`** (`src/DuckmagePlugin.ts`) — Main plugin entry point. Registers views (`HexMapView`, `HexTableView`, `RandomTableView`), ribbon icons, commands, and the settings tab. Key public API: - - `hexPath(x, y)` — vault-relative path for a hex note - - `createHexNote(x, y)` — creates hex note from template - - `loadAvailableIcons()` — merges plugin `icons/` with user custom icons folder into `availableIcons: string[]` - - `refreshHexMap()` — re-renders all open `HexMapView` instances - - `ensureTerrainTables()` — creates missing terrain table files under `tablesFolder/terrain/` - - `ensureAllRollerLinks()` — adds roller-link preamble to all table files - - `backfillTerrainLinks()` — links each hex note's terrain table into its Encounters Table section - - `buildRollerLink(path)` — generates the `[Roll]()` URI for a table file - -- **`HexMapView`** (`src/HexMapView.ts`, extends `ItemView`) — Renders the hex grid and handles all user interaction. - - **DOM structure**: `contentEl` (`.duckmage-hex-map-container`) → `.duckmage-hex-map-clip` (panning viewport, `overflow: hidden`) + `.duckmage-hex-map-controls` (overlay for buttons, `pointer-events: none`). This keeps toolbar/expand buttons unclipped by the viewport transform. - - **`renderGrid(terrainOverrides?, iconOverrides?)`** — full DOM re-render. Optional override Maps allow passing values not yet in the metadata cache. - - **Drawing tools**: `drawingMode` union `"road" | "river" | "terrain" | "icon" | "tableLink" | "factionLink" | null`. Toolbar buttons toggle mode; each mode has a `handle*Button()` opener, `exit*Mode()` closer, and `onHex*Click()` handler. - - **Write queues**: `scheduleTerrainWrite` / `scheduleIconWrite` coalesce rapid repaints — only the latest value per hex is written, preventing stale overwrites. - - **Link tools** (`tableLink`, `factionLink`): pick a file via folder-tree modal, then click hexes to add a wiki-link to the `Encounters Table` or `Factions` section. Visual feedback: badge span + CSS ripple blip animation (`duckmage-hex-blip`). - - Left-click: opens/creates hex note (normal), paints terrain/icon, extends road/river chain, or adds a link. - - Right-click: opens `HexEditorModal` (normal), deletes road/river node, or exits current tool mode. - - Expand buttons (+) grow the grid in four cardinal directions, adjusting `gridOffset` and `gridSize` in settings. - - **`centerOnHex(x, y)`** (public) — pans the viewport to centre on a given hex coordinate. - - **`activeRegionName`** (public) — the currently displayed region name. - -- **`HexEditorModal`** (`src/HexEditorModal.ts`, extends `Modal`) — The right-click per-hex editor: - - Terrain picker (2-row scrollable grid) with icon override and "Clear terrain". - - Dropdown link sections for **Towns, Dungeons, Features, Quests, Factions, Encounters Table** — each backed by its own configured folder, rendered via `renderDropdownSection`. Uses `LinkPickerModal` internally (file list + create-new). - - Free-text note sections: Description, Landmark, Hidden, Secret, Weather, Hooks & Rumors. - - Fetches all section data in a single read before touching the DOM (`getAllSectionData`). - -- **`HexTableView`** (`src/HexTableView.ts`, extends `ItemView`) — Spreadsheet of all hex notes: - - Columns: Hex (coords + jump button), Terrain, Description, Landmark, Towns, Dungeons, Features, Quests, Factions, Enc. Table, Hidden, Secret, Weather, Hooks & Rumors. - - Enc. Table cell shows the basename of the linked table file; clicking opens `RandomTableView` at that file. - - Toolbar filters: X/Y range inputs, terrain multi-select (left-click include / right-click exclude), Has Town/Dungeon/Feature/Quest/Faction checkboxes, region selector, X→Y / Y→X sort priority, Asc/Desc direction. - - Live updates on vault `modify` events (300 ms debounce per file). - - Jump button (◎) calls `HexMapView.centerOnHex(x, y)` on the open map view. - -- **`RandomTableView`** (`src/RandomTableView.ts`, extends `ItemView`) — Tabbed browser with two modes: - - **Tables mode**: folder tree + search + new-table creator. Detail pane shows entries with die-range and % odds, die-size selector, Roll button, copy result, roll history. Edit opens `RandomTableEditorModal`. Bottom of detail pane shows "Workflows using this table" links (each opens that workflow in Workflows mode) and a "+ New workflow with this table" link. - - **Workflows mode**: folder tree of workflow files. Detail pane shows each step as a clickable link (opens that table in Tables mode) with roll count. Edit opens `WorkflowEditorModal`. "Roll workflow" button opens `WorkflowWizardModal`. - - **`openTable(filePath)`** (public) — switches to Tables mode, expands ancestor folders so the target is visible, and loads the table detail; called from `HexTableView` (Enc. Table cell), `HexEditorModal`, workflow step links, and the protocol handler. - -- **`RandomTableModal`** (`src/RandomTableModal.ts`, extends `Modal`) — Lightweight inline roll modal opened from `HexEditorModal` (🎲 button per link section or 📖 for terrain description). Skips the picker if `initialFilePath` is supplied. - -- **`RandomTableEditorModal`** (`src/RandomTableEditorModal.ts`, extends `Modal`) — Edit table entries (result text + weight), linked folder, description, filter flags. Auto-saves on close. Accepts optional `initialContent` to avoid a redundant vault read when the caller already has the file content. - -- **`WorkflowEditorModal`** (`src/WorkflowEditorModal.ts`, extends `Modal`) — Edit a workflow definition: - - Rename workflow, set results folder, manage steps (table picker + roll count + label) with drag-to-reorder. - - Template textarea with live placeholder validation — shows missing `$placeholder` names. - - Template auto-syncs: new step appends `## label\n$label` block; label change updates the heading AND all `$var`/`$var_N` placeholder references; roll-count change adds or removes `_N` suffixed placeholders (reducing to 1 collapses back to bare `$var`). - - Auto-saves workflow file and template file on close. Modal is draggable by its title bar. - -- **`WorkflowWizardModal`** (`src/WorkflowWizardModal.ts`, extends `Modal`) — Execute a workflow: - - Shows each step with a manual-pick dropdown and a Roll button. Fixed-width controls to prevent layout shift on roll. - - Result textarea shows the template filled with rolled values. - - Save section writes the filled result as a new vault note in the configured results folder. - -- **`RegionModal`** (`src/RegionModal.ts`, extends `Modal`) — Manage hex map regions: - - Switch the active region displayed on the hex map. - - Create, rename, and delete regions. Regions map to subfolders under `hexFolder`. - -- **`TerrainEntryEditorModal`** (`src/TerrainEntryEditorModal.ts`, extends `Modal`) — Edit a single terrain palette entry: name, color, icon (with preview), and icon color tint. Changes are staged in pending fields and only written to the palette on Save. - -- **`TerrainPickerModal`** (`src/TerrainPickerModal.ts`) — Full terrain palette picker (no row cap). Includes "Clear" to erase terrain. - -- **`IconPickerModal`** (`src/IconPickerModal.ts`) — Full icon picker with image previews. Includes "Remove" option. - -- **`FileLinkSuggestModal`** (`src/FileLinkSuggestModal.ts`) — Reusable fuzzy-search file picker scoped to a configured folder. - -- **`DuckmageSettingTab`** (`src/DuckmageSettingTab.ts`) — Settings UI: - - "Generate folders" button — fills blank folder settings with defaults under `worldFolder` and creates the folders. - - Folder paths: world, hexes, towns, dungeons, quests, features, factions, tables, workflows. - - "Generate terrain tables & hex links" button — runs `ensureTerrainTables`, `ensureAllRollerLinks`, `backfillTerrainLinks`. - - Hex orientation, grid dimensions, hex gap, custom icons folder, road/river colors, terrain palette editor (drag-to-reorder, click entry to open `TerrainEntryEditorModal`). - -### Data model - -- **Hex notes**: `{hexFolder}/{region}/{x}_{y}.md`. Created via `createHexNote(x, y, region)` using the configured template or `defaultHexTemplate.md`. -- **Template placeholders**: `{{x}}`, `{{y}}`, `{{title}}`. Template must include `### Towns`, `### Dungeons`, `### Features`, `### Quests`, `### Factions`, `### Encounters Table` headings. -- **Terrain palettes**: one markdown note per palette in `palettesFolder` (default `{worldFolder}/palettes`; basename = palette name; a `| Terrain | Color | Icon | Icon color | Category |` table). `src/palettes/PaletteStore.ts` syncs both ways: `saveSettings()` → `sync()` writes/renames/trashes notes; vault events re-parse hand edits into `settings.terrainPalettes` (kept as the sync-readable working copy and data.json cache). Edit palettes in memory + `saveSettings()` as before — never write palette notes directly. Built-in presets (Limited, Expanded, Space - Sector, Space - System) live in `src/palettes/presets.ts`; `createNewMap` installs an uninstalled preset on first use. -- **Icon packs**: bundled `bw-*` (Terrain), `place-*` (Places, owned by the World map type, grouped by kind; rebuilt with credits by `dev/build-place-icons.mjs` — add picks there, never by hand) and `space-*` (Space, third-party — credits in `icons/CREDITS.md`, rebuilt by `dev/build-space-icons.mjs`), plus the user's icons folder (Custom). Every icon grid gets search + pack tabs via `HexmakerModal.addIconFilter(grid, …)` — new icon grids must set `data-icon` on tiles and call it. -- **Terrain**: YAML frontmatter `terrain: `. Read via `getTerrainFromFile` (metadata cache); written via `setTerrainInFile` (raw text patch). Both in `frontmatter.ts`. -- **Icon override**: frontmatter `icon: `. Read via `getIconOverrideFromFile`; written via `setIconOverrideInFile`. -- **Terrain icons**: plugin `icons/` folder + user custom icons folder → `plugin.availableIcons`. URLs via `getIconUrl(plugin, filename)`. Vault-sourced filenames tracked in `plugin.vaultIconsSet`. -- **Roads & rivers**: `settings.roadChains` / `settings.riverChains` — arrays of `string[]` chains, each element `"x_y"`. Drawn as SVG polylines over the grid. -- **Link sections** (`LINK_SECTIONS`): `"Towns" | "Dungeons" | "Features" | "Quests" | "Factions" | "Encounters Table"`. Wiki-links inserted under the matching `###` heading via `addLinkToSection`. Read back via `getLinksInSection`. -- **Text sections** (`TEXT_SECTIONS`): Description, Landmark, Hidden, Secret. Free text stored under `###` headings. Weather and Hooks & Rumors are also text sections but not in the `TEXT_SECTIONS` constant. -- **Random tables**: Markdown files with YAML `dice: N` frontmatter and a `| Result | Weight |` table. Parsed by `randomTable.ts`. Stored under `tablesFolder` (default `world/tables`). Terrain tables live at `{tablesFolder}/terrain/{name} - {description|encounters}.md`. -- **Workflows**: Markdown files with YAML frontmatter (`results-folder`, `template-file`) and a `| Table | Rolls | Label |` steps table. Stored under `workflowsFolder`. Templates stored at `{workflowsFolder}/templates/{name}.md`. Parsed/serialized by `workflow.ts`. -- **Settings** (`data.json`): `worldFolder`, `hexFolder`, `townsFolder`, `dungeonsFolder`, `questsFolder`, `featuresFolder`, `factionsFolder`, `tablesFolder`, `workflowsFolder`, `iconsFolder`, `templatePath`, `hexGap`, `hexOrientation`, `terrainPalette`, `gridSize`, `gridOffset`, `zoomLevel`, `roadChains`, `riverChains`, `roadColor`, `riverColor`, `defaultTableDice`, `regions`. - -### Hex orientations - -- **Pointy-top**: points north/south, flat sides east/west. Odd rows offset right. Adjacency via odd-r offset. -- **Flat-top** (default): flat sides north/south, points east/west. Odd columns offset down. Adjacency via odd-q offset. -- `hexNeighbors(x, y)` in `HexMapView` branches on `settings.hexOrientation`. - -### Key conventions - -- Folder paths normalised (no leading/trailing slashes) via `normalizeFolder()`. -- Links use vault-relative paths via `metadataCache.fileToLinktext(file, sourcePath)`. -- `obsidian` is an esbuild external — never bundled; provided by Obsidian at runtime. -- CSS classes use the `duckmage-` prefix (styles in `styles.css`). -- View/modal/tab files use `import type DuckmagePlugin` to avoid circular runtime dependencies. -- Paint tool methods (`onHexPaintClick`, `onHexIconClick`) are synchronous — DOM patched immediately, file writes queued via coalescing queue. -- Link-tool click handlers (`onHexTableLinkClick`, `onHexFactionLinkClick`) are async — no coalescing needed (one-shot writes). -- `onChanged` callback from `HexEditorModal` defers `renderGrid()` 300 ms when no terrain/icon overrides are passed (link-only changes) to avoid a metadata-cache race after `vault.modify`. -- Modals that preload file content accept an optional `preloaded` / `initialContent` parameter — callers that already hold the file content pass it in to avoid a redundant vault read. -- **Map data lives in map notes, not hex notes.** Terrain, icon, GM icons, region, submap and locked are stored in `{hexFolder}/{map}/_{map}.md` (src/maps). Read/write them only through the `src/frontmatter.ts` getters/setters or `plugin.mapStore` — never `cache.frontmatter.terrain` etc., and never gate the read on the hex note existing (most hexes have no note; notes are created when a hex gets content). This mistake caused four separate regressions (submap rings, hex locks, editor terrain, exports) — see the KB plan note `plan-map-notes`. -- **Note-only fields survive a settings reload; missing ≠ empty.** data.json leaves out what only the map note holds (each map's `paths`/`pathChains`, via `withoutNotePaths`; hexes live only in `MapStore`). So `loadSettings` / `onExternalSettingsChange` hand out fresh `MapData` objects WITHOUT those fields, and Obsidian fires `onExternalSettingsChange` for our own saves during a save burst. Never read a missing note-only field as "empty" (`map.paths ?? []` feeding a write is the trap): `MapStore.adopt()` carries the store's copy onto fresh objects, `loadSettings` must not `await` between swapping `this.settings` and `mapStore.adoptAll()`, and `MapStore.writeNote` refuses to drop every path/hex a note holds unless an edit cleared them (`clearedPaths`/`clearedHexes`). Any new field stored only in the map note needs the same treatment. Incident: 2026-10-10 paths wiped when creating a region next to a map (KB `incident-2026-10-10-path-loss-on-external-reload`; regression tests `tests/pathLossReload.test.ts`). -- Exclude notes whose `basename` starts with `"_"` whenever enumerating vault files for display, dropdowns, or linking. Pattern: `.filter(f => !f.basename.startsWith("_"))`. -- **All modals must extend `DuckmageModal`** (`src/DuckmageModal.ts`) rather than Obsidian's `Modal` directly. `DuckmageModal` is the single place for shared modal behaviour. Any functionality needed by more than one modal belongs there, not in `utils.ts` or duplicated across files. -- All modals call `this.makeDraggable()` in `onOpen` (inherited from `DuckmageModal`), which adds the `duckmage-editor-modal-drag` class and locks dragging to the title-bar area. (`FileLinkSuggestModal` is the sole exception — it extends `SuggestModal` and cannot inherit from `DuckmageModal`.) -- **NEVER interleave layout reads (`offsetWidth/Height/Left/Top`, `getBoundingClientRect`, `getComputedStyle`) with DOM writes (`createDiv`/`createEl`/`appendChild`/`setCssProps`/style changes) inside a per-hex loop.** Each read after a write forces a full synchronous layout flush → O(n²) thrash. On large maps (chult = 3843 hexes) this stalled the main thread for ~20s on open (regression in `renderCoordLabelsLayer`, commit 10475fd; fixed by batching). **Pattern:** read ALL geometry into a plain array first, THEN do all DOM writes. This is the established pattern in `renderPathOverlay`/`renderFactionOverlay` (build `centerMap` read-only, then build the SVG). The overlay/label builders in `HexMapView` are the hot path — any new one MUST follow read-then-write. Reproduce/validate with `dev/coord-label-thrash-bench.{html,mjs}` (~198× speedup batched vs interleaved). - -### Obsidian directory review in CI (never via the dashboard by hand) - -Every branch push runs Obsidian's automated review (preview scan) in CI, and -master releases are gated on it, then the published release scan is watched -(`.github/workflows/obsidian-review.yml`, `release.yml`, `dev/obsidian-review.mjs`). -**When an "Obsidian review" job fails, follow the Runbook in -`.github/OBSIDIAN_REVIEW.md`**: the failure message names the entry. The -common one is an expired session: the fix is `npm run obsidian:login` -(opens a browser, user logs in if asked, it sets the -`OBSIDIAN_COMMUNITY_COOKIE` secret), then re-run the job. Use -`gh` as `sbuffkin` (`GH_TOKEN=$(gh auth token --user sbuffkin)`) for this repo. - -### Obsidian reviewer-bot conventions (enforced beyond what eslint catches) - -The obsidianmd reviewer flags patterns the locally-installed -`eslint-plugin-obsidianmd` doesn't have rules for. Watch for these -in any new code; failing these means another bump-and-fix cycle. - -- **Keep `eslint-plugin-obsidianmd` AND `typescript-eslint` current.** The - reviewer bot runs the LATEST versions; stale pins let findings through - local lint twice on 2026-08-09 (obsidianmd 0.1.9 → 22 `prefer-create-el` - sites; typescript-eslint 8.58 → 6 unnecessary-assertion sites its newer - "receiver accepts the original type" check catches). When reviewer - warnings arrive that local lint missed, first `npm view version` - vs `npm ls ` for both packages and upgrade. -- **`prefer-create-el` + `@typescript-eslint/no-unnecessary-type-assertion` - are now enforced locally** (plugin 0.4.1 + type-aware rule in - eslint.config.mjs). Use `parent.createEl/createDiv/createSpan` (or the - global `createEl` for genuinely detached elements), never - `document.createElement`/`activeDocument.createElement`. -- **Settings tab is declarative (Obsidian ≥1.13).** `HexmakerSettingTab` - implements `getSettingDefinitions()`; on 1.13+ the tab renders FROM THE - DEFINITIONS and `display()` is never called (it remains only as the - pre-1.13 fallback). Any new setting must be added to BOTH paths until - minAppVersion reaches 1.13. Local `obsidian` typings are 1.12 — the - 1.13 shapes are mirrored as local interfaces in HexmakerSettingTab.ts; - delete them when the package is bumped. -- **CSS lint "css-clip-path partially supported" warnings are accepted** — - our clip-paths are basic `polygon()` hex shapes, fully supported in - desktop Electron, and the plugin is `isDesktopOnly`. Don't churn on them. - -- **`document` / `window` → `activeDocument` / `activeWindow`.** Required - for popout-window compatibility. Globals are listed in `eslint.config.mjs`. - Use `activeDocument.createElementNS(...)`, `activeDocument.body.createDiv(...)`, - `window.setTimeout(...)` is OK but prefer `activeWindow.setTimeout(...)` - inside view code where popouts could fire it. -- **Dynamic CSS: never `.style.foo = …` or `setCssProps({ transform: … })`.** - The local eslint rule (`obsidianmd/no-static-styles-assignment`) is - promoted to an error to catch this. The pattern is: declare the - `transform` / `opacity` / etc. in CSS using `var(--duckmage-..., default)` - fallbacks, and write the dynamic values to the custom properties from - JS. See `.duckmage-bg-image-layer`, `.duckmage-hex-map-grid`, - `.duckmage-hex-map-viewport` for the canonical examples. -- **`setDynamicTooltip()` is deprecated.** The slider value is now always - shown inline. Drop the call from any new `.addSlider(...)` chain. +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Commands + +```bash +# Development (watch mode with inline sourcemaps) — use with Hot Reload (see below) +npm run dev + +# Production build (type-checks then bundles) +npm run build + +# Run tests (vitest) +npm test + +# Bump version (updates manifest.json and versions.json, stages both) +npm run version +``` + +Slash commands (invoke inside Claude Code): +- `/dev` — starts esbuild in watch mode (long-running; pairs with Hot Reload) +- `/rebuild` — one-off production build + test run; reports errors if either fails + +**Always run `/rebuild` after making code changes.** The TypeScript type-check and test suite are the only automated verification — catch errors before the user does. + +## Dev loop + +Each coding session: +1. Run `npm run dev` in a terminal (or `/dev` from Claude Code) — esbuild watches for changes and rebuilds `main.js` on every save +2. After a rebuild, reload the plugin in Obsidian: + ```bash + powershell.exe -Command "obsidian eval code=\"(async()=>{await app.plugins.disablePlugin('hexmaker'); await app.plugins.enablePlugin('hexmaker'); return 'ok'})()\"" + ``` + The plugin **id is `hexmaker`** (the folder is `duckmage-plugin`). On this machine's Obsidian installer the CLI's `plugin:reload` / `plugin:disable` / `plugin:enable` and `dev:*` commands silently do nothing (exit 255, "installer out of date"); `obsidian eval` works. To check what's loaded: `obsidian eval code="Object.keys(app.commands.commands).filter(c=>c.startsWith('hexmaker:'))"`. Screenshot: `require('@electron/remote').getCurrentWebContents().capturePage()` inside `eval`. `app.plugins.plugins.hexmaker.manifest.version` is cached from startup — don't use it to tell builds apart. + **Before copying a build into this folder**, check which branch the current vault build came from — other sessions deploy from their own branches, and a deploy reverts theirs. +3. Use `/rebuild` for a final production build before committing (runs the TypeScript type-check and tests too) + +## Before merging or deploying: `npm run premerge` + +**Before merging into `feat/region-notes` (or master) or deploying a build into the live vault, run `npm run premerge`** (from WSL, like every npm script here) and only go ahead when it ends with `PREMERGE PASSED`. It runs build → lint → unit tests → integration tests → the **smoke vault matrix**, stopping loudly at the first failure (owner decision WM5: the matrix runs locally, not in CI; CI keeps the Obsidian-free tests). + +- The matrix (`dev/smoke/run.mjs`, plan [[plan-work-modes]] §3) builds 9 vault setups (fresh install, a synthetic 1.5.5 vault, a copy of the owner's real data `C:/Users/markr/work/tmp/migtest/seedF` + a copy of the live `data.json`, space only, overworld + regions, neighbours world, a custom palette with no default names, everything deleted, 80 maps), each in its own sandboxed Obsidian (fresh-eyes `sandbox.mjs`, up to 4 at once), and checks: no plugin console errors; settings saved; every map opens and renders; untouched files unchanged on disk (migrations verified separately: map notes, backups, hex data vs the old frontmatter, paths resolve, palette upgrades keep every terrain); a restart rewrites nothing; paint → undo round trip; registered commands; Play refuses a path edit. ~5 minutes, mostly the real-data migration. +- Run parts of it: `npm run smoke -- --only fresh,v155 --jobs 2` (`--list` for the setup ids, `--keep` to keep run folders, `--build ` to test another build). A failed setup keeps its run folder (path in `dev/smoke/last-run.json`); a full pass writes `dev/smoke/last-pass.json` (commit, build hash, per-check results). +- It only stops the sandboxes it started and checks every other Obsidian process is still there (`otherObsidianBefore == otherObsidianAfter`). Never point it at the main vault. +- A new feature with a user-visible write path (paint, paths, a new note type, a migration) should get a smoke check in `dev/smoke/lib/page.mjs` / `setups.mjs` as well as unit tests. + +## Architecture + +The plugin source is split across `main.ts` (entry point re-export) and modules under `src/`. esbuild bundles everything into `main.js`, which Obsidian loads directly. + +See `ARCHITECTURE.md` for a full overview of the system. + +### Source layout + +``` +main.ts ← thin re-export: export { default } from "./src/DuckmagePlugin" +src/ + DuckmagePlugin.ts ← Plugin class (entry point, default export) + HexMapView.ts ← ItemView — hex grid, all drawing tools, inline modals + HexEditorModal.ts ← Modal — right-click per-hex editor (terrain, links, notes, icon override) + HexTableView.ts ← ItemView — spreadsheet view of all hex notes with filters/sort + TerrainPickerModal.ts ← Modal — full terrain palette picker for the terrain paint tool + TerrainEntryEditorModal.ts ← Modal — edit a single terrain palette entry (name, color, icon) + IconPickerModal.ts ← Modal — icon picker for the icon paint tool + RegionModal.ts ← Modal — switch active region, create/rename/delete regions + FileLinkSuggestModal.ts ← SuggestModal — file picker scoped to worldFolder + RandomTableView.ts ← ItemView — random table + workflow browser (tabbed: Tables / Workflows) + RandomTableModal.ts ← Modal — inline roll modal used from HexEditorModal + RandomTableEditorModal.ts ← Modal — edit entries of a random table file + WorkflowEditorModal.ts ← Modal — edit workflow definition (steps, template, results folder) + WorkflowWizardModal.ts ← Modal — execute a workflow (roll steps, fill template, save as note) + randomTable.ts ← Pure logic: parse, roll, weight, die-range helpers + workflow.ts ← Pure logic: parse/serialize workflows, generate templates, placeholder helpers + DuckmageSettingTab.ts ← PluginSettingTab — settings UI + types.ts ← Interfaces & type constants (TerrainColor, DuckmagePluginSettings, LINK_SECTIONS, TEXT_SECTIONS) + constants.ts ← Runtime constants (VIEW_TYPE_*, DEFAULT_TERRAIN_PALETTE, DEFAULT_SETTINGS) + defaultHexTemplate.md ← Built-in hex note template (imported as text via esbuild loader) + frontmatter.ts ← YAML frontmatter helpers (terrain + icon override read/write) + sections.ts ← Markdown section helpers (addLinkToSection, getLinksInSection, getAllSectionData, …) + utils.ts ← Shared utilities (normalizeFolder, getIconUrl, makeTableTemplate) + md.d.ts ← TypeScript declaration for "*.md" text imports +``` + +The `.md` loader is configured in `esbuild.config.mjs` (`loader: { '.md': 'text' }`), allowing `defaultHexTemplate.md` to be imported as a plain string. + +### Plugin purpose + +Renders an interactive hex-grid map for tabletop RPG world-building inside Obsidian. Each hex cell corresponds to a Markdown note on disk. The map supports terrain painting, icon painting, road/river chain drawing, link-to-hex tools (random tables, factions), panning, and zooming. A spreadsheet view summarises all hex notes with filtering. A random tables view lets users browse, roll, and edit weighted random tables, and execute multi-step workflows that chain table rolls into a filled template note. + +### Key classes + +- **`DuckmagePlugin`** (`src/DuckmagePlugin.ts`) — Main plugin entry point. Registers views (`HexMapView`, `HexTableView`, `RandomTableView`), ribbon icons, commands, and the settings tab. Key public API: + - `hexPath(x, y)` — vault-relative path for a hex note + - `createHexNote(x, y)` — creates hex note from template + - `loadAvailableIcons()` — merges plugin `icons/` with user custom icons folder into `availableIcons: string[]` + - `refreshHexMap()` — re-renders all open `HexMapView` instances + - `ensureTerrainTables()` — creates missing terrain table files under `tablesFolder/terrain/` + - `ensureAllRollerLinks()` — adds roller-link preamble to all table files + - `backfillTerrainLinks()` — links each hex note's terrain table into its Encounters Table section + - `buildRollerLink(path)` — generates the `[Roll]()` URI for a table file + +- **`HexMapView`** (`src/HexMapView.ts`, extends `ItemView`) — Renders the hex grid and handles all user interaction. + - **DOM structure**: `contentEl` (`.duckmage-hex-map-container`) → `.duckmage-hex-map-clip` (panning viewport, `overflow: hidden`) + `.duckmage-hex-map-controls` (overlay for buttons, `pointer-events: none`). This keeps toolbar/expand buttons unclipped by the viewport transform. + - **`renderGrid(terrainOverrides?, iconOverrides?)`** — full DOM re-render. Optional override Maps allow passing values not yet in the metadata cache. + - **Drawing tools**: `drawingMode` union `"road" | "river" | "terrain" | "icon" | "tableLink" | "factionLink" | null`. Toolbar buttons toggle mode; each mode has a `handle*Button()` opener, `exit*Mode()` closer, and `onHex*Click()` handler. + - **Write queues**: `scheduleTerrainWrite` / `scheduleIconWrite` coalesce rapid repaints — only the latest value per hex is written, preventing stale overwrites. + - **Link tools** (`tableLink`, `factionLink`): pick a file via folder-tree modal, then click hexes to add a wiki-link to the `Encounters Table` or `Factions` section. Visual feedback: badge span + CSS ripple blip animation (`duckmage-hex-blip`). + - Left-click: opens/creates hex note (normal), paints terrain/icon, extends road/river chain, or adds a link. + - Right-click: opens `HexEditorModal` (normal), deletes road/river node, or exits current tool mode. + - Expand buttons (+) grow the grid in four cardinal directions, adjusting `gridOffset` and `gridSize` in settings. + - **`centerOnHex(x, y)`** (public) — pans the viewport to centre on a given hex coordinate. + - **`activeRegionName`** (public) — the currently displayed region name. + +- **`HexEditorModal`** (`src/HexEditorModal.ts`, extends `Modal`) — The right-click per-hex editor: + - Terrain picker (2-row scrollable grid) with icon override and "Clear terrain". + - Dropdown link sections for **Towns, Dungeons, Features, Quests, Factions, Encounters Table** — each backed by its own configured folder, rendered via `renderDropdownSection`. Uses `LinkPickerModal` internally (file list + create-new). + - Free-text note sections: Description, Landmark, Hidden, Secret, Weather, Hooks & Rumors. + - Fetches all section data in a single read before touching the DOM (`getAllSectionData`). + +- **`HexTableView`** (`src/HexTableView.ts`, extends `ItemView`) — Spreadsheet of all hex notes: + - Columns: Hex (coords + jump button), Terrain, Description, Landmark, Towns, Dungeons, Features, Quests, Factions, Enc. Table, Hidden, Secret, Weather, Hooks & Rumors. + - Enc. Table cell shows the basename of the linked table file; clicking opens `RandomTableView` at that file. + - Toolbar filters: X/Y range inputs, terrain multi-select (left-click include / right-click exclude), Has Town/Dungeon/Feature/Quest/Faction checkboxes, region selector, X→Y / Y→X sort priority, Asc/Desc direction. + - Live updates on vault `modify` events (300 ms debounce per file). + - Jump button (◎) calls `HexMapView.centerOnHex(x, y)` on the open map view. + +- **`RandomTableView`** (`src/RandomTableView.ts`, extends `ItemView`) — Tabbed browser with two modes: + - **Tables mode**: folder tree + search + new-table creator. Detail pane shows entries with die-range and % odds, die-size selector, Roll button, copy result, roll history. Edit opens `RandomTableEditorModal`. Bottom of detail pane shows "Workflows using this table" links (each opens that workflow in Workflows mode) and a "+ New workflow with this table" link. + - **Workflows mode**: folder tree of workflow files. Detail pane shows each step as a clickable link (opens that table in Tables mode) with roll count. Edit opens `WorkflowEditorModal`. "Roll workflow" button opens `WorkflowWizardModal`. + - **`openTable(filePath)`** (public) — switches to Tables mode, expands ancestor folders so the target is visible, and loads the table detail; called from `HexTableView` (Enc. Table cell), `HexEditorModal`, workflow step links, and the protocol handler. + +- **`RandomTableModal`** (`src/RandomTableModal.ts`, extends `Modal`) — Lightweight inline roll modal opened from `HexEditorModal` (🎲 button per link section or 📖 for terrain description). Skips the picker if `initialFilePath` is supplied. + +- **`RandomTableEditorModal`** (`src/RandomTableEditorModal.ts`, extends `Modal`) — Edit table entries (result text + weight), linked folder, description, filter flags. Auto-saves on close. Accepts optional `initialContent` to avoid a redundant vault read when the caller already has the file content. + +- **`WorkflowEditorModal`** (`src/WorkflowEditorModal.ts`, extends `Modal`) — Edit a workflow definition: + - Rename workflow, set results folder, manage steps (table picker + roll count + label) with drag-to-reorder. + - Template textarea with live placeholder validation — shows missing `$placeholder` names. + - Template auto-syncs: new step appends `## label\n$label` block; label change updates the heading AND all `$var`/`$var_N` placeholder references; roll-count change adds or removes `_N` suffixed placeholders (reducing to 1 collapses back to bare `$var`). + - Auto-saves workflow file and template file on close. Modal is draggable by its title bar. + +- **`WorkflowWizardModal`** (`src/WorkflowWizardModal.ts`, extends `Modal`) — Execute a workflow: + - Shows each step with a manual-pick dropdown and a Roll button. Fixed-width controls to prevent layout shift on roll. + - Result textarea shows the template filled with rolled values. + - Save section writes the filled result as a new vault note in the configured results folder. + +- **`RegionModal`** (`src/RegionModal.ts`, extends `Modal`) — Manage hex map regions: + - Switch the active region displayed on the hex map. + - Create, rename, and delete regions. Regions map to subfolders under `hexFolder`. + +- **`TerrainEntryEditorModal`** (`src/TerrainEntryEditorModal.ts`, extends `Modal`) — Edit a single terrain palette entry: name, color, icon (with preview), and icon color tint. Changes are staged in pending fields and only written to the palette on Save. + +- **`TerrainPickerModal`** (`src/TerrainPickerModal.ts`) — Full terrain palette picker (no row cap). Includes "Clear" to erase terrain. + +- **`IconPickerModal`** (`src/IconPickerModal.ts`) — Full icon picker with image previews. Includes "Remove" option. + +- **`FileLinkSuggestModal`** (`src/FileLinkSuggestModal.ts`) — Reusable fuzzy-search file picker scoped to a configured folder. + +- **`DuckmageSettingTab`** (`src/DuckmageSettingTab.ts`) — Settings UI: + - "Generate folders" button — fills blank folder settings with defaults under `worldFolder` and creates the folders. + - Folder paths: world, hexes, towns, dungeons, quests, features, factions, tables, workflows. + - "Generate terrain tables & hex links" button — runs `ensureTerrainTables`, `ensureAllRollerLinks`, `backfillTerrainLinks`. + - Hex orientation, grid dimensions, hex gap, custom icons folder, road/river colors, terrain palette editor (drag-to-reorder, click entry to open `TerrainEntryEditorModal`). + +### Data model + +- **Hex notes**: `{hexFolder}/{region}/{x}_{y}.md`. Created via `createHexNote(x, y, region)` using the configured template or `defaultHexTemplate.md`. +- **Template placeholders**: `{{x}}`, `{{y}}`, `{{title}}`. Template must include `### Towns`, `### Dungeons`, `### Features`, `### Quests`, `### Factions`, `### Encounters Table` headings. +- **Terrain palettes**: one markdown note per palette in `palettesFolder` (default `{worldFolder}/palettes`; basename = palette name; a `| Terrain | Color | Icon | Icon color | Category |` table). `src/palettes/PaletteStore.ts` syncs both ways: `saveSettings()` → `sync()` writes/renames/trashes notes; vault events re-parse hand edits into `settings.terrainPalettes` (kept as the sync-readable working copy and data.json cache). Edit palettes in memory + `saveSettings()` as before — never write palette notes directly. Built-in presets (Limited, Expanded, Space - Sector, Space - System) live in `src/palettes/presets.ts`; `createNewMap` installs an uninstalled preset on first use. +- **Icon packs**: bundled `bw-*` (Terrain), `place-*` (Places, owned by the World map type, grouped by kind; rebuilt with credits by `dev/build-place-icons.mjs` — add picks there, never by hand) and `space-*` (Space, third-party — credits in `icons/CREDITS.md`, rebuilt by `dev/build-space-icons.mjs`), plus the user's icons folder (Custom). Every icon grid gets search + pack tabs via `HexmakerModal.addIconFilter(grid, …)` — new icon grids must set `data-icon` on tiles and call it. +- **Terrain**: YAML frontmatter `terrain: `. Read via `getTerrainFromFile` (metadata cache); written via `setTerrainInFile` (raw text patch). Both in `frontmatter.ts`. +- **Icon override**: frontmatter `icon: `. Read via `getIconOverrideFromFile`; written via `setIconOverrideInFile`. +- **Terrain icons**: plugin `icons/` folder + user custom icons folder → `plugin.availableIcons`. URLs via `getIconUrl(plugin, filename)`. Vault-sourced filenames tracked in `plugin.vaultIconsSet`. +- **Roads & rivers**: `settings.roadChains` / `settings.riverChains` — arrays of `string[]` chains, each element `"x_y"`. Drawn as SVG polylines over the grid. +- **Link sections** (`LINK_SECTIONS`): `"Towns" | "Dungeons" | "Features" | "Quests" | "Factions" | "Encounters Table"`. Wiki-links inserted under the matching `###` heading via `addLinkToSection`. Read back via `getLinksInSection`. +- **Text sections** (`TEXT_SECTIONS`): Description, Landmark, Hidden, Secret. Free text stored under `###` headings. Weather and Hooks & Rumors are also text sections but not in the `TEXT_SECTIONS` constant. +- **Random tables**: Markdown files with YAML `dice: N` frontmatter and a `| Result | Weight |` table. Parsed by `randomTable.ts`. Stored under `tablesFolder` (default `world/tables`). Terrain tables live at `{tablesFolder}/terrain/{name} - {description|encounters}.md`. +- **Workflows**: Markdown files with YAML frontmatter (`results-folder`, `template-file`) and a `| Table | Rolls | Label |` steps table. Stored under `workflowsFolder`. Templates stored at `{workflowsFolder}/templates/{name}.md`. Parsed/serialized by `workflow.ts`. +- **Settings** (`data.json`): `worldFolder`, `hexFolder`, `townsFolder`, `dungeonsFolder`, `questsFolder`, `featuresFolder`, `factionsFolder`, `tablesFolder`, `workflowsFolder`, `iconsFolder`, `templatePath`, `hexGap`, `hexOrientation`, `terrainPalette`, `gridSize`, `gridOffset`, `zoomLevel`, `roadChains`, `riverChains`, `roadColor`, `riverColor`, `defaultTableDice`, `regions`. + +### Hex orientations + +- **Pointy-top**: points north/south, flat sides east/west. Odd rows offset right. Adjacency via odd-r offset. +- **Flat-top** (default): flat sides north/south, points east/west. Odd columns offset down. Adjacency via odd-q offset. +- `hexNeighbors(x, y)` in `HexMapView` branches on `settings.hexOrientation`. + +### Key conventions + +- Folder paths normalised (no leading/trailing slashes) via `normalizeFolder()`. +- Links use vault-relative paths via `metadataCache.fileToLinktext(file, sourcePath)`. +- `obsidian` is an esbuild external — never bundled; provided by Obsidian at runtime. +- CSS classes use the `duckmage-` prefix (styles in `styles.css`). +- View/modal/tab files use `import type DuckmagePlugin` to avoid circular runtime dependencies. +- Paint tool methods (`onHexPaintClick`, `onHexIconClick`) are synchronous — DOM patched immediately, file writes queued via coalescing queue. +- Link-tool click handlers (`onHexTableLinkClick`, `onHexFactionLinkClick`) are async — no coalescing needed (one-shot writes). +- `onChanged` callback from `HexEditorModal` defers `renderGrid()` 300 ms when no terrain/icon overrides are passed (link-only changes) to avoid a metadata-cache race after `vault.modify`. +- Modals that preload file content accept an optional `preloaded` / `initialContent` parameter — callers that already hold the file content pass it in to avoid a redundant vault read. +- **Map data lives in map notes, not hex notes.** Terrain, icon, GM icons, region, submap and locked are stored in `{hexFolder}/{map}/_{map}.md` (src/maps). Read/write them only through the `src/frontmatter.ts` getters/setters or `plugin.mapStore` — never `cache.frontmatter.terrain` etc., and never gate the read on the hex note existing (most hexes have no note; notes are created when a hex gets content). This mistake caused four separate regressions (submap rings, hex locks, editor terrain, exports) — see the KB plan note `plan-map-notes`. +- **Note-only fields survive a settings reload; missing ≠ empty.** data.json leaves out what only the map note holds (each map's `paths`/`pathChains`, via `withoutNotePaths`; hexes live only in `MapStore`). So `loadSettings` / `onExternalSettingsChange` hand out fresh `MapData` objects WITHOUT those fields, and Obsidian fires `onExternalSettingsChange` for our own saves during a save burst. Never read a missing note-only field as "empty" (`map.paths ?? []` feeding a write is the trap): `MapStore.adopt()` carries the store's copy onto fresh objects, `loadSettings` must not `await` between swapping `this.settings` and `mapStore.adoptAll()`, and `MapStore.writeNote` refuses to drop every path/hex a note holds unless an edit cleared them (`clearedPaths`/`clearedHexes`). Any new field stored only in the map note needs the same treatment. Incident: 2026-10-10 paths wiped when creating a region next to a map (KB `incident-2026-10-10-path-loss-on-external-reload`; regression tests `tests/pathLossReload.test.ts`). +- Exclude notes whose `basename` starts with `"_"` whenever enumerating vault files for display, dropdowns, or linking. Pattern: `.filter(f => !f.basename.startsWith("_"))`. +- **All modals must extend `DuckmageModal`** (`src/DuckmageModal.ts`) rather than Obsidian's `Modal` directly. `DuckmageModal` is the single place for shared modal behaviour. Any functionality needed by more than one modal belongs there, not in `utils.ts` or duplicated across files. +- All modals call `this.makeDraggable()` in `onOpen` (inherited from `DuckmageModal`), which adds the `duckmage-editor-modal-drag` class and locks dragging to the title-bar area. (`FileLinkSuggestModal` is the sole exception — it extends `SuggestModal` and cannot inherit from `DuckmageModal`.) +- **NEVER interleave layout reads (`offsetWidth/Height/Left/Top`, `getBoundingClientRect`, `getComputedStyle`) with DOM writes (`createDiv`/`createEl`/`appendChild`/`setCssProps`/style changes) inside a per-hex loop.** Each read after a write forces a full synchronous layout flush → O(n²) thrash. On large maps (chult = 3843 hexes) this stalled the main thread for ~20s on open (regression in `renderCoordLabelsLayer`, commit 10475fd; fixed by batching). **Pattern:** read ALL geometry into a plain array first, THEN do all DOM writes. This is the established pattern in `renderPathOverlay`/`renderFactionOverlay` (build `centerMap` read-only, then build the SVG). The overlay/label builders in `HexMapView` are the hot path — any new one MUST follow read-then-write. Reproduce/validate with `dev/coord-label-thrash-bench.{html,mjs}` (~198× speedup batched vs interleaved). + +### Obsidian directory review in CI (never via the dashboard by hand) + +Every branch push runs Obsidian's automated review (preview scan) in CI, and +master releases are gated on it, then the published release scan is watched +(`.github/workflows/obsidian-review.yml`, `release.yml`, `dev/obsidian-review.mjs`). +**When an "Obsidian review" job fails, follow the Runbook in +`.github/OBSIDIAN_REVIEW.md`**: the failure message names the entry. The +common one is an expired session: the fix is `npm run obsidian:login` +(opens a browser, user logs in if asked, it sets the +`OBSIDIAN_COMMUNITY_COOKIE` secret), then re-run the job. Use +`gh` as `sbuffkin` (`GH_TOKEN=$(gh auth token --user sbuffkin)`) for this repo. + +### Obsidian reviewer-bot conventions (enforced beyond what eslint catches) + +The obsidianmd reviewer flags patterns the locally-installed +`eslint-plugin-obsidianmd` doesn't have rules for. Watch for these +in any new code; failing these means another bump-and-fix cycle. + +- **Keep `eslint-plugin-obsidianmd` AND `typescript-eslint` current.** The + reviewer bot runs the LATEST versions; stale pins let findings through + local lint twice on 2026-08-09 (obsidianmd 0.1.9 → 22 `prefer-create-el` + sites; typescript-eslint 8.58 → 6 unnecessary-assertion sites its newer + "receiver accepts the original type" check catches). When reviewer + warnings arrive that local lint missed, first `npm view version` + vs `npm ls ` for both packages and upgrade. +- **`prefer-create-el` + `@typescript-eslint/no-unnecessary-type-assertion` + are now enforced locally** (plugin 0.4.1 + type-aware rule in + eslint.config.mjs). Use `parent.createEl/createDiv/createSpan` (or the + global `createEl` for genuinely detached elements), never + `document.createElement`/`activeDocument.createElement`. +- **Settings tab is declarative (Obsidian ≥1.13).** `HexmakerSettingTab` + implements `getSettingDefinitions()`; on 1.13+ the tab renders FROM THE + DEFINITIONS and `display()` is never called (it remains only as the + pre-1.13 fallback). Any new setting must be added to BOTH paths until + minAppVersion reaches 1.13. Local `obsidian` typings are 1.12 — the + 1.13 shapes are mirrored as local interfaces in HexmakerSettingTab.ts; + delete them when the package is bumped. +- **CSS lint "css-clip-path partially supported" warnings are accepted** — + our clip-paths are basic `polygon()` hex shapes, fully supported in + desktop Electron, and the plugin is `isDesktopOnly`. Don't churn on them. + +- **`document` / `window` → `activeDocument` / `activeWindow`.** Required + for popout-window compatibility. Globals are listed in `eslint.config.mjs`. + Use `activeDocument.createElementNS(...)`, `activeDocument.body.createDiv(...)`, + `window.setTimeout(...)` is OK but prefer `activeWindow.setTimeout(...)` + inside view code where popouts could fire it. +- **Dynamic CSS: never `.style.foo = …` or `setCssProps({ transform: … })`.** + The local eslint rule (`obsidianmd/no-static-styles-assignment`) is + promoted to an error to catch this. The pattern is: declare the + `transform` / `opacity` / etc. in CSS using `var(--duckmage-..., default)` + fallbacks, and write the dynamic values to the custom properties from + JS. See `.duckmage-bg-image-layer`, `.duckmage-hex-map-grid`, + `.duckmage-hex-map-viewport` for the canonical examples. +- **`setDynamicTooltip()` is deprecated.** The slider value is now always + shown inline. Drop the call from any new `.addSlider(...)` chain. diff --git a/src/ui/placement.ts b/src/ui/placement.ts index 9ec8b95c..9a80f02d 100644 --- a/src/ui/placement.ts +++ b/src/ui/placement.ts @@ -39,11 +39,11 @@ export const PLACEMENT: Readonly> = { "Settings.workflowsFolder": "advanced", "Settings.templatesFolder": "advanced", "Settings.palettesFolder": "advanced", - "Settings.biomesFolder": "advanced", - "Settings.biomePoolsFolder": "advanced", - "Settings.worldTypesFolder": "advanced", - "Settings.generateFolders": "debug", - "Settings.generateWorldData": "debug", + "Settings.biomesFolder": "debug", + "Settings.biomePoolsFolder": "debug", + "Settings.worldTypesFolder": "debug", + "Settings.generateFolders": "advanced", + "Settings.generateWorldData": "advanced", // ── Generator page: recipe extras are Advanced ── "GenPage.symmetry": "advanced", diff --git a/tests/disclosure.test.ts b/tests/disclosure.test.ts index f7b413c2..d31b81e9 100644 --- a/tests/disclosure.test.ts +++ b/tests/disclosure.test.ts @@ -34,7 +34,8 @@ describe("placement map", () => { expect(layerOf("Settings.hexGap")).toBe("main"); expect(layerOf("Nowhere.atAll")).toBe("main"); expect(layerOf("Settings.hexFolder")).toBe("advanced"); - expect(layerOf("Settings.generateWorldData")).toBe("debug"); + expect(layerOf("Settings.generateWorldData")).toBe("advanced"); + expect(layerOf("Settings.biomesFolder")).toBe("debug"); expect(layerOf("GenPage.clumping")).toBe("debug"); expect(layerOf("GenPage.symmetry")).toBe("advanced"); // Not a prototype key or a bad value. @@ -54,9 +55,11 @@ describe("placement map", () => { expect(layerOf("Settings.hexFolder", {})).toBe("main"); }); - it("the proof placements: folders Advanced, maintenance and engine tuning Debug", () => { + it("the proof placements: folders and setup tools Advanced, storage plumbing and engine tuning Debug", () => { expect(idsOn("advanced").filter((id) => id.startsWith("Settings."))).toContain("Settings.worldFolder"); - expect(idsOn("debug")).toEqual(expect.arrayContaining(["Settings.generateFolders", "Settings.generateWorldData", "GenPage.scatter", "GenPage.mixStrength"])); + // The setup tools are in the README's manual setup, so Advanced, not Debug. + expect(idsOn("advanced")).toEqual(expect.arrayContaining(["Settings.generateFolders", "Settings.generateWorldData"])); + expect(idsOn("debug")).toEqual(expect.arrayContaining(["Settings.biomesFolder", "Settings.biomePoolsFolder", "Settings.worldTypesFolder", "GenPage.scatter", "GenPage.mixStrength"])); // Customisation is not "advanced" (rule 5): the custom icons folder stays main. expect(layerOf("Settings.iconsFolder")).toBe("main"); }); @@ -200,7 +203,7 @@ describe("settings definitions (Obsidian 1.13+)", () => { expect(all).not.toContain("Feature level"); }); - it("put folders in Advanced (collapsed) and maintenance in Debug (debug mode only)", () => { + it("put folders and setup tools in Advanced (collapsed) and storage plumbing in Debug (debug mode only)", () => { const store = new FakeStore(); let defs = tabWith(store).getSettingDefinitions() as Item[]; const advanced = defs.find((d) => d.items?.[0]?.name === "Advanced")!; @@ -216,7 +219,8 @@ describe("settings definitions (Obsidian 1.13+)", () => { // Debug: only while debug mode is on (and Advanced is open). defs = tabWith(store).getSettingDefinitions() as Item[]; const debug = defs.find((d) => d.heading === "Debug")!; - expect(names(debug.items!)).toEqual(expect.arrayContaining(["Generate terrain tables & hex links", "Set up folders"])); + expect(names(debug.items!)).toEqual(expect.arrayContaining(["Biomes folder", "Biome pools folder", "World types folder"])); + expect(names(advanced.items!)).toEqual(expect.arrayContaining(["Generate terrain tables & hex links", "Set up folders"])); expect(shown(debug.visible)).toBe(false); setDebugMode(store, true); expect(shown(debug.visible)).toBe(true); From 9f636040a967e3558f8fa6a0f062e5b24aad7d12 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 17:01:25 -0400 Subject: [PATCH 315/558] test(modules): P0 characterisation snapshot + module boundary ratchet Snapshot today's map-type answers (kinds, terrain types, presets, icon packs, generator visibility, first-map generator, tables, section words, space-map test, carry-over, moon tethers) over {map types on} x {palette kinds} x {map trees}, and a ratchet on how far the core reaches into module code (imports) and branches on map types by name (decisions). Baseline: imports space 10, world-maps 71; decisions space 46, world 3. isSpaceMap / sectionWordsFor move to pure src/maps/mapKindQueries.ts (same logic) so the snapshot can ask them without the plugin. Co-Authored-By: Claude Opus 5.5 --- package.json | 4 +- src/HexmakerPlugin.ts | 18 +- src/maps/mapKindQueries.ts | 42 + tests/fixtures/moduleBoundary.json | 51 + tests/fixtures/moduleCharacterisation.json | 1973 ++++++++++++++++++++ tests/moduleBoundary.test.ts | 46 + tests/moduleBoundary.ts | 143 ++ tests/moduleCharacterisation.test.ts | 235 +++ 8 files changed, 2496 insertions(+), 16 deletions(-) create mode 100644 src/maps/mapKindQueries.ts create mode 100644 tests/fixtures/moduleBoundary.json create mode 100644 tests/fixtures/moduleCharacterisation.json create mode 100644 tests/moduleBoundary.test.ts create mode 100644 tests/moduleBoundary.ts create mode 100644 tests/moduleCharacterisation.test.ts diff --git a/package.json b/package.json index 67f37715..68cb5f85 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && npm run compat:snapshot && git add manifest.json versions.json tests/fixtures/compat", "compat:snapshot": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs tests/compat/snapshot.ts", - "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/disclosure.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", - "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/disclosure.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts", + "test": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/disclosure.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts tests/moduleCharacterisation.test.ts tests/moduleBoundary.test.ts", + "test:watch": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test --watch tests/eventsLedger.test.ts tests/tableOnce.test.ts tests/arrivalRegion.test.ts tests/unchartedLayer.test.ts tests/mapNote.test.ts tests/worldTypesConvert.test.ts tests/tableRoles.test.ts tests/arrivalSubmapSetup.test.ts tests/mapNoteOnArrival.test.ts tests/arrivalDeferred.test.ts tests/r3Labels.test.ts tests/noteTemplates.test.ts tests/mapStore.test.ts tests/pathLossReload.test.ts tests/stylesBalanced.test.ts tests/frontmatter.test.ts tests/hexEditorModal.test.ts tests/randomTable.test.ts tests/tableFormat.test.ts tests/tableMigration.test.ts tests/tableImport.test.ts tests/sections.test.ts tests/pendingTerrain.test.ts tests/compat.test.ts tests/toolSwitch.test.ts tests/utils.test.ts tests/workflow.test.ts tests/token.test.ts tests/randomTableExport.test.ts tests/singleNoteExport.test.ts tests/hexGeometry.test.ts tests/mapWithTableExport.test.ts tests/singleHexExport.test.ts tests/workflowExport.test.ts tests/textUtils.test.ts tests/overlayPatterns.test.ts tests/overlayHideRules.test.ts tests/transformVars.test.ts tests/obsidianReview.test.ts tests/hexcrawlManual.test.ts tests/hexWfc.test.ts tests/hexWfcCleanup.test.ts tests/hexWfcPathTweaks.test.ts tests/worldgenShares.test.ts tests/worldgenScrub.test.ts tests/worldgenGenerators.test.ts tests/worldgenLibrary.test.ts tests/hexWfcMerge.test.ts tests/worldgenSizePresets.test.ts tests/palettes.test.ts tests/workMode.test.ts tests/mapNav.test.ts tests/overworldChanges.test.ts tests/submapNav.test.ts tests/spaceSoloFixes.test.ts tests/worldTypesAutosave.test.ts tests/proceduralGenerators.test.ts tests/submapDefaults.test.ts tests/terrainTypes.test.ts tests/hexTableTypes.test.ts tests/regionContext.test.ts tests/contextPaths.test.ts tests/generatorPaths.test.ts tests/worldgenRegionWeights.test.ts tests/worldgenImpassableHint.test.ts tests/worldgenWorld.test.ts tests/mapKinds.test.ts tests/worldgenFirstMap.test.ts tests/hexWfcPlacement.test.ts tests/wheelChain.test.ts tests/toolMode.test.ts tests/wheelZoom.test.ts tests/saveStatus.test.ts tests/freshEyesR7b.test.ts tests/encounterLinks.test.ts tests/tokenDefaults.test.ts tests/hexHover.test.ts tests/neighbourGenerators.test.ts tests/mapExportNames.test.ts tests/readmeCommands.test.ts tests/openNote.test.ts tests/coordStyle.test.ts tests/tokenIconPicker.test.ts tests/safeArea.test.ts tests/hitTest.test.ts tests/terrainSection.test.ts tests/ghostPaths.test.ts tests/sizeInput.test.ts tests/freshEyesR4Setup.test.ts tests/freshEyesR5Setup.test.ts tests/disclosure.test.ts tests/mapTree.test.ts tests/mapMarkers.test.ts tests/builtinGenerators.test.ts tests/whenSized.test.ts tests/autoRoute.test.ts tests/impassable.test.ts tests/regionTables.test.ts tests/hexNames.test.ts tests/overworldLayout.test.ts tests/overworldBlend.test.ts tests/overworldBiomes.test.ts tests/overworldRegion.test.ts tests/hexBodyFields.test.ts tests/hexMapData.test.ts tests/pathTypeTable.test.ts tests/submaps.test.ts tests/placeIcons.test.ts tests/workflowNotes.test.ts tests/exportProvenance.test.ts tests/regionMapData.test.ts tests/paletteDerived.test.ts tests/pathTypeOptions.test.ts tests/generatorNotes.test.ts tests/anchorText.test.ts tests/pathLegacy.test.ts tests/pathRouter.golden.test.ts tests/pathModel.test.ts tests/pathGeometry.test.ts tests/pathRender.test.ts tests/pathMigrate.test.ts tests/paletteColors.test.ts tests/overworldRegionWorld.test.ts tests/overworldRender.test.ts tests/presetTerrains.test.ts tests/mapNotePaths.test.ts tests/pathTool.test.ts tests/routePins.test.ts tests/pathToolPolish.test.ts tests/pathEditGate.test.ts tests/walkNewRegion.test.ts tests/overworldInput.test.ts tests/editRegion.test.ts tests/overworldIslands.test.ts tests/biomeNotes.test.ts tests/biomeGenerators.test.ts tests/biomeClimate.test.ts tests/biomePool.test.ts tests/worldTypes.test.ts tests/worldTypeStars.test.ts tests/smokeSuite.test.ts tests/workModeCoverage.test.ts tests/workModeUndo.test.ts tests/moonLinks.test.ts tests/palettePreview.test.ts tests/calloutSync.test.ts tests/missingMaps.test.ts tests/regionGenerator.test.ts tests/overworldPaths.test.ts tests/pathForks.test.ts tests/overworldTools.test.ts tests/noteFormats.test.ts tests/spaceSetup.test.ts tests/tableGolden.test.ts tests/tableTypedRows.test.ts tests/tableAttributes.test.ts tests/tableHeadingRef.test.ts tests/tableResolve.test.ts tests/generatorRoles.test.ts tests/starScatterTables.test.ts tests/orbitsTables.test.ts tests/noteRefLinks.test.ts tests/tablePickerGroups.test.ts tests/moduleCharacterisation.test.ts tests/moduleBoundary.test.ts", "test:integration": "tsx --tsconfig ./tsconfig.test.json --import ./tests/register.mjs --test tests/integration/*.integration.ts", "smoke": "node dev/smoke/cli.mjs", "premerge": "node dev/smoke/premerge.mjs", diff --git a/src/HexmakerPlugin.ts b/src/HexmakerPlugin.ts index 3eeeadf3..04db0930 100644 --- a/src/HexmakerPlugin.ts +++ b/src/HexmakerPlugin.ts @@ -44,9 +44,9 @@ import { PathsService } from "./paths/PathsService"; import { RoutePins } from "./paths/routePins"; import { setPathEditMapLookup } from "./paths/editGate"; import { PaletteEditorView } from "./palettes/PaletteEditorView"; -import { enabledKinds, isIconHiddenByKind, newTerrains, paletteKind, resolveMapKinds, sectionKindFor, sectionWordsFor, terrainsForTables, type MapKind, type SectionWordsFn } from "./mapKinds"; +import { enabledKinds, isIconHiddenByKind, newTerrains, paletteKind, resolveMapKinds, terrainsForTables, type MapKind, type SectionWordsFn } from "./mapKinds"; import { defaultPaletteFor, resolveDefaultPalette, resolveExpandedDefault, setPaletteTerrainSource } from "./palettes/paletteOptions"; -import { mapAncestors } from "./hex-map/submapNav"; +import { isSpaceMapIn, sectionWordsIn } from "./maps/mapKindQueries"; import { isDebugMode, onDebugModeChange, setDebugMode } from "./ui/debugMode"; import { getPreset, @@ -2836,11 +2836,7 @@ export default class HexmakerPlugin extends Plugin { * offered there even when the Space map type is off. */ isSpaceMap(mapName: string): boolean { - const chain = [...mapAncestors(mapName, (m) => this.parentOf(m)?.map), mapName]; - return chain.some((m) => { - const paletteName = this.getMap(m)?.paletteName; - return !!paletteName && this.getPaletteOrPresetKind(paletteName) === "space"; - }); + return isSpaceMapIn(this, mapName); } /** @@ -2849,13 +2845,7 @@ export default class HexmakerPlugin extends Plugin { * its parents. Headings in notes don't change. No map = the usual words. */ sectionWordsFor(mapName: string | undefined): SectionWordsFn { - if (!mapName || !this.getMap(mapName)) return sectionWordsFor(undefined); - const chain = [mapName, ...mapAncestors(mapName, (m) => this.parentOf(m)?.map).reverse()]; - const palettes = chain.map((m) => this.getMap(m)?.paletteName); - const terrains = palettes.map((n) => (n ? this.getPaletteOrPresetTerrains(n) : [])); - // A palette's declared type counts too (a planet map on Space - Planet). - const declared = palettes.map((n) => (n ? this.getPaletteByName(n)?.kind ?? getPreset(n)?.kind : undefined)); - return sectionWordsFor(sectionKindFor(terrains, undefined, declared)); + return sectionWordsIn(this, mapName); } getAllTerrains(): TerrainColor[] { diff --git a/src/maps/mapKindQueries.ts b/src/maps/mapKindQueries.ts new file mode 100644 index 00000000..09d8a62c --- /dev/null +++ b/src/maps/mapKindQueries.ts @@ -0,0 +1,42 @@ +/** + * Map-type questions about one map, answered from the map tree: the map, + * its parent, and so on up. Pure: the host hands over the lookups, so the + * plugin and the tests ask the same code. + */ + +import type { TerrainColor } from "../types"; +import { mapAncestors } from "../hex-map/submapNav"; +import { getPreset } from "../palettes/presets"; +import { paletteKind, sectionKindFor, sectionWordsFor, type SectionWordsFn } from "../mapKinds"; + +export interface MapKindHost { + getMap(name: string): { paletteName?: string } | undefined; + parentOf(name: string): { map: string } | undefined; + getPaletteByName(name: string): { kind?: string; terrains: TerrainColor[] } | undefined; +} + +/** The palette names from `mapName` up its parents (nearest first). */ +export function paletteChain(host: MapKindHost, mapName: string): (string | undefined)[] { + const chain = [mapName, ...mapAncestors(mapName, (m) => host.parentOf(m)?.map).reverse()]; + return chain.map((m) => host.getMap(m)?.paletteName); +} + +const paletteOrPreset = (host: MapKindHost, name: string) => host.getPaletteByName(name) ?? getPreset(name); + +/** + * Is `mapName` in space: its palette, or any ancestor map's (a planet + * submap of a star system), is a space palette? + */ +export function isSpaceMapIn(host: MapKindHost, mapName: string): boolean { + return paletteChain(host, mapName).some((n) => !!n && paletteKind(paletteOrPreset(host, n)) === "space"); +} + +/** Display words for link sections on `mapName` (G4b); see HexmakerPlugin.sectionWordsFor. */ +export function sectionWordsIn(host: MapKindHost, mapName: string | undefined): SectionWordsFn { + if (!mapName || !host.getMap(mapName)) return sectionWordsFor(undefined); + const palettes = paletteChain(host, mapName); + const terrains = palettes.map((n) => (n ? host.getPaletteByName(n)?.terrains ?? getPreset(n)?.terrains ?? [] : [])); + // A palette's declared type counts too (a planet map on Space - Planet). + const declared = palettes.map((n) => (n ? host.getPaletteByName(n)?.kind ?? getPreset(n)?.kind : undefined)); + return sectionWordsFor(sectionKindFor(terrains, undefined, declared)); +} diff --git a/tests/fixtures/moduleBoundary.json b/tests/fixtures/moduleBoundary.json new file mode 100644 index 00000000..433e66af --- /dev/null +++ b/tests/fixtures/moduleBoundary.json @@ -0,0 +1,51 @@ +{ + "imports": { + "src/HexmakerPlugin.ts -> space": 2, + "src/HexmakerPlugin.ts -> world-maps": 5, + "src/arrival/ArrivalService.ts -> world-maps": 2, + "src/arrival/arrival.ts -> space": 1, + "src/hex-map/BiomeLibraryModal.ts -> world-maps": 5, + "src/hex-map/BiomeModals.ts -> world-maps": 5, + "src/hex-map/EditRegionModal.ts -> world-maps": 4, + "src/hex-map/HexEditorModal.ts -> world-maps": 2, + "src/hex-map/HexMapView.ts -> world-maps": 7, + "src/hex-map/MapModal.ts -> world-maps": 3, + "src/hex-map/OverworldModals.ts -> world-maps": 9, + "src/hex-map/mapTablesForm.ts -> space": 1, + "src/hex-map/newChildMap.ts -> world-maps": 1, + "src/hex-map/overworldLayer.ts -> world-maps": 6, + "src/hex-map/overworldMinimap.ts -> world-maps": 4, + "src/maps/mapNav.ts -> world-maps": 1, + "src/noteFormatUpgrade.ts -> space": 1, + "src/random-tables/tableConditions.ts -> space": 1, + "src/random-tables/tableConditions.ts -> world-maps": 1, + "src/worldgen/BiomePanel.ts -> world-maps": 6, + "src/worldgen/NewMapSetupModal.ts -> space": 2, + "src/worldgen/WalkRegionModal.ts -> world-maps": 3, + "src/worldgen/generators.ts -> world-maps": 1, + "src/worldgen/procedural/orbits.ts -> space": 1, + "src/worldgen/regionGenerator.ts -> world-maps": 4, + "src/worldgen/registry.ts -> space": 1, + "src/worldgen/registry.ts -> world-maps": 2 + }, + "decisions": { + "src/HexmakerPlugin.ts -> space": 3, + "src/SetupWizardView.ts -> space": 2, + "src/arrival/ArrivalService.ts -> space": 3, + "src/hex-map/OverworldModals.ts -> space": 2, + "src/hex-map/mapTablesForm.ts -> space": 1, + "src/hex-map/newChildMap.ts -> space": 1, + "src/mapKinds.ts -> space": 10, + "src/mapKinds.ts -> world": 1, + "src/maps/mapKindQueries.ts -> space": 1, + "src/palettes/PaletteEditorView.ts -> space": 4, + "src/terrainTypes.ts -> space": 1, + "src/utils.ts -> space": 1, + "src/utils.ts -> world": 1, + "src/worldgen/GeneratorPanel.ts -> space": 4, + "src/worldgen/NewMapSetupModal.ts -> space": 6, + "src/worldgen/WalkRegionModal.ts -> space": 2, + "src/worldgen/registry.ts -> space": 5, + "src/worldgen/registry.ts -> world": 1 + } +} diff --git a/tests/fixtures/moduleCharacterisation.json b/tests/fixtures/moduleCharacterisation.json new file mode 100644 index 00000000..90f7057b --- /dev/null +++ b/tests/fixtures/moduleCharacterisation.json @@ -0,0 +1,1973 @@ +{ + "mapKinds": [ + { + "id": "world", + "label": "World / fantasy overland", + "description": "Continents, regions and local areas: forests, mountains, coasts. Includes the Limited and Expanded palettes, the Region detail generator and the Places icon pack (towns, castles, ruins…).", + "iconPrefix": "place-" + }, + { + "id": "space", + "label": "Space", + "description": "Sector charts, star systems and planets: Space - Sector, Space - System and Space - Planet palettes, Star scatter, Orbits and Planet surface generators, planet generators, the space icon pack. Pick Space alone and nothing fantasy is installed.", + "iconPrefix": "space-", + "sectionWords": { + "Towns": { + "label": "Settlements", + "one": "Settlement", + "noun": "a settlement" + }, + "Dungeons": { + "label": "Sites", + "one": "Site", + "noun": "a site" + }, + "Features": { + "label": "Points of Interest", + "one": "Point of interest", + "noun": "a point of interest" + }, + "Quests": { + "label": "Missions", + "one": "Mission", + "noun": "a mission" + } + } + } + ], + "terrainGroups": [ + { + "id": "water", + "label": "Water" + }, + { + "id": "land", + "label": "Land" + }, + { + "id": "space", + "label": "Space" + } + ], + "terrainTypes": [ + "deep-water|world|water|Deep water|trench,abyss,deep", + "water|world|water|Water|ocean,sea,water,lake,river", + "shallows|world|water|Shallows|shallow,reef,shoal", + "coast|world|land|Coast|beach,coast,shore,salt flat,sand", + "grassland|world|land|Grassland|grass,plain,meadow,steppe,prairie,savanna,field,farm", + "forest|world|land|Forest|forest,wood,evergreen,pine,taiga,grove", + "jungle|world|land|Jungle|jungle,rainforest", + "wetland|world|land|Wetland|swamp,marsh,bog,fen,mire", + "hills|world|land|Hills|hill,highland,downs", + "mountains|world|land|Mountains|mountain,cliff,ridge,crag", + "peaks|world|land|Peaks|peak,summit,alpine", + "snow|world|land|Snow / ice|snow,ice,glacier,tundra,frozen", + "desert|world|land|Desert|desert,dune,cactus,arid", + "badlands|world|land|Badlands|badland,brokenland,waste,canyon,mesa", + "volcanic|world|land|Volcanic|volcan,lava,ash,magma", + "settlement|world|land|Settlement|urban,city,town,village,ruin", + "void|space|space|Void / empty space|void,empty space,deep space", + "jump-limit|space|space|Jump limit (ring)|jump limit", + "nebula|space|space|Nebula / cloud|nebula,dust,cloud", + "rift|space|space|Rift|rift", + "star|space|space|Star|star,sun,dwarf,giant star", + "star-system|space|space|Star system (sector marker)|star system", + "world|space|space|World / planet|world,planet", + "moon|space|space|Moon|moon,satellite", + "gas-giant|space|space|Gas giant|gas giant,ice giant", + "asteroids|space|space|Asteroid belt|asteroid,belt,meteor", + "comet|space|space|Comet|comet", + "debris|space|space|Debris field|debris,wreck", + "station|space|space|Station|station,outpost", + "starport|space|space|Starport|starport,spaceport,port", + "jump-point|space|space|Jump point / gate|jump point,gate", + "anomaly|space|space|Anomaly / hazard|anomaly,black hole,radiation,hazard" + ], + "presets": [ + { + "name": "Expanded", + "kind": "world", + "terrains": [ + "trench|deep-water|#14223d|", + "ocean|water|#29507f|", + "shallows|shallows|#4a82a5|", + "water|water|#60a5fa|", + "urban|settlement|#888888|", + "grass|grassland|#69a168|bw-grassland.png", + "hills|hills|#e0e8a1|bw-hills.png", + "foothills|hills|#81c191|bw-hills.png", + "snow|snow|#e0f2fe|", + "mountains snow|peaks|#bfdbfe|bw-mountains-snow.png", + "desert|desert|#ecdba2|", + "desert rocky|desert|#e6bc60|bw-desert-rocky.png", + "dunes|desert|#eccd7e|bw-dunes.png", + "cactus|desert|#e2b75a|bw-cactus.png", + "cactus heavy|desert|#ddb869|bw-cactus-heavy.png", + "badlands|badlands|#c2410c|bw-badlands.png", + "brokenlands|badlands|#92400e|bw-brokenlands.png", + "forest|forest|#2d9553|bw-forest.png", + "forest heavy|forest|#15803d|bw-forest-heavy.png", + "forested hills|hills|#22c55e|bw-forested-hills.png", + "forested mountain|mountains|#6b9e7c|bw-forested-mountain.png", + "forested mountains|mountains|#466d46|bw-forested-mountains.png", + "mixed forest|forest|#16a34a|bw-forest-mixed.png", + "mixed forest heavy|forest|#15803d|bw-forest-mixed-heavy.png", + "mixed forest hills|hills|#22c55e|bw-forest-mixed-hills.png", + "mixed forest mountain|mountains|#6b9e7c|bw-forest-mixed-mountain.png", + "mixed forest mountains|mountains|#5e8c6a|bw-forest-mixed-mountains.png", + "evergreen|forest|#428a5e|bw-evergreen.png", + "evergreen heavy|forest|#257445|bw-evergreen-heavy.png", + "evergreen hills|hills|#328651|bw-evergreen-hills.png", + "evergreen mountain|mountains|#6b806b|bw-evergreen-mountain.png", + "evergreen mountains|mountains|#8c9d80|bw-evergreen-mountains.png", + "jungle|jungle|#15803d|bw-jungle.png", + "jungle heavy|jungle|#14532d|bw-jungle-heavy.png", + "jungle hills|hills|#4ade80|bw-jungle-hills.png", + "jungle mountain|mountains|#4d7c0f|bw-jungle-mountain.png", + "jungle mountains|mountains|#3f6212|bw-jungle-mountains.png", + "volcano|volcanic|#b91c1c|bw-volcano.png", + "volcano dormant|volcanic|#78350f|bw-volcano-dormant.png", + "cliffs|mountains|#a86f1f|bw-brokenlands.png", + "mountain|mountains|#a77649|bw-mountain.png", + "mountain ridge|mountains|#c55f0d|bw-mountains.png", + "peak|peaks|#78716c|bw-mountain.png", + "marsh|wetland|#909f23|bw-marsh.png", + "swamp|wetland|#4e5214|bw-swamp.png", + "bog|wetland|#432e6b|bw-swamp.png", + "beach|coast|#cac181|bw-grassland.png", + "salt flats|coast|#f7eaba|bw-dunes.png", + "savanna|grassland|#c4b25c|bw-grassland.png", + "river delta|wetland|#5f9a7a|bw-marsh.png" + ], + "pathTypes": [] + }, + { + "name": "Limited", + "kind": "world", + "terrains": [ + "ocean|water|#29507f|", + "grass|grassland|#69a168|bw-grassland.png", + "hill|hills|#e0e8a1|bw-hills.png", + "forest|forest|#2d9553|bw-forest.png", + "mountain|mountains|#a77649|bw-mountain.png", + "desert|desert|#ecdba2|", + "snow|snow|#e0f2fe|" + ], + "pathTypes": [] + }, + { + "name": "Space - Sector", + "kind": "space", + "terrains": [ + "empty space|void|#0b1020|", + "nebula|nebula|#3b2a5c|", + "dust cloud|nebula|#4a3b33|space-dust-cloud.svg", + "rift|rift|#020308|space-portal.svg", + "garden world|world|#3f8f5a|space-world.svg", + "ocean world|world|#2e6fa8|space-water-world.svg", + "desert world|world|#b8924f|space-ring-segments.svg", + "ice world|world|#9cc3d9|space-frozen-orb.svg", + "barren world|world|#6e6c74|space-moon.svg", + "molten world|world|#a8402a|space-planet-core.svg", + "asteroid belt|asteroids|#5e554d|space-asteroid.png", + "gas giant|gas-giant|#b07d45|space-ringed-planet.svg", + "star system|star-system|#c9a227|space-orbit.svg", + "deep-space station|station|#7d8794|space-orbital.svg", + "black hole|anomaly|#000000|space-target-outline.svg", + "anomaly|anomaly|#7c3aad|space-anomaly.svg" + ], + "pathTypes": [ + "Jump route", + "Trade route" + ], + "childPalette": "Space - System", + "pathRoles": { + "routes": "Jump route" + }, + "submapDefaults": { + "garden world": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + }, + "ocean world": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + }, + "desert world": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + }, + "ice world": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + }, + "barren world": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + }, + "molten world": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + }, + "asteroid belt": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + }, + "gas giant": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + }, + "star system": { + "palette": "Space - System", + "cols": 13, + "rows": 13, + "generator": "procedural:orbits", + "baseTerrain": "void" + } + } + }, + { + "name": "Space - System", + "kind": "space", + "terrains": [ + "void|void|#05070f|", + "nebula|nebula|#3b2a5c|", + "jump limit|jump-limit|#1d1838|space-ring-dashed.svg", + "yellow star|star|#f2c94c|space-sun.svg", + "red dwarf|star|#d9573b|space-sun.svg", + "blue giant|star|#79a8ff|space-sun.svg", + "white dwarf|star|#e3e9f7|space-sun.svg", + "brown dwarf|star|#6f4434|space-sun.svg", + "terrestrial planet|world|#3f8f5a|space-world.svg", + "ocean planet|world|#2e6fa8|space-water-world.svg", + "desert planet|world|#b8924f|space-ring-segments.svg", + "ice planet|world|#9cc3d9|space-frozen-orb.svg", + "rocky planet|world|#7a7068|space-stone-sphere.svg", + "molten planet|world|#a8402a|space-planet-core.svg", + "gas giant|gas-giant|#b07d45|space-ringed-planet.svg", + "ice giant|gas-giant|#5f9fb8|space-frozen-orb.svg", + "moon|moon|#9a9aa2|space-moon.svg", + "asteroid belt|asteroids|#5e554d|space-asteroid.png", + "comet|comet|#8fb3c4|space-meteor.svg", + "space station|station|#7d8794|space-orbital.svg", + "starport|starport|#c0c7cf|space-star-gate.svg", + "jump point|jump-point|#5b3fc4|space-portal.svg", + "debris field|debris|#4d4640|space-dots-hex.svg", + "radiation belt|anomaly|#7d6a1f|space-radioactive.svg" + ], + "pathTypes": [ + "Orbit" + ], + "pathRoles": { + "orbits": "Orbit" + }, + "submapDefaults": { + "terrestrial planet": { + "palette": "Space - Planet", + "cols": 20, + "rows": 14, + "generator": "procedural:planet-surface", + "options": { + "water": "65", + "climate": "temperate", + "relief": "normal" + }, + "baseTerrain": "ocean" + }, + "ocean planet": { + "palette": "Space - Planet", + "cols": 20, + "rows": 14, + "generator": "procedural:planet-surface", + "options": { + "water": "85", + "climate": "lush", + "relief": "normal" + }, + "baseTerrain": "ocean" + }, + "desert planet": { + "palette": "Space - Planet", + "cols": 20, + "rows": 14, + "generator": "procedural:planet-surface", + "options": { + "water": "10", + "climate": "arid", + "relief": "normal" + }, + "baseTerrain": "dunes" + }, + "ice planet": { + "palette": "Space - Planet", + "cols": 20, + "rows": 14, + "generator": "procedural:planet-surface", + "options": { + "water": "30", + "climate": "frozen", + "relief": "normal" + }, + "baseTerrain": "ocean" + }, + "rocky planet": { + "palette": "Space - Planet", + "cols": 20, + "rows": 14, + "generator": "procedural:planet-surface", + "options": { + "water": "10", + "climate": "arid", + "relief": "rugged" + }, + "baseTerrain": "regolith" + }, + "molten planet": { + "palette": "Space - Planet", + "cols": 20, + "rows": 14, + "generator": "procedural:planet-surface", + "options": { + "water": "10", + "climate": "volcanic", + "relief": "rugged" + }, + "baseTerrain": "regolith" + }, + "moon": { + "palette": "Space - Planet", + "cols": 20, + "rows": 14, + "generator": "procedural:planet-surface", + "options": { + "water": "10", + "climate": "frozen", + "relief": "rugged" + }, + "baseTerrain": "regolith" + } + } + }, + { + "name": "Space - Planet", + "kind": "space", + "terrains": [ + "deep ocean|deep-water|#10233f|", + "ocean|water|#245a87|", + "shallows|shallows|#3f86a3|", + "shore|coast|#b9ad84|", + "plains|grassland|#6f9a5a|bw-grassland.png", + "forest|forest|#2f6b4a|bw-forest.png", + "jungle|jungle|#1f6b3a|bw-jungle.png", + "toxic marsh|wetland|#7d8f2a|bw-swamp.png", + "regolith|badlands|#8a8178|bw-desert-rocky.png", + "bare rock|badlands|#6b6560|bw-brokenlands.png", + "dunes|desert|#d6b46a|bw-dunes.png", + "ice|snow|#dbeaf5|", + "hills|hills|#a49a72|bw-hills.png", + "crater field|hills|#7b7268|space-ring.svg", + "mountains|mountains|#7a6a58|bw-mountains.png", + "peaks|peaks|#c9d3dc|bw-mountains-snow.png", + "lava field|volcanic|#8f2d1c|bw-volcano.png", + "crystal field|badlands|#6d5bb5|space-twinkle.svg", + "ruins|settlement|#8c7b6b|space-debris.svg", + "colony|settlement|#9ca3af|space-beacon-outline.svg" + ], + "pathTypes": [] + } + ], + "bundledIcons": [ + "bw-badlands.png", + "bw-brokenlands.png", + "bw-cactus.png", + "bw-cactus-heavy.png", + "bw-desert.png", + "bw-desert-rocky.png", + "bw-dunes.png", + "bw-evergreen.png", + "bw-evergreen-heavy.png", + "bw-evergreen-hills.png", + "bw-evergreen-mountain.png", + "bw-evergreen-mountains.png", + "bw-forest.png", + "bw-forested-hills.png", + "bw-forested-mountain.png", + "bw-forested-mountains.png", + "bw-forest-heavy.png", + "bw-forest-mixed.png", + "bw-forest-mixed-heavy.png", + "bw-forest-mixed-hills.png", + "bw-forest-mixed-mountain.png", + "bw-forest-mixed-mountains.png", + "bw-grassland.png", + "bw-hills.png", + "bw-jungle.png", + "bw-jungle-heavy.png", + "bw-jungle-hills.png", + "bw-jungle-mountain.png", + "bw-jungle-mountains.png", + "bw-marsh.png", + "bw-mountain.png", + "bw-mountains.png", + "bw-mountain-snow.png", + "bw-mountains-snow.png", + "bw-swamp.png", + "bw-volcano.png", + "bw-volcano-dormant.png", + "place-village.svg", + "place-huts-village.svg", + "place-medieval-village-01.svg", + "place-house.svg", + "place-family-house.svg", + "place-hut.svg", + "place-viking-longhouse.svg", + "place-windmill.svg", + "place-harbor-dock.svg", + "place-tavern-sign.svg", + "place-treehouse.svg", + "place-castle.svg", + "place-elven-castle.svg", + "place-hill-fort.svg", + "place-military-fort.svg", + "place-locked-fortress.svg", + "place-medieval-gate.svg", + "place-defensive-wall.svg", + "place-stone-tower.svg", + "place-watchtower.svg", + "place-white-tower.svg", + "place-guarded-tower.svg", + "place-tower-flag.svg", + "place-evil-tower.svg", + "place-clock-tower.svg", + "place-lighthouse.svg", + "place-castle-ruins.svg", + "place-ancient-ruins.svg", + "place-tower-fall.svg", + "place-broken-wall.svg", + "place-damaged-house.svg", + "place-spooky-house.svg", + "place-tombstone.svg", + "place-church.svg", + "place-greek-temple.svg", + "place-egyptian-temple.svg", + "place-byzantin-temple.svg", + "place-temple-gate.svg", + "place-shinto-shrine.svg", + "place-fire-shrine.svg", + "place-crystal-shrine.svg", + "place-mayan-pyramid.svg", + "place-great-pyramid.svg", + "place-egyptian-pyramids.svg", + "place-camping-tent.svg", + "place-campfire.svg", + "place-forest-camp.svg", + "place-desert-camp.svg", + "place-goblin-camp.svg", + "place-barracks-tent.svg", + "place-cave-entrance.svg", + "place-mountain-cave.svg", + "place-dungeon-gate.svg", + "place-gold-mine.svg", + "place-mine-wagon.svg", + "space-anomaly.svg", + "space-asteroid.png", + "space-atom-outline.svg", + "space-beacon-outline.svg", + "space-black-hole.svg", + "space-comet.svg", + "space-debris.svg", + "space-defense-satellite.svg", + "space-dots-hex.svg", + "space-double-ring.svg", + "space-dust-cloud.svg", + "space-earth.svg", + "space-frozen-orb.svg", + "space-galaxy.svg", + "space-meteor-outline.svg", + "space-meteor.svg", + "space-moon-outline.svg", + "space-moon.svg", + "space-orbit-outline.svg", + "space-orbit.svg", + "space-orbital.svg", + "space-planet-core.svg", + "space-planet-outline.svg", + "space-planet.svg", + "space-portal.svg", + "space-radial-balance.svg", + "space-radioactive.svg", + "space-raider-a.png", + "space-raider-b.png", + "space-raider-c.png", + "space-raider-d.png", + "space-ring-dashed.svg", + "space-ring-segments.svg", + "space-ring.svg", + "space-ringed-planet.svg", + "space-rocket.svg", + "space-satellite-a.png", + "space-satellite-b.png", + "space-satellite-c.png", + "space-satellite-d.png", + "space-shield-outline.svg", + "space-ship-a.png", + "space-ship-b.png", + "space-ship-c.png", + "space-ship-d.png", + "space-ship-f.png", + "space-ship-g.png", + "space-ship-i.png", + "space-ship-j.png", + "space-ship-k.png", + "space-ship-l.png", + "space-ship-sides-a.png", + "space-star-gate.svg", + "space-star-large.png", + "space-star-medium.png", + "space-star-swirl.svg", + "space-station-a.png", + "space-station-b.png", + "space-station-c.png", + "space-station.svg", + "space-stone-sphere.svg", + "space-sun-outline.svg", + "space-sun-rays.svg", + "space-sun.svg", + "space-target-outline.svg", + "space-twinkle.svg", + "space-ufo.svg", + "space-vortex.svg", + "space-water-world.svg", + "space-world.svg" + ], + "iconPackLabels": { + "terrain": "Terrain", + "places": "Places", + "space": "Space", + "custom": "Custom" + }, + "iconPack": { + "bw-forest.png": "terrain", + "place-castle.svg": "places", + "space-sun.svg": "space", + "my-own.png": "custom", + "bw-badlands.png": "terrain", + "bw-evergreen-hills.png": "terrain", + "bw-forest-mixed-heavy.png": "terrain", + "bw-jungle-mountain.png": "terrain", + "bw-volcano-dormant.png": "terrain", + "place-harbor-dock.svg": "places", + "place-defensive-wall.svg": "places", + "place-castle-ruins.svg": "places", + "place-egyptian-temple.svg": "places", + "place-camping-tent.svg": "places", + "place-gold-mine.svg": "places", + "space-defense-satellite.svg": "space", + "space-moon-outline.svg": "space", + "space-radial-balance.svg": "space", + "space-ringed-planet.svg": "space", + "space-ship-c.png": "space", + "space-star-gate.svg": "space", + "space-sun-outline.svg": "space" + }, + "iconLabel": { + "bw-forest.png": "forest", + "place-castle.svg": "castle", + "space-sun.svg": "sun", + "my-own.png": "my own", + "bw-badlands.png": "badlands", + "bw-evergreen-hills.png": "evergreen hills", + "bw-forest-mixed-heavy.png": "forest mixed heavy", + "bw-jungle-mountain.png": "jungle mountain", + "bw-volcano-dormant.png": "volcano dormant", + "place-harbor-dock.svg": "harbor dock", + "place-defensive-wall.svg": "defensive wall", + "place-castle-ruins.svg": "castle ruins", + "place-egyptian-temple.svg": "egyptian temple", + "place-camping-tent.svg": "camping tent", + "place-gold-mine.svg": "gold mine", + "space-defense-satellite.svg": "defense satellite", + "space-moon-outline.svg": "moon outline", + "space-radial-balance.svg": "radial balance", + "space-ringed-planet.svg": "ringed planet", + "space-ship-c.png": "ship c", + "space-star-gate.svg": "star gate", + "space-sun-outline.svg": "sun outline" + }, + "sortIcons": [ + "bw-badlands.png", + "bw-brokenlands.png", + "bw-cactus-heavy.png", + "bw-cactus.png", + "bw-desert-rocky.png", + "bw-desert.png", + "bw-dunes.png", + "bw-evergreen-heavy.png", + "bw-evergreen-hills.png", + "bw-evergreen-mountain.png", + "bw-evergreen-mountains.png", + "bw-evergreen.png", + "bw-forest-heavy.png", + "bw-forest-mixed-heavy.png", + "bw-forest-mixed-hills.png", + "bw-forest-mixed-mountain.png", + "bw-forest-mixed-mountains.png", + "bw-forest-mixed.png", + "bw-forest.png", + "bw-forested-hills.png", + "bw-forested-mountain.png", + "bw-forested-mountains.png", + "bw-grassland.png", + "bw-hills.png", + "bw-jungle-heavy.png", + "bw-jungle-hills.png", + "bw-jungle-mountain.png", + "bw-jungle-mountains.png", + "bw-jungle.png", + "bw-marsh.png", + "bw-mountain-snow.png", + "bw-mountain.png", + "bw-mountains-snow.png", + "bw-mountains.png", + "bw-swamp.png", + "bw-volcano-dormant.png", + "bw-volcano.png", + "place-village.svg", + "place-huts-village.svg", + "place-medieval-village-01.svg", + "place-house.svg", + "place-family-house.svg", + "place-hut.svg", + "place-viking-longhouse.svg", + "place-windmill.svg", + "place-harbor-dock.svg", + "place-tavern-sign.svg", + "place-treehouse.svg", + "place-castle.svg", + "place-elven-castle.svg", + "place-hill-fort.svg", + "place-military-fort.svg", + "place-locked-fortress.svg", + "place-medieval-gate.svg", + "place-defensive-wall.svg", + "place-stone-tower.svg", + "place-watchtower.svg", + "place-white-tower.svg", + "place-guarded-tower.svg", + "place-tower-flag.svg", + "place-evil-tower.svg", + "place-clock-tower.svg", + "place-lighthouse.svg", + "place-castle-ruins.svg", + "place-ancient-ruins.svg", + "place-tower-fall.svg", + "place-broken-wall.svg", + "place-damaged-house.svg", + "place-spooky-house.svg", + "place-tombstone.svg", + "place-church.svg", + "place-greek-temple.svg", + "place-egyptian-temple.svg", + "place-byzantin-temple.svg", + "place-temple-gate.svg", + "place-shinto-shrine.svg", + "place-fire-shrine.svg", + "place-crystal-shrine.svg", + "place-mayan-pyramid.svg", + "place-great-pyramid.svg", + "place-egyptian-pyramids.svg", + "place-camping-tent.svg", + "place-campfire.svg", + "place-forest-camp.svg", + "place-desert-camp.svg", + "place-goblin-camp.svg", + "place-barracks-tent.svg", + "place-cave-entrance.svg", + "place-mountain-cave.svg", + "place-dungeon-gate.svg", + "place-gold-mine.svg", + "place-mine-wagon.svg", + "space-anomaly.svg", + "space-asteroid.png", + "space-atom-outline.svg", + "space-beacon-outline.svg", + "space-black-hole.svg", + "space-comet.svg", + "space-debris.svg", + "space-defense-satellite.svg", + "space-dots-hex.svg", + "space-double-ring.svg", + "space-dust-cloud.svg", + "space-earth.svg", + "space-frozen-orb.svg", + "space-galaxy.svg", + "space-meteor-outline.svg", + "space-meteor.svg", + "space-moon-outline.svg", + "space-moon.svg", + "space-orbit-outline.svg", + "space-orbit.svg", + "space-orbital.svg", + "space-planet-core.svg", + "space-planet-outline.svg", + "space-planet.svg", + "space-portal.svg", + "space-radial-balance.svg", + "space-radioactive.svg", + "space-raider-a.png", + "space-raider-b.png", + "space-raider-c.png", + "space-raider-d.png", + "space-ring-dashed.svg", + "space-ring-segments.svg", + "space-ring.svg", + "space-ringed-planet.svg", + "space-rocket.svg", + "space-satellite-a.png", + "space-satellite-b.png", + "space-satellite-c.png", + "space-satellite-d.png", + "space-shield-outline.svg", + "space-ship-a.png", + "space-ship-b.png", + "space-ship-c.png", + "space-ship-d.png", + "space-ship-f.png", + "space-ship-g.png", + "space-ship-i.png", + "space-ship-j.png", + "space-ship-k.png", + "space-ship-l.png", + "space-ship-sides-a.png", + "space-star-gate.svg", + "space-star-large.png", + "space-star-medium.png", + "space-star-swirl.svg", + "space-station-a.png", + "space-station-b.png", + "space-station-c.png", + "space-station.svg", + "space-stone-sphere.svg", + "space-sun-outline.svg", + "space-sun-rays.svg", + "space-sun.svg", + "space-target-outline.svg", + "space-twinkle.svg", + "space-ufo.svg", + "space-vortex.svg", + "space-water-world.svg", + "space-world.svg" + ], + "iconPackTabs": [ + [ + "all", + "All", + 5 + ], + [ + "terrain", + "Terrain", + 3 + ], + [ + "places", + "Places", + 2 + ], + [ + "custom", + "Custom", + 0 + ] + ], + "generatorMapKind": { + "planet": "space", + "space": "space", + " Planet ": "space", + "world": "world", + "dungeon": null, + "(blank)": null + }, + "paletteKind": { + "Expanded": "world", + "Limited": "world", + "Space - Sector": "space", + "Space - System": "space", + "Space - Planet": "space", + "Custom space": "space", + "Custom plain": "world", + "Custom land": "world", + "Edge": "world" + }, + "isSpacePalette": { + "Expanded": false, + "Limited": false, + "Space - Sector": true, + "Space - System": true, + "Space - Planet": false, + "Custom space": true, + "Custom plain": false, + "Custom land": false, + "Edge": true + }, + "suggestBaseTerrain": { + "Expanded": null, + "Limited": null, + "Space - Sector": "empty space", + "Space - System": "void", + "Space - Planet": null, + "Custom space": "nothing", + "Custom plain": null, + "Custom land": null, + "Edge": "nothing" + }, + "refinedSpaceType": [ + "moon|world -> moon", + "Luna satellite|world -> moon", + "comet|asteroids -> comet", + "wreck|asteroids -> debris", + "jump gate|station -> jump-point", + "starport|station -> starport", + "jump limit|void -> jump-limit", + "star system|star -> star-system", + "forest|forest -> " + ], + "inferTerrainType": [ + "dark forest| -> forest", + "dark forest|world -> forest", + "dark forest|space -> ", + "gas giant| -> gas-giant", + "gas giant|world -> ", + "gas giant|space -> gas-giant", + "ice moon| -> moon", + "ice moon|world -> snow", + "ice moon|space -> moon", + "black lake| -> water", + "black lake|world -> water", + "black lake|space -> ", + "planet| -> world", + "planet|world -> ", + "planet|space -> world", + "red dwarf| -> star", + "red dwarf|world -> ", + "red dwarf|space -> star", + "salt flat| -> coast", + "salt flat|world -> coast", + "salt flat|space -> " + ], + "normalizeTerrainType": [ + "Deep-Water -> deep-water", + "snow -> snow", + "Void / empty space -> void", + "gas giant -> gas-giant", + "nope -> " + ], + "engineRoles": [ + "sector-hexes|procedural:star-scatter|Sector hexes|world,gas-giant,asteroids,station,starport,jump-point,anomaly", + "star|procedural:orbits|Star|star", + "inner-orbits|procedural:orbits|Inner orbits|world,gas-giant,asteroids", + "habitable-orbits|procedural:orbits|Habitable orbits|world,gas-giant,asteroids", + "outer-orbits|procedural:orbits|Outer orbits|world,gas-giant,asteroids" + ], + "defaultPathTypeFor": { + "routes": "Jump route", + "orbits": "Orbit", + "none": null + }, + "childKindText": { + "space": { + "region": { + "title": "Region", + "desc": "This stretch of space up close, at the same scale as the regions next to it. Not for a single star system or planet." + }, + "location": { + "title": "Location", + "desc": "A star system, planet or station in this hex, with its own map and size. Pick this for a system or a planet." + } + }, + "other": { + "region": { + "title": "Region", + "desc": "This hex up close. Same scale for every hex on this map, and it lines up with the regions next to it." + }, + "location": { + "title": "Location", + "desc": "A separate place in this hex, like a town or dungeon, with its own size." + } + } + }, + "moonLinks": [ + [ + "1_1", + "1_2" + ], + [ + "1_1", + "2_1" + ] + ], + "perKinds": { + "world": { + "resolveMapKinds": [ + "world" + ], + "defaultIconPack": "all", + "iconHidden": [ + "space-sun.svg", + "space-defense-satellite.svg", + "space-moon-outline.svg", + "space-radial-balance.svg", + "space-ringed-planet.svg", + "space-ship-c.png", + "space-star-gate.svg", + "space-sun-outline.svg" + ], + "terrainsForTables": [ + "trench", + "ocean", + "shallows", + "water", + "urban", + "grass", + "hills", + "foothills", + "snow", + "mountains snow", + "desert", + "desert rocky", + "dunes", + "cactus", + "cactus heavy", + "badlands", + "brokenlands", + "forest", + "forest heavy", + "forested hills", + "forested mountain", + "forested mountains", + "mixed forest", + "mixed forest heavy", + "mixed forest hills", + "mixed forest mountain", + "mixed forest mountains", + "evergreen", + "evergreen heavy", + "evergreen hills", + "evergreen mountain", + "evergreen mountains", + "jungle", + "jungle heavy", + "jungle hills", + "jungle mountain", + "jungle mountains", + "volcano", + "volcano dormant", + "cliffs", + "mountain", + "mountain ridge", + "peak", + "marsh", + "swamp", + "bog", + "beach", + "salt flats", + "savanna", + "river delta", + "hill", + "empty space", + "nebula", + "dust cloud", + "rift", + "garden world", + "ocean world", + "desert world", + "ice world", + "barren world", + "molten world", + "asteroid belt", + "gas giant", + "star system", + "deep-space station", + "black hole", + "anomaly", + "void", + "jump limit", + "yellow star", + "red dwarf", + "blue giant", + "white dwarf", + "brown dwarf", + "terrestrial planet", + "ocean planet", + "desert planet", + "ice planet", + "rocky planet", + "molten planet", + "ice giant", + "moon", + "comet", + "space station", + "starport", + "jump point", + "debris field", + "radiation belt", + "deep ocean", + "shore", + "plains", + "toxic marsh", + "regolith", + "bare rock", + "ice", + "crater field", + "mountains", + "peaks", + "lava field", + "crystal field", + "ruins", + "colony", + "nothing", + "sun", + "rock", + "red", + "blue", + "woods", + "sea" + ], + "generatorShown": { + "world|ctx=false": true, + "world|ctx=true": true, + "space|ctx=false": false, + "space|ctx=true": true, + "none|ctx=false": true, + "none|ctx=true": true + }, + "visible": { + "noContext": [ + "blank", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes" + ], + "spaceContext": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "selectedPlanet": [ + "blank", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ] + }, + "newMapChoices": { + "Expanded": [ + "procedural:overland", + "procedural:world-biomes" + ], + "Limited": [ + "procedural:overland", + "procedural:world-biomes" + ], + "Space - Sector": [ + "procedural:star-scatter" + ], + "Space - System": [ + "procedural:orbits" + ], + "Space - Planet": [ + "procedural:overland", + "procedural:world-biomes" + ], + "Custom space": [ + "procedural:orbits" + ], + "Custom plain": [], + "Custom land": [], + "Edge": [] + }, + "firstMapGenerator": { + "Expanded": "procedural:overland", + "Limited": "procedural:overland", + "Space - Sector": "procedural:star-scatter", + "Space - System": "blank", + "Space - Planet": "procedural:overland", + "Custom space": "blank", + "Custom plain": "blank", + "Custom land": "blank", + "Edge": "blank" + }, + "planKindContent": { + "install": [], + "remove": [ + "Space - Sector", + "Space - System", + "Space - Planet" + ], + "newKinds": [], + "done": [ + "world" + ] + }, + "isSpaceMap": { + "sector": true, + "system": true, + "planet": true, + "world": false, + "region": false, + "surface-on-system": true, + "custom-space": true, + "custom-space-in-world": true, + "plain": false, + "plain-in-sector": true, + "land": false, + "land-in-system": true, + "edge": false, + "edge-child": false, + "limited-under-edge": false + } + }, + "space": { + "resolveMapKinds": [ + "space" + ], + "defaultIconPack": "space", + "iconHidden": [ + "place-castle.svg", + "place-harbor-dock.svg", + "place-defensive-wall.svg", + "place-castle-ruins.svg", + "place-egyptian-temple.svg", + "place-camping-tent.svg", + "place-gold-mine.svg" + ], + "terrainsForTables": [ + "empty space", + "nebula", + "dust cloud", + "rift", + "garden world", + "ocean world", + "desert world", + "ice world", + "barren world", + "molten world", + "asteroid belt", + "gas giant", + "star system", + "deep-space station", + "black hole", + "anomaly", + "void", + "jump limit", + "yellow star", + "red dwarf", + "blue giant", + "white dwarf", + "brown dwarf", + "terrestrial planet", + "ocean planet", + "desert planet", + "ice planet", + "rocky planet", + "molten planet", + "ice giant", + "moon", + "comet", + "space station", + "starport", + "jump point", + "debris field", + "radiation belt", + "deep ocean", + "ocean", + "shallows", + "shore", + "plains", + "forest", + "jungle", + "toxic marsh", + "regolith", + "bare rock", + "dunes", + "ice", + "hills", + "crater field", + "mountains", + "peaks", + "lava field", + "crystal field", + "ruins", + "colony", + "nothing", + "sun", + "rock", + "red", + "blue" + ], + "generatorShown": { + "world|ctx=false": false, + "world|ctx=true": false, + "space|ctx=false": true, + "space|ctx=true": true, + "none|ctx=false": true, + "none|ctx=true": true + }, + "visible": { + "noContext": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:planet-surface" + ], + "spaceContext": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:planet-surface" + ], + "selectedPlanet": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:planet-surface" + ] + }, + "newMapChoices": { + "Expanded": [ + "procedural:planet-surface" + ], + "Limited": [ + "procedural:planet-surface" + ], + "Space - Sector": [ + "procedural:star-scatter" + ], + "Space - System": [ + "procedural:orbits" + ], + "Space - Planet": [ + "procedural:planet-surface" + ], + "Custom space": [ + "procedural:orbits" + ], + "Custom plain": [], + "Custom land": [], + "Edge": [] + }, + "firstMapGenerator": { + "Expanded": "procedural:overland", + "Limited": "procedural:overland", + "Space - Sector": "procedural:star-scatter", + "Space - System": "blank", + "Space - Planet": "procedural:overland", + "Custom space": "blank", + "Custom plain": "blank", + "Custom land": "blank", + "Edge": "blank" + }, + "planKindContent": { + "install": [], + "remove": [ + "Limited" + ], + "newKinds": [ + "space" + ], + "defaultPalette": "Space - Sector", + "done": [ + "world", + "space" + ] + }, + "isSpaceMap": { + "sector": true, + "system": true, + "planet": true, + "world": false, + "region": false, + "surface-on-system": true, + "custom-space": true, + "custom-space-in-world": true, + "plain": false, + "plain-in-sector": true, + "land": false, + "land-in-system": true, + "edge": false, + "edge-child": false, + "limited-under-edge": false + } + }, + "world+space": { + "resolveMapKinds": [ + "world", + "space" + ], + "defaultIconPack": "all", + "iconHidden": [], + "terrainsForTables": [ + "trench", + "ocean", + "shallows", + "water", + "urban", + "grass", + "hills", + "foothills", + "snow", + "mountains snow", + "desert", + "desert rocky", + "dunes", + "cactus", + "cactus heavy", + "badlands", + "brokenlands", + "forest", + "forest heavy", + "forested hills", + "forested mountain", + "forested mountains", + "mixed forest", + "mixed forest heavy", + "mixed forest hills", + "mixed forest mountain", + "mixed forest mountains", + "evergreen", + "evergreen heavy", + "evergreen hills", + "evergreen mountain", + "evergreen mountains", + "jungle", + "jungle heavy", + "jungle hills", + "jungle mountain", + "jungle mountains", + "volcano", + "volcano dormant", + "cliffs", + "mountain", + "mountain ridge", + "peak", + "marsh", + "swamp", + "bog", + "beach", + "salt flats", + "savanna", + "river delta", + "hill", + "empty space", + "nebula", + "dust cloud", + "rift", + "garden world", + "ocean world", + "desert world", + "ice world", + "barren world", + "molten world", + "asteroid belt", + "gas giant", + "star system", + "deep-space station", + "black hole", + "anomaly", + "void", + "jump limit", + "yellow star", + "red dwarf", + "blue giant", + "white dwarf", + "brown dwarf", + "terrestrial planet", + "ocean planet", + "desert planet", + "ice planet", + "rocky planet", + "molten planet", + "ice giant", + "moon", + "comet", + "space station", + "starport", + "jump point", + "debris field", + "radiation belt", + "deep ocean", + "shore", + "plains", + "toxic marsh", + "regolith", + "bare rock", + "ice", + "crater field", + "mountains", + "peaks", + "lava field", + "crystal field", + "ruins", + "colony", + "nothing", + "sun", + "rock", + "red", + "blue", + "woods", + "sea" + ], + "generatorShown": { + "world|ctx=false": true, + "world|ctx=true": true, + "space|ctx=false": true, + "space|ctx=true": true, + "none|ctx=false": true, + "none|ctx=true": true + }, + "visible": { + "noContext": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "spaceContext": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "selectedPlanet": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ] + }, + "newMapChoices": { + "Expanded": [ + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "Limited": [ + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "Space - Sector": [ + "procedural:star-scatter" + ], + "Space - System": [ + "procedural:orbits" + ], + "Space - Planet": [ + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "Custom space": [ + "procedural:orbits" + ], + "Custom plain": [], + "Custom land": [], + "Edge": [] + }, + "firstMapGenerator": { + "Expanded": "procedural:overland", + "Limited": "procedural:overland", + "Space - Sector": "procedural:star-scatter", + "Space - System": "blank", + "Space - Planet": "procedural:overland", + "Custom space": "blank", + "Custom plain": "blank", + "Custom land": "blank", + "Edge": "blank" + }, + "planKindContent": { + "install": [], + "remove": [], + "newKinds": [ + "space" + ], + "done": [ + "world", + "space" + ] + }, + "isSpaceMap": { + "sector": true, + "system": true, + "planet": true, + "world": false, + "region": false, + "surface-on-system": true, + "custom-space": true, + "custom-space-in-world": true, + "plain": false, + "plain-in-sector": true, + "land": false, + "land-in-system": true, + "edge": false, + "edge-child": false, + "limited-under-edge": false + } + }, + "none": { + "resolveMapKinds": [], + "defaultIconPack": "all", + "iconHidden": [ + "place-castle.svg", + "space-sun.svg", + "place-harbor-dock.svg", + "place-defensive-wall.svg", + "place-castle-ruins.svg", + "place-egyptian-temple.svg", + "place-camping-tent.svg", + "place-gold-mine.svg", + "space-defense-satellite.svg", + "space-moon-outline.svg", + "space-radial-balance.svg", + "space-ringed-planet.svg", + "space-ship-c.png", + "space-star-gate.svg", + "space-sun-outline.svg" + ], + "terrainsForTables": [ + "empty space", + "nebula", + "dust cloud", + "rift", + "garden world", + "ocean world", + "desert world", + "ice world", + "barren world", + "molten world", + "asteroid belt", + "gas giant", + "star system", + "deep-space station", + "black hole", + "anomaly", + "void", + "jump limit", + "yellow star", + "red dwarf", + "blue giant", + "white dwarf", + "brown dwarf", + "terrestrial planet", + "ocean planet", + "desert planet", + "ice planet", + "rocky planet", + "molten planet", + "ice giant", + "moon", + "comet", + "space station", + "starport", + "jump point", + "debris field", + "radiation belt", + "deep ocean", + "ocean", + "shallows", + "shore", + "plains", + "forest", + "jungle", + "toxic marsh", + "regolith", + "bare rock", + "dunes", + "ice", + "hills", + "crater field", + "mountains", + "peaks", + "lava field", + "crystal field", + "ruins", + "colony", + "nothing", + "sun", + "rock", + "red", + "blue" + ], + "generatorShown": { + "world|ctx=false": false, + "world|ctx=true": false, + "space|ctx=false": false, + "space|ctx=true": true, + "none|ctx=false": true, + "none|ctx=true": true + }, + "visible": { + "noContext": [ + "blank" + ], + "spaceContext": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:planet-surface" + ], + "selectedPlanet": [ + "blank", + "procedural:planet-surface" + ] + }, + "newMapChoices": { + "Expanded": [], + "Limited": [], + "Space - Sector": [ + "procedural:star-scatter" + ], + "Space - System": [ + "procedural:orbits" + ], + "Space - Planet": [], + "Custom space": [ + "procedural:orbits" + ], + "Custom plain": [], + "Custom land": [], + "Edge": [] + }, + "firstMapGenerator": { + "Expanded": "procedural:overland", + "Limited": "procedural:overland", + "Space - Sector": "procedural:star-scatter", + "Space - System": "blank", + "Space - Planet": "procedural:overland", + "Custom space": "blank", + "Custom plain": "blank", + "Custom land": "blank", + "Edge": "blank" + }, + "planKindContent": { + "install": [], + "remove": [ + "Limited", + "Space - Sector", + "Space - System", + "Space - Planet" + ], + "newKinds": [], + "done": [ + "world" + ] + }, + "isSpaceMap": { + "sector": true, + "system": true, + "planet": true, + "world": false, + "region": false, + "surface-on-system": true, + "custom-space": true, + "custom-space-in-world": true, + "plain": false, + "plain-in-sector": true, + "land": false, + "land-in-system": true, + "edge": false, + "edge-child": false, + "limited-under-edge": false + } + }, + "unset": { + "resolveMapKinds": [ + "world" + ], + "defaultIconPack": "all", + "iconHidden": [], + "terrainsForTables": [ + "trench", + "ocean", + "shallows", + "water", + "urban", + "grass", + "hills", + "foothills", + "snow", + "mountains snow", + "desert", + "desert rocky", + "dunes", + "cactus", + "cactus heavy", + "badlands", + "brokenlands", + "forest", + "forest heavy", + "forested hills", + "forested mountain", + "forested mountains", + "mixed forest", + "mixed forest heavy", + "mixed forest hills", + "mixed forest mountain", + "mixed forest mountains", + "evergreen", + "evergreen heavy", + "evergreen hills", + "evergreen mountain", + "evergreen mountains", + "jungle", + "jungle heavy", + "jungle hills", + "jungle mountain", + "jungle mountains", + "volcano", + "volcano dormant", + "cliffs", + "mountain", + "mountain ridge", + "peak", + "marsh", + "swamp", + "bog", + "beach", + "salt flats", + "savanna", + "river delta", + "hill", + "empty space", + "nebula", + "dust cloud", + "rift", + "garden world", + "ocean world", + "desert world", + "ice world", + "barren world", + "molten world", + "asteroid belt", + "gas giant", + "star system", + "deep-space station", + "black hole", + "anomaly", + "void", + "jump limit", + "yellow star", + "red dwarf", + "blue giant", + "white dwarf", + "brown dwarf", + "terrestrial planet", + "ocean planet", + "desert planet", + "ice planet", + "rocky planet", + "molten planet", + "ice giant", + "moon", + "comet", + "space station", + "starport", + "jump point", + "debris field", + "radiation belt", + "deep ocean", + "shore", + "plains", + "toxic marsh", + "regolith", + "bare rock", + "ice", + "crater field", + "mountains", + "peaks", + "lava field", + "crystal field", + "ruins", + "colony", + "nothing", + "sun", + "rock", + "red", + "blue", + "woods", + "sea" + ], + "generatorShown": { + "world|ctx=false": true, + "world|ctx=true": true, + "space|ctx=false": true, + "space|ctx=true": true, + "none|ctx=false": true, + "none|ctx=true": true + }, + "visible": { + "noContext": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "spaceContext": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "selectedPlanet": [ + "blank", + "procedural:star-scatter", + "procedural:orbits", + "procedural:region-detail", + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ] + }, + "newMapChoices": { + "Expanded": [ + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "Limited": [ + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "Space - Sector": [ + "procedural:star-scatter" + ], + "Space - System": [ + "procedural:orbits" + ], + "Space - Planet": [ + "procedural:overland", + "procedural:world-biomes", + "procedural:planet-surface" + ], + "Custom space": [ + "procedural:orbits" + ], + "Custom plain": [], + "Custom land": [], + "Edge": [] + }, + "firstMapGenerator": { + "Expanded": "procedural:overland", + "Limited": "procedural:overland", + "Space - Sector": "procedural:star-scatter", + "Space - System": "blank", + "Space - Planet": "procedural:overland", + "Custom space": "blank", + "Custom plain": "blank", + "Custom land": "blank", + "Edge": "blank" + }, + "planKindContent": { + "install": [], + "remove": [], + "newKinds": [ + "space" + ], + "done": [ + "world", + "space" + ] + }, + "isSpaceMap": { + "sector": true, + "system": true, + "planet": true, + "world": false, + "region": false, + "surface-on-system": true, + "custom-space": true, + "custom-space-in-world": true, + "plain": false, + "plain-in-sector": true, + "land": false, + "land-in-system": true, + "edge": false, + "edge-child": false, + "limited-under-edge": false + } + } + }, + "sectionWords": { + "sector": "Settlements,Sites,Points of Interest,Missions,Factions", + "system": "Settlements,Sites,Points of Interest,Missions,Factions", + "planet": "Settlements,Sites,Points of Interest,Missions,Factions", + "world": "Towns,Dungeons,Features,Quests,Factions", + "region": "Towns,Dungeons,Features,Quests,Factions", + "surface-on-system": "Settlements,Sites,Points of Interest,Missions,Factions", + "custom-space": "Settlements,Sites,Points of Interest,Missions,Factions", + "custom-space-in-world": "Settlements,Sites,Points of Interest,Missions,Factions", + "plain": "Towns,Dungeons,Features,Quests,Factions", + "plain-in-sector": "Settlements,Sites,Points of Interest,Missions,Factions", + "land": "Towns,Dungeons,Features,Quests,Factions", + "land-in-system": "Settlements,Sites,Points of Interest,Missions,Factions", + "edge": "Settlements,Sites,Points of Interest,Missions,Factions", + "edge-child": "Settlements,Sites,Points of Interest,Missions,Factions", + "limited-under-edge": "Settlements,Sites,Points of Interest,Missions,Factions" + }, + "runGeneratorCarry": { + "Expanded": 1, + "Limited": 1, + "Space - Sector": 0, + "Space - System": 0, + "Space - Planet": 1, + "Custom space": 0, + "Custom plain": 1, + "Custom land": 1, + "Edge": 0 + } +} diff --git a/tests/moduleBoundary.test.ts b/tests/moduleBoundary.test.ts new file mode 100644 index 00000000..8fa5b75e --- /dev/null +++ b/tests/moduleBoundary.test.ts @@ -0,0 +1,46 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { readFileSync } from "node:fs"; +import { scanBoundary, totals } from "./moduleBoundary"; + +/** + * The module boundary ratchet (owner call CM8, plan-code-modules §3.4 + * rule 1). The core reaches a module only through src/modules/index.ts + * and src/modules/runtime.ts; every other import of a module's code from + * the core, and every branch on a map type by name, is listed in + * tests/fixtures/moduleBoundary.json. A count may never go up, and when + * one goes down the list must come down with it (so it can only shrink). + */ +const allowed = JSON.parse(readFileSync(new URL("./fixtures/moduleBoundary.json", import.meta.url), "utf8")) as { + imports: Record; + decisions: Record; +}; + +const now = scanBoundary(); + +function ratchet(kind: "imports" | "decisions"): void { + const have = now[kind]; + const allow = allowed[kind]; + const grew: string[] = []; + const shrank: string[] = []; + for (const [k, n] of Object.entries(have)) { + const a = allow[k] ?? 0; + if (n > a) grew.push(`${k}: ${n} (allowed ${a})`); + } + for (const [k, a] of Object.entries(allow)) { + const n = have[k] ?? 0; + if (n < a) shrank.push(`${k}: ${n} (list says ${a})`); + } + expect({ grew }).toEqual({ grew: [] }); + // Lower tests/fixtures/moduleBoundary.json to the new counts. + expect({ shrank }).toEqual({ shrank: [] }); +} + +describe("module boundary ratchet", () => { + it("the core imports no more module code than the allow-list says", () => ratchet("imports")); + it("the core branches on map types by name no more than the allow-list says", () => ratchet("decisions")); + it("reports totals per module (for the record)", () => { + expect(totals(now.imports)).toEqual(totals(allowed.imports)); + expect(totals(now.decisions)).toEqual(totals(allowed.decisions)); + }); +}); diff --git a/tests/moduleBoundary.ts b/tests/moduleBoundary.ts new file mode 100644 index 00000000..ee386e7a --- /dev/null +++ b/tests/moduleBoundary.ts @@ -0,0 +1,143 @@ +/** + * The module boundary scan (plan-code-modules §3.4 rule 1, owner call CM8): + * how far the core still reaches into a module's code, and how often it + * still branches on a map type by name. tests/moduleBoundary.test.ts holds + * the counts to a ratchet (tests/fixtures/moduleBoundary.json): a count may + * only go down, and when it does the allow-list has to come down with it. + * + * The allow-list is edited by hand, never regenerated, so every + * change to it is a deliberate, reviewed line in a diff. + * + * Pure node: no Obsidian imports. + */ + +import { readFileSync, readdirSync, statSync } from "node:fs"; +import { join, relative, resolve, dirname, sep } from "node:path"; +import { fileURLToPath } from "node:url"; + +/** Each module's own code: files under these folders belong to it. */ +export const MODULE_DIRS: Record = { + space: ["src/space/", "src/modules/space/"], + "world-maps": ["src/overworld/", "src/modules/world-maps/"], + world: ["src/modules/world/"], +}; + +/** + * The core may import a module only through these files (the registry's + * two entry points and its shared types). Everything else under + * src/modules// is that module's own. + */ +export const MODULE_ENTRY_POINTS = new Set([ + "src/modules/index.ts", + "src/modules/runtime.ts", + "src/modules/registry.ts", + "src/modules/types.ts", +]); + +/** + * Branches on a map type by name in core code (the "random if statements" + * of owner note Q7). Each pattern is one decision site. + */ +export const DECISION_PATTERNS: Record = { + space: [ + /\bisSpaceMap\b/g, + /\bisSpacePalette\b/g, + /\bspaceContext\b/g, + /[!=]==\s*"space"/g, + /"space"\s*[!=]==/g, + /\.(?:has|includes)\("space"\)/g, + /[!=]==\s*"planet"/g, + ], + world: [ + /\.(?:has|includes)\("world"\)/g, + ], +}; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +function walk(dir: string, out: string[] = []): string[] { + for (const name of readdirSync(dir)) { + const p = join(dir, name); + if (statSync(p).isDirectory()) walk(p, out); + else if (/\.ts$/.test(name) && !/\.d\.ts$/.test(name)) out.push(p); + } + return out; +} + +const rel = (p: string) => relative(root, p).split(sep).join("/"); + +/** The module a file belongs to (undefined = core). */ +export function ownerOf(file: string): string | undefined { + if (MODULE_ENTRY_POINTS.has(file)) return undefined; + for (const [id, dirs] of Object.entries(MODULE_DIRS)) if (dirs.some((d) => file.startsWith(d))) return id; + return undefined; +} + +/** Strip comments (block and line) so prose about "space" never counts. */ +function code(text: string): string { + return text + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1"); +} + +/** Value imports (not `import type`, not all-`type` specifier lists). */ +function valueImports(text: string): string[] { + const out: string[] = []; + const re = /import\s+(type\s+)?([\s\S]*?)\s+from\s+"([^"]+)"|import\s+"([^"]+)"|export\s+(?:\*|\{[\s\S]*?\})\s+from\s+"([^"]+)"/g; + for (const m of text.matchAll(re)) { + if (m[4]) { out.push(m[4]); continue; } + if (m[5]) { out.push(m[5]); continue; } + if (m[1]) continue; + const spec = m[2].trim(); + const braces = /^\{([\s\S]*)\}$/.exec(spec); + if (braces) { + const parts = braces[1].split(",").map((s) => s.trim()).filter(Boolean); + if (parts.length && parts.every((s) => s.startsWith("type "))) continue; + } + out.push(m[3]); + } + return out; +} + +export interface BoundaryCounts { + /** "core file -> module": value imports of that module's code. */ + imports: Record; + /** "core file -> module": map-type decision sites. */ + decisions: Record; +} + +export function scanBoundary(): BoundaryCounts { + const imports: Record = {}; + const decisions: Record = {}; + for (const abs of walk(join(root, "src"))) { + const file = rel(abs); + if (ownerOf(file) !== undefined) continue; + const text = readFileSync(abs, "utf8"); + const body = code(text); + for (const spec of valueImports(body)) { + if (!spec.startsWith(".")) continue; + let target = rel(resolve(dirname(abs), spec)); + if (!/\.ts$/.test(target)) target += ".ts"; + const owner = ownerOf(target) ?? ownerOf(target.replace(/\.ts$/, "/index.ts")); + if (!owner) continue; + const key = `${file} -> ${owner}`; + imports[key] = (imports[key] ?? 0) + 1; + } + for (const [id, patterns] of Object.entries(DECISION_PATTERNS)) { + const n = patterns.reduce((sum, re) => sum + [...body.matchAll(re)].length, 0); + if (n) decisions[`${file} -> ${id}`] = n; + } + } + const sorted = (r: Record) => Object.fromEntries(Object.entries(r).sort(([a], [b]) => (a < b ? -1 : 1))); + return { imports: sorted(imports), decisions: sorted(decisions) }; +} + +/** Totals per module. */ +export function totals(r: Record): Record { + const out: Record = {}; + for (const [k, n] of Object.entries(r)) { + const id = k.split(" -> ")[1]; + out[id] = (out[id] ?? 0) + n; + } + return out; +} diff --git a/tests/moduleCharacterisation.test.ts b/tests/moduleCharacterisation.test.ts new file mode 100644 index 00000000..263f38a8 --- /dev/null +++ b/tests/moduleCharacterisation.test.ts @@ -0,0 +1,235 @@ +import { describe, it } from "node:test"; +import expect from "expect"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { TFile } from "obsidian"; +import type HexmakerPlugin from "../src/HexmakerPlugin"; +import { isSpaceMapIn, sectionWordsIn, type MapKindHost } from "../src/maps/mapKindQueries"; +import { + MAP_KINDS, + generatorMapKind, + isGeneratorShown, + isIconHiddenByKind, + isSpacePalette, + paletteKind, + resolveMapKinds, + terrainsForTables, +} from "../src/mapKinds"; +import { TERRAIN_GROUPS, TERRAIN_TYPES, inferTerrainType, normalizeTerrainType, refinedSpaceType } from "../src/terrainTypes"; +import { PALETTE_PRESETS, getPreset } from "../src/palettes/presets"; +import { BUNDLED_ICONS } from "../src/bundledIcons"; +import { ICON_PACK_LABELS, defaultIconPack, iconLabel, iconPack, iconPackTabs, sortIcons } from "../src/utils"; +import { planKindContent } from "../src/kindContent"; +import { childKindText } from "../src/hex-map/newChildMap"; +import { + firstMapGenerator, + listGeneratorKinds, + newMapGeneratorChoices, + runGenerator, + suggestBaseTerrain, + visibleKinds, + type TerrainGeneratorKind, +} from "../src/worldgen/registry"; +import { ENGINE_ROLES } from "../src/worldgen/tableRoles"; +import { defaultPathTypeFor } from "../src/worldgen/generatorPathTypes"; +import { moonPlanetLinks } from "../src/hex-map/moonLinks"; +import type { MapData, TerrainColor, TerrainPalette } from "../src/types"; + +/** + * Characterisation snapshot for the module refactor (plan-code-modules + * P0): what the core answers today about map types, over a matrix of + * {map types on} × {palette kinds} × {map trees}. Every phase of the + * refactor must leave this unchanged, except where an owner call changes + * it on purpose (CM3: one map-type rule; see the "kindFor" entries). + * + * UPDATE_SNAPSHOT=1 rewrites tests/fixtures/moduleCharacterisation.json. + */ + +const SNAP = new URL("./fixtures/moduleCharacterisation.json", import.meta.url); + +// ── Palettes ──────────────────────────────────────────────────────────── +const custom = (name: string, terrains: TerrainColor[], kind?: string): TerrainPalette => + ({ name, terrains, ...(kind ? { kind } : {}) }) as TerrainPalette; +const T = (name: string, type?: string): TerrainColor => ({ name, color: "#000", ...(type ? { type } : {}) }); + +const CUSTOM: TerrainPalette[] = [ + custom("Custom space", [T("nothing", "void"), T("sun", "star"), T("rock", "world")]), + custom("Custom plain", [T("red"), T("blue")]), + custom("Custom land", [T("woods", "forest"), T("sea", "water")]), + // The CM3 edge case: declared world, holding space types. + custom("Edge", [T("nothing", "void"), T("woods", "forest")], "world"), +]; +const PRESET_NAMES = PALETTE_PRESETS.map((p) => p.name); +const ALL_PALETTES = [...PRESET_NAMES, ...CUSTOM.map((p) => p.name)]; + +// ── Map trees ─────────────────────────────────────────────────────────── +// [name, palette, parent] +const TREE: [string, string, string | undefined][] = [ + ["sector", "Space - Sector", undefined], + ["system", "Space - System", "sector"], + ["planet", "Space - Planet", "system"], + ["world", "Expanded", undefined], + ["region", "Expanded", "world"], + ["surface-on-system", "Expanded", "system"], + ["custom-space", "Custom space", undefined], + ["custom-space-in-world", "Custom space", "world"], + ["plain", "Custom plain", undefined], + ["plain-in-sector", "Custom plain", "sector"], + ["land", "Custom land", undefined], + ["land-in-system", "Custom land", "system"], + ["edge", "Edge", undefined], + ["edge-child", "Custom plain", "edge"], + ["limited-under-edge", "Limited", "edge"], +]; + +const KIND_SETS: (string[] | undefined)[] = [["world"], ["space"], ["world", "space"], [], undefined]; +const ks = (k: string[] | undefined) => (k === undefined ? "unset" : k.length ? k.join("+") : "none"); + +/** A plugin with just enough state for the map-type questions. */ +function fakePlugin(mapKinds: string[] | undefined): HexmakerPlugin & MapKindHost { + const maps: MapData[] = TREE.map(([name, paletteName, parent]) => ({ + name, + paletteName, + gridSize: { cols: 4, rows: 4 }, + gridOffset: { x: 0, y: 0 }, + pathChains: [], + ...(parent ? { parent: { map: parent, hex: "1_1" } } : {}), + })) as MapData[]; + const terrainPalettes = [...PALETTE_PRESETS.map((p) => ({ name: p.name, terrains: p.terrains, kind: p.kind })), ...CUSTOM]; + return { + settings: { maps, terrainPalettes, worldFolder: "world", pathTypes: [], hexOrientation: "flat", ...(mapKinds ? { mapKinds } : {}) }, + app: { vault: { getMarkdownFiles: () => [] as TFile[], cachedRead: async () => "" } }, + getMap: (m: string) => maps.find((x) => x.name === m), + parentOf: (m: string) => { + const par = maps.find((x) => x.name === m)?.parent; + return par ? { map: par.map, hex: par.hex } : undefined; + }, + getPaletteByName: (n: string) => terrainPalettes.find((p) => p.name === n), + } as unknown as HexmakerPlugin & MapKindHost; +} + +const palTerrains = (name: string): TerrainColor[] => + getPreset(name)?.terrains ?? CUSTOM.find((p) => p.name === name)?.terrains ?? []; +const palObj = (name: string) => getPreset(name) ?? CUSTOM.find((p) => p.name === name); + +async function collect(): Promise> { + const out: Record = {}; + + // Static registries. + out.mapKinds = MAP_KINDS.map((k) => ({ id: k.id, label: k.label, description: k.description, iconPrefix: k.iconPrefix, sectionWords: k.sectionWords })); + out.terrainGroups = TERRAIN_GROUPS; + out.terrainTypes = TERRAIN_TYPES.map((t) => `${t.id}|${t.kind}|${t.group}|${t.label}|${t.keywords.join(",")}`); + out.presets = PALETTE_PRESETS.map((p) => ({ + name: p.name, + kind: p.kind, + terrains: p.terrains.map((t) => `${t.name}|${t.type ?? ""}|${t.color}|${t.icon ?? ""}`), + pathTypes: (p.pathTypes ?? []).map((t) => t.name), + childPalette: p.childPalette, + pathRoles: p.pathRoles, + submapDefaults: p.submapDefaults, + })); + out.bundledIcons = [...BUNDLED_ICONS.keys()]; + out.iconPackLabels = ICON_PACK_LABELS; + const sampleIcons = ["bw-forest.png", "place-castle.svg", "space-sun.svg", "my-own.png", ...[...BUNDLED_ICONS.keys()].filter((_, i) => i % 9 === 0)]; + out.iconPack = Object.fromEntries(sampleIcons.map((i) => [i, iconPack(i, new Set(["my-own.png"]))])); + out.iconLabel = Object.fromEntries(sampleIcons.map((i) => [i, iconLabel(i)])); + out.sortIcons = sortIcons([...BUNDLED_ICONS.keys()].reverse()); + out.iconPackTabs = iconPackTabs(new Map([["terrain", 3], ["places", 2], ["space", 0]] as [never, number][])); + out.generatorMapKind = Object.fromEntries(["planet", "space", " Planet ", "world", "dungeon", ""].map((v) => [v || "(blank)", generatorMapKind({ "map-kind": v }) ?? null])); + out.paletteKind = Object.fromEntries(ALL_PALETTES.map((n) => [n, paletteKind(palObj(n))])); + out.isSpacePalette = Object.fromEntries(ALL_PALETTES.map((n) => [n, isSpacePalette(palTerrains(n))])); + out.suggestBaseTerrain = Object.fromEntries(ALL_PALETTES.map((n) => [n, suggestBaseTerrain(palTerrains(n)) ?? null])); + out.refinedSpaceType = ["moon|world", "Luna satellite|world", "comet|asteroids", "wreck|asteroids", "jump gate|station", "starport|station", "jump limit|void", "star system|star", "forest|forest"] + .map((s) => { const [name, type] = s.split("|"); return `${s} -> ${refinedSpaceType({ name, type }) ?? ""}`; }); + out.inferTerrainType = ["dark forest", "gas giant", "ice moon", "black lake", "planet", "red dwarf", "salt flat"] + .flatMap((n) => [undefined, "world", "space"].map((k) => `${n}|${k ?? ""} -> ${inferTerrainType(n, undefined, k as never) ?? ""}`)); + out.normalizeTerrainType = ["Deep-Water", "snow", "Void / empty space", "gas giant", "nope"].map((v) => `${v} -> ${normalizeTerrainType(v) ?? ""}`); + out.engineRoles = ENGINE_ROLES.map((r) => `${r.id}|${r.engine}|${r.name}|${r.terrainTypes.join(",")}`); + out.defaultPathTypeFor = { + routes: defaultPathTypeFor("routes", [{ name: "Jump route" }, { name: "Road" }]) ?? null, + orbits: defaultPathTypeFor("orbits", [{ name: "Orbit" }]) ?? null, + none: defaultPathTypeFor("routes", [{ name: "Road" }]) ?? null, + }; + out.childKindText = { space: childKindText(true), other: childKindText(false) }; + out.moonLinks = moonPlanetLinks( + new Map([["1_1", "moon"], ["2_1", "terrestrial planet"], ["1_2", "gas giant"], ["3_3", "moon"]]), + getPreset("Space - System")!.terrains, "flat", "odd"); + + // Per map-types setting. + const perKinds: Record = {}; + for (const kinds of KIND_SETS) { + const s = kinds === undefined ? {} : { mapKinds: kinds }; + const plugin = fakePlugin(kinds); + const gens = await listGeneratorKinds(plugin); + const row: Record = {}; + row.resolveMapKinds = resolveMapKinds(kinds, []); + row.defaultIconPack = defaultIconPack(s); + row.iconHidden = sampleIcons.filter((i) => isIconHiddenByKind(s, i)); + row.terrainsForTables = terrainsForTables( + ALL_PALETTES.map((n) => ({ name: n, kind: palObj(n)?.kind, terrains: palTerrains(n) })), + kinds ?? ["world", "space"], + ["Custom plain"], + ).map((t) => t.name); + row.generatorShown = Object.fromEntries(["world", "space", undefined].flatMap((k) => [false, true].map((ctx) => + [`${k ?? "none"}|ctx=${ctx}`, isGeneratorShown(s, k as never, { spaceContext: ctx })]))); + row.visible = { + noContext: visibleKinds(gens, s, false).map((g) => g.id), + spaceContext: visibleKinds(gens, s, true).map((g) => g.id), + selectedPlanet: visibleKinds(gens, s, false, "procedural:planet-surface").map((g) => g.id), + }; + row.newMapChoices = Object.fromEntries(ALL_PALETTES.map((n) => [n, newMapGeneratorChoices(gens, s, palTerrains(n), undefined, false).map((g) => g.id)])); + row.firstMapGenerator = Object.fromEntries(ALL_PALETTES.map((n) => { + const fitting = gens.filter((g) => g.fits(palTerrains(n))); + return [n, firstMapGenerator(fitting, kinds ?? [])]; + })); + row.planKindContent = planKindContent({ + kinds: (kinds ?? ["world", "space"]) as never, + done: ["world"], + firstSetup: true, + palettes: PALETTE_PRESETS.map((p) => ({ name: p.name, kind: p.kind, terrains: p.terrains })), + inUse: new Set(["Expanded"]), + defaultPalette: "Expanded", + }); + row.isSpaceMap = Object.fromEntries(TREE.map(([m]) => [m, isSpaceMapIn(plugin, m)])); + perKinds[ks(kinds)] = row; + } + out.perKinds = perKinds; + + // Section words per map (independent of the setting). + const plugin = fakePlugin(["world", "space"]); + out.sectionWords = Object.fromEntries(TREE.map(([m]) => { + const w = sectionWordsIn(plugin, m); + return [m, ["Towns", "Dungeons", "Features", "Quests", "Factions"].map((s) => w(s).label).join(",")]; + })); + + // runGenerator: context paths carried over (not on space palettes). + const fake: TerrainGeneratorKind = { + id: "fake", label: "fake", description: "", source: "built-in", options: [], fits: () => true, + generate: (req) => ({ ok: true, cells: new Map([...Array(16).keys()].map((i) => [`${i % 4}_${Math.floor(i / 4)}`, req.terrains[0].name])), paths: [], warnings: [] }), + toPaths: () => ({ paths: [], missing: [] }), + }; + out.runGeneratorCarry = Object.fromEntries(ALL_PALETTES.map((n) => { + const terrains = palTerrains(n); + if (!terrains.length) return [n, null]; + const r = runGenerator("flat", fake, { + terrains, + grid: { cols: 4, rows: 4, offset: { x: 0, y: 0 }, stagger: "odd" }, + seed: 1, + options: {}, + context: { paths: [{ type: "Road", from: "W", to: "E" }] }, + }); + return [n, r.ok ? r.paths.length : `fail:${r.message}`]; + })); + return out; +} + +describe("module refactor characterisation (P0)", () => { + it("answers exactly as recorded", async () => { + const now = JSON.parse(JSON.stringify(await collect())) as Record; + if (process.env.UPDATE_SNAPSHOT === "1" || !existsSync(SNAP)) { + writeFileSync(SNAP, JSON.stringify(now, null, 2) + "\n"); + } + const recorded = JSON.parse(readFileSync(SNAP, "utf8")) as Record; + for (const key of Object.keys(recorded)) expect({ [key]: now[key] }).toEqual({ [key]: recorded[key] }); + expect(Object.keys(now).sort()).toEqual(Object.keys(recorded).sort()); + }); +}); From 8247d07deb3e21e081a30d07420533e62d452bb8 Mon Sep 17 00:00:00 2001 From: nyxsys Date: Sun, 11 Oct 2026 17:23:38 -0400 Subject: [PATCH 316/558] chore(dev): keep the UI inventory worksheet and the owner's tags (2026-10-11) Co-Authored-By: Claude Opus 5.5 --- dev/ui-inventory/README.md | 20 + dev/ui-inventory/config.json | 29 + dev/ui-inventory/inputs-tags-resolved.csv | 1143 ++ dev/ui-inventory/inputs-tags-resolved.json | 17132 ++++++++++++++++ dev/ui-inventory/inputs-tags-summary.md | 226 + dev/ui-inventory/inputs-tags.html | 501 + dev/ui-inventory/items.json | 18334 ++++++++++++++++++ dev/ui-inventory/submission-2026-10-11.json | 1 + 8 files changed, 37386 insertions(+) create mode 100644 dev/ui-inventory/README.md create mode 100644 dev/ui-inventory/config.json create mode 100644 dev/ui-inventory/inputs-tags-resolved.csv create mode 100644 dev/ui-inventory/inputs-tags-resolved.json create mode 100644 dev/ui-inventory/inputs-tags-summary.md create mode 100644 dev/ui-inventory/inputs-tags.html create mode 100644 dev/ui-inventory/items.json create mode 100644 dev/ui-inventory/submission-2026-10-11.json diff --git a/dev/ui-inventory/README.md b/dev/ui-inventory/README.md new file mode 100644 index 00000000..8f555e80 --- /dev/null +++ b/dev/ui-inventory/README.md @@ -0,0 +1,20 @@ +# UI inventory worksheet (owner tags, 2026-10-11) + +Every user-facing input, picker, command and menu item, tagged by the owner: +- keep: as today +- simple: everyone +- advanced: the page's Advanced dropdown +- overkill: Debug, only in debug mode +- drop: removed + +Built with the `ui-inventory` skill (`work/tools/skills-share/ux-testing/ui-inventory`). + +- `items.json`: the inventory (ids are permanent; `src/ui/placement.ts` is keyed by them) +- `config.json`: the tier scheme and page settings +- `inputs-tags.html`: the worksheet page (serve with `npm run sandbox`, open `/dev/ui-inventory/inputs-tags.html`) +- `submission-2026-10-11.json`: the owner's submission (group picks, own picks, notes) +- `inputs-tags-resolved.json` / `.csv` / `-summary.md`: effective tag per item, with source (own / group / twin) + +To review again, run the skill's `build-page.mjs` with `items.json` + `config.json` and load the last submission as progress, so the owner starts from these answers. Then apply the new resolved tags to `src/ui/placement.ts`. + +KB: `knowledgebase/projects/duckmage-plugin/notes/impl/audit-inputs-2026-10-11.md`. diff --git a/dev/ui-inventory/config.json b/dev/ui-inventory/config.json new file mode 100644 index 00000000..71b9c407 --- /dev/null +++ b/dev/ui-inventory/config.json @@ -0,0 +1,29 @@ +{ + "page": "inputs-tags", + "prefix": "hexmaker", + "title": "Hexmaker: tag every input and picker (round 6, SP3, tree view)", + "lead": "Every user-facing input, picker, button, command and menu item on `feat/region-notes`, as a tree: **screen › section › item**. Pick once for a whole screen or section, or open it and pick items one by one. Your 65 picks so far are kept as they were. Submit any time.", + "suggestionName": "suggestion", + "tiers": [ + { "v": "keep", "short": "Keep", "label": "Keep (as today)", "desc": "Whatever it does today, unchanged, including its feature switch or greyed-out rules. Feature switches that ramp Simple users up are keep.", "color": "#1f4d33" }, + { "v": "simple", "short": "Simple", "label": "Simple (show to everyone)", "desc": "Shown at every level. **Simple stays customizable**: palettes and palette management, look and feel, and defaults lean here.", "color": "#2f6b3e" }, + { "v": "advanced", "short": "Adv.", "label": "Advanced (hide from Simple)", "desc": "A real extra feature, or an option of one. When unsure between Advanced and Overkill, pick Advanced.", "color": "#1f4f6b" }, + { "v": "overkill", "short": "Overkill", "label": "Overkill (\"All\" level only)", "desc": "Backend-fiddler stuff: engine tuning, raw seeds and ids, maintenance and diagnostics. Shown only at the new All level.", "color": "#6b4f12" }, + { "v": "drop", "short": "Drop", "label": "Drop entirely", "desc": "Redundant or dead; removed at every level.", "color": "#6b1f1f" } + ], + "levels": { + "columns": ["Simple", "Advanced", "All (new)"], + "rows": { + "keep": ["as today", "as today", "shown"], + "simple": ["shown", "shown", "shown"], + "advanced": ["hidden", "shown", "shown"], + "overkill": ["hidden", "hidden", "shown, with a \"you probably don't need these\" caveat"], + "drop": ["removed", "removed", "removed"] + } + }, + "facts": [ + "**Legacy (pre-1.13)** items in Settings are the fallback copies of the same settings. Each follows its twin; you tagged them before twins existed, so they show as overrides. Use \"Follow twin\" on a row, or the filter \"Twins picked differently\", to line them up.", + "Blue chip: when the item shows today. Red **mixed list** chip: a picker that lists unrelated kinds of note.", + "Full inventory with reasons and line numbers: KB note `projects/duckmage-plugin/notes/impl/audit-inputs-2026-10-11`." + ] +} diff --git a/dev/ui-inventory/inputs-tags-resolved.csv b/dev/ui-inventory/inputs-tags-resolved.csv new file mode 100644 index 00000000..67caf4ea --- /dev/null +++ b/dev/ui-inventory/inputs-tags-resolved.csv @@ -0,0 +1,1143 @@ +id,group,subgroup,label,suggestion,choice,source,via,overrides,twinOf,loc,note +"Settings.rerunSetupWizard","Settings","Setup & feature switches","Re-run setup wizard","keep","keep","own","","","","src/HexmakerSettingTab.ts:247","" +"Settings.featureLevel","Settings","Setup & feature switches","Feature level","keep","keep","own","","","","src/HexmakerSettingTab.ts:894","" +"Settings.featureGenerators","Settings","Setup & feature switches","Terrain generators","keep","keep","own","","","","src/HexmakerSettingTab.ts:906","" +"Settings.featureWorkflows","Settings","Setup & feature switches","Workflows","keep","keep","own","","","","src/HexmakerSettingTab.ts:906","" +"Settings.featurePalettes","Settings","Setup & feature switches","Custom palettes","keep","keep","own","","","","src/HexmakerSettingTab.ts:906","" +"Settings.featureRegions","Settings","Setup & feature switches","Regions and overworlds","keep","keep","own","","","","src/HexmakerSettingTab.ts:906","" +"Settings.showHintsAgain","Settings","Setup & feature switches","Show hints again","keep","keep","own","","","","src/HexmakerSettingTab.ts:923","" +"Settings.mapKindWorld","Settings","Setup & feature switches","World / fantasy overland","keep","keep","own","","","","src/HexmakerSettingTab.ts:695","" +"Settings.mapKindSpace","Settings","Setup & feature switches","Space","keep","keep","own","","","","src/HexmakerSettingTab.ts:695","" +"Settings.hexOrientation","Settings","Look & labels","Hex orientation","keep","keep","own","","","","src/HexmakerSettingTab.ts:310","" +"Settings.staggerOffset","Settings","Look & labels","Stagger offset","advanced","simple","own","","","","src/HexmakerSettingTab.ts:320","" +"Settings.coordPlacement","Settings","Look & labels","Coordinate placement","advanced","simple","own","","","","src/HexmakerSettingTab.ts:339","" +"Settings.coordFontSize","Settings","Look & labels","Coordinate label size","overkill","simple","own","","","","src/HexmakerSettingTab.ts:349","" +"Settings.coordFontFamily","Settings","Look & labels","Coordinate label font","overkill","simple","own","","","","src/HexmakerSettingTab.ts:362","" +"Settings.coordFontColor","Settings","Look & labels","Coordinate label color","overkill","simple","own","","","","src/HexmakerSettingTab.ts:376","" +"Settings.hexNameFont","Settings","Look & labels","Hex name font","overkill","simple","own","","","","src/HexmakerSettingTab.ts:385","" +"Settings.hexNameSize","Settings","Look & labels","Hex name size","overkill","simple","own","","","","src/HexmakerSettingTab.ts:395","" +"Settings.hexNameStyle","Settings","Look & labels","Hex name style","overkill","simple","own","","","","src/HexmakerSettingTab.ts:405","" +"Settings.hexGap","Settings","Look & labels","Hex cell spacing","advanced","simple","own","","","","src/HexmakerSettingTab.ts:415","" +"Settings.defaultTableDice","Settings","Defaults","Default die for new tables","advanced","simple","own","","","","src/HexmakerSettingTab.ts:266","" +"Settings.collapseTerrain","Settings","Defaults","Terrain","advanced","simple","own","","","","src/HexmakerSettingTab.ts:989","" +"Settings.collapseFeatures","Settings","Defaults","Features","advanced","simple","own","","","","src/HexmakerSettingTab.ts:996","" +"Settings.collapseNotes","Settings","Defaults","Notes","advanced","simple","own","","","","src/HexmakerSettingTab.ts:1003","" +"Settings.templatePath","Settings","Defaults","Template path","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:293","" +"Settings.defaultMap","Settings","Defaults","Default map","keep","keep","own","","","","src/HexmakerSettingTab.ts:300","" +"Settings.defaultNewMapCols","Settings","Defaults","Default new map columns","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:428","" +"Settings.defaultNewMapRows","Settings","Defaults","Default new map rows","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:440","" +"Settings.defaultSubmapCols","Settings","Defaults","Default submap columns","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:452","" +"Settings.defaultSubmapRows","Settings","Defaults","Default submap rows","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:464","" +"Settings.iconsFolder","Settings","Folders","Custom icons folder","keep","keep","own","","","","src/HexmakerSettingTab.ts:475","" +"Settings.worldFolder","Settings","Folders","World notes folder","keep","keep","own","","","","src/HexmakerSettingTab.ts:527","" +"Settings.hexFolder","Settings","Folders","Hex notes folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:608","" +"Settings.townsFolder","Settings","Folders","Towns folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:614","" +"Settings.dungeonsFolder","Settings","Folders","Dungeons folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:620","" +"Settings.questsFolder","Settings","Folders","Quests folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:626","" +"Settings.featuresFolder","Settings","Folders","Features folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:632","" +"Settings.factionsFolder","Settings","Folders","Factions folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:638","" +"Settings.regionsFolder","Settings","Folders","Regions folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:644","" +"Settings.tablesFolder","Settings","Folders","Tables folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:650","" +"Settings.workflowsFolder","Settings","Folders","Workflows folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:656","" +"Settings.templatesFolder","Settings","Folders","Templates folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:662","" +"Settings.palettesFolder","Settings","Folders","Palettes folder","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:668","" +"Settings.biomesFolder","Settings","Folders","Biomes folder","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:674","" +"Settings.biomePoolsFolder","Settings","Folders","Biome pools folder","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:680","" +"Settings.worldTypesFolder","Settings","Folders","World types folder","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:686","" +"Settings.defaultPalette","Settings","Palette management","Palette for new maps","advanced","simple","own","","","","src/HexmakerSettingTab.ts:721","" +"Settings.addDefaultPalettes","Settings","Palette management","Add ","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:731","" +"Settings.paletteRowName","Settings","Palette management","(palette name)","advanced","simple","own","","","","src/HexmakerSettingTab.ts:212","" +"Settings.paletteRowEdit","Settings","Palette management","Edit","advanced","simple","own","","","","src/HexmakerSettingTab.ts:868","" +"Settings.paletteRowOpenNote","Settings","Palette management","Open note","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:871","" +"Settings.paletteDelete","Settings","Palette management","Delete (list delete)","advanced","advanced","own","","","","src/HexmakerSettingTab.ts:748","" +"Settings.addPalette","Settings","Palette management","Add palette","advanced","simple","own","","","","src/HexmakerSettingTab.ts:767","" +"AddPalette.presetOption","Settings","Palette management","","simple","simple","own","","","","src/palettes/AddPaletteModal.ts:30","" +"AddPalette.copyOption","Settings","Palette management","Copy of ","simple","simple","own","","","","src/palettes/AddPaletteModal.ts:46","" +"AddPalette.emptyPalette","Settings","Palette management","Empty palette","simple","simple","own","","","","src/palettes/AddPaletteModal.ts:64","" +"AddPalette.preset","Settings","Palette management"," / (another copy)","keep","keep","own","","","","src/palettes/AddPaletteModal.ts:30","" +"AddPalette.closeButtons","Settings","Palette management","(modal ✕)","keep","keep","own","","","","src/palettes/AddPaletteModal.ts:20","" +"Settings.generateWorldData","Settings","Maintenance","Generate","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:491","but note this might need to be surfaced in the case of debugging etc, we might need to point users to ""all"" if ""health""/""repair"" type settings hide there. " +"Settings.generateFolders","Settings","Maintenance","Generate folders","overkill","overkill","own","","","","src/HexmakerSettingTab.ts:534","" +"Settings.legacyCoordLabelSize","Settings","Legacy (pre-1.13)","Coordinate label (slider)","overkill","overkill","own","","simple (twin Settings.coordFontSize)","Settings.coordFontSize","src/HexmakerSettingTab.ts:1167","this and other stuff like it should just map to the same setting ideally. " +"Settings.legacyCoordLabelFont","Settings","Legacy (pre-1.13)","Coordinate label (font)","overkill","overkill","own","","simple (twin Settings.coordFontFamily)","Settings.coordFontFamily","src/HexmakerSettingTab.ts:1178","" +"Settings.legacyCoordLabelColor","Settings","Legacy (pre-1.13)","Coordinate label (color)","overkill","overkill","own","","simple (twin Settings.coordFontColor)","Settings.coordFontColor","src/HexmakerSettingTab.ts:1193","" +"Settings.legacyHexNameFont","Settings","Legacy (pre-1.13)","Hex name font (font)","overkill","overkill","own","","simple (twin Settings.hexNameFont)","Settings.hexNameFont","src/HexmakerSettingTab.ts:1214","" +"Settings.legacyHexNameSize","Settings","Legacy (pre-1.13)","Hex name font (size)","overkill","overkill","own","","simple (twin Settings.hexNameSize)","Settings.hexNameSize","src/HexmakerSettingTab.ts:1221","" +"Settings.legacyHexNameStyle","Settings","Legacy (pre-1.13)","Hex name font (style)","overkill","overkill","own","","simple (twin Settings.hexNameStyle)","Settings.hexNameStyle","src/HexmakerSettingTab.ts:1228","" +"Settings.legacyNewMapCols","Settings","Legacy (pre-1.13)","Default new map size (Cols)","advanced","advanced","own","","","Settings.defaultNewMapCols","src/HexmakerSettingTab.ts:1263","" +"Settings.legacyNewMapRows","Settings","Legacy (pre-1.13)","Default new map size (Rows)","advanced","advanced","own","","","Settings.defaultNewMapRows","src/HexmakerSettingTab.ts:1272","" +"Settings.legacySubmapCols","Settings","Legacy (pre-1.13)","Default submap size (Cols)","advanced","advanced","own","","","Settings.defaultSubmapCols","src/HexmakerSettingTab.ts:1285","" +"Settings.legacySubmapRows","Settings","Legacy (pre-1.13)","Default submap size (Rows)","advanced","advanced","own","","","Settings.defaultSubmapRows","src/HexmakerSettingTab.ts:1294","" +"Settings.legacyPaletteDeleteButton","Settings","Legacy (pre-1.13)","Delete","advanced","simple","own","","advanced (twin Settings.paletteDelete)","Settings.paletteDelete","src/HexmakerSettingTab.ts:1742","i think custom palettes should be simple. We want a streamlined but still customizable experience for simple, not to hide every little possible scary thing. " +"Wizard.mapKindWorld","Setup wizard","Welcome","World / fantasy overland","keep","keep","group","group:Setup wizard/Welcome","","","src/SetupWizardView.ts:243","" +"Wizard.mapKindSpace","Setup wizard","Welcome","Space","keep","keep","group","group:Setup wizard/Welcome","","","src/SetupWizardView.ts:243","" +"Wizard.featureLevel","Setup wizard","Welcome","How much do you want to start with? (Simple/Advanced)","keep","keep","group","group:Setup wizard/Welcome","","","src/SetupWizardView.ts:261","" +"Wizard.worldFolder","Setup wizard","Folders","World folder","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:304","" +"Wizard.configureFoldersIndividually","Setup wizard","Folders","Configure each folder path individually","advanced","advanced","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:324","" +"Wizard.folder.hex","Setup wizard","Folders","Hex notes","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.towns","Setup wizard","Folders","Towns","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.dungeons","Setup wizard","Folders","Dungeons","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.quests","Setup wizard","Folders","Quests","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.features","Setup wizard","Folders","Features","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.factions","Setup wizard","Folders","Factions","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.regions","Setup wizard","Folders","Regions","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.tables","Setup wizard","Folders","Tables","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.workflows","Setup wizard","Folders","Workflows","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.templates","Setup wizard","Folders","Templates","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.folder.icons","Setup wizard","Folders","Icons","keep","keep","group","group:Setup wizard/Folders","","","src/SetupWizardView.ts:350","" +"Wizard.mapName","Setup wizard","Map","Map name","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:440","" +"Wizard.gridCols","Setup wizard","Map","Grid size (columns)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:469","" +"Wizard.gridRows","Setup wizard","Map","Grid size (rows)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:479","" +"Wizard.hexOrientation","Setup wizard","Map","Hex orientation (Flat-top / Pointy-top)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:544","" +"Wizard.terrainPalette","Setup wizard","Map","Terrain palette","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:579","" +"Wizard.generatorCards","Setup wizard","Map","Terrain (generator cards)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:633","" +"Wizard.genOptWater","Setup wizard","Map","Water","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.genOptClimate","Setup wizard","Map","Climate","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.genOptRelief","Setup wizard","Map","Relief","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.genOptSea","Setup wizard","Map","Sea","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.genOptOther","Setup wizard","Map","(other generator options)","advanced","advanced","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:647","" +"Wizard.reroll","Setup wizard","Map","Re-roll (dice)","keep","keep","group","group:Setup wizard/Map","","","src/SetupWizardView.ts:607","" +"Wizard.openHexMap","Setup wizard","Done","Open hex map","keep","keep","group","group:Setup wizard/Done","","","src/SetupWizardView.ts:841","" +"Wizard.exploreOnOwn","Setup wizard","Done","I'll explore on my own","keep","keep","group","group:Setup wizard/Done","","","src/SetupWizardView.ts:847","" +"Wizard.back","Setup wizard","Navigation","back","keep","keep","group","group:Setup wizard/Navigation","","","src/SetupWizardView.ts:943","" +"Wizard.next","Setup wizard","Navigation","Next","keep","keep","group","group:Setup wizard/Navigation","","","src/SetupWizardView.ts:957","" +"Wizard.remindLater","Setup wizard","Navigation","Remind me later","keep","keep","group","group:Setup wizard/Navigation","","","src/SetupWizardView.ts:967","" +"Wizard.dontShowAgain","Setup wizard","Navigation","Don't show again","keep","keep","group","group:Setup wizard/Navigation","","","src/SetupWizardView.ts:975","" +"Hint.turnOnFeature","Feature hints","Inline hints","Turn on ","keep","keep","group","group:Feature hints/Inline hints","","","src/advancedHints.ts:158","" +"Hint.close","Feature hints","Inline hints","X (Hide this hint)","keep","keep","group","group:Feature hints/Inline hints","","","src/advancedHints.ts:160","" +"Hints.show","Feature hints","Inline hints","Show","keep","keep","group","group:Feature hints/Inline hints","","","src/advancedHints.ts:191","" +"MoreFeatures.turnOn","Feature hints","More options modal","Turn on","keep","keep","group","group:Feature hints/More options modal","","","src/advancedHints.ts:235","" +"MoreFeatures.turnOnAll","Feature hints","More options modal","Turn on all advanced features","keep","keep","group","group:Feature hints/More options modal","","","src/advancedHints.ts:241","" +"MoreFeatures.closeButtons","Feature hints","More options modal","Done","keep","keep","group","group:Feature hints/More options modal","","","src/advancedHints.ts:244","" +"EnableFeature.turnOnOne","Feature hints","Turn on ? modal","Turn on ","keep","keep","group","group:Feature hints/Turn on ? modal","","","src/advancedHints.ts:274","" +"EnableFeature.turnOnAll","Feature hints","Turn on ? modal","Turn on all advanced features","keep","keep","group","group:Feature hints/Turn on ? modal","","","src/advancedHints.ts:276","" +"EnableFeature.closeButtons","Feature hints","Turn on ? modal","Not now","keep","keep","group","group:Feature hints/Turn on ? modal","","","src/advancedHints.ts:277","" +"Nudge.turnOnAdvanced","Feature hints","Ready for more? modal","Turn on advanced features","keep","keep","group","group:Feature hints/Ready for more? modal","","","src/advancedHints.ts:318","" +"Nudge.closeButtons","Feature hints","Ready for more? modal","Not now","keep","keep","group","group:Feature hints/Ready for more? modal","","","src/advancedHints.ts:323","" +"Nudge.dontAskAgain","Feature hints","Ready for more? modal","Don't ask again","keep","keep","group","group:Feature hints/Ready for more? modal","","","src/advancedHints.ts:324","" +"Plugin.ribbonOpenHexMap","Commands & menus","Open views","Open hex map","simple","simple","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:278","" +"Plugin.cmd.openHexMap","Commands & menus","Open views","Open hex map","keep","keep","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:281","" +"Plugin.cmd.openHexTable","Commands & menus","Open views","Open hex table","simple","simple","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:286","" +"Plugin.cmd.openTerrainGenerator","Commands & menus","Open views","Open terrain generator","keep","keep","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:294","" +"Plugin.cmd.openPaletteEditor","Commands & menus","Open views","Open palette editor","simple","simple","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:299","" +"Plugin.cmd.editWorldTypes","Commands & menus","Open views","Edit world types...","keep","keep","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:304","" +"Plugin.cmd.newOverworld","Commands & menus","Open views","New overworld...","keep","keep","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:316","" +"Plugin.cmd.openRandomTables","Commands & menus","Open views","Open random tables","simple","simple","group","group:Commands & menus/Open views","","","src/HexmakerPlugin.ts:355","" +"WorldTypes.command","Commands & menus","Open views","Edit world types…","keep","keep","twin","Plugin.cmd.editWorldTypes","","Plugin.cmd.editWorldTypes","src/space/WorldTypesModal.ts:311","" +"Plugin.cmd.mapGoUp","Commands & menus","Map navigation commands","Go up to parent map","keep","keep","group","group:Commands & menus/Map navigation commands","","","src/HexmakerPlugin.ts:325","" +"Plugin.cmd.mapGoBack","Commands & menus","Map navigation commands","Go back to previous map","keep","keep","group","group:Commands & menus/Map navigation commands","","","src/HexmakerPlugin.ts:335","" +"Plugin.cmd.mapGoForward","Commands & menus","Map navigation commands","Go forward to the next map","keep","keep","group","group:Commands & menus/Map navigation commands","","","src/HexmakerPlugin.ts:345","" +"Plugin.cmd.addRollRanges","Commands & menus","Maintenance commands","Add roll ranges to tables","overkill","overkill","group","group:Commands & menus/Maintenance commands","","","src/HexmakerPlugin.ts:363","" +"Plugin.cmd.checkTables","Commands & menus","Maintenance commands","Check tables","overkill","overkill","group","group:Commands & menus/Maintenance commands","","","src/HexmakerPlugin.ts:368","" +"Plugin.cmd.addMapDataToHexNotes","Commands & menus","Maintenance commands","Add map data to this map's hex notes","overkill","overkill","group","group:Commands & menus/Maintenance commands","","","src/HexmakerPlugin.ts:416","" +"Plugin.cmd.updateRegionFactionMapData","Commands & menus","Maintenance commands","Update map data in region and faction notes","overkill","overkill","group","group:Commands & menus/Maintenance commands","","","src/HexmakerPlugin.ts:438","" +"Plugin.cmd.exportNotePdf","Commands & menus","Export commands","Export current note to PDF","advanced","advanced","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:373","" +"Plugin.cmd.exportNoteMarkdown","Commands & menus","Export commands","Export current note to Markdown","advanced","advanced","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:383","" +"Plugin.cmd.exportCurrentHex","Commands & menus","Export commands","Export current hex (structured PDF / Markdown)","simple","simple","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:393","" +"Plugin.cmd.exportCurrentWorkflow","Commands & menus","Export commands","Export current workflow with rolled samples","advanced","advanced","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:403","" +"Plugin.cmd.exportCurrentMap","Commands & menus","Export commands","Export current map...","simple","simple","group","group:Commands & menus/Export commands","","","src/HexmakerPlugin.ts:456","" +"Plugin.fileMenuExportPdf","Commands & menus","Note right-click menus","Export to PDF","advanced","advanced","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:473","" +"Plugin.fileMenuExportMarkdown","Commands & menus","Note right-click menus","Export to Markdown","advanced","advanced","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:480","" +"Plugin.editorMenuInsertRoller","Commands & menus","Note right-click menus","Insert table roller","keep","keep","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:506","" +"Plugin.editorMenuInsertMapLink","Commands & menus","Note right-click menus","Insert map link","keep","keep","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:523","" +"Plugin.insertRollerPicker","Commands & menus","Note right-click menus","Search for a file to link...","keep","keep","twin","Editor.insertTableRoller","","Editor.insertTableRoller","src/hex-map/FileLinkSuggestModal.ts:19","" +"Editor.insertTableRoller","Commands & menus","Note right-click menus","Search for a file to link...","keep","keep","group","group:Commands & menus/Note right-click menus","","","src/HexmakerPlugin.ts:512","" +"MapToolbar.hexTableBtn","Hex map view","Top bar","Open hex table (⊞)","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1473","" +"MapToolbar.randomTablesBtn","Hex map view","Top bar","Open random tables (🎲)","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1497","" +"MapToolbar.mapSwitcher","Hex map view","Top bar"," ▾ (Manage maps)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1529","" +"MapToolbar.workModeBtn","Hex map view","Top bar","Mode: Play / Build / God","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1551","" +"MapToolbar.undo","Hex map view","Top bar","Undo (up to 20) ↩","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1555","" +"MapToolbar.redo","Hex map view","Top bar","Redo ↪","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1565","" +"MapToolbar.help","Hex map view","Top bar","Controls & tools (?)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1577","" +"MapToolbar.drawingToolsToggle","Hex map view","Top bar","Drawing tools (pencil)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:22","" +"MapToolbar.layersToggle","Hex map view","Top bar","Map overlays (layers)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:22","" +"MapNav.breadcrumb","Hex map view","Map navigation","Go to (breadcrumb)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:690","" +"MapNav.back","Hex map view","Map navigation","← Back to (Alt+←)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:723","" +"MapNav.up","Hex map view","Map navigation","↑ Up to (Alt+↑)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:723","" +"MapNav.forward","Hex map view","Map navigation","→ Forward to (Alt+→)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:723","" +"MapNav.regionFlowerHere","Hex map view","Map navigation","Here: . Click to edit this region.","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:859","" +"MapNav.regionFlowerPetal","Hex map view","Map navigation"," petal","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:878","" +"MapNav.regionFlowerNewLand","Hex map view","Map navigation","+ (new land petal)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:878","" +"MapNav.mapPadGo","Hex map view","Map navigation","D-pad neighbour map (◀▲▶▼)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:921","" +"MapNav.mapPadNew","Hex map view","Map navigation","+ (new neighbouring map)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:921","" +"WorkModeMenu.play","Hex map view","Work modes","Play: Run a game…","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:758","" +"WorkModeMenu.build","Hex map view","Work modes","Build: Add to and edit the map…","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:758","" +"WorkModeMenu.god","Hex map view","Work modes","God: Change anything…","advanced","advanced","own","","","","src/hex-map/HexMapView.ts:758","Yes but ask to enable it and other things when they start poking around region/generators/etc." +"ModeBar.stop","Hex map view","Work modes","Stop this tool (✕)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1032","" +"ModeBar.autoRoute","Hex map view","Work modes","Auto-route","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:1423","" +"ModeBar.crossImpassable","Hex map view","Work modes","Cross impassable","advanced","advanced","group","group:Hex map view","","","src/hex-map/pathTool.ts:1453","" +"ModeBar.pathNameChip","Hex map view","Work modes"," (Rename this path)","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:1462","" +"ModeBar.newPath","Hex map view","Work modes","New path","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:1469","" +"ModeBar.done","Hex map view","Work modes","Done","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:1477","" +"ModeBar.confirmIntoRegions","Hex map view","Work modes","Confirm into regions / Update regions","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:6253","" +"DrawingPanel.centerHex","Hex map view","Drawing tools","Center hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2023","" +"DrawingPanel.terrain","Hex map view","Drawing tools","Terrain","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2031","" +"DrawingPanel.biome","Hex map view","Drawing tools","Biome","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2043","" +"DrawingPanel.icon","Hex map view","Drawing tools","Icon","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2051","" +"DrawingPanel.path","Hex map view","Drawing tools","Path","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2062","" +"DrawingPanel.linkTable","Hex map view","Drawing tools","Link table","advanced","advanced","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2073","" +"DrawingPanel.linkSubmap","Hex map view","Drawing tools","Link submap","advanced","advanced","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2083","" +"DrawingPanel.factions","Hex map view","Drawing tools","Factions","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2093","" +"DrawingPanel.regionAreas","Hex map view","Drawing tools","Region areas","advanced","advanced","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2103","" +"DrawingPanel.token","Hex map view","Drawing tools","Token","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2113","" +"MapView.tableLinkToolPicker","Hex map view","Drawing tools","Select table","advanced","advanced","twin","DrawingPanel.linkTable","","DrawingPanel.linkTable","src/hex-map/HexMapView.ts:2424","" +"PainterMenu.switchTerrain","Hex map view","Tool right-click menus","Switch terrain","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2145","" +"PainterMenu.switchIcon","Hex map view","Tool right-click menus","Switch icon","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2149","" +"PainterMenu.switchTable","Hex map view","Tool right-click menus","Switch table","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2153","" +"PainterMenu.switchSubmap","Hex map view","Tool right-click menus","Switch submap","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2157","" +"PainterMenu.switchFaction","Hex map view","Tool right-click menus","Switch faction","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2161","" +"PainterMenu.switchRegion","Hex map view","Tool right-click menus","Switch region","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2165","" +"PainterMenu.switchPathType","Hex map view","Tool right-click menus","Switch path type","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2169","" +"PainterMenu.switchToken","Hex map view","Tool right-click menus","Switch token","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2173","" +"PainterMenu.switchBiome","Hex map view","Tool right-click menus","Switch biome","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2176","" +"PainterMenu.exitTool","Hex map view","Tool right-click menus","Exit tool","keep","keep","group","group:Hex map view","","","src/hex-map/PainterContextMenu.ts:24","" +"PainterMenu.eraseToggle","Hex map view","Tool right-click menus","Erase mode / Paint (Link, Draw) mode","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2146","" +"PainterMenu.newPath","Hex map view","Tool right-click menus","New path","drop","drop","group","group:Hex map view","","","src/hex-map/HexMapView.ts:2171","" +"PathMenu.splitHere","Hex map view","Tool right-click menus","Split here","advanced","advanced","group","group:Hex map view","","","src/hex-map/pathTool.ts:296","" +"PathMenu.deleteBranch","Hex map view","Tool right-click menus","Delete this fork / Delete main line","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:297","" +"PathMenu.deletePath","Hex map view","Tool right-click menus","Delete path: ","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:299","" +"PathMenu.rename","Hex map view","Tool right-click menus","Rename…","simple","simple","group","group:Hex map view","","","src/hex-map/pathTool.ts:300","" +"PathMenu.changeType","Hex map view","Tool right-click menus","Change type…","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:301","" +"PathMenu.reverse","Hex map view","Tool right-click menus","Reverse","advanced","advanced","group","group:Hex map view","","","src/hex-map/pathTool.ts:302","" +"PathMenu.switchToType","Hex map view","Tool right-click menus","Switch to to edit ","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:1075","" +"PathMenu.confirmIntoRegions","Hex map view","Tool right-click menus","Confirm into regions / Update regions","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:6274","" +"PathMenu.removeFromRegions","Hex map view","Tool right-click menus","Remove from regions","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:6274","" +"HexMenu.center","Hex map view","Hex right-click menu","Center on this hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4773","" +"HexMenu.openNote","Hex map view","Hex right-click menu","Open note","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4777","" +"HexMenu.enterRegion","Hex map view","Hex right-click menu","Enter region: ","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4792","" +"HexMenu.openLocation","Hex map view","Hex right-click menu","Open: ","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4795","" +"HexMenu.locationsList","Hex map view","Hex right-click menu","Locations (n)…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4801","" +"HexMenu.newMap","Hex map view","Hex right-click menu","New map from this hex…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4803","" +"HexMenu.linkExistingMap","Hex map view","Hex right-click menu","Link existing map…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4804","" +"HexMenu.manageLocations","Hex map view","Hex right-click menu","Manage locations…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4807","" +"HexMenu.linkTable","Hex map view","Hex right-click menu","Link table","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4810","" +"HexMenu.swapHex","Hex map view","Hex right-click menu","Swap hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4828","" +"HexMenu.createToken","Hex map view","Hex right-click menu","Create token here","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4833","" +"HexMenu.clearTerrain","Hex map view","Hex right-click menu","Clear terrain","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4839","" +"HexMenu.removeIconOverride","Hex map view","Hex right-click menu","Remove icon override","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4844","" +"HexMenu.lockedHint","Hex map view","Hex right-click menu","Switch to Build to … (disabled)","keep","keep","group","group:Hex map view","","","src/hex-map/modeMenu.ts:52","" +"MapView.linkTableMenuPicker","Hex map view","Hex right-click menu","Link table","keep","keep","twin","HexMenu.linkTable","","HexMenu.linkTable","src/hex-map/HexMapView.ts:4811","" +"OverworldMenu.enterRegion","Hex map view","Overworld menu & minimap","Enter region: ","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.editRegion","Hex map view","Overworld menu & minimap","Edit region…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.setBiome","Hex map view","Overworld menu & minimap","Set biome…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.center","Hex map view","Overworld menu & minimap","Center on this hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.locations","Hex map view","Overworld menu & minimap","Locations (n)…","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4871","" +"OverworldMenu.createToken","Hex map view","Overworld menu & minimap","Create token here","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4882","" +"Minimap.viewRegions","Hex map view","Overworld menu & minimap","View: Regions","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:61","" +"Minimap.viewBiomes","Hex map view","Overworld menu & minimap","View: Biomes","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:61","" +"Minimap.biomeLibrary","Hex map view","Overworld menu & minimap","Biomes…","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:71","" +"Minimap.toggle","Hex map view","Overworld menu & minimap","Show / Hide the overworld map","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:79","" +"Minimap.canvasClick","Hex map view","Overworld menu & minimap","Overworld minimap (click to go)","keep","keep","group","group:Hex map view","","","src/hex-map/overworldMinimap.ts:122","" +"OverworldMinimap.viewRegions","Hex map view","Overworld menu & minimap","View: Regions","keep","keep","twin","Minimap.viewRegions","","Minimap.viewRegions","src/hex-map/overworldMinimap.ts:393","" +"OverworldMinimap.viewBiomes","Hex map view","Overworld menu & minimap","View: Biomes","keep","keep","twin","Minimap.viewBiomes","","Minimap.viewBiomes","src/hex-map/overworldMinimap.ts:393","" +"OverworldMinimap.biomes","Hex map view","Overworld menu & minimap","Biomes…","keep","keep","twin","Minimap.biomeLibrary","","Minimap.biomeLibrary","src/hex-map/overworldMinimap.ts:403","" +"OverworldMinimap.toggle","Hex map view","Overworld menu & minimap","Show/Hide the overworld map","keep","keep","twin","Minimap.toggle","","Minimap.toggle","src/hex-map/overworldMinimap.ts:411","" +"OverworldMinimap.canvasClick","Hex map view","Overworld menu & minimap","(minimap hex click)","keep","keep","twin","Minimap.canvasClick","","Minimap.canvasClick","src/hex-map/overworldMinimap.ts:454","" +"OverworldMenu.enterRegion_2","Hex map view","Overworld menu & minimap","Enter region","keep","keep","twin","OverworldMenu.enterRegion","","OverworldMenu.enterRegion","src/overworld/overworldInput.ts:71","" +"OverworldMenu.editRegion_2","Hex map view","Overworld menu & minimap","Edit region…","keep","keep","twin","OverworldMenu.editRegion","","OverworldMenu.editRegion","src/overworld/overworldInput.ts:72","" +"OverworldMenu.setBiome_2","Hex map view","Overworld menu & minimap","Set biome…","keep","keep","twin","OverworldMenu.setBiome","","OverworldMenu.setBiome","src/overworld/overworldInput.ts:75","" +"OverworldMenu.center_2","Hex map view","Overworld menu & minimap","Center on this hex","keep","keep","twin","OverworldMenu.center","","OverworldMenu.center","src/overworld/overworldInput.ts:77","" +"OverworldMenu.locations_2","Hex map view","Overworld menu & minimap","Locations (n)…","keep","keep","twin","OverworldMenu.locations","","OverworldMenu.locations","src/overworld/overworldInput.ts:78","" +"TokenMenu.info","Hex map view","Token right-click menu","Token info","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:8010","" +"TokenMenu.edit","Hex map view","Token right-click menu","Edit token","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:8011","" +"TokenMenu.openNote","Hex map view","Token right-click menu","Open note","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:8012","" +"TokenMenu.remove","Hex map view","Token right-click menu","Remove token","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:8017","" +"LayersMenu.coordinates","Hex map view","Layers panel","Coordinates","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:105","" +"LayersMenu.hexNames","Hex map view","Layers panel","Hex names","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:106","" +"LayersMenu.tokenNames","Hex map view","Layers panel","Token names","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:107","" +"LayersMenu.nameFontBtn","Hex map view","Layers panel","Aa (Hex name font)","simple","simple","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:319","" +"LayersMenu.nameFontFamily","Hex map view","Layers panel","Font","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:337","" +"LayersMenu.nameSize","Hex map view","Layers panel","Name size S / M / L / XL","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:347","" +"LayersMenu.nameBold","Hex map view","Layers panel","Bold (B)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:371","" +"LayersMenu.nameItalic","Hex map view","Layers panel","Italic (I)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:372","" +"LayersMenu.nameFontReset","Hex map view","Layers panel","Use the default name font (settings)","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:374","" +"LayersMenu.terrainIcons","Hex map view","Layers panel","Show terrain icons","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:102","" +"LayersMenu.iconOverrides","Hex map view","Layers panel","Show icon overrides","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:103","" +"LayersMenu.paths","Hex map view","Layers panel","Show paths","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:104","" +"LayersMenu.tokens","Hex map view","Layers panel","Show tokens","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:153","" +"LayersMenu.factionOverlay","Hex map view","Layers panel","Show faction overlay","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:178","" +"LayersMenu.regionOverlay","Hex map view","Layers panel","Show region overlay","advanced","advanced","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:202","" +"LayersMenu.gmLayer","Hex map view","Layers panel","Show GM layer","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:226","" +"LayersMenu.linkBadges","Hex map view","Layers panel","Show link badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:430","" +"LayersMenu.badgeSize","Hex map view","Layers panel","Badge size S / M / L","simple","simple","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:436","" +"LayersMenu.badgeTypesMore","Hex map view","Layers panel","Pick badge types (▸)","simple","simple","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:451","" +"LayersMenu.badgeTowns","Hex map view","Layers panel","Towns badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.badgeDungeons","Hex map view","Layers panel","Dungeons badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.badgeFeatures","Hex map view","Layers panel","Features badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.badgeQuests","Hex map view","Layers panel","Quests badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.badgeFactions","Hex map view","Layers panel","Factions badges","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:484","" +"LayersMenu.legend","Hex map view","Layers panel","Show legend","keep","keep","group","group:Hex map view","","","src/hex-map/HexSidePanel.ts:251","" +"Legend.size","Hex map view","Legend, grid edges & notices","Legend size S / M / L","simple","simple","group","group:Hex map view","","","src/hex-map/terrainLegend.ts:160","" +"Legend.minimize","Hex map view","Legend, grid edges & notices","Minimize (–)","keep","keep","group","group:Hex map view","","","src/hex-map/terrainLegend.ts:171","" +"Legend.hide","Hex map view","Legend, grid edges & notices","Hide legend (×)","keep","keep","group","group:Hex map view","","","src/hex-map/terrainLegend.ts:183","" +"Legend.expandChip","Hex map view","Legend, grid edges & notices","Legend (Show the legend)","keep","keep","group","group:Hex map view","","","src/hex-map/terrainLegend.ts:145","" +"MapGrid.expand","Hex map view","Legend, grid edges & notices","+ (grow edge, 4 sides)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1961","" +"MapGrid.shrink","Hex map view","Legend, grid edges & notices","− / OK? (shrink edge, 4 sides)","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1966","" +"PathTool.rerouteInstead","Hex map view","Legend, grid edges & notices","Reroute instead","keep","keep","group","group:Hex map view","","","src/paths/routePins.ts:196","" +"MapView.calibrationDone","Hex map view","Mouse & keyboard","Done calibrating (✓)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:3680","" +"MapView.missingRestore","Hex map view","Mouse & keyboard","Restore","keep","keep","group","group:Hex map view","","","src/hex-map/MapModal.ts:46","" +"MapView.missingRemove","Hex map view","Mouse & keyboard","Remove","keep","keep","group","group:Hex map view","","","src/hex-map/MapModal.ts:52","" +"MapView.hexClick","Hex map view","Mouse & keyboard","Click hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4897","" +"MapView.hexCtrlClick","Hex map view","Mouse & keyboard","Ctrl/Cmd+click hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4953","" +"MapView.hexCtrlShiftClick","Hex map view","Mouse & keyboard","Ctrl/Cmd+Shift+click hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4957","" +"MapView.hexRightClick","Hex map view","Mouse & keyboard","Right-click hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1451","" +"MapView.locationBadge","Hex map view","Mouse & keyboard","Location badge (Enter location / Locations)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4423","" +"MapView.regionShadowHex","Hex map view","Mouse & keyboard","Neighbouring region hex (shadow)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4638","" +"MapView.overworldClick","Hex map view","Mouse & keyboard","Click overworld hex","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:4936","" +"MapView.tokenDrag","Hex map view","Mouse & keyboard","Drag token","simple","simple","group","group:Hex map view","","","src/hex-map/HexMapView.ts:7853","" +"MapView.tokenRightClick","Hex map view","Mouse & keyboard","Right-click token","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:7840","" +"MapView.wheelZoom","Hex map view","Mouse & keyboard","Mouse wheel","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1100","" +"MapView.dragPan","Hex map view","Mouse & keyboard","Drag (left/middle/right)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1147","" +"MapView.dblRightClickExit","Hex map view","Mouse & keyboard","Double right-click","drop","drop","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1395","" +"MapView.dblClickOffGridExit","Hex map view","Mouse & keyboard","Double-click off the grid","drop","drop","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1458","" +"MapView.gmIconRightClick","Hex map view","Mouse & keyboard","Right-click hex (GM icon paint)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1408","" +"PathTool.anchorRightClick","Hex map view","Mouse & keyboard","Right-click path anchor","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:1063","" +"PathTool.anchorDrag","Hex map view","Mouse & keyboard","Drag path point/line","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1270","" +"Keys.escape","Hex map view","Mouse & keyboard","Esc","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1043","" +"Keys.undoRedo","Hex map view","Mouse & keyboard","Ctrl/Cmd+Z, Ctrl/Cmd+Shift+Z","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:990","" +"Keys.altArrows","Hex map view","Mouse & keyboard","Alt+← / Alt+↑ / Alt+→","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1001","" +"Keys.deleteAnchor","Hex map view","Mouse & keyboard","Backspace / Delete","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:1055","" +"Keys.altClickNewPath","Hex map view","Mouse & keyboard","Alt+click","keep","keep","group","group:Hex map view","","","src/hex-map/pathTool.ts:1472","" +"Keys.calibrationArrows","Hex map view","Mouse & keyboard","Arrow keys (Shift = 10px)","keep","keep","group","group:Hex map view","","","src/hex-map/HexMapView.ts:3605","" +"HexEditor.centerOnHex","Hex editor","Header","⌖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:196","" +"HexEditor.openNote","Hex editor","Header","Open note","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:216","" +"HexEditor.exportHex","Hex editor","Header","Export","simple","simple","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:224","" +"HexEditor.runWorkflow","Hex editor","Header","Run workflow","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:236","" +"HexEditor.workflowPicker","Hex editor","Header","Pick a workflow to run…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1660","" +"HexEditor.neighborTile","Hex editor","Header","Neighbour hex tiles","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:578","" +"HexEditor.neighborCrossRegion","Hex editor","Header","Neighbour tile (other region)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:600","" +"HexEditor.neighborWalkOverworld","Hex editor","Header","Neighbour tile (new region)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:621","" +"HexEditor.neighborNewLand","Hex editor","Header","Neighbour tile (new land)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:636","" +"HexEditor.neighborCentreDot","Hex editor","Header","Centre dot","drop","drop","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:660","do these actually link directly to a given hex? If a map is big enough I could see wanting to let a note direct-link a centered view on it, if this is the case then we should consider keeping this, maybe even as simple. " +"HexEditor.nameInput","Hex editor","Header","Name","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:449","" +"HexEditor.mapsChip","Hex editor","Header","Maps: region/location chips","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:694","" +"HexEditor.mapsAdd","Hex editor","Header","+ (Maps)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:709","" +"HexEditor.mapsNewMap","Hex editor","Header","New map from this hex…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:713","" +"HexEditor.mapsLinkExisting","Hex editor","Header","Link existing map…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:715","" +"HexEditor.mapsManageLocations","Hex editor","Header","Manage locations (N)…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:718","" +"HexEditor.closeButtons","Hex editor","Header","Close (×)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:428","" +"HexEditor.collapseTerrain","Hex editor","Section headers","Terrain ▶/▼","keep","keep","group","group:Hex editor/Section headers","","","src/hex-map/HexEditorModal.ts:276","" +"HexEditor.collapseNotes","Hex editor","Section headers","Notes ▶/▼","keep","keep","group","group:Hex editor/Section headers","","","src/hex-map/HexEditorModal.ts:298","" +"HexEditor.collapseLinked","Hex editor","Section headers","Linked notes ▶/▼","keep","keep","group","group:Hex editor/Section headers","","","src/hex-map/HexEditorModal.ts:356","" +"HexEditor.collapseIcons","Hex editor","Section headers","Icons ▶/▼","keep","keep","group","group:Hex editor/Section headers","","","src/hex-map/HexEditorModal.ts:414","" +"HexEditor.terrainChangeHint","Hex editor","Terrain","▸ change","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:286","" +"HexEditor.terrainFilter","Hex editor","Terrain","Filter terrains…","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:815","" +"HexEditor.terrainPicker","Hex editor","Terrain","Terrain swatches","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:860","" +"HexEditor.terrainClear","Hex editor","Terrain","Clear","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:846","" +"HexEditor.bodyFieldUseOnMap","Hex editor","Terrain","Use ""X"" on the map","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1493","" +"HexEditor.bodyFieldUpdateNote","Hex editor","Terrain","Change the note to ""X""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1510","" +"HexEditor.description","Hex editor","Notes","Description","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1575","" +"HexEditor.descriptionRoll","Hex editor","Notes","📖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1584","" +"HexEditor.landmark","Hex editor","Notes","Landmark","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1575","" +"HexEditor.landmarkRoll","Hex editor","Notes","📖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1584","" +"HexEditor.hidden","Hex editor","Notes","Hidden","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1575","" +"HexEditor.hiddenRoll","Hex editor","Notes","📖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1584","" +"HexEditor.secret","Hex editor","Notes","Secret","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1575","" +"HexEditor.secretRoll","Hex editor","Notes","📖","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1584","" +"HexEditor.gmLayerShow","Hex editor","Notes","Show them","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:319","" +"HexEditor.rolledSectionsFold","Hex editor","Notes","Weather · Hooks & Rumors","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:329","" +"HexEditor.weather","Hex editor","Notes","Weather","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:332","" +"HexEditor.weatherRoll","Hex editor","Notes","🎲 (Weather)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1710","" +"HexEditor.weatherSource","Hex editor","Notes","⋯ (Weather)","advanced","advanced","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1711","" +"HexEditor.hooks","Hex editor","Notes","Hooks & Rumors","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:332","" +"HexEditor.hooksRoll","Hex editor","Notes","🎲 (Hooks & Rumors)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1710","" +"HexEditor.hooksSource","Hex editor","Notes","⋯ (Hooks & Rumors)","advanced","advanced","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1711","" +"HexEditor.rolledSetMapTable","Hex editor","Notes","Set/Change the map's … table…","advanced","advanced","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1760","" +"HexEditor.rolledSetHexTable","Hex editor","Notes","Use a different table for this hex…","advanced","advanced","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1761","" +"HexEditor.rolledUseMapTable","Hex editor","Notes","Use the map's table on this hex","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1763","" +"HexEditor.rolledTablePicker","Hex editor","Notes","Weather/rumour table chooser","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1722","" +"HexEditor.moreInNoteFold","Hex editor","Notes","More in this note (N)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:345","" +"HexEditor.moreInNoteText","Hex editor","Notes"," (other sections)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:348","" +"HexEditor.sectionTablePicker","Hex editor","Notes","(set map's / this hex's table)","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1722","" +"HexEditor.encountersLink","Hex editor","Linked notes","Encounters Table","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.encountersShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.encountersCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.encountersOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.encountersRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.townsLink","Hex editor","Linked notes","Towns","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.townsShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.townsCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.townsOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.townsRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.dungeonsLink","Hex editor","Linked notes","Dungeons","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.dungeonsShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.dungeonsCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.dungeonsOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.dungeonsRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.questsLink","Hex editor","Linked notes","Quests","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.questsShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.questsCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.questsOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.questsRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.factionsLink","Hex editor","Linked notes","Factions","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.factionsShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.factionsCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.factionsOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.factionsRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.featuresLink","Hex editor","Linked notes","Features","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1144","" +"HexEditor.featuresShowAll","Hex editor","Linked notes","▾","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1151","" +"HexEditor.featuresCreate","Hex editor","Linked notes","+ Create ""…""","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1272","" +"HexEditor.featuresOpenLink","Hex editor","Linked notes","","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1440","" +"HexEditor.featuresRemove","Hex editor","Linked notes","×","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1459","" +"HexEditor.encountersRoll","Hex editor","Linked notes","🎲 (Encounters)","simple","simple","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1450","" +"HexEditor.iconOverride","Hex editor","Icons","Icon override","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:922","" +"HexEditor.iconTerrainDefault","Hex editor","Icons","— terrain default —","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:926","" +"HexEditor.iconPackTabs","Hex editor","Icons","All / / Custom tabs","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:108","" +"HexEditor.iconPlaceKinds","Hex editor","Icons","All places / Settlements / Castles…","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:133","" +"HexEditor.gmIcons","Hex editor","Icons","Game master icons","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:941","" +"HexEditor.gmIconsRemoveOne","Hex editor","Icons","Right-click icon","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1037","" +"HexEditor.gmIconsClearAll","Hex editor","Icons","— clear all —","keep","keep","group","group:Hex editor","","","src/hex-map/HexEditorModal.ts:1050","" +"HexEditor.gmIconFilterSearch","Hex editor","Icons","Filter icons… (GM)","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:45","" +"HexEditor.gmIconPackTabs","Hex editor","Icons","All / / Custom tabs (GM)","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:108","" +"HexEditor.gmIconPlaceKinds","Hex editor","Icons","Place kind chips (GM)","keep","keep","group","group:Hex editor","","","src/HexmakerModal.ts:133","" +"HexTable.refresh","Hex table","Toolbar","Refresh","overkill","overkill","group","group:Hex table","","","src/hex-table/HexTableView.ts:143","" +"HexTable.xMin","Hex table","Toolbar","X: Min","advanced","advanced","group","group:Hex table","","","src/hex-table/HexTableView.ts:153","" +"HexTable.xMax","Hex table","Toolbar","X: Max","advanced","advanced","group","group:Hex table","","","src/hex-table/HexTableView.ts:164","" +"HexTable.yMin","Hex table","Toolbar","Y: Min","advanced","advanced","group","group:Hex table","","","src/hex-table/HexTableView.ts:179","" +"HexTable.yMax","Hex table","Toolbar","Y: Max","advanced","advanced","group","group:Hex table","","","src/hex-table/HexTableView.ts:190","" +"HexTable.terrainFilter","Hex table","Toolbar","Terrain: all","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:204","" +"HexTable.hasTown","Hex table","Toolbar","Town","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:240","" +"HexTable.hasDungeon","Hex table","Toolbar","Dungeon","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:252","" +"HexTable.hasFeature","Hex table","Toolbar","Feature","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:264","" +"HexTable.hasQuest","Hex table","Toolbar","Quest","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:276","" +"HexTable.hasFaction","Hex table","Toolbar","Faction","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:288","" +"HexTable.mapSelect","Hex table","Toolbar","All maps / ","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:299","" +"HexTable.sortCycle","Hex table","Toolbar","Sort: xy / yx / type","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:329","" +"HexTable.sortDirection","Hex table","Toolbar","↑ asc / ↓ desc","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:341","" +"HexTable.clearFilters","Hex table","Toolbar","Clear filters","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:355","" +"HexTable.jumpToHex","Hex table","Rows & cells","◎","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:802","" +"HexTable.openHexNote","Hex table","Rows & cells","","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:812","" +"HexTable.terrainCell","Hex table","Rows & cells","Terrain cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:889","" +"HexTable.townsCell","Hex table","Rows & cells","Towns cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:970","" +"HexTable.dungeonsCell","Hex table","Rows & cells","Dungeons cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:970","" +"HexTable.encountersCell","Hex table","Rows & cells","Enc. Table cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:970","" +"HexTable.encountersMiddleClick","Hex table","Rows & cells","Middle-click Enc. Table","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:947","" +"HexTable.otherLinkCell","Hex table","Rows & cells","Features/Quests/Factions cell","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:1031","" +"HexTable.textCell","Hex table","Rows & cells","Text cells (Description…Hooks)","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:1054","" +"HexTable.columnResize","Hex table","Rows & cells","Column edge drag","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:1119","" +"HexTable.hiddenSecretColumns","Hex table","Rows & cells","Hidden / Secret columns","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:44","" +"HexTable.weatherHooksColumns","Hex table","Rows & cells","Weather / Hooks & Rumors columns","keep","keep","group","group:Hex table","","","src/hex-table/HexTableView.ts:46","" +"HexCell.textarea","Hex table","Rows & cells","
text","keep","keep","group","group:Hex table","","","src/hex-table/HexCellModal.ts:38","" +"HexCell.rollOnTable","Hex table","Rows & cells","🎲 Roll on table","keep","keep","group","group:Hex table","","","src/hex-table/HexCellModal.ts:46","" +"HexCell.linkList","Hex table","Rows & cells","","keep","keep","group","group:Hex table","","","src/hex-table/HexCellModal.ts:33","" +"HexCell.closeButtons","Hex table","Rows & cells","×","keep","keep","group","group:Hex table","","","src/hex-table/HexCellModal.ts:69","" +"TerrainFilter.noTerrain","Hex table","Terrain filter","No terrain","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:156","" +"TerrainFilter.typeRow","Hex table","Terrain filter"," row","advanced","advanced","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:160","" +"TerrainFilter.terrainRow","Hex table","Terrain filter"," rows","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:168","" +"TerrainFilter.excludeRightClick","Hex table","Terrain filter","Right-click to exclude","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:94","" +"TerrainFilter.categoryHeading","Hex table","Terrain filter"," heading","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:130","" +"TerrainFilter.clearAll","Hex table","Terrain filter","Clear all","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:206","" +"TerrainFilter.closeButtons","Hex table","Terrain filter","Done / ×","keep","keep","group","group:Hex table","","","src/hex-table/TerrainFilterModal.ts:216","" +"HexTerrainPicker.terrains","Hex table","Terrain filter","Select terrain","keep","keep","group","group:Hex table","","","src/hex-table/HexTerrainPickerModal.ts:129","" +"HexTerrainPicker.clear","Hex table","Terrain filter","Clear terrain","keep","keep","group","group:Hex table","","","src/hex-table/HexTerrainPickerModal.ts:160","" +"HexTerrainPicker.closeButtons","Hex table","Terrain filter","×","keep","keep","group","group:Hex table","","","src/hex-table/HexTerrainPickerModal.ts:120","" +"LinkPicker.townsList","Hex table","Linking","Select existing: (Towns)","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:206","" +"LinkPicker.dungeonsList","Hex table","Linking","Select existing: (Dungeons)","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:206","" +"LinkPicker.encountersList","Hex table","Linking","Select existing: (Encounters Table)","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:206","" +"LinkPicker.createName","Hex table","Linking","Or create new: ","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:232","" +"LinkPicker.createButton","Hex table","Linking","Create","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:237","" +"LinkPicker.closeButtons","Hex table","Linking","×","keep","keep","group","group:Hex table","","","src/hex-table/LinkPickerModal.ts:199","" +"MultiLinkNav.items","Hex table","Linking","","keep","keep","group","group:Hex table","","","src/hex-table/MultiLinkNavModal.ts:20","" +"MultiLinkNav.closeButtons","Hex table","Linking","×","keep","keep","group","group:Hex table","","","src/hex-table/MultiLinkNavModal.ts:13","" +"IconFilter.search","Map pickers & editors","Icons","Filter icons...","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:45","" +"IconFilter.packTabs","Map pickers & editors","Icons","All / Terrain / Places / Space / Custom (+counts)","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:108","" +"IconFilter.placeKindChips","Map pickers & editors","Icons","All places / Settlements / Castles / ...","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:134","" +"IconPicker.gmLayerOnly","Map pickers & editors","Icons","GM layer only","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:45","" +"IconPicker.manageIcons","Map pickers & editors","Icons","Manage icons / ← pick icons","simple","simple","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:57","" +"IconPicker.remove","Map pickers & editors","Icons","Remove","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:79","" +"IconPicker.grid","Map pickers & editors","Icons","(icon tiles)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:89","" +"IconPicker.packTabs","Map pickers & editors","Icons","All / Terrain / Places / Space / Custom","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:109","" +"IconPicker.hideToggle","Map pickers & editors","Icons","eye / eye-off","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:138","" +"IconPicker.dragReorder","Map pickers & editors","Icons","⠿ (drag to reorder)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:157","" +"IconPicker.uploadDropZone","Map pickers & editors","Icons","Drag & drop images here, or click to browse","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:204","" +"IconPicker.closeButtons","Map pickers & editors","Icons","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/IconPickerModal.ts:29","" +"Token.notePicker","Map pickers & editors","Tokens","Note","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:94","" +"Token.noteStatus","Map pickers & editors","Tokens","Links to … / Creates a new note: …","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:115","" +"Token.iconPackTabs","Map pickers & editors","Tokens","All / Terrain / Places / Space / Custom","keep","keep","group","group:Map pickers & editors","","","src/HexmakerModal.ts:109","" +"Token.iconGrid","Map pickers & editors","Tokens","Icon","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:199","" +"Token.shape","Map pickers & editors","Tokens","Shape","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:233","" +"Token.size","Map pickers & editors","Tokens","Size","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:244","" +"Token.fillColor","Map pickers & editors","Tokens","Fill color","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:262","" +"Token.borderToggle","Map pickers & editors","Tokens","Border color (on/off)","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:284","" +"Token.borderColor","Map pickers & editors","Tokens","Border color","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:292","" +"Token.description","Map pickers & editors","Tokens","Description","advanced","advanced","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:315","" +"Token.removeButton","Map pickers & editors","Tokens","Remove token","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:333","" +"Token.saveButton","Map pickers & editors","Tokens","Next: place on map / Save","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:340","" +"Token.closeButtons","Map pickers & editors","Tokens","Cancel","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenModal.ts:372","" +"TokenInfo.jumpButton","Map pickers & editors","Tokens","⌖","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:31","" +"TokenInfo.openNoteLink","Map pickers & editors","Tokens","Open note","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:44","" +"TokenInfo.editButton","Map pickers & editors","Tokens","Edit token","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:56","" +"TokenInfo.noteLinks","Map pickers & editors","Tokens","(links inside the note preview)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:91","" +"TokenInfo.removeButton","Map pickers & editors","Tokens","× remove / Confirm remove?","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:117","" +"TokenInfo.closeButtons","Map pickers & editors","Tokens","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TokenInfoModal.ts:20","" +"PathName.nameInput","Map pickers & editors","Path types","(path name)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathNameModal.ts:45","" +"PathName.saveButton","Map pickers & editors","Path types","Save","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathNameModal.ts:48","" +"PathName.closeButtons","Map pickers & editors","Path types","Cancel","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathNameModal.ts:49","" +"PathPicker.editToggle","Map pickers & editors","Path types","✏ Edit / ← Done","simple","simple","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:158","" +"PathPicker.drawMode","Map pickers & editors","Path types","1. How to draw: Hex by hex / Auto-route","simple","simple","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:107","" +"PathPicker.removeTile","Map pickers & editors","Path types","Remove","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:187","" +"PathPicker.typeGrid","Map pickers & editors","Path types","2. Pick a path type to start drawing","simple","simple","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:198","" +"PathPicker.pathsOnMap","Map pickers & editors","Path types","Paths on this map","advanced","advanced","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:229","" +"PathPicker.editTypeTile","Map pickers & editors","Path types","(type tile, edit mode)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:268","" +"PathPicker.dragReorder","Map pickers & editors","Path types","⠿ (drag to reorder)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:285","" +"PathPicker.addTypeTile","Map pickers & editors","Path types","+ Add","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:315","" +"PathPicker.closeButtons","Map pickers & editors","Path types","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathPickerModal.ts:133","" +"PathType.name","Map pickers & editors","Path types","Name","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:78","" +"PathType.color","Map pickers & editors","Path types","Color","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:88","" +"PathType.width","Map pickers & editors","Path types","Width","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:99","" +"PathType.lineStyle","Map pickers & editors","Path types","Line style","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:111","" +"PathType.routing","Map pickers & editors","Path types","Routing","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:125","" +"PathType.avoidImpassable","Map pickers & editors","Path types","Avoid impassable terrain","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:140","" +"PathType.autoRoute","Map pickers & editors","Path types","Auto-route","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:149","" +"PathType.carves","Map pickers & editors","Path types","Carves terrain","advanced","advanced","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:163","" +"PathType.carveWidth","Map pickers & editors","Path types","Carve width","overkill","overkill","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:173","" +"PathType.saveButton","Map pickers & editors","Path types","Save","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:185","" +"PathType.deleteButton","Map pickers & editors","Path types","Delete","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:194","" +"PathType.deleteConfirm","Map pickers & editors","Path types","Yes, delete / Cancel","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:212","" +"PathType.closeButtons","Map pickers & editors","Path types","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/PathTypeEditorModal.ts:225","" +"GotoHex.xInput","Map pickers & editors","Go to hex & help","X:","keep","keep","group","group:Map pickers & editors","","","src/hex-map/GotoHexModal.ts:21","" +"GotoHex.yInput","Map pickers & editors","Go to hex & help","Y:","keep","keep","group","group:Map pickers & editors","","","src/hex-map/GotoHexModal.ts:26","" +"GotoHex.goButton","Map pickers & editors","Go to hex & help","Go","keep","keep","group","group:Map pickers & editors","","","src/hex-map/GotoHexModal.ts:40","" +"GotoHex.closeButtons","Map pickers & editors","Go to hex & help","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/GotoHexModal.ts:14","" +"HexHelp.closeButtons","Map pickers & editors","Go to hex & help","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/HexHelpModal.ts:10","" +"Locations.search","Map pickers & editors","Locations","Find a location…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:45","" +"Locations.list","Map pickers & editors","Locations","(location name)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:111","" +"Locations.openButton","Map pickers & editors","Locations","Open","drop","drop","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:118","" +"Locations.unlink","Map pickers & editors","Locations","✕","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:122","" +"Locations.dragReorder","Map pickers & editors","Locations","⋮⋮ (drag)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:89","" +"Locations.newLocation","Map pickers & editors","Locations","New location…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:62","" +"Locations.linkExisting","Map pickers & editors","Locations","Link existing map…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:66","" +"Locations.closeButtons","Map pickers & editors","Locations","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/LocationsModal.ts:42","" +"FactionPicker.grid","Map pickers & editors","Factions","(faction tiles)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:207","" +"FactionPicker.removeTile","Map pickers & editors","Factions","Remove","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:193","" +"FactionPicker.editTile","Map pickers & editors","Factions","✏","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:221","" +"FactionPicker.newName","Map pickers & editors","Factions","New faction name…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:270","" +"FactionPicker.createButton","Map pickers & editors","Factions","Create","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:274","" +"FactionPicker.closeButtons","Map pickers & editors","Factions","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:300","" +"FactionEditor.openNote","Map pickers & editors","Factions","Open note →","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:46","" +"FactionEditor.name","Map pickers & editors","Factions","Name","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:74","" +"FactionEditor.color","Map pickers & editors","Factions","Color","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:81","" +"FactionEditor.pattern","Map pickers & editors","Factions","Pattern","simple","simple","group","group:Map pickers & editors","","","src/hex-map/overlayPatternControls.ts:139","" +"FactionEditor.patternScale","Map pickers & editors","Factions","Pattern scale","simple","simple","group","group:Map pickers & editors","","","src/hex-map/overlayPatternControls.ts:149","" +"FactionEditor.opacity","Map pickers & editors","Factions","Opacity","simple","simple","group","group:Map pickers & editors","","","src/hex-map/overlayPatternControls.ts:159","" +"FactionEditor.outlineWidth","Map pickers & editors","Factions","Outline width","simple","simple","group","group:Map pickers & editors","","","src/hex-map/overlayPatternControls.ts:169","" +"FactionEditor.save","Map pickers & editors","Factions","Save","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:102","" +"FactionEditor.clearColor","Map pickers & editors","Factions","Clear color","simple","simple","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:126","" +"FactionEditor.closeButtons","Map pickers & editors","Factions","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/FactionPickerModal.ts:36","" +"TerrainPicker.editToggle","Map pickers & editors","Terrain","✏ Edit / ← Done","simple","simple","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:52","" +"TerrainPicker.fullEditor","Map pickers & editors","Terrain","Full editor…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:63","" +"TerrainPicker.brushSize","Map pickers & editors","Terrain","Brush: 1× 3× 7×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:83","" +"TerrainPicker.eyedropper","Map pickers & editors","Terrain","⌖ Pick","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:104","" +"TerrainPicker.clear","Map pickers & editors","Terrain","Clear","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:119","" +"TerrainPicker.grid","Map pickers & editors","Terrain","(terrain tiles)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:132","" +"TerrainPicker.editTile","Map pickers & editors","Terrain","(terrain tile, edit mode)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:175","" +"TerrainPicker.dragReorder","Map pickers & editors","Terrain","⠿ (drag to reorder)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:198","" +"TerrainPicker.addTile","Map pickers & editors","Terrain","+ Add","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:232","" +"TerrainPicker.refreshEncounterLinks","Map pickers & editors","Terrain","Refresh all encounter table links","overkill","overkill","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:275","" +"TerrainPicker.closeButtons","Map pickers & editors","Terrain","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:33","" +"TerrainTemplate.newBlank","Map pickers & editors","Terrain","New blank","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:309","" +"TerrainTemplate.copyList","Map pickers & editors","Terrain","Or copy from an existing palette:","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:329","" +"TerrainTemplate.closeButtons","Map pickers & editors","Terrain","×","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainPickerModal.ts:345","" +"TerrainEntry.name","Map pickers & editors","Terrain","Name","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:57","" +"TerrainEntry.type","Map pickers & editors","Terrain","Type","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:73","" +"TerrainEntry.impassable","Map pickers & editors","Terrain","Impassable","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:85","" +"TerrainEntry.color","Map pickers & editors","Terrain","Color","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:94","" +"TerrainEntry.icon","Map pickers & editors","Terrain","Icon","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:102","" +"TerrainEntry.iconTintToggle","Map pickers & editors","Terrain","Icon tint (on/off)","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:125","" +"TerrainEntry.iconTintColor","Map pickers & editors","Terrain","Icon tint","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:136","" +"TerrainEntry.category","Map pickers & editors","Terrain","Category","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:159","" +"TerrainEntry.save","Map pickers & editors","Terrain","Save / Updating hexes…","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:180","" +"TerrainEntry.delete","Map pickers & editors","Terrain","Delete","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:198","" +"TerrainEntry.closeButtons","Map pickers & editors","Terrain","Cancel","keep","keep","group","group:Map pickers & editors","","","src/hex-map/TerrainEntryEditorModal.ts:193","" +"MapModal.tabMaps","Maps modal","Tabs & general","Maps","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:119","" +"MapModal.tabProperties","Maps modal","Tabs & general","Properties","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:119","" +"MapModal.tabRegions","Maps modal","Tabs & general","Regions","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:107","" +"MapModal.tabExport","Maps modal","Tabs & general","Export","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:119","" +"MapModal.newMap","Maps modal","Tabs & general","New map…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:127","" +"MapModal.newOverworld","Maps modal","Tabs & general","New overworld…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:130","" +"MapModal.mapSearch","Maps modal","Maps list","Find a map…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:242","" +"MapModal.mapTree","Maps modal","Maps list","(map list)","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:254","" +"MapModal.treeToggle","Maps modal","Maps list","▸ / ▾","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:317","" +"MapModal.regionsGroupRow","Maps modal","Maps list","Regions of ","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:290","" +"MapModal.neighboursGroupRow","Maps modal","Maps list","Neighbours: ","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:299","" +"MapModal.mapRowContextGenerator","Maps modal","Maps list","Open generator """"","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:355","" +"MapModal.mapRowContextMakeGenerator","Maps modal","Maps list","Make generator from …","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:363","" +"MapModal.missingRemove","Maps modal","Maps list","Remove / Remove from list?","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:52","" +"MapProps.sectionTablePicker","Maps modal","Properties","Pick table…","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:624","" +"MapModal.propsName","Maps modal","Properties","Name","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:425","" +"MapModal.propsSaveName","Maps modal","Properties","Save name","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:430","" +"MapModal.propsFolderName","Maps modal","Properties","Folder name","overkill","overkill","group","group:Maps modal","","","src/hex-map/MapModal.ts:448","" +"MapModal.propsRenameFolder","Maps modal","Properties","Rename folder","overkill","overkill","group","group:Maps modal","","","src/hex-map/MapModal.ts:453","" +"MapModal.propsStagger","Maps modal","Properties","Stagger offset (Odd/Even)","simple","simple","group","group:Maps modal","","","src/hex-map/MapModal.ts:466","" +"MapModal.propsNeighbourHint","Maps modal","Properties","(enable Regions hint)","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:696","" +"MapModal.propsTerrainTheme","Maps modal","Properties","Terrain theme","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:494","" +"MapModal.propsDelete","Maps modal","Properties","Delete """"…","simple","simple","group","group:Maps modal","","","src/hex-map/MapModal.ts:660","" +"MapModal.propsDeleteConfirm","Maps modal","Properties","Delete / Cancel","simple","simple","group","group:Maps modal","","","src/hex-map/MapModal.ts:671","" +"MapModal.propsNeighbourNorth","Maps modal","Neighbouring regions","North","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:711","" +"MapModal.propsNeighbourEast","Maps modal","Neighbouring regions","East","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:711","" +"MapModal.propsNeighbourSouth","Maps modal","Neighbouring regions","South","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:711","" +"MapModal.propsNeighbourWest","Maps modal","Neighbouring regions","West","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:711","" +"MapModal.propsNewRegionHere","Maps modal","Neighbouring regions","New region here…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:733","" +"MapModal.propsDetach","Maps modal","Neighbouring regions","Detach from its neighbours","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:740","" +"MapModal.propsWeatherTable","Maps modal","Weather & rumours","Weather: Pick table…","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:623","" +"MapModal.propsWeatherClear","Maps modal","Weather & rumours","Clear (weather)","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:635","" +"MapModal.propsRumoursTable","Maps modal","Weather & rumours","Rumours: Pick table…","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:623","" +"MapModal.propsRumoursClear","Maps modal","Weather & rumours","Clear (rumours)","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:635","" +"MapProps.backgroundImagePicker","Maps modal","Background image","Pick image…","advanced","advanced","group","group:Maps modal","","","src/hex-map/MapModal.ts:548","" +"MapModal.propsBgDrop","Maps modal","Background image","(drop an image here)","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:567","" +"MapModal.propsBgClear","Maps modal","Background image","Clear","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:556","" +"MapModal.propsBgOpacity","Maps modal","Background image","Opacity","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:578","" +"MapModal.propsBgCalibrate","Maps modal","Background image","Calibrate position & scale","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:590","" +"MapModal.regionsSetUp","Maps modal","Regions tab","Set up regions…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:169","" +"MapModal.regionsSettingsForm","Maps modal","Regions tab","(region settings form)","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:182","" +"MapModal.regionsMakeMissing","Maps modal","Regions tab","Make the missing regions (N)…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:189","" +"MapModal.regionsGenerateOverworld","Maps modal","Regions tab","Generate overworld…","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:200","" +"MapModal.regionsList","Maps modal","Regions tab","Regions (N) list","keep","keep","group","group:Maps modal","","","src/hex-map/MapModal.ts:209","" +"NewMap.name","New maps & map links","New map form","Name","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:222","" +"NewMap.palette","New maps & map links","New map form","Palette","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:247","" +"NewMap.rememberPalette","New maps & map links","New map form","Use this palette for new submaps of hexes","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:259","" +"NewMap.sizePresets","New maps & map links","New map form","(size presets)","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:274","" +"NewMap.size","New maps & map links","New map form","Size (columns × rows)","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:266","" +"NewMap.rememberSize","New maps & map links","New map form","Use this size for new submaps…","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:306","" +"NewMap.nextTo","New maps & map links","New map form","Next to","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:324","" +"NewMap.nextToSide","New maps & map links","New map form","(side of the neighbouring map)","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:327","" +"NewMap.generator","New maps & map links","New map form","Generator","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:569","" +"NewMap.rememberGenerator","New maps & map links","New map form","Use this generator and its options for new submaps…","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:398","" +"NewMap.moreOptionsHint","New maps & map links","New map form","More options: … Show / ✕","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:401","" +"NewMap.baseTerrain","New maps & map links","New map form","Base terrain","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:411","" +"NewMap.rememberBase","New maps & map links","New map form","Use this base terrain for new submaps…","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:412","" +"NewMap.more","New maps & map links","New map form","More: folder name, starting coordinates, stagger, background image","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:420","" +"NewMap.reroll","New maps & map links","New map form","🎲 Re-roll","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:509","" +"NewMap.create","New maps & map links","New map form","Generate / Create (& enter)","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:518","" +"NewMap.openInGenerator","New maps & map links","New map form","Open in generator","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:519","" +"NewMap.closeButtons","New maps & map links","New map form","Cancel","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:521","" +"NewMapSetup.backgroundImagePicker","New maps & map links","New map form: More","Pick image…","advanced","advanced","twin","NewMap.bgPick","","NewMap.bgPick","src/worldgen/NewMapSetupModal.ts:459","" +"NewMap.folderName","New maps & map links","New map form: More","Folder name","overkill","overkill","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:425","" +"NewMap.startCoords","New maps & map links","New map form: More","Starting coordinates","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:433","" +"NewMap.stagger","New maps & map links","New map form: More","Stagger offset","simple","simple","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:444","" +"NewMap.bgPick","New maps & map links","New map form: More","Pick image…","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:455","" +"NewMap.bgClear","New maps & map links","New map form: More","Clear","advanced","advanced","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:456","" +"NewMap.overlandWater","New maps & map links","Generator options (world)","Water","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:40","" +"NewMap.overlandClimate","New maps & map links","Generator options (world)","Climate","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:52","" +"NewMap.overlandRelief","New maps & map links","Generator options (world)","Relief","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:64","" +"NewMap.overlandSea","New maps & map links","Generator options (world)","Sea","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:88","" +"NewMap.planetWater","New maps & map links","Generator options (world)","Water","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:40","" +"NewMap.planetClimate","New maps & map links","Generator options (world)","Climate","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:52","" +"NewMap.planetRelief","New maps & map links","Generator options (world)","Relief","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:64","" +"NewMap.regionDetailInfluence","New maps & map links","Generator options (world)","Neighbour influence","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:500","" +"NewMap.regionDetailVariety","New maps & map links","Generator options (world)","Variety","advanced","advanced","group","group:New maps & map links","","","src/worldgen/procedural/planetSurface.ts:510","" +"NewMap.worldBiomesClimate","New maps & map links","Generator options (world)","Climate","keep","keep","group","group:New maps & map links","","","src/overworld/worldBiomes.ts:576","" +"NewMap.worldBiomesWater","New maps & map links","Generator options (world)","Water %","keep","keep","group","group:New maps & map links","","","src/overworld/worldBiomes.ts:579","" +"NewMap.worldBiomesLand","New maps & map links","Generator options (world)","Land","keep","keep","group","group:New maps & map links","","","src/overworld/worldBiomes.ts:580","" +"NewMap.worldBiomesNorth","New maps & map links","Generator options (world)","North is","keep","keep","group","group:New maps & map links","","","src/overworld/worldBiomes.ts:583","" +"NewMap.starDensity","New maps & map links","Generator options (space)","System density","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/starScatter.ts:33","" +"NewMap.starNebulae","New maps & map links","Generator options (space)","Nebulae","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/starScatter.ts:43","" +"NewMap.starJumpRoutes","New maps & map links","Generator options (space)","Jump routes","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/starScatter.ts:53","" +"NewMap.starRouteType","New maps & map links","Generator options (space)","Path type for routes","advanced","advanced","group","group:New maps & map links","","","src/worldgen/generatorPathTypes.ts:27","" +"NewMap.orbitsStar","New maps & map links","Generator options (space)","Star","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/orbits.ts:37","" +"NewMap.orbitsPlanets","New maps & map links","Generator options (space)","Planets","keep","keep","group","group:New maps & map links","","","src/worldgen/procedural/orbits.ts:49","" +"NewMap.orbitsPathType","New maps & map links","Generator options (space)","Path type for orbits","advanced","advanced","group","group:New maps & map links","","","src/worldgen/generatorPathTypes.ts:28","" +"NewMap.editWorldTypes","New maps & map links","Generator options (space)","Edit world types…","keep","keep","group","group:New maps & map links","","","src/worldgen/NewMapSetupModal.ts:634","" +"ChildKind.region","New maps & map links","New map from a hex","Region","keep","keep","group","group:New maps & map links","","","src/hex-map/newChildMap.ts:104","" +"ChildKind.location","New maps & map links","New map from a hex","Location","keep","keep","group","group:New maps & map links","","","src/hex-map/newChildMap.ts:104","" +"ChildKind.enterRegion","New maps & map links","New map from a hex","Enter ","keep","keep","group","group:New maps & map links","","","src/hex-map/newChildMap.ts:124","" +"ChildKind.regionsHint","New maps & map links","New map from a hex","Turn on regions and overworlds / ✕","keep","keep","group","group:New maps & map links","","","src/hex-map/newChildMap.ts:128","" +"WalkOW.biome","New maps & map links","New land beside a map","Biome","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:97","" +"WalkOW.roll","New maps & map links","New land beside a map","Roll","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:101","" +"WalkOW.seed","New maps & map links","New land beside a map","Seed","overkill","overkill","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:105","" +"WalkOW.rerollTerrain","New maps & map links","New land beside a map","Re-roll terrain","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:107","" +"WalkOW.name","New maps & map links","New land beside a map","Name","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:117","" +"WalkOW.create","New maps & map links","New land beside a map","Create and go","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:123","" +"WalkOW.closeButtons","New maps & map links","New land beside a map","Cancel","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:124","" +"WalkSide.biome","New maps & map links","New land beside a map","Biome","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:222","" +"WalkSide.roll","New maps & map links","New land beside a map","Roll","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:225","" +"WalkSide.rerollTerrain","New maps & map links","New land beside a map","Re-roll terrain","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:230","" +"WalkSide.name","New maps & map links","New land beside a map","Name","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:234","" +"WalkSide.create","New maps & map links","New land beside a map","Create and go","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:237","" +"WalkSide.closeButtons","New maps & map links","New land beside a map","Cancel","keep","keep","group","group:New maps & map links","","","src/worldgen/WalkRegionModal.ts:238","" +"MapLink.map","New maps & map links","Link submap & insert map link","Map","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:344","" +"MapLink.showAll","New maps & map links","Link submap & insert map link","▾ Show all","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:351","" +"MapLink.linkText","New maps & map links","Link submap & insert map link","Link text","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:420","" +"MapLink.insert","New maps & map links","Link submap & insert map link","Insert","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:428","" +"MapLink.closeButtons","New maps & map links","Link submap & insert map link","Cancel","keep","keep","group","group:New maps & map links","","","src/hex-map/MapLinkModal.ts:441","" +"SubmapPicker.filter","New maps & map links","Link submap & insert map link","Filter maps…","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:52","" +"SubmapPicker.mapList","New maps & map links","Link submap & insert map link","(map list)","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:58","" +"SubmapPicker.newLocation","New maps & map links","Link submap & insert map link","New location…","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:106","" +"SubmapPicker.removeLink","New maps & map links","Link submap & insert map link","Remove link","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:272","" +"SubmapPicker.link","New maps & map links","Link submap & insert map link","Link","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:275","" +"SubmapPicker.closeButtons","New maps & map links","Link submap & insert map link","Cancel","keep","keep","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:281","" +"SubmapPicker.createSection","New maps & map links","Link submap: inline create form","Create & link new map","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:115","" +"SubmapPicker.createName","New maps & map links","Link submap: inline create form","Name","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:135","" +"SubmapPicker.createCols","New maps & map links","Link submap: inline create form","Size (columns)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:150","" +"SubmapPicker.createRows","New maps & map links","Link submap: inline create form","Size (rows)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:153","" +"SubmapPicker.createPalette","New maps & map links","Link submap: inline create form","Palette","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:159","" +"SubmapPicker.createStartX","New maps & map links","Link submap: inline create form","Start at (x)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:170","" +"SubmapPicker.createStartY","New maps & map links","Link submap: inline create form","Start at (y)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:173","" +"SubmapPicker.createStagger","New maps & map links","Link submap: inline create form","Stagger (Odd/Even)","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:180","" +"SubmapPicker.createTerrainTheme","New maps & map links","Link submap: inline create form","Map terrain theme","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:192","" +"SubmapPicker.createAndLink","New maps & map links","Link submap: inline create form","Create & link / Create & enter","drop","drop","group","group:New maps & map links","","","src/hex-map/SubmapPickerModal.ts:241","" +"NewMapFields.name","New maps & map links","Dead code","Map name","drop","drop","group","group:New maps & map links","","","src/hex-map/newMapFields.ts:23","" +"NewMapFields.size","New maps & map links","Dead code","(cols × rows)","drop","drop","group","group:New maps & map links","","","src/hex-map/newMapFields.ts:28","" +"NewMapFields.palette","New maps & map links","Dead code","(palette)","drop","drop","group","group:New maps & map links","","","src/hex-map/newMapFields.ts:39","" +"GenerateRegions.makeThem","Regions, overworlds & biomes","Missing regions & go to region","Make them","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:62","" +"GenerateRegions.cancelStop","Regions, overworlds & biomes","Missing regions & go to region","Cancel / Stop / Close","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:61","" +"RegionNavigate.go","Regions, overworlds & biomes","Missing regions & go to region","Go to ","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/RegionNavigateModal.ts:378","" +"RegionNavigate.stay","Regions, overworlds & biomes","Missing regions & go to region","Stay","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/RegionNavigateModal.ts:383","" +"NewOverworld.name","Regions, overworlds & biomes","New overworld","Name","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:178","" +"NewOverworld.shape","Regions, overworlds & biomes","New overworld","Shape","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:182","" +"NewOverworld.hexCount","Regions, overworlds & biomes","New overworld","Hexes (N hexes)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:190","" +"NewOverworld.columns","Regions, overworlds & biomes","New overworld","Columns","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:195","" +"NewOverworld.rows","Regions, overworlds & biomes","New overworld","Rows","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:197","" +"NewOverworld.palette","Regions, overworlds & biomes","New overworld","Palette","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:210","" +"NewOverworld.climate","Regions, overworlds & biomes","New overworld","Climate","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:287","" +"NewOverworld.land","Regions, overworlds & biomes","New overworld","Land","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:288","" +"NewOverworld.northIs","Regions, overworlds & biomes","New overworld","North is","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:289","" +"NewOverworld.water","Regions, overworlds & biomes","New overworld","Water","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:291","" +"NewOverworld.blankHexes","Regions, overworlds & biomes","New overworld","Blank hexes","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:300","" +"NewOverworld.blankBiome","Regions, overworlds & biomes","New overworld","Blank biome","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:303","" +"NewOverworld.seed","Regions, overworlds & biomes","New overworld","Seed","overkill","overkill","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:318","just make sure its saved for the saved rolls etc, its fine if it shows up on saves too. " +"NewOverworld.reroll","Regions, overworlds & biomes","New overworld","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:320","" +"NewOverworld.regionSize","Regions, overworlds & biomes","New overworld","Each hex opens into","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:333","" +"NewOverworld.blend","Regions, overworlds & biomes","New overworld","Blend","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:337","" +"NewOverworld.makeAll","Regions, overworlds & biomes","New overworld","Make every region now / Remake the regions too","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:343","" +"NewOverworld.create","Regions, overworlds & biomes","New overworld","Create / Regenerate","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:351","" +"NewOverworld.closeButtons","Regions, overworlds & biomes","New overworld","Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:350","" +"NewOverworld.biomePool","Regions, overworlds & biomes","Biome pools","Biome pool","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:218","" +"NewOverworld.poolSave","Regions, overworlds & biomes","Biome pools","Save","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:219","" +"NewOverworld.poolSaveAs","Regions, overworlds & biomes","Biome pools","Save as…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:220","" +"NewOverworld.unclimated","Regions, overworlds & biomes","Biome pools","Biomes without a climate","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:224","" +"NewOverworld.poolList","Regions, overworlds & biomes","Biome pools","Biomes in the pool (N)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:374","" +"NewOverworld.poolWeight","Regions, overworlds & biomes","Biome pools","(weight per biome)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:385","" +"NewOverworld.poolRemove","Regions, overworlds & biomes","Biome pools","✕ Remove ","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:393","" +"NewOverworld.poolAdd","Regions, overworlds & biomes","Biome pools","Add a biome…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:404","" +"PoolName.name","Regions, overworlds & biomes","Biome pools","Pool name","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:529","" +"PoolName.closeButtons","Regions, overworlds & biomes","Biome pools","Save / Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/OverworldModals.ts:531","" +"BiomeLibrary.edit","Regions, overworlds & biomes","Biome library & biome form","Edit…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:87","" +"BiomeLibrary.editGenerator","Regions, overworlds & biomes","Biome library & biome form","Edit generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:93","" +"BiomeLibrary.add","Regions, overworlds & biomes","Biome library & biome form","Add biome…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:99","" +"BiomeLibrary.biomeList","Regions, overworlds & biomes","Biome library & biome form","(biome list)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:81","" +"BiomeForm.madeBy","Regions, overworlds & biomes","Biome library & biome form","Made by","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:162","" +"BiomeForm.regionsStartBlank","Regions, overworlds & biomes","Biome library & biome form","Regions start blank","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:173","" +"BiomeForm.name","Regions, overworlds & biomes","Biome library & biome form","Name","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:179","" +"BiomeForm.colour","Regions, overworlds & biomes","Biome library & biome form","Colour","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:182","" +"BiomeForm.mixSlider","Regions, overworlds & biomes","Biome library & biome form"," weight (slider)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:195","" +"BiomeForm.mixNumber","Regions, overworlds & biomes","Biome library & biome form"," weight value","drop","drop","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:196","" +"BiomeForm.blend","Regions, overworlds & biomes","Biome library & biome form","Blend with neighbours","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:206","" +"BiomeForm.landShareOn","Regions, overworlds & biomes","Biome library & biome form","Set a land share","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:216","" +"BiomeForm.landShare","Regions, overworlds & biomes","Biome library & biome form","Land share","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:217","" +"BiomeForm.fewestIslands","Regions, overworlds & biomes","Biome library & biome form","Fewest islands","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:228","" +"BiomeForm.temperature","Regions, overworlds & biomes","Biome library & biome form","Temperature","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:244","" +"BiomeForm.moisture","Regions, overworlds & biomes","Biome library & biome form","Moisture","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:245","" +"BiomeForm.height","Regions, overworlds & biomes","Biome library & biome form","Height","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:246","" +"BiomeForm.chance","Regions, overworlds & biomes","Biome library & biome form","Chance %","overkill","overkill","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:250","" +"BiomeForm.coastOnly","Regions, overworlds & biomes","Biome library & biome form","Coast only","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:260","" +"BiomeForm.rare","Regions, overworlds & biomes","Biome library & biome form","Rare","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:261","" +"BiomeForm.transitionNext","Regions, overworlds & biomes","Biome library & biome form","Next to","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:284","" +"BiomeForm.transitionBetween","Regions, overworlds & biomes","Biome library & biome form","Put between","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:286","" +"BiomeForm.transitionRemove","Regions, overworlds & biomes","Biome library & biome form","Remove","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:289","" +"BiomeForm.transitionAdd","Regions, overworlds & biomes","Biome library & biome form","Add transition","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:294","" +"BiomeForm.previewReroll","Regions, overworlds & biomes","Biome library & biome form","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:306","" +"BiomeForm.restoreDefault","Regions, overworlds & biomes","Biome library & biome form","Restore default","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:311","" +"BiomeForm.editGenerator","Regions, overworlds & biomes","Biome library & biome form","Edit generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:321","" +"BiomeForm.save","Regions, overworlds & biomes","Biome library & biome form","Save","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:327","" +"BiomeForm.closeButtons","Regions, overworlds & biomes","Biome library & biome form","Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeLibraryModal.ts:326","" +"BiomePicker.biomeGrid","Regions, overworlds & biomes","Biome picker & paint","(biome tiles)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:130","" +"BiomePicker.enterRegion","Regions, overworlds & biomes","Biome picker & paint","Enter region","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:146","" +"BiomePicker.reroll","Regions, overworlds & biomes","Biome picker & paint","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:147","" +"BiomePicker.settings","Regions, overworlds & biomes","Biome picker & paint","Settings…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:155","" +"BiomePicker.biomes","Regions, overworlds & biomes","Biome picker & paint","Biomes…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:159","" +"BiomePalette.biomeTiles","Regions, overworlds & biomes","Biome picker & paint","(biome tiles)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomePaletteModal.ts:401","" +"BiomePalette.biomes","Regions, overworlds & biomes","Biome picker & paint","Biomes…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomePaletteModal.ts:421","" +"RegionGen.biome","Regions, overworlds & biomes","Region settings","Biome","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:212","" +"RegionGen.editGenerator","Regions, overworlds & biomes","Region settings","Edit generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:219","" +"RegionGen.blend","Regions, overworlds & biomes","Region settings","Blend with neighbours","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:225","" +"RegionGen.wigglyBorders","Regions, overworlds & biomes","Region settings","Wiggly borders","overkill","overkill","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:231","" +"RegionGen.seed","Regions, overworlds & biomes","Region settings","Seed","overkill","overkill","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:238","" +"RegionGen.reroll","Regions, overworlds & biomes","Region settings","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:241","" +"RegionGen.apply","Regions, overworlds & biomes","Region settings","Apply / Make region","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:254","" +"RegionGen.closeButtons","Regions, overworlds & biomes","Region settings","Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/BiomeModals.ts:253","" +"RegionSettings.shape","Regions, overworlds & biomes","Region settings","Shape (Rectangle / Hex flower)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:52","" +"RegionSettings.sizePresets","Regions, overworlds & biomes","Region settings","Size","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:75","" +"RegionSettings.customSize","Regions, overworlds & biomes","Region settings","Hexes across (custom)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:89","" +"RegionSettings.palette","Regions, overworlds & biomes","Region settings","Palette","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:119","" +"RegionSettings.blend","Regions, overworlds & biomes","Region settings","Blend","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/regionSettingsForm.ts:130","" +"RegionSettings.save","Regions, overworlds & biomes","Region settings","Save and continue","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/newChildMap.ts:173","" +"RegionSettings.closeButtons","Regions, overworlds & biomes","Region settings","Cancel","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/newChildMap.ts:172","" +"EditRegion.name","Regions, overworlds & biomes","Edit region","Region name","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:82","" +"EditRegion.enterRegion","Regions, overworlds & biomes","Edit region","Enter region","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:105","" +"EditRegion.openMapNote","Regions, overworlds & biomes","Edit region","Open map note","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:112","" +"EditRegion.biomeGrid","Regions, overworlds & biomes","Edit region","(biome tiles)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:147","" +"EditRegion.reroll","Regions, overworlds & biomes","Edit region","Reroll","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:176","" +"EditRegion.settings","Regions, overworlds & biomes","Edit region","Settings…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:180","" +"EditRegion.editGenerator","Regions, overworlds & biomes","Edit region","Edit generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:134","" +"EditRegion.makeGenerator","Regions, overworlds & biomes","Edit region","Make generator…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:140","" +"EditRegion.neighbourLinks","Regions, overworlds & biomes","Edit region","Next to: links","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:220","" +"EditRegion.locationsList","Regions, overworlds & biomes","Edit region","List…","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:237","" +"EditRegion.confirmPath","Regions, overworlds & biomes","Edit region","Confirm into regions / Update regions","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:254","" +"EditRegion.notes","Regions, overworlds & biomes","Edit region","Region notes","simple","simple","group","group:Regions, overworlds & biomes","","","src/hex-map/EditRegionModal.ts:266","" +"GeoRegionPicker.regionTiles","Regions, overworlds & biomes","Region areas","(region note tiles)","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:181","" +"GeoRegionPicker.remove","Regions, overworlds & biomes","Region areas","Remove","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:184","" +"GeoRegionPicker.editTile","Regions, overworlds & biomes","Region areas","✏ Edit region","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:210","" +"GeoRegionPicker.newName","Regions, overworlds & biomes","Region areas","New region name…","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:257","" +"GeoRegionPicker.create","Regions, overworlds & biomes","Region areas","Create","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:261","" +"GeoRegionEditor.openNote","Regions, overworlds & biomes","Region areas","Open note →","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:42","" +"GeoRegionEditor.name","Regions, overworlds & biomes","Region areas","Name","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:68","" +"GeoRegionEditor.color","Regions, overworlds & biomes","Region areas","Color","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:77","" +"GeoRegionEditor.save","Regions, overworlds & biomes","Region areas","Save","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:96","" +"GeoRegionEditor.clearColor","Regions, overworlds & biomes","Region areas","Clear color","keep","keep","group","group:Regions, overworlds & biomes","","","src/hex-map/GeoRegionPickerModal.ts:116","" +"WorldTypes.table","Space: world types","General","Table","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:232","" +"WorldTypes.newTable","Space: world types","General","New table…","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:241","" +"WorldTypes.newTableName","Space: world types","General","Table name","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:330","" +"WorldTypes.newTableCreate","Space: world types","General","Create","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:331","" +"WorldTypes.openNote","Space: world types","General","Open note","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:244","" +"WorldTypes.restoreDefault","Space: world types","General","Restore default","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:250","" +"WorldTypes.tabWorlds","Space: world types","General","Worlds (N)","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:279","" +"WorldTypes.tabStars","Space: world types","General","Stars (N)","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:279","" +"WorldTypes.tabFeatures","Space: world types","General","Sector features (N)","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:279","" +"WorldTypes.rowMoveUp","Space: world types","General","↑ Move up","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:414","" +"WorldTypes.rowMoveDown","Space: world types","General","↓ Move down","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:415","" +"WorldTypes.rowRemove","Space: world types","General","✕ Remove row","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:416","" +"WorldTypes.addRow","Space: world types","General","Add row","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:298","" +"WorldTypes.save","Space: world types","General","Save","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:309","" +"WorldTypes.worldName","Space: world types","Worlds tab","World","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldWeight","Space: world types","Worlds tab","Weight","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldMap","Space: world types","Worlds tab","Map","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:425","" +"WorldTypes.worldOrbit","Space: world types","Worlds tab","Orbit","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldStars","Space: world types","Worlds tab","Stars","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldTemperature","Space: world types","Worlds tab","Temperature","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldSize","Space: world types","Worlds tab","Size","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldGenerator","Space: world types","Worlds tab","Generator","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldOptions","Space: world types","Worlds tab","Options","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldPalette","Space: world types","Worlds tab","Palette","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldBase","Space: world types","Worlds tab","Base","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.worldNotes","Space: world types","Worlds tab","Notes","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.starName","Space: world types","Stars tab","Star","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.starWeight","Space: world types","Stars tab","Weight","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.starNotes","Space: world types","Stars tab","Notes","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.featureName","Space: world types","Sector features tab","Feature","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.featureChance","Space: world types","Sector features tab","Chance","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.featureNotes","Space: world types","Sector features tab","Notes","keep","keep","group","group:Space: world types","","","src/space/WorldTypesModal.ts:434","" +"WorldTypes.previewMap","Space: world types","Preview","Map","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:464","" +"WorldTypes.previewOrbit","Space: world types","Preview","Orbit","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:465","" +"WorldTypes.previewStar","Space: world types","Preview","Star","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:466","" +"WorldTypes.previewTemperature","Space: world types","Preview","Temperature","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:467","" +"WorldTypes.previewRolls","Space: world types","Preview","Rolls","overkill","overkill","group","group:Space: world types","","","src/space/WorldTypesModal.ts:473","" +"GenLib.generatorsTab","Generator page","Library","Generators","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:70","" +"GenLib.mapsTab","Generator page","Library","Maps","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:71","" +"GenLib.filter","Generator page","Library","Filter…","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:50","" +"GenLib.generatorRow","Generator page","Library","(generator row: click to load)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:113","" +"GenLib.generatorRowTick","Generator page","Library","(row checkbox)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:263","" +"GenLib.selectAll","Generator page","Library","Select all shown","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:246","" +"GenLib.openFile","Generator page","Library","Open file","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:125","" +"GenLib.relearn","Generator page","Library","Re-learn","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:126","" +"GenLib.blend","Generator page","Library","Blend","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:127","" +"GenLib.delete","Generator page","Library","Delete","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:131","" +"GenLib.mapRow","Generator page","Library","(map row: tick to learn from)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:192","" +"GenLib.learnName","Generator page","Library","Generator name","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:206","" +"GenLib.learn","Generator page","Library","Learn generator","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorLibrary.ts:210","" +"GenPage.saveDraft","Generator page","Recipe","Save generator","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:336","" +"GenPage.discardDraft","Generator page","Recipe","Discard","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:349","" +"GenPage.name","Generator page","Recipe","Name","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:358","" +"GenPage.rename","Generator page","Recipe","Rename","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:359","" +"GenPage.generatorPalette","Generator page","Recipe","Palette","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:395","" +"GenPage.relearn","Generator page","Recipe","Re-learn / Re-blend","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:417","" +"GenPage.openFile","Generator page","Recipe","Open file","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:436","" +"GenPage.sourceInfluence","Generator page","Recipe"," influence","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:457","" +"GenPage.sourceCompass","Generator page","Recipe","(direction arrows ↖↑↗←•→↙↓↘)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:461","" +"GenPage.backToMapSize","Generator page","Recipe","Back to map size","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:522","" +"GenPage.resetSettings","Generator page","Recipe","Reset settings to defaults","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:536","" +"GenPage.sizePresets","Generator page","Recipe","(size presets)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:593","" +"GenPage.connectTo","Generator page","Recipe","Connect to","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:619","" +"GenPage.connectSide","Generator page","Recipe","(side: east/west/north/south of it)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:622","" +"GenPage.regionsHint","Generator page","Recipe","Turn on regions and overworlds / ✕","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:631","" +"GenPage.leanToNeighbours","Generator page","Recipe","Lean toward neighbours","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:665","" +"GenPage.guaranteedFeatures","Generator page","Recipe","Guaranteed features","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1046","" +"GenPage.connectedLand","Generator page","Recipe","Connected land","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1048","" +"GenPage.impassableSearch","Generator page","Recipe","Impassable terrain","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1502","" +"GenPage.impassableRemove","Generator page","Recipe","× (remove chip)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1515","" +"GenPage.impassableSuggestAdd","Generator page","Recipe","Add / Add all","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1064","" +"GenPage.mix","Generator page","Recipe","Mix","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1118","" +"GenPage.minPatches","Generator page","Recipe","Min","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1132","" +"GenPage.maxPatches","Generator page","Recipe","Max","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1132","" +"GenPage.sectionFold","Generator page","Recipe","(section heading fold)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1415","" +"GenPage.seed","Generator page","Preview & saves","Seed","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:556","" +"GenPage.seedLock","Generator page","Preview & saves","(lock seed)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:559","" +"GenPage.reroll","Generator page","Preview & saves","Re-roll / Regenerate","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:560","" +"GenPage.previewSize","Generator page","Preview & saves","Size (cols × rows)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:562","" +"GenPage.previewPalette","Generator page","Preview & saves","Palette","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:567","" +"GenPage.newMapName","Generator page","Preview & saves","Name for the new map","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:690","" +"GenPage.createMap","Generator page","Preview & saves","Create map","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:691","" +"GenPage.saveName","Generator page","Preview & saves","Save name (optional)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:697","" +"GenPage.saveSnapshot","Generator page","Preview & saves","Save","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:698","" +"GenPage.loadSelect","Generator page","Preview & saves","(saved snapshot list)","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:700","" +"GenPage.loadSnapshot","Generator page","Preview & saves","Load","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:701","" +"GenPage.featureSize","Generator page","Engine tuning","Feature size","keep","keep","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1012","" +"GenPage.clumping","Generator page","Engine tuning","Clumping","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1013","Engine tuning should have its own separate overkill setting. Basically all these ones marked ""overkill"" for generator settings should go into an ""advanced"" dropdown that defaults closed rather than them being gated under the global overkill setting. That way people can muck about with them when they wanna go a bit further on one gen or another, instead of having to flip and stick with a top-level setting. " +"GenPage.lineWidth","Generator page","Engine tuning","Line width","keep","keep","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1016","" +"GenPage.edgeSmoothing","Generator page","Engine tuning","Edge smoothing","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1021","" +"GenPage.removeSmallPatches","Generator page","Engine tuning","Remove small patches","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1023","" +"GenPage.keepRare","Generator page","Engine tuning","Keep rare terrain","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1025","" +"GenPage.symmetry","Generator page","Engine tuning","Symmetry","keep","keep","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1027","" +"GenPage.edgeStyle","Generator page","Engine tuning","Edge style","keep","keep","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1029","" +"GenPage.edgeStrength","Generator page","Engine tuning","Edge strength","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1032","" +"GenPage.directionalBias","Generator page","Engine tuning","Directional bias","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1036","" +"GenPage.scatter","Generator page","Engine tuning","Scatter","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1037","" +"GenPage.spacing","Generator page","Engine tuning","Spacing","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1039","" +"GenPage.randomness","Generator page","Engine tuning","Randomness","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1041","" +"GenPage.near","Generator page","Engine tuning","Near","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1146","" +"GenPage.mixStrength","Generator page","Engine tuning","Mix strength","overkill","overkill","group","group:Generator page/Engine tuning","","","src/worldgen/GeneratorPanel.ts:1176","" +"GenPage.drawPaths","Generator page","Paths","Draw paths","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1204","" +"GenPage.pathTypeFold","Generator page","Paths","(show routes chevron)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1225","ditto for the above, make sure these go into an ""advanced"" section, Maybe the advanced section can have collapsible sub-sections as well so its clean to view. " +"GenPage.pathTypeOn","Generator page","Paths","Draw paths","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1227","" +"GenPage.pathTypeAmount","Generator page","Paths","Amount","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1261","" +"GenPage.pathTypeWiggle","Generator page","Paths","Wiggle","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1277","" +"GenPage.pathTypeLength","Generator page","Paths","Length","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1278","" +"GenPage.pathTypeFollow","Generator page","Paths","Follow terrain","keep","keep","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1279","" +"GenPage.pathTypeAvoid","Generator page","Paths","Avoid impassable terrain and the map border","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1290","" +"GenPage.routeOn","Generator page","Paths","(route checkbox)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1315","" +"GenPage.routeCount","Generator page","Paths","Count","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1330","" +"GenPage.routeAs","Generator page","Paths","As","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1347","" +"GenPage.routeWiggle","Generator page","Paths","Wiggle (route)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1373","" +"GenPage.routeLength","Generator page","Paths","Length (route)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1374","" +"GenPage.routeFollow","Generator page","Paths","Follow terrain (route)","overkill","overkill","group","group:Generator page","","","src/worldgen/GeneratorPanel.ts:1375","" +"BiomePage.biome","Generator page","Biome (blend field)","Biome","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:150","" +"BiomePage.openNote","Generator page","Biome (blend field)","Open note","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:160","" +"BiomePage.restoreDefault","Generator page","Biome (blend field)","Restore default","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:165","" +"BiomePage.back","Generator page","Biome (blend field)","Back to generators","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:173","" +"BiomePage.weightSlider","Generator page","Biome (blend field)","Weight","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:191","" +"BiomePage.weightNumber","Generator page","Biome (blend field)","(weight value)","drop","drop","group","group:Generator page","","","src/worldgen/BiomePanel.ts:192","" +"BiomePage.minPatches","Generator page","Biome (blend field)","Min patches","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:193","" +"BiomePage.blendWidth","Generator page","Biome (blend field)","Blend width","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:231","" +"BiomePage.landShareOn","Generator page","Biome (blend field)","Land share (on/off)","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:242","" +"BiomePage.landShare","Generator page","Biome (blend field)","Land share","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:243","" +"BiomePage.minIslands","Generator page","Biome (blend field)","Min islands","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:261","" +"BiomePage.shore","Generator page","Biome (blend field)","Shore","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:270","" +"BiomePage.transitionNext","Generator page","Biome (blend field)","Next to","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:299","" +"BiomePage.transitionBetween","Generator page","Biome (blend field)","put","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:301","" +"BiomePage.transitionRemove","Generator page","Biome (blend field)","Remove","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:309","" +"BiomePage.transitionAdd","Generator page","Biome (blend field)","Add transition","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:315","" +"BiomePage.seed","Generator page","Biome (blend field)","Seed","overkill","overkill","group","group:Generator page","","","src/worldgen/BiomePanel.ts:330","" +"BiomePage.reroll","Generator page","Biome (blend field)","Re-roll","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:332","" +"BiomePage.size","Generator page","Biome (blend field)","Size","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:338","" +"BiomePage.aroundIt","Generator page","Biome (blend field)","Around it","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:346","" +"BiomePage.palette","Generator page","Biome (blend field)","Palette","keep","keep","group","group:Generator page","","","src/worldgen/BiomePanel.ts:353","" +"MakeGen.newRadio","Generator page","Make generator from a map","New generator","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:68","" +"MakeGen.name","Generator page","Make generator from a map","Name","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:70","" +"MakeGen.overwriteRadio","Generator page","Make generator from a map","Overwrite existing","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:80","" +"MakeGen.overwriteList","Generator page","Make generator from a map","Generator to overwrite","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:96","" +"MakeGen.make","Generator page","Make generator from a map","Make generator / Overwrite","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:90","" +"MakeGen.closeButtons","Generator page","Make generator from a map","Cancel","keep","keep","group","group:Generator page","","","src/hex-map/MakeGeneratorModal.ts:92","" +"PaletteEditor.paletteSelect","Palette editor","Toolbar","Palette","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:99","" +"PaletteEditor.addPalette","Palette editor","Toolbar","Add palette…","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:103","" +"PaletteEditor.openNote","Palette editor","Toolbar","Open note","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:112","" +"PaletteEditor.filter","Palette editor","Toolbar","Filter terrains…","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:118","" +"PaletteEditor.guessTypes","Palette editor","Terrains","Guess types from names","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:140","" +"PaletteEditor.rowDrag","Palette editor","Terrains","Drag to reorder (⠿)","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:260","" +"PaletteEditor.color","Palette editor","Terrains"," color","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:277","" +"PaletteEditor.name","Palette editor","Terrains","Terrain name","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:283","" +"PaletteEditor.type","Palette editor","Terrains"," type","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:301","" +"PaletteEditor.category","Palette editor","Terrains"," category","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:312","" +"PaletteEditor.icon","Palette editor","Terrains","Choose icon","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:326","" +"PaletteEditor.tintOn","Palette editor","Terrains","Tint icon","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:345","" +"PaletteEditor.tintColor","Palette editor","Terrains","Icon tint","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:347","" +"PaletteEditor.impassable","Palette editor","Terrains"," impassable","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:361","" +"PaletteEditor.delete","Palette editor","Terrains","Delete terrain (×)","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:370","" +"PaletteEditor.addTerrain","Palette editor","Terrains","Add terrain","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:178","" +"PaletteEditor.submapPalette","Palette editor","Palette settings & path types","Submap palette","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:195","" +"PaletteEditor.pathTypeRow","Palette editor","Palette settings & path types","(path type row)","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:228","" +"PaletteEditor.addPathType","Palette editor","Palette settings & path types","Add path type","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:236","" +"PaletteEditor.submapDefaultPalette","Palette editor","Submap defaults","Palette","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:410","" +"PaletteEditor.submapDefaultCols","Palette editor","Submap defaults","Columns","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:417","" +"PaletteEditor.submapDefaultRows","Palette editor","Submap defaults","Rows","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:419","" +"PaletteEditor.submapDefaultGenerator","Palette editor","Submap defaults","Generator","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:429","" +"PaletteEditor.generatorOptions","Palette editor","Submap defaults","Generator options","overkill","overkill","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:444","" +"PaletteEditor.submapDefaultBaseTerrain","Palette editor","Submap defaults","Base terrain","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:455","" +"PaletteEditor.submapDefaultDelete","Palette editor","Submap defaults","Remove default (×)","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:459","" +"PaletteEditor.addDefaultTerrain","Palette editor","Submap defaults","Terrain to add a default for","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:473","" +"PaletteEditor.addDefault","Palette editor","Submap defaults","Add default","keep","keep","group","group:Palette editor","","","src/palettes/PaletteEditorView.ts:475","" +"RTView.refreshList","Random tables","Tables list","Refresh list (↺)","overkill","overkill","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:149","we should confirm that it does it at a good cadence for all of these ""sink refresh"" bits " +"RTView.tablesTab","Random tables","Tables list","Tables","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:156","" +"RTView.workflowsTab","Random tables","Tables list","Workflows","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:160","" +"RTView.tabMiddleClick","Random tables","Tables list","(middle-click a tab)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:172","" +"RTView.workflowsHintTurnOn","Random tables","Tables list","Turn on workflows","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:89","" +"RTView.workflowsHintHide","Random tables","Tables list","Hide this hint (✕)","keep","keep","group","group:Random tables/Tables list","","","src/advancedHints.ts:36","" +"RTView.filterSearch","Random tables","Tables list","Filter tables…","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:198","" +"RTView.tablesTree","Random tables","Tables list","(table folder tree)","simple","simple","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:607","" +"RTView.folderToggle","Random tables","Tables list","(folder ▶/▼)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/FolderTree.ts:161","" +"RTView.fileMiddleClick","Random tables","Tables list","(middle-click a table)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1121","" +"RTView.dragToMove","Random tables","Tables list","(drag table onto folder)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1137","" +"RTView.folderMenuRollPicker","Random tables","Tables list","Exclude from roll picker / Include in roll picker","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1153","" +"RTView.folderMenuEncounters","Random tables","Tables list","Exclude from encounters table / Include in encounters table","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1180","" +"RTView.fileMenuOpenNewTab","Random tables","Tables list","Open in new tab","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1213","" +"RTView.fileMenuRollPicker","Random tables","Tables list","Exclude from roll picker / Include in roll picker","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1227","" +"RTView.fileMenuEncounters","Random tables","Tables list","Exclude from encounters table / Include in encounters table","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1247","" +"RTView.fileMenuDelete","Random tables","Tables list","Delete table","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:1270","" +"RTView.newTableName","Random tables","Tables list","New table name…","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:283","" +"RTView.newTableButton","Random tables","Tables list","+ new","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:305","" +"RTView.generateFromFolder","Random tables","Tables list","Generate from folder or file (optional)…","advanced","advanced","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:367","" +"RTView.newWorkflow","Random tables","Tables list","+ new workflow","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:271","" +"RTView.workflowsTree","Random tables","Tables list","(workflow folder tree)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:735","" +"RTView.workflowMenuOpenNewTab","Random tables","Tables list","Open in new tab","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:781","" +"RTView.workflowMenuDelete","Random tables","Tables list","Delete workflow","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:795","" +"RTView.workflowMiddleClick","Random tables","Tables list","(middle-click a workflow)","keep","keep","group","group:Random tables/Tables list","","","src/random-tables/RandomTableView.ts:769","" +"RTView.edit","Random tables","Table detail","Edit","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1478","" +"RTView.openNote","Random tables","Table detail","Open note","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1494","" +"RTView.exportPdf","Random tables","Table detail","Export PDF","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1503","" +"RTView.exportMarkdown","Random tables","Table detail","Export Markdown","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1513","" +"RTView.refreshLinked","Random tables","Table detail","Refresh","overkill","overkill","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1523","" +"RTView.dieSelect","Random tables","Table detail","(die: — no die —, d4…d1000)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1537","" +"RTView.fixKeepRanges","Random tables","Table detail","Keep ranges → set weights","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1428","" +"RTView.fixKeepWeights","Random tables","Table detail","Keep weights → redo ranges","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1431","" +"RTView.fixBiggerDie","Random tables","Table detail","Use a d","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1437","" +"RTView.fixAddRanges","Random tables","Table detail","Add roll ranges","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1445","" +"RTView.fixRollerLink","Random tables","Table detail","Replace old roller link","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1450","" +"RTView.descriptionCollapse","Random tables","Table detail","Collapse description (▼)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1569","" +"RTView.tableCollapse","Random tables","Table detail","Collapse table (▼)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1605","" +"RTView.entryLink","Random tables","Table detail","(result link)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1648","" +"RTView.entryCopy","Random tables","Table detail","Copy entry (⎘)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1676","" +"RTView.addEntriesEmpty","Random tables","Table detail","Add entries","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1622","" +"RTView.copyRollLink","Random tables","Table detail","🎲 Copy link","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1694","" +"RTView.roll","Random tables","Table detail","Roll","simple","simple","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1708","" +"RTView.resultText","Random tables","Table detail","(roll result)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1721","" +"RTView.resultCopy","Random tables","Table detail","Copy","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1727","" +"RTView.resultOpenNote","Random tables","Table detail","Open note","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1737","" +"RTView.historyCopy","Random tables","Table detail","Copy (⎘) in Recent rolls","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1876","" +"RTView.usedByWorkflowLink","Random tables","Table detail","(Workflows using this table)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1766","" +"RTView.newWorkflowWithTable","Random tables","Table detail","+ new workflow with this table","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableView.ts:1779","" +"RollModal.tableSelect","Random tables","Rolling","— choose a table —","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:116","" +"RollModal.openInRoller","Random tables","Rolling","Open in roller view","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:125","" +"RollModal.edit","Random tables","Rolling","Edit","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:184","" +"RollModal.roll","Random tables","Rolling","Roll","simple","simple","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:135","" +"RollModal.resultText","Random tables","Rolling","(roll result)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:254","" +"RollModal.useResult","Random tables","Rolling","Use result","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:262","" +"RollModal.addSectionSelect","Random tables","Rolling","Section to add the result to","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:33","" +"RollModal.addToHex","Random tables","Rolling","Add to this hex","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:41","" +"RollModal.copy","Random tables","Rolling","Copy","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:280","" +"RollModal.entryCopy","Random tables","Rolling","Copy entry (⎘)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:350","" +"RollModal.addEntries","Random tables","Rolling","Add entries","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:309","" +"RollModal.closeButtons","Random tables","Rolling","(modal ✕)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableModal.ts:84","" +"RollerBlock.roll","Random tables","Rolling","Roll","simple","simple","group","group:Random tables","","","src/random-tables/RollerBlock.ts:48","" +"RollerBlock.openTable","Random tables","Rolling","Open table","keep","keep","group","group:Random tables","","","src/random-tables/RollerBlock.ts:58","" +"RollerBlock.resultText","Random tables","Rolling","(roll result)","keep","keep","group","group:Random tables","","","src/random-tables/RollerBlock.ts:66","" +"RollerBlock.copy","Random tables","Rolling","Copy","keep","keep","group","group:Random tables","","","src/random-tables/RollerBlock.ts:73","" +"RollerBlock.historyCopy","Random tables","Rolling","Copy (⎘)","keep","keep","group","group:Random tables","","","src/random-tables/RollerBlock.ts:92","" +"TableEditor.importPicker","Random tables","Table editor","Search for a file to link...","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:210","" +"TableEditor.name","Random tables","Table editor","Name","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:94","" +"TableEditor.sortWeight","Random tables","Table editor","Wt ↑","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:149","" +"TableEditor.sortAlpha","Random tables","Table editor","A→z","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:166","" +"TableEditor.minusOneAll","Random tables","Table editor","-1","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:185","" +"TableEditor.plusOneAll","Random tables","Table editor","+1","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:194","" +"TableEditor.import","Random tables","Table editor","Import…","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:204","" +"TableEditor.rowDrag","Random tables","Table editor","Drag to reorder (⠿)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:274","" +"TableEditor.rowResult","Random tables","Table editor","Result…","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:283","" +"TableEditor.rowWeight","Random tables","Table editor","Weight (0 = never rolled)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:305","" +"TableEditor.rowDelete","Random tables","Table editor","Remove row (×)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:317","" +"TableEditor.newResult","Random tables","Table editor","New result…","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:374","" +"TableEditor.newWeight","Random tables","Table editor","(new row weight)","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:380","" +"TableEditor.add","Random tables","Table editor","Add","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:387","" +"TableEditor.description","Random tables","Table editor","Description","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:405","" +"TableEditor.linkedFolder","Random tables","Table editor","Linked folder","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:467","" +"TableEditor.excludeRollPicker","Random tables","Table editor","Exclude from roll picker","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:486","" +"TableEditor.excludeEncounters","Random tables","Table editor","Exclude from encounters table","advanced","advanced","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:494","" +"TableEditor.closeButtons","Random tables","Table editor","Close","keep","keep","group","group:Random tables","","","src/random-tables/RandomTableEditorModal.ts:640","" +"TableRanges.addRanges","Random tables","Table editor","Add ranges (a backup is made first)","keep","keep","group","group:Random tables","","","src/random-tables/tableMaintenance.ts:260","" +"TableRanges.dontAskAgain","Random tables","Table editor","Don't ask again","keep","keep","group","group:Random tables","","","src/random-tables/tableMaintenance.ts:268","" +"TableRanges.closeButtons","Random tables","Table editor","Not now","keep","keep","group","group:Random tables","","","src/random-tables/tableMaintenance.ts:266","" +"FolderTree.openTablesView","Random tables","Table picker","🎲 Open tables view","drop","drop","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:85","" +"FolderTree.filter","Random tables","Table picker","Filter tables…","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:93","" +"FolderTree.folderToggles","Random tables","Table picker","(folder rows)","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:174","" +"FolderTree.newTableName","Random tables","Table picker","table-name","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:190","" +"FolderTree.createButton","Random tables","Table picker","+ create","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:194","" +"FolderTree.closeButtons","Random tables","Table picker","×","keep","keep","group","group:Random tables","","","src/hex-map/FolderTreePickerModal.ts:77","" +"RTView.workflowEdit","Workflows","Workflow detail","Edit","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:924","" +"RTView.workflowRoll","Workflows","Workflow detail","Roll workflow","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:955","" +"RTView.workflowCopyLink","Workflows","Workflow detail","🔗 Copy link","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:963","" +"RTView.workflowStepLink","Workflows","Workflow detail","(step table link)","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:1015","" +"RTView.workflowTemplateLink","Workflows","Workflow detail","(template link)","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableView.ts:1053","" +"WorkflowEditor.name","Workflows","Workflow editor","Name","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:88","" +"WorkflowEditor.stepDrag","Workflows","Workflow editor","Drag to reorder (⠿)","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:343","" +"WorkflowEditor.stepFormula","Workflows","Workflow editor","E.g. 2D6+6","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:360","" +"WorkflowEditor.stepTable","Workflows","Workflow editor","— select table —","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:379","" +"WorkflowEditor.stepRolls","Workflows","Workflow editor","Number of rolls","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:420","" +"WorkflowEditor.stepLabel","Workflows","Workflow editor","Label…","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:434","" +"WorkflowEditor.stepDelete","Workflows","Workflow editor","Remove step (×)","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:454","" +"WorkflowEditor.addType","Workflows","Workflow editor","Table / Dice","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:505","" +"WorkflowEditor.addTable","Workflows","Workflow editor","— select table —","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:543","" +"WorkflowEditor.addFormula","Workflows","Workflow editor","E.g. 2D6+6","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:532","" +"WorkflowEditor.addRolls","Workflows","Workflow editor","Number of rolls","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:572","" +"WorkflowEditor.addLabel","Workflows","Workflow editor","Label (auto)…","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:578","" +"WorkflowEditor.addStep","Workflows","Workflow editor","Add step","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:585","" +"WorkflowEditor.template","Workflows","Workflow editor","Template","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:145","" +"WorkflowEditor.description","Workflows","Workflow editor","Description","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:164","" +"WorkflowEditor.resultsFolder","Workflows","Workflow editor","Results folder","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:200","" +"WorkflowEditor.export","Workflows","Workflow editor","Export…","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:690","" +"WorkflowEditor.closeButtons","Workflows","Workflow editor","Close","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowEditorModal.ts:696","" +"WorkflowWizard.rollAll","Workflows","Workflow wizard","Roll all","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:148","" +"WorkflowWizard.rerollAll","Workflows","Workflow wizard","Reroll all","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:155","" +"WorkflowWizard.slotValue","Workflows","Workflow wizard","—","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:320","" +"WorkflowWizard.slotPick","Workflows","Workflow wizard","— pick —","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:337","" +"WorkflowWizard.slotRoll","Workflows","Workflow wizard","Roll / Reroll","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:359","" +"WorkflowWizard.slotSum","Workflows","Workflow wizard","sum","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:381","" +"WorkflowWizard.sumAll","Workflows","Workflow wizard","sum all","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:301","" +"WorkflowWizard.resultText","Workflows","Workflow wizard","Result","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:179","" +"WorkflowWizard.copyResult","Workflows","Workflow wizard","Copy result","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:186","" +"WorkflowWizard.addSectionSelect","Workflows","Workflow wizard","Section to add the result to","keep","keep","group","group:Workflows","","","src/random-tables/RandomTableModal.ts:33","" +"WorkflowWizard.addToHex","Workflows","Workflow wizard","Add to this hex","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:197","" +"WorkflowWizard.noteName","Workflows","Workflow wizard","Note name","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:216","" +"WorkflowWizard.resultsFolder","Workflows","Workflow wizard","Results folder","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:244","" +"WorkflowWizard.saveAsNote","Workflows","Workflow wizard","Save as note","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:254","" +"WorkflowWizard.closeButtons","Workflows","Workflow wizard","(modal ✕) / Replace confirm","keep","keep","group","group:Workflows","","","src/random-tables/WorkflowWizardModal.ts:524","" +"MapExport.mapSelect","Export","Map export","Map","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:82","" +"MapExport.fileName","Export","Map export","File name","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:94","" +"MapExport.showCoords","Export","Map export","Coordinates","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:108","" +"MapExport.showIcons","Export","Map export","Icons","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:109","" +"MapExport.showPaths","Export","Map export","Paths","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:110","" +"MapExport.boldPaths","Export","Map export","Bolder paths","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:111","" +"MapExport.showHexNames","Export","Map export","Hex names","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:116","" +"MapExport.showTokens","Export","Map export","Tokens","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:117","" +"MapExport.showLinkBadges","Export","Map export","Link badges","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:118","" +"MapExport.showLegend","Export","Map export","Legend","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:120","" +"MapExport.showFactionOverlay","Export","Map export","Faction overlay","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:122","" +"MapExport.showRegionOverlay","Export","Map export","Region overlay","advanced","advanced","group","group:Export","","","src/export/MapExportModal.ts:124","" +"MapExport.pdfColumnsFold","Export","Map export","PDF table columns","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:131","" +"MapExport.manualFold","Export","Map export","Hexcrawl manual","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:137","" +"MapExport.outputSize","Export","Map export","Output size","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:147","" +"MapExport.exportPng","Export","Map export","Export PNG","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:239","" +"MapExport.exportPdf","Export","Map export","Export PDF with reference table","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:244","" +"MapExport.exportManual","Export","Map export","Export hexcrawl manual (PDF)","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:251","" +"MapExport.closeButtons","Export","Map export","×","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:276","" +"MapModal.exportForm","Export","Map export","(export form)","keep","keep","group","group:Export","","","src/hex-map/MapModal.ts:226","" +"MapExport.pdfColumnName","Export","Map export: PDF table columns","Name","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnTerrain","Export","Map export: PDF table columns","Terrain","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnTowns","Export","Map export: PDF table columns","Towns","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnDungeons","Export","Map export: PDF table columns","Dungeons","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnFeatures","Export","Map export: PDF table columns","Features","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnQuests","Export","Map export: PDF table columns","Quests","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnFactions","Export","Map export: PDF table columns","Factions","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnEncounters","Export","Map export: PDF table columns","Encounters","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.pdfColumnDescription","Export","Map export: PDF table columns","Description","keep","keep","group","group:Export","","","src/export/MapExportModal.ts:134","" +"MapExport.playerEdition","Export","Map export: Hexcrawl manual","Player version (leave out the hidden and secret sections)","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:139","" +"MapExport.manualPartLegend","Export","Map export: Hexcrawl manual","Map legend","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:141","" +"MapExport.manualPartTables","Export","Map export: Hexcrawl manual","Encounter tables","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:141","" +"MapExport.manualPartFactions","Export","Map export: Hexcrawl manual","Factions and regions","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:141","" +"MapExport.manualPartIndex","Export","Map export: Hexcrawl manual","Index","simple","simple","group","group:Export","","","src/export/MapExportModal.ts:141","" +"HexExport.fileName","Export","Hex export","File name","keep","keep","group","group:Export","","","src/hex-map/HexExportModal.ts:55","" +"HexExport.includeGm","Export","Hex export","Include game master only sections (hidden, secret)","keep","keep","group","group:Export","","","src/hex-map/HexExportModal.ts:64","" +"HexExport.exportPdf","Export","Hex export","Export PDF","keep","keep","group","group:Export","","","src/hex-map/HexExportModal.ts:90","" +"HexExport.exportMarkdown","Export","Hex export","Export Markdown","advanced","simple","own","","advanced (group group:Export)","","src/hex-map/HexExportModal.ts:101","" +"HexExport.closeButtons","Export","Hex export","×","keep","keep","group","group:Export","","","src/hex-map/HexExportModal.ts:29","" +"WorkflowExport.fileName","Export","Workflow export","File name","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:53","" +"WorkflowExport.sampleCount","Export","Workflow export","Number of sample outputs","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:66","" +"WorkflowExport.includeTemplate","Export","Workflow export","Include the workflow template","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:76","" +"WorkflowExport.includeBreakdown","Export","Workflow export","Include the per-sample rolls breakdown","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:81","" +"WorkflowExport.exportPdf","Export","Workflow export","Export PDF","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:104","" +"WorkflowExport.exportMarkdown","Export","Workflow export","Export Markdown","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:112","" +"WorkflowExport.closeButtons","Export","Workflow export","×","keep","keep","group","group:Export","","","src/random-tables/WorkflowExportModal.ts:27","" +"ConfirmModal.confirm","Confirm dialogs","Confirm modal (shared)","","keep","keep","group","group:Confirm dialogs","","","src/worldgen/ConfirmModal.ts:421","" +"ConfirmModal.closeButtons","Confirm dialogs","Confirm modal (shared)","Cancel","keep","keep","group","group:Confirm dialogs","","","src/worldgen/ConfirmModal.ts:426","" +"ConfirmDelete.delete","Confirm dialogs","Confirm delete table modal","Delete","keep","keep","group","group:Confirm dialogs","","","src/random-tables/ConfirmDeleteModal.ts:451","" +"ConfirmDelete.closeButtons","Confirm dialogs","Confirm delete table modal","Cancel","keep","keep","group","group:Confirm dialogs","","","src/random-tables/ConfirmDeleteModal.ts:462","" +"GenConfirm.confirm","Confirm dialogs","Confirm dialog (Reset / Delete)","Reset / Delete","keep","keep","group","group:Confirm dialogs","","","src/worldgen/ConfirmModal.ts:22","" +"GenConfirm.closeButtons","Confirm dialogs","Confirm dialog (Reset / Delete)","Cancel","keep","keep","group","group:Confirm dialogs","","","src/worldgen/ConfirmModal.ts:27","" +"ConfirmDelete.delete_2","Confirm dialogs","Confirm delete modal","Delete","keep","keep","group","group:Confirm dialogs","","","src/random-tables/ConfirmDeleteModal.ts:19","" +"ConfirmDelete.closeButtons_2","Confirm dialogs","Confirm delete modal","Cancel","keep","keep","group","group:Confirm dialogs","","","src/random-tables/ConfirmDeleteModal.ts:30","" diff --git a/dev/ui-inventory/inputs-tags-resolved.json b/dev/ui-inventory/inputs-tags-resolved.json new file mode 100644 index 00000000..749024dd --- /dev/null +++ b/dev/ui-inventory/inputs-tags-resolved.json @@ -0,0 +1,17132 @@ +[ + { + "id": "Settings.rerunSetupWizard", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Re-run setup wizard", + "loc": "src/HexmakerSettingTab.ts:247", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.featureLevel", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Feature level", + "loc": "src/HexmakerSettingTab.ts:894", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.featureGenerators", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Terrain generators", + "loc": "src/HexmakerSettingTab.ts:906", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.featureWorkflows", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Workflows", + "loc": "src/HexmakerSettingTab.ts:906", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.featurePalettes", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Custom palettes", + "loc": "src/HexmakerSettingTab.ts:906", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.featureRegions", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Regions and overworlds", + "loc": "src/HexmakerSettingTab.ts:906", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.showHintsAgain", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Show hints again", + "loc": "src/HexmakerSettingTab.ts:923", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.mapKindWorld", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "World / fantasy overland", + "loc": "src/HexmakerSettingTab.ts:695", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.mapKindSpace", + "group": "Settings", + "subgroup": "Setup & feature switches", + "label": "Space", + "loc": "src/HexmakerSettingTab.ts:695", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexOrientation", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex orientation", + "loc": "src/HexmakerSettingTab.ts:310", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.staggerOffset", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Stagger offset", + "loc": "src/HexmakerSettingTab.ts:320", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.coordPlacement", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Coordinate placement", + "loc": "src/HexmakerSettingTab.ts:339", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.coordFontSize", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Coordinate label size", + "loc": "src/HexmakerSettingTab.ts:349", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.coordFontFamily", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Coordinate label font", + "loc": "src/HexmakerSettingTab.ts:362", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.coordFontColor", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Coordinate label color", + "loc": "src/HexmakerSettingTab.ts:376", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexNameFont", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex name font", + "loc": "src/HexmakerSettingTab.ts:385", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexNameSize", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex name size", + "loc": "src/HexmakerSettingTab.ts:395", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexNameStyle", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex name style", + "loc": "src/HexmakerSettingTab.ts:405", + "suggestion": "overkill", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexGap", + "group": "Settings", + "subgroup": "Look & labels", + "label": "Hex cell spacing", + "loc": "src/HexmakerSettingTab.ts:415", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultTableDice", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default die for new tables", + "loc": "src/HexmakerSettingTab.ts:266", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.collapseTerrain", + "group": "Settings", + "subgroup": "Defaults", + "label": "Terrain", + "loc": "src/HexmakerSettingTab.ts:989", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.collapseFeatures", + "group": "Settings", + "subgroup": "Defaults", + "label": "Features", + "loc": "src/HexmakerSettingTab.ts:996", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.collapseNotes", + "group": "Settings", + "subgroup": "Defaults", + "label": "Notes", + "loc": "src/HexmakerSettingTab.ts:1003", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.templatePath", + "group": "Settings", + "subgroup": "Defaults", + "label": "Template path", + "loc": "src/HexmakerSettingTab.ts:293", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultMap", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default map", + "loc": "src/HexmakerSettingTab.ts:300", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultNewMapCols", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default new map columns", + "loc": "src/HexmakerSettingTab.ts:428", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultNewMapRows", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default new map rows", + "loc": "src/HexmakerSettingTab.ts:440", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultSubmapCols", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default submap columns", + "loc": "src/HexmakerSettingTab.ts:452", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultSubmapRows", + "group": "Settings", + "subgroup": "Defaults", + "label": "Default submap rows", + "loc": "src/HexmakerSettingTab.ts:464", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.iconsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Custom icons folder", + "loc": "src/HexmakerSettingTab.ts:475", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.worldFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "World notes folder", + "loc": "src/HexmakerSettingTab.ts:527", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.hexFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Hex notes folder", + "loc": "src/HexmakerSettingTab.ts:608", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.townsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Towns folder", + "loc": "src/HexmakerSettingTab.ts:614", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.dungeonsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Dungeons folder", + "loc": "src/HexmakerSettingTab.ts:620", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.questsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Quests folder", + "loc": "src/HexmakerSettingTab.ts:626", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.featuresFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Features folder", + "loc": "src/HexmakerSettingTab.ts:632", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.factionsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Factions folder", + "loc": "src/HexmakerSettingTab.ts:638", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.regionsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Regions folder", + "loc": "src/HexmakerSettingTab.ts:644", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.tablesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Tables folder", + "loc": "src/HexmakerSettingTab.ts:650", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.workflowsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Workflows folder", + "loc": "src/HexmakerSettingTab.ts:656", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.templatesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Templates folder", + "loc": "src/HexmakerSettingTab.ts:662", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.palettesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Palettes folder", + "loc": "src/HexmakerSettingTab.ts:668", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.biomesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Biomes folder", + "loc": "src/HexmakerSettingTab.ts:674", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.biomePoolsFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "Biome pools folder", + "loc": "src/HexmakerSettingTab.ts:680", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.worldTypesFolder", + "group": "Settings", + "subgroup": "Folders", + "label": "World types folder", + "loc": "src/HexmakerSettingTab.ts:686", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.defaultPalette", + "group": "Settings", + "subgroup": "Palette management", + "label": "Palette for new maps", + "loc": "src/HexmakerSettingTab.ts:721", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.addDefaultPalettes", + "group": "Settings", + "subgroup": "Palette management", + "label": "Add ", + "loc": "src/HexmakerSettingTab.ts:731", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.paletteRowName", + "group": "Settings", + "subgroup": "Palette management", + "label": "(palette name)", + "loc": "src/HexmakerSettingTab.ts:212", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.paletteRowEdit", + "group": "Settings", + "subgroup": "Palette management", + "label": "Edit", + "loc": "src/HexmakerSettingTab.ts:868", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.paletteRowOpenNote", + "group": "Settings", + "subgroup": "Palette management", + "label": "Open note", + "loc": "src/HexmakerSettingTab.ts:871", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.paletteDelete", + "group": "Settings", + "subgroup": "Palette management", + "label": "Delete (list delete)", + "loc": "src/HexmakerSettingTab.ts:748", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.addPalette", + "group": "Settings", + "subgroup": "Palette management", + "label": "Add palette", + "loc": "src/HexmakerSettingTab.ts:767", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.presetOption", + "group": "Settings", + "subgroup": "Palette management", + "label": "", + "loc": "src/palettes/AddPaletteModal.ts:30", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.copyOption", + "group": "Settings", + "subgroup": "Palette management", + "label": "Copy of ", + "loc": "src/palettes/AddPaletteModal.ts:46", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.emptyPalette", + "group": "Settings", + "subgroup": "Palette management", + "label": "Empty palette", + "loc": "src/palettes/AddPaletteModal.ts:64", + "suggestion": "simple", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.preset", + "group": "Settings", + "subgroup": "Palette management", + "label": " / (another copy)", + "loc": "src/palettes/AddPaletteModal.ts:30", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "AddPalette.closeButtons", + "group": "Settings", + "subgroup": "Palette management", + "label": "(modal ✕)", + "loc": "src/palettes/AddPaletteModal.ts:20", + "suggestion": "keep", + "choice": "keep", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.generateWorldData", + "group": "Settings", + "subgroup": "Maintenance", + "label": "Generate", + "loc": "src/HexmakerSettingTab.ts:491", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "but note this might need to be surfaced in the case of debugging etc, we might need to point users to \"all\" if \"health\"/\"repair\" type settings hide there. " + }, + { + "id": "Settings.generateFolders", + "group": "Settings", + "subgroup": "Maintenance", + "label": "Generate folders", + "loc": "src/HexmakerSettingTab.ts:534", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Settings.legacyCoordLabelSize", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Coordinate label (slider)", + "loc": "src/HexmakerSettingTab.ts:1167", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.coordFontSize)", + "twinOf": "Settings.coordFontSize", + "note": "this and other stuff like it should just map to the same setting ideally. " + }, + { + "id": "Settings.legacyCoordLabelFont", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Coordinate label (font)", + "loc": "src/HexmakerSettingTab.ts:1178", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.coordFontFamily)", + "twinOf": "Settings.coordFontFamily", + "note": "" + }, + { + "id": "Settings.legacyCoordLabelColor", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Coordinate label (color)", + "loc": "src/HexmakerSettingTab.ts:1193", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.coordFontColor)", + "twinOf": "Settings.coordFontColor", + "note": "" + }, + { + "id": "Settings.legacyHexNameFont", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Hex name font (font)", + "loc": "src/HexmakerSettingTab.ts:1214", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.hexNameFont)", + "twinOf": "Settings.hexNameFont", + "note": "" + }, + { + "id": "Settings.legacyHexNameSize", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Hex name font (size)", + "loc": "src/HexmakerSettingTab.ts:1221", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.hexNameSize)", + "twinOf": "Settings.hexNameSize", + "note": "" + }, + { + "id": "Settings.legacyHexNameStyle", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Hex name font (style)", + "loc": "src/HexmakerSettingTab.ts:1228", + "suggestion": "overkill", + "choice": "overkill", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "simple (twin Settings.hexNameStyle)", + "twinOf": "Settings.hexNameStyle", + "note": "" + }, + { + "id": "Settings.legacyNewMapCols", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Default new map size (Cols)", + "loc": "src/HexmakerSettingTab.ts:1263", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "Settings.defaultNewMapCols", + "note": "" + }, + { + "id": "Settings.legacyNewMapRows", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Default new map size (Rows)", + "loc": "src/HexmakerSettingTab.ts:1272", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "Settings.defaultNewMapRows", + "note": "" + }, + { + "id": "Settings.legacySubmapCols", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Default submap size (Cols)", + "loc": "src/HexmakerSettingTab.ts:1285", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "Settings.defaultSubmapCols", + "note": "" + }, + { + "id": "Settings.legacySubmapRows", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Default submap size (Rows)", + "loc": "src/HexmakerSettingTab.ts:1294", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "Settings.defaultSubmapRows", + "note": "" + }, + { + "id": "Settings.legacyPaletteDeleteButton", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "label": "Delete", + "loc": "src/HexmakerSettingTab.ts:1742", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "advanced (twin Settings.paletteDelete)", + "twinOf": "Settings.paletteDelete", + "note": "i think custom palettes should be simple. We want a streamlined but still customizable experience for simple, not to hide every little possible scary thing. " + }, + { + "id": "Wizard.mapKindWorld", + "group": "Setup wizard", + "subgroup": "Welcome", + "label": "World / fantasy overland", + "loc": "src/SetupWizardView.ts:243", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Welcome", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.mapKindSpace", + "group": "Setup wizard", + "subgroup": "Welcome", + "label": "Space", + "loc": "src/SetupWizardView.ts:243", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Welcome", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.featureLevel", + "group": "Setup wizard", + "subgroup": "Welcome", + "label": "How much do you want to start with? (Simple/Advanced)", + "loc": "src/SetupWizardView.ts:261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Welcome", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.worldFolder", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "World folder", + "loc": "src/SetupWizardView.ts:304", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.configureFoldersIndividually", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Configure each folder path individually", + "loc": "src/SetupWizardView.ts:324", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.hex", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Hex notes", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.towns", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Towns", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.dungeons", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Dungeons", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.quests", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Quests", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.features", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Features", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.factions", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Factions", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.regions", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Regions", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.tables", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Tables", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.workflows", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Workflows", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.templates", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Templates", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.folder.icons", + "group": "Setup wizard", + "subgroup": "Folders", + "label": "Icons", + "loc": "src/SetupWizardView.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Folders", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.mapName", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Map name", + "loc": "src/SetupWizardView.ts:440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.gridCols", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Grid size (columns)", + "loc": "src/SetupWizardView.ts:469", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.gridRows", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Grid size (rows)", + "loc": "src/SetupWizardView.ts:479", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.hexOrientation", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Hex orientation (Flat-top / Pointy-top)", + "loc": "src/SetupWizardView.ts:544", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.terrainPalette", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Terrain palette", + "loc": "src/SetupWizardView.ts:579", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.generatorCards", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Terrain (generator cards)", + "loc": "src/SetupWizardView.ts:633", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptWater", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Water", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptClimate", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Climate", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptRelief", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Relief", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptSea", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Sea", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.genOptOther", + "group": "Setup wizard", + "subgroup": "Map", + "label": "(other generator options)", + "loc": "src/SetupWizardView.ts:647", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.reroll", + "group": "Setup wizard", + "subgroup": "Map", + "label": "Re-roll (dice)", + "loc": "src/SetupWizardView.ts:607", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Map", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.openHexMap", + "group": "Setup wizard", + "subgroup": "Done", + "label": "Open hex map", + "loc": "src/SetupWizardView.ts:841", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Done", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.exploreOnOwn", + "group": "Setup wizard", + "subgroup": "Done", + "label": "I'll explore on my own", + "loc": "src/SetupWizardView.ts:847", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Done", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.back", + "group": "Setup wizard", + "subgroup": "Navigation", + "label": "back", + "loc": "src/SetupWizardView.ts:943", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Navigation", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.next", + "group": "Setup wizard", + "subgroup": "Navigation", + "label": "Next", + "loc": "src/SetupWizardView.ts:957", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Navigation", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.remindLater", + "group": "Setup wizard", + "subgroup": "Navigation", + "label": "Remind me later", + "loc": "src/SetupWizardView.ts:967", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Navigation", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Wizard.dontShowAgain", + "group": "Setup wizard", + "subgroup": "Navigation", + "label": "Don't show again", + "loc": "src/SetupWizardView.ts:975", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Setup wizard/Navigation", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Hint.turnOnFeature", + "group": "Feature hints", + "subgroup": "Inline hints", + "label": "Turn on ", + "loc": "src/advancedHints.ts:158", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Inline hints", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Hint.close", + "group": "Feature hints", + "subgroup": "Inline hints", + "label": "X (Hide this hint)", + "loc": "src/advancedHints.ts:160", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Inline hints", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Hints.show", + "group": "Feature hints", + "subgroup": "Inline hints", + "label": "Show", + "loc": "src/advancedHints.ts:191", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Inline hints", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MoreFeatures.turnOn", + "group": "Feature hints", + "subgroup": "More options modal", + "label": "Turn on", + "loc": "src/advancedHints.ts:235", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/More options modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MoreFeatures.turnOnAll", + "group": "Feature hints", + "subgroup": "More options modal", + "label": "Turn on all advanced features", + "loc": "src/advancedHints.ts:241", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/More options modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MoreFeatures.closeButtons", + "group": "Feature hints", + "subgroup": "More options modal", + "label": "Done", + "loc": "src/advancedHints.ts:244", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/More options modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EnableFeature.turnOnOne", + "group": "Feature hints", + "subgroup": "Turn on ? modal", + "label": "Turn on ", + "loc": "src/advancedHints.ts:274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Turn on ? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EnableFeature.turnOnAll", + "group": "Feature hints", + "subgroup": "Turn on ? modal", + "label": "Turn on all advanced features", + "loc": "src/advancedHints.ts:276", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Turn on ? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EnableFeature.closeButtons", + "group": "Feature hints", + "subgroup": "Turn on ? modal", + "label": "Not now", + "loc": "src/advancedHints.ts:277", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Turn on ? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Nudge.turnOnAdvanced", + "group": "Feature hints", + "subgroup": "Ready for more? modal", + "label": "Turn on advanced features", + "loc": "src/advancedHints.ts:318", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Ready for more? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Nudge.closeButtons", + "group": "Feature hints", + "subgroup": "Ready for more? modal", + "label": "Not now", + "loc": "src/advancedHints.ts:323", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Ready for more? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Nudge.dontAskAgain", + "group": "Feature hints", + "subgroup": "Ready for more? modal", + "label": "Don't ask again", + "loc": "src/advancedHints.ts:324", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Feature hints/Ready for more? modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.ribbonOpenHexMap", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open hex map", + "loc": "src/HexmakerPlugin.ts:278", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openHexMap", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open hex map", + "loc": "src/HexmakerPlugin.ts:281", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openHexTable", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open hex table", + "loc": "src/HexmakerPlugin.ts:286", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openTerrainGenerator", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open terrain generator", + "loc": "src/HexmakerPlugin.ts:294", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openPaletteEditor", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open palette editor", + "loc": "src/HexmakerPlugin.ts:299", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.editWorldTypes", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Edit world types...", + "loc": "src/HexmakerPlugin.ts:304", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.newOverworld", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "New overworld...", + "loc": "src/HexmakerPlugin.ts:316", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.openRandomTables", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Open random tables", + "loc": "src/HexmakerPlugin.ts:355", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Open views", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.command", + "group": "Commands & menus", + "subgroup": "Open views", + "label": "Edit world types…", + "loc": "src/space/WorldTypesModal.ts:311", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Plugin.cmd.editWorldTypes", + "viaSuggested": false, + "overrides": "", + "twinOf": "Plugin.cmd.editWorldTypes", + "note": "" + }, + { + "id": "Plugin.cmd.mapGoUp", + "group": "Commands & menus", + "subgroup": "Map navigation commands", + "label": "Go up to parent map", + "loc": "src/HexmakerPlugin.ts:325", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Map navigation commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.mapGoBack", + "group": "Commands & menus", + "subgroup": "Map navigation commands", + "label": "Go back to previous map", + "loc": "src/HexmakerPlugin.ts:335", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Map navigation commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.mapGoForward", + "group": "Commands & menus", + "subgroup": "Map navigation commands", + "label": "Go forward to the next map", + "loc": "src/HexmakerPlugin.ts:345", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Map navigation commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.addRollRanges", + "group": "Commands & menus", + "subgroup": "Maintenance commands", + "label": "Add roll ranges to tables", + "loc": "src/HexmakerPlugin.ts:363", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Commands & menus/Maintenance commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.checkTables", + "group": "Commands & menus", + "subgroup": "Maintenance commands", + "label": "Check tables", + "loc": "src/HexmakerPlugin.ts:368", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Commands & menus/Maintenance commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.addMapDataToHexNotes", + "group": "Commands & menus", + "subgroup": "Maintenance commands", + "label": "Add map data to this map's hex notes", + "loc": "src/HexmakerPlugin.ts:416", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Commands & menus/Maintenance commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.updateRegionFactionMapData", + "group": "Commands & menus", + "subgroup": "Maintenance commands", + "label": "Update map data in region and faction notes", + "loc": "src/HexmakerPlugin.ts:438", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Commands & menus/Maintenance commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportNotePdf", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current note to PDF", + "loc": "src/HexmakerPlugin.ts:373", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportNoteMarkdown", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current note to Markdown", + "loc": "src/HexmakerPlugin.ts:383", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportCurrentHex", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current hex (structured PDF / Markdown)", + "loc": "src/HexmakerPlugin.ts:393", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportCurrentWorkflow", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current workflow with rolled samples", + "loc": "src/HexmakerPlugin.ts:403", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.cmd.exportCurrentMap", + "group": "Commands & menus", + "subgroup": "Export commands", + "label": "Export current map...", + "loc": "src/HexmakerPlugin.ts:456", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Commands & menus/Export commands", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.fileMenuExportPdf", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Export to PDF", + "loc": "src/HexmakerPlugin.ts:473", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.fileMenuExportMarkdown", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Export to Markdown", + "loc": "src/HexmakerPlugin.ts:480", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.editorMenuInsertRoller", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Insert table roller", + "loc": "src/HexmakerPlugin.ts:506", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.editorMenuInsertMapLink", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Insert map link", + "loc": "src/HexmakerPlugin.ts:523", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Plugin.insertRollerPicker", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Search for a file to link...", + "loc": "src/hex-map/FileLinkSuggestModal.ts:19", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Editor.insertTableRoller", + "viaSuggested": false, + "overrides": "", + "twinOf": "Editor.insertTableRoller", + "note": "" + }, + { + "id": "Editor.insertTableRoller", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "label": "Search for a file to link...", + "loc": "src/HexmakerPlugin.ts:512", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Commands & menus/Note right-click menus", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.hexTableBtn", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Open hex table (⊞)", + "loc": "src/hex-map/HexMapView.ts:1473", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.randomTablesBtn", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Open random tables (🎲)", + "loc": "src/hex-map/HexMapView.ts:1497", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.mapSwitcher", + "group": "Hex map view", + "subgroup": "Top bar", + "label": " ▾ (Manage maps)", + "loc": "src/hex-map/HexMapView.ts:1529", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.workModeBtn", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Mode: Play / Build / God", + "loc": "src/hex-map/HexMapView.ts:1551", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.undo", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Undo (up to 20) ↩", + "loc": "src/hex-map/HexMapView.ts:1555", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.redo", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Redo ↪", + "loc": "src/hex-map/HexMapView.ts:1565", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.help", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Controls & tools (?)", + "loc": "src/hex-map/HexMapView.ts:1577", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.drawingToolsToggle", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Drawing tools (pencil)", + "loc": "src/hex-map/HexSidePanel.ts:22", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapToolbar.layersToggle", + "group": "Hex map view", + "subgroup": "Top bar", + "label": "Map overlays (layers)", + "loc": "src/hex-map/HexSidePanel.ts:22", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.breadcrumb", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "Go to (breadcrumb)", + "loc": "src/hex-map/HexMapView.ts:690", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.back", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "← Back to (Alt+←)", + "loc": "src/hex-map/HexMapView.ts:723", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.up", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "↑ Up to (Alt+↑)", + "loc": "src/hex-map/HexMapView.ts:723", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.forward", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "→ Forward to (Alt+→)", + "loc": "src/hex-map/HexMapView.ts:723", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.regionFlowerHere", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "Here: . Click to edit this region.", + "loc": "src/hex-map/HexMapView.ts:859", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.regionFlowerPetal", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": " petal", + "loc": "src/hex-map/HexMapView.ts:878", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.regionFlowerNewLand", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "+ (new land petal)", + "loc": "src/hex-map/HexMapView.ts:878", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.mapPadGo", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "D-pad neighbour map (◀▲▶▼)", + "loc": "src/hex-map/HexMapView.ts:921", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapNav.mapPadNew", + "group": "Hex map view", + "subgroup": "Map navigation", + "label": "+ (new neighbouring map)", + "loc": "src/hex-map/HexMapView.ts:921", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkModeMenu.play", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Play: Run a game…", + "loc": "src/hex-map/HexMapView.ts:758", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkModeMenu.build", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Build: Add to and edit the map…", + "loc": "src/hex-map/HexMapView.ts:758", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkModeMenu.god", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "God: Change anything…", + "loc": "src/hex-map/HexMapView.ts:758", + "suggestion": "advanced", + "choice": "advanced", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "", + "twinOf": "", + "note": "Yes but ask to enable it and other things when they start poking around region/generators/etc." + }, + { + "id": "ModeBar.stop", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Stop this tool (✕)", + "loc": "src/hex-map/HexMapView.ts:1032", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.autoRoute", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Auto-route", + "loc": "src/hex-map/pathTool.ts:1423", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.crossImpassable", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Cross impassable", + "loc": "src/hex-map/pathTool.ts:1453", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.pathNameChip", + "group": "Hex map view", + "subgroup": "Work modes", + "label": " (Rename this path)", + "loc": "src/hex-map/pathTool.ts:1462", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.newPath", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "New path", + "loc": "src/hex-map/pathTool.ts:1469", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.done", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Done", + "loc": "src/hex-map/pathTool.ts:1477", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ModeBar.confirmIntoRegions", + "group": "Hex map view", + "subgroup": "Work modes", + "label": "Confirm into regions / Update regions", + "loc": "src/hex-map/HexMapView.ts:6253", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.centerHex", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Center hex", + "loc": "src/hex-map/HexMapView.ts:2023", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.terrain", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Terrain", + "loc": "src/hex-map/HexMapView.ts:2031", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.biome", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Biome", + "loc": "src/hex-map/HexMapView.ts:2043", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.icon", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Icon", + "loc": "src/hex-map/HexMapView.ts:2051", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.path", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Path", + "loc": "src/hex-map/HexMapView.ts:2062", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.linkTable", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Link table", + "loc": "src/hex-map/HexMapView.ts:2073", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.linkSubmap", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Link submap", + "loc": "src/hex-map/HexMapView.ts:2083", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.factions", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Factions", + "loc": "src/hex-map/HexMapView.ts:2093", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.regionAreas", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Region areas", + "loc": "src/hex-map/HexMapView.ts:2103", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "DrawingPanel.token", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Token", + "loc": "src/hex-map/HexMapView.ts:2113", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.tableLinkToolPicker", + "group": "Hex map view", + "subgroup": "Drawing tools", + "label": "Select table", + "loc": "src/hex-map/HexMapView.ts:2424", + "suggestion": "advanced", + "choice": "advanced", + "source": "twin", + "via": "DrawingPanel.linkTable", + "viaSuggested": false, + "overrides": "", + "twinOf": "DrawingPanel.linkTable", + "note": "" + }, + { + "id": "PainterMenu.switchTerrain", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch terrain", + "loc": "src/hex-map/HexMapView.ts:2145", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchIcon", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch icon", + "loc": "src/hex-map/HexMapView.ts:2149", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchTable", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch table", + "loc": "src/hex-map/HexMapView.ts:2153", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchSubmap", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch submap", + "loc": "src/hex-map/HexMapView.ts:2157", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchFaction", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch faction", + "loc": "src/hex-map/HexMapView.ts:2161", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchRegion", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch region", + "loc": "src/hex-map/HexMapView.ts:2165", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchPathType", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch path type", + "loc": "src/hex-map/HexMapView.ts:2169", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchToken", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch token", + "loc": "src/hex-map/HexMapView.ts:2173", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.switchBiome", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch biome", + "loc": "src/hex-map/HexMapView.ts:2176", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.exitTool", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Exit tool", + "loc": "src/hex-map/PainterContextMenu.ts:24", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.eraseToggle", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Erase mode / Paint (Link, Draw) mode", + "loc": "src/hex-map/HexMapView.ts:2146", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PainterMenu.newPath", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "New path", + "loc": "src/hex-map/HexMapView.ts:2171", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.splitHere", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Split here", + "loc": "src/hex-map/pathTool.ts:296", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.deleteBranch", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Delete this fork / Delete main line", + "loc": "src/hex-map/pathTool.ts:297", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.deletePath", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Delete path: ", + "loc": "src/hex-map/pathTool.ts:299", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.rename", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Rename…", + "loc": "src/hex-map/pathTool.ts:300", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.changeType", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Change type…", + "loc": "src/hex-map/pathTool.ts:301", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.reverse", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Reverse", + "loc": "src/hex-map/pathTool.ts:302", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.switchToType", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Switch to to edit ", + "loc": "src/hex-map/pathTool.ts:1075", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.confirmIntoRegions", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Confirm into regions / Update regions", + "loc": "src/hex-map/HexMapView.ts:6274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathMenu.removeFromRegions", + "group": "Hex map view", + "subgroup": "Tool right-click menus", + "label": "Remove from regions", + "loc": "src/hex-map/HexMapView.ts:6274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.center", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Center on this hex", + "loc": "src/hex-map/HexMapView.ts:4773", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.openNote", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Open note", + "loc": "src/hex-map/HexMapView.ts:4777", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.enterRegion", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Enter region: ", + "loc": "src/hex-map/HexMapView.ts:4792", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.openLocation", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Open: ", + "loc": "src/hex-map/HexMapView.ts:4795", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.locationsList", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Locations (n)…", + "loc": "src/hex-map/HexMapView.ts:4801", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.newMap", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "New map from this hex…", + "loc": "src/hex-map/HexMapView.ts:4803", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.linkExistingMap", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Link existing map…", + "loc": "src/hex-map/HexMapView.ts:4804", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.manageLocations", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Manage locations…", + "loc": "src/hex-map/HexMapView.ts:4807", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.linkTable", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Link table", + "loc": "src/hex-map/HexMapView.ts:4810", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.swapHex", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Swap hex", + "loc": "src/hex-map/HexMapView.ts:4828", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.createToken", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Create token here", + "loc": "src/hex-map/HexMapView.ts:4833", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.clearTerrain", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Clear terrain", + "loc": "src/hex-map/HexMapView.ts:4839", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.removeIconOverride", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Remove icon override", + "loc": "src/hex-map/HexMapView.ts:4844", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexMenu.lockedHint", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Switch to Build to … (disabled)", + "loc": "src/hex-map/modeMenu.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.linkTableMenuPicker", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "label": "Link table", + "loc": "src/hex-map/HexMapView.ts:4811", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "HexMenu.linkTable", + "viaSuggested": false, + "overrides": "", + "twinOf": "HexMenu.linkTable", + "note": "" + }, + { + "id": "OverworldMenu.enterRegion", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Enter region: ", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.editRegion", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Edit region…", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.setBiome", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Set biome…", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.center", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Center on this hex", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.locations", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Locations (n)…", + "loc": "src/hex-map/HexMapView.ts:4871", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMenu.createToken", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Create token here", + "loc": "src/hex-map/HexMapView.ts:4882", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.viewRegions", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "View: Regions", + "loc": "src/hex-map/overworldMinimap.ts:61", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.viewBiomes", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "View: Biomes", + "loc": "src/hex-map/overworldMinimap.ts:61", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.biomeLibrary", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Biomes…", + "loc": "src/hex-map/overworldMinimap.ts:71", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.toggle", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Show / Hide the overworld map", + "loc": "src/hex-map/overworldMinimap.ts:79", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Minimap.canvasClick", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Overworld minimap (click to go)", + "loc": "src/hex-map/overworldMinimap.ts:122", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "OverworldMinimap.viewRegions", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "View: Regions", + "loc": "src/hex-map/overworldMinimap.ts:393", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.viewRegions", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.viewRegions", + "note": "" + }, + { + "id": "OverworldMinimap.viewBiomes", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "View: Biomes", + "loc": "src/hex-map/overworldMinimap.ts:393", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.viewBiomes", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.viewBiomes", + "note": "" + }, + { + "id": "OverworldMinimap.biomes", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Biomes…", + "loc": "src/hex-map/overworldMinimap.ts:403", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.biomeLibrary", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.biomeLibrary", + "note": "" + }, + { + "id": "OverworldMinimap.toggle", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Show/Hide the overworld map", + "loc": "src/hex-map/overworldMinimap.ts:411", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.toggle", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.toggle", + "note": "" + }, + { + "id": "OverworldMinimap.canvasClick", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "(minimap hex click)", + "loc": "src/hex-map/overworldMinimap.ts:454", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "Minimap.canvasClick", + "viaSuggested": false, + "overrides": "", + "twinOf": "Minimap.canvasClick", + "note": "" + }, + { + "id": "OverworldMenu.enterRegion_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Enter region", + "loc": "src/overworld/overworldInput.ts:71", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.enterRegion", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.enterRegion", + "note": "" + }, + { + "id": "OverworldMenu.editRegion_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Edit region…", + "loc": "src/overworld/overworldInput.ts:72", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.editRegion", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.editRegion", + "note": "" + }, + { + "id": "OverworldMenu.setBiome_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Set biome…", + "loc": "src/overworld/overworldInput.ts:75", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.setBiome", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.setBiome", + "note": "" + }, + { + "id": "OverworldMenu.center_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Center on this hex", + "loc": "src/overworld/overworldInput.ts:77", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.center", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.center", + "note": "" + }, + { + "id": "OverworldMenu.locations_2", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "label": "Locations (n)…", + "loc": "src/overworld/overworldInput.ts:78", + "suggestion": "keep", + "choice": "keep", + "source": "twin", + "via": "OverworldMenu.locations", + "viaSuggested": false, + "overrides": "", + "twinOf": "OverworldMenu.locations", + "note": "" + }, + { + "id": "TokenMenu.info", + "group": "Hex map view", + "subgroup": "Token right-click menu", + "label": "Token info", + "loc": "src/hex-map/HexMapView.ts:8010", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenMenu.edit", + "group": "Hex map view", + "subgroup": "Token right-click menu", + "label": "Edit token", + "loc": "src/hex-map/HexMapView.ts:8011", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenMenu.openNote", + "group": "Hex map view", + "subgroup": "Token right-click menu", + "label": "Open note", + "loc": "src/hex-map/HexMapView.ts:8012", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenMenu.remove", + "group": "Hex map view", + "subgroup": "Token right-click menu", + "label": "Remove token", + "loc": "src/hex-map/HexMapView.ts:8017", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.coordinates", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Coordinates", + "loc": "src/hex-map/HexSidePanel.ts:105", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.hexNames", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Hex names", + "loc": "src/hex-map/HexSidePanel.ts:106", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.tokenNames", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Token names", + "loc": "src/hex-map/HexSidePanel.ts:107", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameFontBtn", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Aa (Hex name font)", + "loc": "src/hex-map/HexSidePanel.ts:319", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameFontFamily", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Font", + "loc": "src/hex-map/HexSidePanel.ts:337", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameSize", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Name size S / M / L / XL", + "loc": "src/hex-map/HexSidePanel.ts:347", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameBold", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Bold (B)", + "loc": "src/hex-map/HexSidePanel.ts:371", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameItalic", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Italic (I)", + "loc": "src/hex-map/HexSidePanel.ts:372", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.nameFontReset", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Use the default name font (settings)", + "loc": "src/hex-map/HexSidePanel.ts:374", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.terrainIcons", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show terrain icons", + "loc": "src/hex-map/HexSidePanel.ts:102", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.iconOverrides", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show icon overrides", + "loc": "src/hex-map/HexSidePanel.ts:103", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.paths", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show paths", + "loc": "src/hex-map/HexSidePanel.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.tokens", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show tokens", + "loc": "src/hex-map/HexSidePanel.ts:153", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.factionOverlay", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show faction overlay", + "loc": "src/hex-map/HexSidePanel.ts:178", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.regionOverlay", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show region overlay", + "loc": "src/hex-map/HexSidePanel.ts:202", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.gmLayer", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show GM layer", + "loc": "src/hex-map/HexSidePanel.ts:226", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.linkBadges", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show link badges", + "loc": "src/hex-map/HexSidePanel.ts:430", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeSize", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Badge size S / M / L", + "loc": "src/hex-map/HexSidePanel.ts:436", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeTypesMore", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Pick badge types (▸)", + "loc": "src/hex-map/HexSidePanel.ts:451", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeTowns", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Towns badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeDungeons", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Dungeons badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeFeatures", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Features badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeQuests", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Quests badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.badgeFactions", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Factions badges", + "loc": "src/hex-map/HexSidePanel.ts:484", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LayersMenu.legend", + "group": "Hex map view", + "subgroup": "Layers panel", + "label": "Show legend", + "loc": "src/hex-map/HexSidePanel.ts:251", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Legend.size", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Legend size S / M / L", + "loc": "src/hex-map/terrainLegend.ts:160", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Legend.minimize", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Minimize (–)", + "loc": "src/hex-map/terrainLegend.ts:171", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Legend.hide", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Hide legend (×)", + "loc": "src/hex-map/terrainLegend.ts:183", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Legend.expandChip", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Legend (Show the legend)", + "loc": "src/hex-map/terrainLegend.ts:145", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapGrid.expand", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "+ (grow edge, 4 sides)", + "loc": "src/hex-map/HexMapView.ts:1961", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapGrid.shrink", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "− / OK? (shrink edge, 4 sides)", + "loc": "src/hex-map/HexMapView.ts:1966", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathTool.rerouteInstead", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "label": "Reroute instead", + "loc": "src/paths/routePins.ts:196", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.calibrationDone", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Done calibrating (✓)", + "loc": "src/hex-map/HexMapView.ts:3680", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.missingRestore", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Restore", + "loc": "src/hex-map/MapModal.ts:46", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.missingRemove", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Remove", + "loc": "src/hex-map/MapModal.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.hexClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Click hex", + "loc": "src/hex-map/HexMapView.ts:4897", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.hexCtrlClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Ctrl/Cmd+click hex", + "loc": "src/hex-map/HexMapView.ts:4953", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.hexCtrlShiftClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Ctrl/Cmd+Shift+click hex", + "loc": "src/hex-map/HexMapView.ts:4957", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.hexRightClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Right-click hex", + "loc": "src/hex-map/HexMapView.ts:1451", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.locationBadge", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Location badge (Enter location / Locations)", + "loc": "src/hex-map/HexMapView.ts:4423", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.regionShadowHex", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Neighbouring region hex (shadow)", + "loc": "src/hex-map/HexMapView.ts:4638", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.overworldClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Click overworld hex", + "loc": "src/hex-map/HexMapView.ts:4936", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.tokenDrag", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Drag token", + "loc": "src/hex-map/HexMapView.ts:7853", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.tokenRightClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Right-click token", + "loc": "src/hex-map/HexMapView.ts:7840", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.wheelZoom", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Mouse wheel", + "loc": "src/hex-map/HexMapView.ts:1100", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.dragPan", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Drag (left/middle/right)", + "loc": "src/hex-map/HexMapView.ts:1147", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.dblRightClickExit", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Double right-click", + "loc": "src/hex-map/HexMapView.ts:1395", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.dblClickOffGridExit", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Double-click off the grid", + "loc": "src/hex-map/HexMapView.ts:1458", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapView.gmIconRightClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Right-click hex (GM icon paint)", + "loc": "src/hex-map/HexMapView.ts:1408", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathTool.anchorRightClick", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Right-click path anchor", + "loc": "src/hex-map/pathTool.ts:1063", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathTool.anchorDrag", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Drag path point/line", + "loc": "src/hex-map/HexMapView.ts:1270", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.escape", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Esc", + "loc": "src/hex-map/HexMapView.ts:1043", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.undoRedo", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Ctrl/Cmd+Z, Ctrl/Cmd+Shift+Z", + "loc": "src/hex-map/HexMapView.ts:990", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.altArrows", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Alt+← / Alt+↑ / Alt+→", + "loc": "src/hex-map/HexMapView.ts:1001", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.deleteAnchor", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Backspace / Delete", + "loc": "src/hex-map/HexMapView.ts:1055", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.altClickNewPath", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Alt+click", + "loc": "src/hex-map/pathTool.ts:1472", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Keys.calibrationArrows", + "group": "Hex map view", + "subgroup": "Mouse & keyboard", + "label": "Arrow keys (Shift = 10px)", + "loc": "src/hex-map/HexMapView.ts:3605", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex map view", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.centerOnHex", + "group": "Hex editor", + "subgroup": "Header", + "label": "⌖", + "loc": "src/hex-map/HexEditorModal.ts:196", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.openNote", + "group": "Hex editor", + "subgroup": "Header", + "label": "Open note", + "loc": "src/hex-map/HexEditorModal.ts:216", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.exportHex", + "group": "Hex editor", + "subgroup": "Header", + "label": "Export", + "loc": "src/hex-map/HexEditorModal.ts:224", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.runWorkflow", + "group": "Hex editor", + "subgroup": "Header", + "label": "Run workflow", + "loc": "src/hex-map/HexEditorModal.ts:236", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.workflowPicker", + "group": "Hex editor", + "subgroup": "Header", + "label": "Pick a workflow to run…", + "loc": "src/hex-map/HexEditorModal.ts:1660", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborTile", + "group": "Hex editor", + "subgroup": "Header", + "label": "Neighbour hex tiles", + "loc": "src/hex-map/HexEditorModal.ts:578", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborCrossRegion", + "group": "Hex editor", + "subgroup": "Header", + "label": "Neighbour tile (other region)", + "loc": "src/hex-map/HexEditorModal.ts:600", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborWalkOverworld", + "group": "Hex editor", + "subgroup": "Header", + "label": "Neighbour tile (new region)", + "loc": "src/hex-map/HexEditorModal.ts:621", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborNewLand", + "group": "Hex editor", + "subgroup": "Header", + "label": "Neighbour tile (new land)", + "loc": "src/hex-map/HexEditorModal.ts:636", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.neighborCentreDot", + "group": "Hex editor", + "subgroup": "Header", + "label": "Centre dot", + "loc": "src/hex-map/HexEditorModal.ts:660", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "do these actually link directly to a given hex? If a map is big enough I could see wanting to let a note direct-link a centered view on it, if this is the case then we should consider keeping this, maybe even as simple. " + }, + { + "id": "HexEditor.nameInput", + "group": "Hex editor", + "subgroup": "Header", + "label": "Name", + "loc": "src/hex-map/HexEditorModal.ts:449", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsChip", + "group": "Hex editor", + "subgroup": "Header", + "label": "Maps: region/location chips", + "loc": "src/hex-map/HexEditorModal.ts:694", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsAdd", + "group": "Hex editor", + "subgroup": "Header", + "label": "+ (Maps)", + "loc": "src/hex-map/HexEditorModal.ts:709", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsNewMap", + "group": "Hex editor", + "subgroup": "Header", + "label": "New map from this hex…", + "loc": "src/hex-map/HexEditorModal.ts:713", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsLinkExisting", + "group": "Hex editor", + "subgroup": "Header", + "label": "Link existing map…", + "loc": "src/hex-map/HexEditorModal.ts:715", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.mapsManageLocations", + "group": "Hex editor", + "subgroup": "Header", + "label": "Manage locations (N)…", + "loc": "src/hex-map/HexEditorModal.ts:718", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.closeButtons", + "group": "Hex editor", + "subgroup": "Header", + "label": "Close (×)", + "loc": "src/hex-map/HexEditorModal.ts:428", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.collapseTerrain", + "group": "Hex editor", + "subgroup": "Section headers", + "label": "Terrain ▶/▼", + "loc": "src/hex-map/HexEditorModal.ts:276", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor/Section headers", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.collapseNotes", + "group": "Hex editor", + "subgroup": "Section headers", + "label": "Notes ▶/▼", + "loc": "src/hex-map/HexEditorModal.ts:298", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor/Section headers", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.collapseLinked", + "group": "Hex editor", + "subgroup": "Section headers", + "label": "Linked notes ▶/▼", + "loc": "src/hex-map/HexEditorModal.ts:356", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor/Section headers", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.collapseIcons", + "group": "Hex editor", + "subgroup": "Section headers", + "label": "Icons ▶/▼", + "loc": "src/hex-map/HexEditorModal.ts:414", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor/Section headers", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.terrainChangeHint", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "▸ change", + "loc": "src/hex-map/HexEditorModal.ts:286", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.terrainFilter", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Filter terrains…", + "loc": "src/hex-map/HexEditorModal.ts:815", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.terrainPicker", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Terrain swatches", + "loc": "src/hex-map/HexEditorModal.ts:860", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.terrainClear", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Clear", + "loc": "src/hex-map/HexEditorModal.ts:846", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.bodyFieldUseOnMap", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Use \"X\" on the map", + "loc": "src/hex-map/HexEditorModal.ts:1493", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.bodyFieldUpdateNote", + "group": "Hex editor", + "subgroup": "Terrain", + "label": "Change the note to \"X\"", + "loc": "src/hex-map/HexEditorModal.ts:1510", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.description", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Description", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.descriptionRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "📖", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.landmark", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Landmark", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.landmarkRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "📖", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hidden", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Hidden", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hiddenRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "📖", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.secret", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Secret", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.secretRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "📖", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmLayerShow", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Show them", + "loc": "src/hex-map/HexEditorModal.ts:319", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledSectionsFold", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Weather · Hooks & Rumors", + "loc": "src/hex-map/HexEditorModal.ts:329", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.weather", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Weather", + "loc": "src/hex-map/HexEditorModal.ts:332", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.weatherRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "🎲 (Weather)", + "loc": "src/hex-map/HexEditorModal.ts:1710", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.weatherSource", + "group": "Hex editor", + "subgroup": "Notes", + "label": "⋯ (Weather)", + "loc": "src/hex-map/HexEditorModal.ts:1711", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hooks", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Hooks & Rumors", + "loc": "src/hex-map/HexEditorModal.ts:332", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hooksRoll", + "group": "Hex editor", + "subgroup": "Notes", + "label": "🎲 (Hooks & Rumors)", + "loc": "src/hex-map/HexEditorModal.ts:1710", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.hooksSource", + "group": "Hex editor", + "subgroup": "Notes", + "label": "⋯ (Hooks & Rumors)", + "loc": "src/hex-map/HexEditorModal.ts:1711", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledSetMapTable", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Set/Change the map's … table…", + "loc": "src/hex-map/HexEditorModal.ts:1760", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledSetHexTable", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Use a different table for this hex…", + "loc": "src/hex-map/HexEditorModal.ts:1761", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledUseMapTable", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Use the map's table on this hex", + "loc": "src/hex-map/HexEditorModal.ts:1763", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.rolledTablePicker", + "group": "Hex editor", + "subgroup": "Notes", + "label": "Weather/rumour table chooser", + "loc": "src/hex-map/HexEditorModal.ts:1722", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.moreInNoteFold", + "group": "Hex editor", + "subgroup": "Notes", + "label": "More in this note (N)", + "loc": "src/hex-map/HexEditorModal.ts:345", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.moreInNoteText", + "group": "Hex editor", + "subgroup": "Notes", + "label": " (other sections)", + "loc": "src/hex-map/HexEditorModal.ts:348", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.sectionTablePicker", + "group": "Hex editor", + "subgroup": "Notes", + "label": "(set map's / this hex's table)", + "loc": "src/hex-map/HexEditorModal.ts:1722", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Encounters Table", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Towns", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.townsRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Dungeons", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.dungeonsRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Quests", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.questsRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Factions", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.factionsRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "Features", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresShowAll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "▾", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresCreate", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "+ Create \"…\"", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresOpenLink", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.featuresRemove", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "×", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.encountersRoll", + "group": "Hex editor", + "subgroup": "Linked notes", + "label": "🎲 (Encounters)", + "loc": "src/hex-map/HexEditorModal.ts:1450", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.iconOverride", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Icon override", + "loc": "src/hex-map/HexEditorModal.ts:922", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.iconTerrainDefault", + "group": "Hex editor", + "subgroup": "Icons", + "label": "— terrain default —", + "loc": "src/hex-map/HexEditorModal.ts:926", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.iconPackTabs", + "group": "Hex editor", + "subgroup": "Icons", + "label": "All / / Custom tabs", + "loc": "src/HexmakerModal.ts:108", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.iconPlaceKinds", + "group": "Hex editor", + "subgroup": "Icons", + "label": "All places / Settlements / Castles…", + "loc": "src/HexmakerModal.ts:133", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIcons", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Game master icons", + "loc": "src/hex-map/HexEditorModal.ts:941", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconsRemoveOne", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Right-click icon", + "loc": "src/hex-map/HexEditorModal.ts:1037", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconsClearAll", + "group": "Hex editor", + "subgroup": "Icons", + "label": "— clear all —", + "loc": "src/hex-map/HexEditorModal.ts:1050", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconFilterSearch", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Filter icons… (GM)", + "loc": "src/HexmakerModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconPackTabs", + "group": "Hex editor", + "subgroup": "Icons", + "label": "All / / Custom tabs (GM)", + "loc": "src/HexmakerModal.ts:108", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexEditor.gmIconPlaceKinds", + "group": "Hex editor", + "subgroup": "Icons", + "label": "Place kind chips (GM)", + "loc": "src/HexmakerModal.ts:133", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.refresh", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Refresh", + "loc": "src/hex-table/HexTableView.ts:143", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.xMin", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "X: Min", + "loc": "src/hex-table/HexTableView.ts:153", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.xMax", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "X: Max", + "loc": "src/hex-table/HexTableView.ts:164", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.yMin", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Y: Min", + "loc": "src/hex-table/HexTableView.ts:179", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.yMax", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Y: Max", + "loc": "src/hex-table/HexTableView.ts:190", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.terrainFilter", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Terrain: all", + "loc": "src/hex-table/HexTableView.ts:204", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasTown", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Town", + "loc": "src/hex-table/HexTableView.ts:240", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasDungeon", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Dungeon", + "loc": "src/hex-table/HexTableView.ts:252", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasFeature", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Feature", + "loc": "src/hex-table/HexTableView.ts:264", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasQuest", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Quest", + "loc": "src/hex-table/HexTableView.ts:276", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hasFaction", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Faction", + "loc": "src/hex-table/HexTableView.ts:288", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.mapSelect", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "All maps / ", + "loc": "src/hex-table/HexTableView.ts:299", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.sortCycle", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Sort: xy / yx / type", + "loc": "src/hex-table/HexTableView.ts:329", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.sortDirection", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "↑ asc / ↓ desc", + "loc": "src/hex-table/HexTableView.ts:341", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.clearFilters", + "group": "Hex table", + "subgroup": "Toolbar", + "label": "Clear filters", + "loc": "src/hex-table/HexTableView.ts:355", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.jumpToHex", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "◎", + "loc": "src/hex-table/HexTableView.ts:802", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.openHexNote", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "", + "loc": "src/hex-table/HexTableView.ts:812", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.terrainCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Terrain cell", + "loc": "src/hex-table/HexTableView.ts:889", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.townsCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Towns cell", + "loc": "src/hex-table/HexTableView.ts:970", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.dungeonsCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Dungeons cell", + "loc": "src/hex-table/HexTableView.ts:970", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.encountersCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Enc. Table cell", + "loc": "src/hex-table/HexTableView.ts:970", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.encountersMiddleClick", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Middle-click Enc. Table", + "loc": "src/hex-table/HexTableView.ts:947", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.otherLinkCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Features/Quests/Factions cell", + "loc": "src/hex-table/HexTableView.ts:1031", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.textCell", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Text cells (Description…Hooks)", + "loc": "src/hex-table/HexTableView.ts:1054", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.columnResize", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Column edge drag", + "loc": "src/hex-table/HexTableView.ts:1119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.hiddenSecretColumns", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Hidden / Secret columns", + "loc": "src/hex-table/HexTableView.ts:44", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTable.weatherHooksColumns", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "Weather / Hooks & Rumors columns", + "loc": "src/hex-table/HexTableView.ts:46", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexCell.textarea", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "
text", + "loc": "src/hex-table/HexCellModal.ts:38", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexCell.rollOnTable", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "🎲 Roll on table", + "loc": "src/hex-table/HexCellModal.ts:46", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexCell.linkList", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "", + "loc": "src/hex-table/HexCellModal.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexCell.closeButtons", + "group": "Hex table", + "subgroup": "Rows & cells", + "label": "×", + "loc": "src/hex-table/HexCellModal.ts:69", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.noTerrain", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "No terrain", + "loc": "src/hex-table/TerrainFilterModal.ts:156", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.typeRow", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": " row", + "loc": "src/hex-table/TerrainFilterModal.ts:160", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.terrainRow", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": " rows", + "loc": "src/hex-table/TerrainFilterModal.ts:168", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.excludeRightClick", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Right-click to exclude", + "loc": "src/hex-table/TerrainFilterModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.categoryHeading", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": " heading", + "loc": "src/hex-table/TerrainFilterModal.ts:130", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.clearAll", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Clear all", + "loc": "src/hex-table/TerrainFilterModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainFilter.closeButtons", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Done / ×", + "loc": "src/hex-table/TerrainFilterModal.ts:216", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTerrainPicker.terrains", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Select terrain", + "loc": "src/hex-table/HexTerrainPickerModal.ts:129", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTerrainPicker.clear", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "Clear terrain", + "loc": "src/hex-table/HexTerrainPickerModal.ts:160", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexTerrainPicker.closeButtons", + "group": "Hex table", + "subgroup": "Terrain filter", + "label": "×", + "loc": "src/hex-table/HexTerrainPickerModal.ts:120", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.townsList", + "group": "Hex table", + "subgroup": "Linking", + "label": "Select existing: (Towns)", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.dungeonsList", + "group": "Hex table", + "subgroup": "Linking", + "label": "Select existing: (Dungeons)", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.encountersList", + "group": "Hex table", + "subgroup": "Linking", + "label": "Select existing: (Encounters Table)", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.createName", + "group": "Hex table", + "subgroup": "Linking", + "label": "Or create new: ", + "loc": "src/hex-table/LinkPickerModal.ts:232", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.createButton", + "group": "Hex table", + "subgroup": "Linking", + "label": "Create", + "loc": "src/hex-table/LinkPickerModal.ts:237", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "LinkPicker.closeButtons", + "group": "Hex table", + "subgroup": "Linking", + "label": "×", + "loc": "src/hex-table/LinkPickerModal.ts:199", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MultiLinkNav.items", + "group": "Hex table", + "subgroup": "Linking", + "label": "", + "loc": "src/hex-table/MultiLinkNavModal.ts:20", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MultiLinkNav.closeButtons", + "group": "Hex table", + "subgroup": "Linking", + "label": "×", + "loc": "src/hex-table/MultiLinkNavModal.ts:13", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Hex table", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconFilter.search", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "Filter icons...", + "loc": "src/HexmakerModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconFilter.packTabs", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "All / Terrain / Places / Space / Custom (+counts)", + "loc": "src/HexmakerModal.ts:108", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconFilter.placeKindChips", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "All places / Settlements / Castles / ...", + "loc": "src/HexmakerModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.gmLayerOnly", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "GM layer only", + "loc": "src/hex-map/IconPickerModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.manageIcons", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "Manage icons / ← pick icons", + "loc": "src/hex-map/IconPickerModal.ts:57", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.remove", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "Remove", + "loc": "src/hex-map/IconPickerModal.ts:79", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.grid", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "(icon tiles)", + "loc": "src/hex-map/IconPickerModal.ts:89", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.packTabs", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "All / Terrain / Places / Space / Custom", + "loc": "src/HexmakerModal.ts:109", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.hideToggle", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "eye / eye-off", + "loc": "src/hex-map/IconPickerModal.ts:138", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.dragReorder", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "⠿ (drag to reorder)", + "loc": "src/hex-map/IconPickerModal.ts:157", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.uploadDropZone", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "Drag & drop images here, or click to browse", + "loc": "src/hex-map/IconPickerModal.ts:204", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "IconPicker.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Icons", + "label": "×", + "loc": "src/hex-map/IconPickerModal.ts:29", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.notePicker", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Note", + "loc": "src/hex-map/TokenModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.noteStatus", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Links to … / Creates a new note: …", + "loc": "src/hex-map/TokenModal.ts:115", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.iconPackTabs", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "All / Terrain / Places / Space / Custom", + "loc": "src/HexmakerModal.ts:109", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.iconGrid", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Icon", + "loc": "src/hex-map/TokenModal.ts:199", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.shape", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Shape", + "loc": "src/hex-map/TokenModal.ts:233", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.size", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Size", + "loc": "src/hex-map/TokenModal.ts:244", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.fillColor", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Fill color", + "loc": "src/hex-map/TokenModal.ts:262", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.borderToggle", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Border color (on/off)", + "loc": "src/hex-map/TokenModal.ts:284", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.borderColor", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Border color", + "loc": "src/hex-map/TokenModal.ts:292", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.description", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Description", + "loc": "src/hex-map/TokenModal.ts:315", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.removeButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Remove token", + "loc": "src/hex-map/TokenModal.ts:333", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.saveButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Next: place on map / Save", + "loc": "src/hex-map/TokenModal.ts:340", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Token.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Cancel", + "loc": "src/hex-map/TokenModal.ts:372", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.jumpButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "⌖", + "loc": "src/hex-map/TokenInfoModal.ts:31", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.openNoteLink", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Open note", + "loc": "src/hex-map/TokenInfoModal.ts:44", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.editButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "Edit token", + "loc": "src/hex-map/TokenInfoModal.ts:56", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.noteLinks", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "(links inside the note preview)", + "loc": "src/hex-map/TokenInfoModal.ts:91", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.removeButton", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "× remove / Confirm remove?", + "loc": "src/hex-map/TokenInfoModal.ts:117", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TokenInfo.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "label": "×", + "loc": "src/hex-map/TokenInfoModal.ts:20", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathName.nameInput", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "(path name)", + "loc": "src/hex-map/PathNameModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathName.saveButton", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Save", + "loc": "src/hex-map/PathNameModal.ts:48", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathName.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Cancel", + "loc": "src/hex-map/PathNameModal.ts:49", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.editToggle", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "✏ Edit / ← Done", + "loc": "src/hex-map/PathPickerModal.ts:158", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.drawMode", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "1. How to draw: Hex by hex / Auto-route", + "loc": "src/hex-map/PathPickerModal.ts:107", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.removeTile", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Remove", + "loc": "src/hex-map/PathPickerModal.ts:187", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.typeGrid", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "2. Pick a path type to start drawing", + "loc": "src/hex-map/PathPickerModal.ts:198", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.pathsOnMap", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Paths on this map", + "loc": "src/hex-map/PathPickerModal.ts:229", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.editTypeTile", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "(type tile, edit mode)", + "loc": "src/hex-map/PathPickerModal.ts:268", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.dragReorder", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "⠿ (drag to reorder)", + "loc": "src/hex-map/PathPickerModal.ts:285", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.addTypeTile", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "+ Add", + "loc": "src/hex-map/PathPickerModal.ts:315", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathPicker.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "×", + "loc": "src/hex-map/PathPickerModal.ts:133", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.name", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Name", + "loc": "src/hex-map/PathTypeEditorModal.ts:78", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.color", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Color", + "loc": "src/hex-map/PathTypeEditorModal.ts:88", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.width", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Width", + "loc": "src/hex-map/PathTypeEditorModal.ts:99", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.lineStyle", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Line style", + "loc": "src/hex-map/PathTypeEditorModal.ts:111", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.routing", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Routing", + "loc": "src/hex-map/PathTypeEditorModal.ts:125", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.avoidImpassable", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Avoid impassable terrain", + "loc": "src/hex-map/PathTypeEditorModal.ts:140", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.autoRoute", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Auto-route", + "loc": "src/hex-map/PathTypeEditorModal.ts:149", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.carves", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Carves terrain", + "loc": "src/hex-map/PathTypeEditorModal.ts:163", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.carveWidth", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Carve width", + "loc": "src/hex-map/PathTypeEditorModal.ts:173", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.saveButton", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Save", + "loc": "src/hex-map/PathTypeEditorModal.ts:185", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.deleteButton", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Delete", + "loc": "src/hex-map/PathTypeEditorModal.ts:194", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.deleteConfirm", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "Yes, delete / Cancel", + "loc": "src/hex-map/PathTypeEditorModal.ts:212", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PathType.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Path types", + "label": "×", + "loc": "src/hex-map/PathTypeEditorModal.ts:225", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GotoHex.xInput", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "X:", + "loc": "src/hex-map/GotoHexModal.ts:21", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GotoHex.yInput", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "Y:", + "loc": "src/hex-map/GotoHexModal.ts:26", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GotoHex.goButton", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "Go", + "loc": "src/hex-map/GotoHexModal.ts:40", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GotoHex.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "×", + "loc": "src/hex-map/GotoHexModal.ts:14", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexHelp.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help", + "label": "×", + "loc": "src/hex-map/HexHelpModal.ts:10", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.search", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "Find a location…", + "loc": "src/hex-map/LocationsModal.ts:45", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.list", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "(location name)", + "loc": "src/hex-map/LocationsModal.ts:111", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.openButton", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "Open", + "loc": "src/hex-map/LocationsModal.ts:118", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.unlink", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "✕", + "loc": "src/hex-map/LocationsModal.ts:122", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.dragReorder", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "⋮⋮ (drag)", + "loc": "src/hex-map/LocationsModal.ts:89", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.newLocation", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "New location…", + "loc": "src/hex-map/LocationsModal.ts:62", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.linkExisting", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "Link existing map…", + "loc": "src/hex-map/LocationsModal.ts:66", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "Locations.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Locations", + "label": "×", + "loc": "src/hex-map/LocationsModal.ts:42", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.grid", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "(faction tiles)", + "loc": "src/hex-map/FactionPickerModal.ts:207", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.removeTile", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Remove", + "loc": "src/hex-map/FactionPickerModal.ts:193", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.editTile", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "✏", + "loc": "src/hex-map/FactionPickerModal.ts:221", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.newName", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "New faction name…", + "loc": "src/hex-map/FactionPickerModal.ts:270", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.createButton", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Create", + "loc": "src/hex-map/FactionPickerModal.ts:274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionPicker.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "×", + "loc": "src/hex-map/FactionPickerModal.ts:300", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.openNote", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Open note →", + "loc": "src/hex-map/FactionPickerModal.ts:46", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.name", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Name", + "loc": "src/hex-map/FactionPickerModal.ts:74", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.color", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Color", + "loc": "src/hex-map/FactionPickerModal.ts:81", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.pattern", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Pattern", + "loc": "src/hex-map/overlayPatternControls.ts:139", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.patternScale", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Pattern scale", + "loc": "src/hex-map/overlayPatternControls.ts:149", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.opacity", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Opacity", + "loc": "src/hex-map/overlayPatternControls.ts:159", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.outlineWidth", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Outline width", + "loc": "src/hex-map/overlayPatternControls.ts:169", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.save", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Save", + "loc": "src/hex-map/FactionPickerModal.ts:102", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.clearColor", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "Clear color", + "loc": "src/hex-map/FactionPickerModal.ts:126", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FactionEditor.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Factions", + "label": "×", + "loc": "src/hex-map/FactionPickerModal.ts:36", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.editToggle", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "✏ Edit / ← Done", + "loc": "src/hex-map/TerrainPickerModal.ts:52", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.fullEditor", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Full editor…", + "loc": "src/hex-map/TerrainPickerModal.ts:63", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.brushSize", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Brush: 1× 3× 7×", + "loc": "src/hex-map/TerrainPickerModal.ts:83", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.eyedropper", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "⌖ Pick", + "loc": "src/hex-map/TerrainPickerModal.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.clear", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Clear", + "loc": "src/hex-map/TerrainPickerModal.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.grid", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "(terrain tiles)", + "loc": "src/hex-map/TerrainPickerModal.ts:132", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.editTile", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "(terrain tile, edit mode)", + "loc": "src/hex-map/TerrainPickerModal.ts:175", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.dragReorder", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "⠿ (drag to reorder)", + "loc": "src/hex-map/TerrainPickerModal.ts:198", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.addTile", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "+ Add", + "loc": "src/hex-map/TerrainPickerModal.ts:232", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.refreshEncounterLinks", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Refresh all encounter table links", + "loc": "src/hex-map/TerrainPickerModal.ts:275", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainPicker.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "×", + "loc": "src/hex-map/TerrainPickerModal.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainTemplate.newBlank", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "New blank", + "loc": "src/hex-map/TerrainPickerModal.ts:309", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainTemplate.copyList", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Or copy from an existing palette:", + "loc": "src/hex-map/TerrainPickerModal.ts:329", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainTemplate.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "×", + "loc": "src/hex-map/TerrainPickerModal.ts:345", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.name", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Name", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:57", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.type", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Type", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:73", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.impassable", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Impassable", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:85", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.color", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Color", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.icon", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Icon", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:102", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.iconTintToggle", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Icon tint (on/off)", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:125", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.iconTintColor", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Icon tint", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:136", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.category", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Category", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:159", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.save", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Save / Updating hexes…", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:180", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.delete", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Delete", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:198", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TerrainEntry.closeButtons", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "label": "Cancel", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:193", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Map pickers & editors", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.tabMaps", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "Maps", + "loc": "src/hex-map/MapModal.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.tabProperties", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "Properties", + "loc": "src/hex-map/MapModal.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.tabRegions", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "Regions", + "loc": "src/hex-map/MapModal.ts:107", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.tabExport", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "Export", + "loc": "src/hex-map/MapModal.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.newMap", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "New map…", + "loc": "src/hex-map/MapModal.ts:127", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.newOverworld", + "group": "Maps modal", + "subgroup": "Tabs & general", + "label": "New overworld…", + "loc": "src/hex-map/MapModal.ts:130", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.mapSearch", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Find a map…", + "loc": "src/hex-map/MapModal.ts:242", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.mapTree", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "(map list)", + "loc": "src/hex-map/MapModal.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.treeToggle", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "▸ / ▾", + "loc": "src/hex-map/MapModal.ts:317", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsGroupRow", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Regions of ", + "loc": "src/hex-map/MapModal.ts:290", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.neighboursGroupRow", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Neighbours: ", + "loc": "src/hex-map/MapModal.ts:299", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.mapRowContextGenerator", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Open generator \"\"", + "loc": "src/hex-map/MapModal.ts:355", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.mapRowContextMakeGenerator", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Make generator from …", + "loc": "src/hex-map/MapModal.ts:363", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.missingRemove", + "group": "Maps modal", + "subgroup": "Maps list", + "label": "Remove / Remove from list?", + "loc": "src/hex-map/MapModal.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapProps.sectionTablePicker", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Pick table…", + "loc": "src/hex-map/MapModal.ts:624", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsName", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Name", + "loc": "src/hex-map/MapModal.ts:425", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsSaveName", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Save name", + "loc": "src/hex-map/MapModal.ts:430", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsFolderName", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Folder name", + "loc": "src/hex-map/MapModal.ts:448", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsRenameFolder", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Rename folder", + "loc": "src/hex-map/MapModal.ts:453", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsStagger", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Stagger offset (Odd/Even)", + "loc": "src/hex-map/MapModal.ts:466", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourHint", + "group": "Maps modal", + "subgroup": "Properties", + "label": "(enable Regions hint)", + "loc": "src/hex-map/MapModal.ts:696", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsTerrainTheme", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Terrain theme", + "loc": "src/hex-map/MapModal.ts:494", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsDelete", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Delete \"\"…", + "loc": "src/hex-map/MapModal.ts:660", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsDeleteConfirm", + "group": "Maps modal", + "subgroup": "Properties", + "label": "Delete / Cancel", + "loc": "src/hex-map/MapModal.ts:671", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourNorth", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "North", + "loc": "src/hex-map/MapModal.ts:711", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourEast", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "East", + "loc": "src/hex-map/MapModal.ts:711", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourSouth", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "South", + "loc": "src/hex-map/MapModal.ts:711", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNeighbourWest", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "West", + "loc": "src/hex-map/MapModal.ts:711", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsNewRegionHere", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "New region here…", + "loc": "src/hex-map/MapModal.ts:733", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsDetach", + "group": "Maps modal", + "subgroup": "Neighbouring regions", + "label": "Detach from its neighbours", + "loc": "src/hex-map/MapModal.ts:740", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsWeatherTable", + "group": "Maps modal", + "subgroup": "Weather & rumours", + "label": "Weather: Pick table…", + "loc": "src/hex-map/MapModal.ts:623", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsWeatherClear", + "group": "Maps modal", + "subgroup": "Weather & rumours", + "label": "Clear (weather)", + "loc": "src/hex-map/MapModal.ts:635", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsRumoursTable", + "group": "Maps modal", + "subgroup": "Weather & rumours", + "label": "Rumours: Pick table…", + "loc": "src/hex-map/MapModal.ts:623", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsRumoursClear", + "group": "Maps modal", + "subgroup": "Weather & rumours", + "label": "Clear (rumours)", + "loc": "src/hex-map/MapModal.ts:635", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapProps.backgroundImagePicker", + "group": "Maps modal", + "subgroup": "Background image", + "label": "Pick image…", + "loc": "src/hex-map/MapModal.ts:548", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsBgDrop", + "group": "Maps modal", + "subgroup": "Background image", + "label": "(drop an image here)", + "loc": "src/hex-map/MapModal.ts:567", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsBgClear", + "group": "Maps modal", + "subgroup": "Background image", + "label": "Clear", + "loc": "src/hex-map/MapModal.ts:556", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsBgOpacity", + "group": "Maps modal", + "subgroup": "Background image", + "label": "Opacity", + "loc": "src/hex-map/MapModal.ts:578", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.propsBgCalibrate", + "group": "Maps modal", + "subgroup": "Background image", + "label": "Calibrate position & scale", + "loc": "src/hex-map/MapModal.ts:590", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsSetUp", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "Set up regions…", + "loc": "src/hex-map/MapModal.ts:169", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsSettingsForm", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "(region settings form)", + "loc": "src/hex-map/MapModal.ts:182", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsMakeMissing", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "Make the missing regions (N)…", + "loc": "src/hex-map/MapModal.ts:189", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsGenerateOverworld", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "Generate overworld…", + "loc": "src/hex-map/MapModal.ts:200", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.regionsList", + "group": "Maps modal", + "subgroup": "Regions tab", + "label": "Regions (N) list", + "loc": "src/hex-map/MapModal.ts:209", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Maps modal", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.name", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Name", + "loc": "src/worldgen/NewMapSetupModal.ts:222", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.palette", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Palette", + "loc": "src/worldgen/NewMapSetupModal.ts:247", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.rememberPalette", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Use this palette for new submaps of hexes", + "loc": "src/worldgen/NewMapSetupModal.ts:259", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.sizePresets", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "(size presets)", + "loc": "src/worldgen/NewMapSetupModal.ts:274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.size", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Size (columns × rows)", + "loc": "src/worldgen/NewMapSetupModal.ts:266", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.rememberSize", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Use this size for new submaps…", + "loc": "src/worldgen/NewMapSetupModal.ts:306", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.nextTo", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Next to", + "loc": "src/worldgen/NewMapSetupModal.ts:324", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.nextToSide", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "(side of the neighbouring map)", + "loc": "src/worldgen/NewMapSetupModal.ts:327", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.generator", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Generator", + "loc": "src/worldgen/NewMapSetupModal.ts:569", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.rememberGenerator", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Use this generator and its options for new submaps…", + "loc": "src/worldgen/NewMapSetupModal.ts:398", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.moreOptionsHint", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "More options: … Show / ✕", + "loc": "src/worldgen/NewMapSetupModal.ts:401", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.baseTerrain", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Base terrain", + "loc": "src/worldgen/NewMapSetupModal.ts:411", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.rememberBase", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Use this base terrain for new submaps…", + "loc": "src/worldgen/NewMapSetupModal.ts:412", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.more", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "More: folder name, starting coordinates, stagger, background image", + "loc": "src/worldgen/NewMapSetupModal.ts:420", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.reroll", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "🎲 Re-roll", + "loc": "src/worldgen/NewMapSetupModal.ts:509", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.create", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Generate / Create (& enter)", + "loc": "src/worldgen/NewMapSetupModal.ts:518", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.openInGenerator", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Open in generator", + "loc": "src/worldgen/NewMapSetupModal.ts:519", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.closeButtons", + "group": "New maps & map links", + "subgroup": "New map form", + "label": "Cancel", + "loc": "src/worldgen/NewMapSetupModal.ts:521", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMapSetup.backgroundImagePicker", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Pick image…", + "loc": "src/worldgen/NewMapSetupModal.ts:459", + "suggestion": "advanced", + "choice": "advanced", + "source": "twin", + "via": "NewMap.bgPick", + "viaSuggested": false, + "overrides": "", + "twinOf": "NewMap.bgPick", + "note": "" + }, + { + "id": "NewMap.folderName", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Folder name", + "loc": "src/worldgen/NewMapSetupModal.ts:425", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.startCoords", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Starting coordinates", + "loc": "src/worldgen/NewMapSetupModal.ts:433", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.stagger", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Stagger offset", + "loc": "src/worldgen/NewMapSetupModal.ts:444", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.bgPick", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Pick image…", + "loc": "src/worldgen/NewMapSetupModal.ts:455", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.bgClear", + "group": "New maps & map links", + "subgroup": "New map form: More", + "label": "Clear", + "loc": "src/worldgen/NewMapSetupModal.ts:456", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.overlandWater", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Water", + "loc": "src/worldgen/procedural/planetSurface.ts:40", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.overlandClimate", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Climate", + "loc": "src/worldgen/procedural/planetSurface.ts:52", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.overlandRelief", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Relief", + "loc": "src/worldgen/procedural/planetSurface.ts:64", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.overlandSea", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Sea", + "loc": "src/worldgen/procedural/planetSurface.ts:88", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.planetWater", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Water", + "loc": "src/worldgen/procedural/planetSurface.ts:40", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.planetClimate", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Climate", + "loc": "src/worldgen/procedural/planetSurface.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.planetRelief", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Relief", + "loc": "src/worldgen/procedural/planetSurface.ts:64", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.regionDetailInfluence", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Neighbour influence", + "loc": "src/worldgen/procedural/planetSurface.ts:500", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.regionDetailVariety", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Variety", + "loc": "src/worldgen/procedural/planetSurface.ts:510", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.worldBiomesClimate", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Climate", + "loc": "src/overworld/worldBiomes.ts:576", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.worldBiomesWater", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Water %", + "loc": "src/overworld/worldBiomes.ts:579", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.worldBiomesLand", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "Land", + "loc": "src/overworld/worldBiomes.ts:580", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.worldBiomesNorth", + "group": "New maps & map links", + "subgroup": "Generator options (world)", + "label": "North is", + "loc": "src/overworld/worldBiomes.ts:583", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.starDensity", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "System density", + "loc": "src/worldgen/procedural/starScatter.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.starNebulae", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Nebulae", + "loc": "src/worldgen/procedural/starScatter.ts:43", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.starJumpRoutes", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Jump routes", + "loc": "src/worldgen/procedural/starScatter.ts:53", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.starRouteType", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Path type for routes", + "loc": "src/worldgen/generatorPathTypes.ts:27", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.orbitsStar", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Star", + "loc": "src/worldgen/procedural/orbits.ts:37", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.orbitsPlanets", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Planets", + "loc": "src/worldgen/procedural/orbits.ts:49", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.orbitsPathType", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Path type for orbits", + "loc": "src/worldgen/generatorPathTypes.ts:28", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMap.editWorldTypes", + "group": "New maps & map links", + "subgroup": "Generator options (space)", + "label": "Edit world types…", + "loc": "src/worldgen/NewMapSetupModal.ts:634", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ChildKind.region", + "group": "New maps & map links", + "subgroup": "New map from a hex", + "label": "Region", + "loc": "src/hex-map/newChildMap.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ChildKind.location", + "group": "New maps & map links", + "subgroup": "New map from a hex", + "label": "Location", + "loc": "src/hex-map/newChildMap.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ChildKind.enterRegion", + "group": "New maps & map links", + "subgroup": "New map from a hex", + "label": "Enter ", + "loc": "src/hex-map/newChildMap.ts:124", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ChildKind.regionsHint", + "group": "New maps & map links", + "subgroup": "New map from a hex", + "label": "Turn on regions and overworlds / ✕", + "loc": "src/hex-map/newChildMap.ts:128", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.biome", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Biome", + "loc": "src/worldgen/WalkRegionModal.ts:97", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.roll", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Roll", + "loc": "src/worldgen/WalkRegionModal.ts:101", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.seed", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Seed", + "loc": "src/worldgen/WalkRegionModal.ts:105", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.rerollTerrain", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Re-roll terrain", + "loc": "src/worldgen/WalkRegionModal.ts:107", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.name", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Name", + "loc": "src/worldgen/WalkRegionModal.ts:117", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.create", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Create and go", + "loc": "src/worldgen/WalkRegionModal.ts:123", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkOW.closeButtons", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Cancel", + "loc": "src/worldgen/WalkRegionModal.ts:124", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.biome", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Biome", + "loc": "src/worldgen/WalkRegionModal.ts:222", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.roll", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Roll", + "loc": "src/worldgen/WalkRegionModal.ts:225", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.rerollTerrain", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Re-roll terrain", + "loc": "src/worldgen/WalkRegionModal.ts:230", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.name", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Name", + "loc": "src/worldgen/WalkRegionModal.ts:234", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.create", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Create and go", + "loc": "src/worldgen/WalkRegionModal.ts:237", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WalkSide.closeButtons", + "group": "New maps & map links", + "subgroup": "New land beside a map", + "label": "Cancel", + "loc": "src/worldgen/WalkRegionModal.ts:238", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.map", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Map", + "loc": "src/hex-map/MapLinkModal.ts:344", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.showAll", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "▾ Show all", + "loc": "src/hex-map/MapLinkModal.ts:351", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.linkText", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Link text", + "loc": "src/hex-map/MapLinkModal.ts:420", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.insert", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Insert", + "loc": "src/hex-map/MapLinkModal.ts:428", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapLink.closeButtons", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Cancel", + "loc": "src/hex-map/MapLinkModal.ts:441", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.filter", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Filter maps…", + "loc": "src/hex-map/SubmapPickerModal.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.mapList", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "(map list)", + "loc": "src/hex-map/SubmapPickerModal.ts:58", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.newLocation", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "New location…", + "loc": "src/hex-map/SubmapPickerModal.ts:106", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.removeLink", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Remove link", + "loc": "src/hex-map/SubmapPickerModal.ts:272", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.link", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Link", + "loc": "src/hex-map/SubmapPickerModal.ts:275", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.closeButtons", + "group": "New maps & map links", + "subgroup": "Link submap & insert map link", + "label": "Cancel", + "loc": "src/hex-map/SubmapPickerModal.ts:281", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createSection", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Create & link new map", + "loc": "src/hex-map/SubmapPickerModal.ts:115", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createName", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Name", + "loc": "src/hex-map/SubmapPickerModal.ts:135", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createCols", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Size (columns)", + "loc": "src/hex-map/SubmapPickerModal.ts:150", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createRows", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Size (rows)", + "loc": "src/hex-map/SubmapPickerModal.ts:153", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createPalette", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Palette", + "loc": "src/hex-map/SubmapPickerModal.ts:159", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createStartX", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Start at (x)", + "loc": "src/hex-map/SubmapPickerModal.ts:170", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createStartY", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Start at (y)", + "loc": "src/hex-map/SubmapPickerModal.ts:173", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createStagger", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Stagger (Odd/Even)", + "loc": "src/hex-map/SubmapPickerModal.ts:180", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createTerrainTheme", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Map terrain theme", + "loc": "src/hex-map/SubmapPickerModal.ts:192", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "SubmapPicker.createAndLink", + "group": "New maps & map links", + "subgroup": "Link submap: inline create form", + "label": "Create & link / Create & enter", + "loc": "src/hex-map/SubmapPickerModal.ts:241", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMapFields.name", + "group": "New maps & map links", + "subgroup": "Dead code", + "label": "Map name", + "loc": "src/hex-map/newMapFields.ts:23", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMapFields.size", + "group": "New maps & map links", + "subgroup": "Dead code", + "label": "(cols × rows)", + "loc": "src/hex-map/newMapFields.ts:28", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewMapFields.palette", + "group": "New maps & map links", + "subgroup": "Dead code", + "label": "(palette)", + "loc": "src/hex-map/newMapFields.ts:39", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:New maps & map links", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenerateRegions.makeThem", + "group": "Regions, overworlds & biomes", + "subgroup": "Missing regions & go to region", + "label": "Make them", + "loc": "src/hex-map/OverworldModals.ts:62", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenerateRegions.cancelStop", + "group": "Regions, overworlds & biomes", + "subgroup": "Missing regions & go to region", + "label": "Cancel / Stop / Close", + "loc": "src/hex-map/OverworldModals.ts:61", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionNavigate.go", + "group": "Regions, overworlds & biomes", + "subgroup": "Missing regions & go to region", + "label": "Go to ", + "loc": "src/hex-map/RegionNavigateModal.ts:378", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionNavigate.stay", + "group": "Regions, overworlds & biomes", + "subgroup": "Missing regions & go to region", + "label": "Stay", + "loc": "src/hex-map/RegionNavigateModal.ts:383", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.name", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Name", + "loc": "src/hex-map/OverworldModals.ts:178", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.shape", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Shape", + "loc": "src/hex-map/OverworldModals.ts:182", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.hexCount", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Hexes (N hexes)", + "loc": "src/hex-map/OverworldModals.ts:190", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.columns", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Columns", + "loc": "src/hex-map/OverworldModals.ts:195", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.rows", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Rows", + "loc": "src/hex-map/OverworldModals.ts:197", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.palette", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Palette", + "loc": "src/hex-map/OverworldModals.ts:210", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.climate", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Climate", + "loc": "src/hex-map/OverworldModals.ts:287", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.land", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Land", + "loc": "src/hex-map/OverworldModals.ts:288", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.northIs", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "North is", + "loc": "src/hex-map/OverworldModals.ts:289", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.water", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Water", + "loc": "src/hex-map/OverworldModals.ts:291", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.blankHexes", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Blank hexes", + "loc": "src/hex-map/OverworldModals.ts:300", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.blankBiome", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Blank biome", + "loc": "src/hex-map/OverworldModals.ts:303", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.seed", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Seed", + "loc": "src/hex-map/OverworldModals.ts:318", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "just make sure its saved for the saved rolls etc, its fine if it shows up on saves too. " + }, + { + "id": "NewOverworld.reroll", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Reroll", + "loc": "src/hex-map/OverworldModals.ts:320", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.regionSize", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Each hex opens into", + "loc": "src/hex-map/OverworldModals.ts:333", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.blend", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Blend", + "loc": "src/hex-map/OverworldModals.ts:337", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.makeAll", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Make every region now / Remake the regions too", + "loc": "src/hex-map/OverworldModals.ts:343", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.create", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Create / Regenerate", + "loc": "src/hex-map/OverworldModals.ts:351", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "New overworld", + "label": "Cancel", + "loc": "src/hex-map/OverworldModals.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.biomePool", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Biome pool", + "loc": "src/hex-map/OverworldModals.ts:218", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolSave", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Save", + "loc": "src/hex-map/OverworldModals.ts:219", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolSaveAs", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Save as…", + "loc": "src/hex-map/OverworldModals.ts:220", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.unclimated", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Biomes without a climate", + "loc": "src/hex-map/OverworldModals.ts:224", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolList", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Biomes in the pool (N)", + "loc": "src/hex-map/OverworldModals.ts:374", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolWeight", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "(weight per biome)", + "loc": "src/hex-map/OverworldModals.ts:385", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolRemove", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "✕ Remove ", + "loc": "src/hex-map/OverworldModals.ts:393", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "NewOverworld.poolAdd", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Add a biome…", + "loc": "src/hex-map/OverworldModals.ts:404", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PoolName.name", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Pool name", + "loc": "src/hex-map/OverworldModals.ts:529", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PoolName.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome pools", + "label": "Save / Cancel", + "loc": "src/hex-map/OverworldModals.ts:531", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeLibrary.edit", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Edit…", + "loc": "src/hex-map/BiomeLibraryModal.ts:87", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeLibrary.editGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Edit generator…", + "loc": "src/hex-map/BiomeLibraryModal.ts:93", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeLibrary.add", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Add biome…", + "loc": "src/hex-map/BiomeLibraryModal.ts:99", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeLibrary.biomeList", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "(biome list)", + "loc": "src/hex-map/BiomeLibraryModal.ts:81", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.madeBy", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Made by", + "loc": "src/hex-map/BiomeLibraryModal.ts:162", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.regionsStartBlank", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Regions start blank", + "loc": "src/hex-map/BiomeLibraryModal.ts:173", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.name", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Name", + "loc": "src/hex-map/BiomeLibraryModal.ts:179", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.colour", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Colour", + "loc": "src/hex-map/BiomeLibraryModal.ts:182", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.mixSlider", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": " weight (slider)", + "loc": "src/hex-map/BiomeLibraryModal.ts:195", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.mixNumber", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": " weight value", + "loc": "src/hex-map/BiomeLibraryModal.ts:196", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.blend", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Blend with neighbours", + "loc": "src/hex-map/BiomeLibraryModal.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.landShareOn", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Set a land share", + "loc": "src/hex-map/BiomeLibraryModal.ts:216", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.landShare", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Land share", + "loc": "src/hex-map/BiomeLibraryModal.ts:217", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.fewestIslands", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Fewest islands", + "loc": "src/hex-map/BiomeLibraryModal.ts:228", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.temperature", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Temperature", + "loc": "src/hex-map/BiomeLibraryModal.ts:244", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.moisture", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Moisture", + "loc": "src/hex-map/BiomeLibraryModal.ts:245", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.height", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Height", + "loc": "src/hex-map/BiomeLibraryModal.ts:246", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.chance", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Chance %", + "loc": "src/hex-map/BiomeLibraryModal.ts:250", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.coastOnly", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Coast only", + "loc": "src/hex-map/BiomeLibraryModal.ts:260", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.rare", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Rare", + "loc": "src/hex-map/BiomeLibraryModal.ts:261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.transitionNext", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Next to", + "loc": "src/hex-map/BiomeLibraryModal.ts:284", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.transitionBetween", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Put between", + "loc": "src/hex-map/BiomeLibraryModal.ts:286", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.transitionRemove", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Remove", + "loc": "src/hex-map/BiomeLibraryModal.ts:289", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.transitionAdd", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Add transition", + "loc": "src/hex-map/BiomeLibraryModal.ts:294", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.previewReroll", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Reroll", + "loc": "src/hex-map/BiomeLibraryModal.ts:306", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.restoreDefault", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Restore default", + "loc": "src/hex-map/BiomeLibraryModal.ts:311", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.editGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Edit generator…", + "loc": "src/hex-map/BiomeLibraryModal.ts:321", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.save", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Save", + "loc": "src/hex-map/BiomeLibraryModal.ts:327", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomeForm.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome library & biome form", + "label": "Cancel", + "loc": "src/hex-map/BiomeLibraryModal.ts:326", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.biomeGrid", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "(biome tiles)", + "loc": "src/hex-map/BiomeModals.ts:130", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.enterRegion", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Enter region", + "loc": "src/hex-map/BiomeModals.ts:146", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.reroll", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Reroll", + "loc": "src/hex-map/BiomeModals.ts:147", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.settings", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Settings…", + "loc": "src/hex-map/BiomeModals.ts:155", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePicker.biomes", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Biomes…", + "loc": "src/hex-map/BiomeModals.ts:159", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePalette.biomeTiles", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "(biome tiles)", + "loc": "src/hex-map/BiomePaletteModal.ts:401", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePalette.biomes", + "group": "Regions, overworlds & biomes", + "subgroup": "Biome picker & paint", + "label": "Biomes…", + "loc": "src/hex-map/BiomePaletteModal.ts:421", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.biome", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Biome", + "loc": "src/hex-map/BiomeModals.ts:212", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.editGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Edit generator…", + "loc": "src/hex-map/BiomeModals.ts:219", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.blend", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Blend with neighbours", + "loc": "src/hex-map/BiomeModals.ts:225", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.wigglyBorders", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Wiggly borders", + "loc": "src/hex-map/BiomeModals.ts:231", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.seed", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Seed", + "loc": "src/hex-map/BiomeModals.ts:238", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.reroll", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Reroll", + "loc": "src/hex-map/BiomeModals.ts:241", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.apply", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Apply / Make region", + "loc": "src/hex-map/BiomeModals.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionGen.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Cancel", + "loc": "src/hex-map/BiomeModals.ts:253", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.shape", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Shape (Rectangle / Hex flower)", + "loc": "src/hex-map/regionSettingsForm.ts:52", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.sizePresets", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Size", + "loc": "src/hex-map/regionSettingsForm.ts:75", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.customSize", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Hexes across (custom)", + "loc": "src/hex-map/regionSettingsForm.ts:89", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.palette", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Palette", + "loc": "src/hex-map/regionSettingsForm.ts:119", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.blend", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Blend", + "loc": "src/hex-map/regionSettingsForm.ts:130", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.save", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Save and continue", + "loc": "src/hex-map/newChildMap.ts:173", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RegionSettings.closeButtons", + "group": "Regions, overworlds & biomes", + "subgroup": "Region settings", + "label": "Cancel", + "loc": "src/hex-map/newChildMap.ts:172", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.name", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Region name", + "loc": "src/hex-map/EditRegionModal.ts:82", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.enterRegion", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Enter region", + "loc": "src/hex-map/EditRegionModal.ts:105", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.openMapNote", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Open map note", + "loc": "src/hex-map/EditRegionModal.ts:112", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.biomeGrid", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "(biome tiles)", + "loc": "src/hex-map/EditRegionModal.ts:147", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.reroll", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Reroll", + "loc": "src/hex-map/EditRegionModal.ts:176", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.settings", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Settings…", + "loc": "src/hex-map/EditRegionModal.ts:180", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.editGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Edit generator…", + "loc": "src/hex-map/EditRegionModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.makeGenerator", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Make generator…", + "loc": "src/hex-map/EditRegionModal.ts:140", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.neighbourLinks", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Next to: links", + "loc": "src/hex-map/EditRegionModal.ts:220", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.locationsList", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "List…", + "loc": "src/hex-map/EditRegionModal.ts:237", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.confirmPath", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Confirm into regions / Update regions", + "loc": "src/hex-map/EditRegionModal.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "EditRegion.notes", + "group": "Regions, overworlds & biomes", + "subgroup": "Edit region", + "label": "Region notes", + "loc": "src/hex-map/EditRegionModal.ts:266", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.regionTiles", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "(region note tiles)", + "loc": "src/hex-map/GeoRegionPickerModal.ts:181", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.remove", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Remove", + "loc": "src/hex-map/GeoRegionPickerModal.ts:184", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.editTile", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "✏ Edit region", + "loc": "src/hex-map/GeoRegionPickerModal.ts:210", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.newName", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "New region name…", + "loc": "src/hex-map/GeoRegionPickerModal.ts:257", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionPicker.create", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Create", + "loc": "src/hex-map/GeoRegionPickerModal.ts:261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.openNote", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Open note →", + "loc": "src/hex-map/GeoRegionPickerModal.ts:42", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.name", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Name", + "loc": "src/hex-map/GeoRegionPickerModal.ts:68", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.color", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Color", + "loc": "src/hex-map/GeoRegionPickerModal.ts:77", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.save", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Save", + "loc": "src/hex-map/GeoRegionPickerModal.ts:96", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GeoRegionEditor.clearColor", + "group": "Regions, overworlds & biomes", + "subgroup": "Region areas", + "label": "Clear color", + "loc": "src/hex-map/GeoRegionPickerModal.ts:116", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Regions, overworlds & biomes", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.table", + "group": "Space: world types", + "subgroup": "General", + "label": "Table", + "loc": "src/space/WorldTypesModal.ts:232", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.newTable", + "group": "Space: world types", + "subgroup": "General", + "label": "New table…", + "loc": "src/space/WorldTypesModal.ts:241", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.newTableName", + "group": "Space: world types", + "subgroup": "General", + "label": "Table name", + "loc": "src/space/WorldTypesModal.ts:330", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.newTableCreate", + "group": "Space: world types", + "subgroup": "General", + "label": "Create", + "loc": "src/space/WorldTypesModal.ts:331", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.openNote", + "group": "Space: world types", + "subgroup": "General", + "label": "Open note", + "loc": "src/space/WorldTypesModal.ts:244", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.restoreDefault", + "group": "Space: world types", + "subgroup": "General", + "label": "Restore default", + "loc": "src/space/WorldTypesModal.ts:250", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.tabWorlds", + "group": "Space: world types", + "subgroup": "General", + "label": "Worlds (N)", + "loc": "src/space/WorldTypesModal.ts:279", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.tabStars", + "group": "Space: world types", + "subgroup": "General", + "label": "Stars (N)", + "loc": "src/space/WorldTypesModal.ts:279", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.tabFeatures", + "group": "Space: world types", + "subgroup": "General", + "label": "Sector features (N)", + "loc": "src/space/WorldTypesModal.ts:279", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.rowMoveUp", + "group": "Space: world types", + "subgroup": "General", + "label": "↑ Move up", + "loc": "src/space/WorldTypesModal.ts:414", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.rowMoveDown", + "group": "Space: world types", + "subgroup": "General", + "label": "↓ Move down", + "loc": "src/space/WorldTypesModal.ts:415", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.rowRemove", + "group": "Space: world types", + "subgroup": "General", + "label": "✕ Remove row", + "loc": "src/space/WorldTypesModal.ts:416", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.addRow", + "group": "Space: world types", + "subgroup": "General", + "label": "Add row", + "loc": "src/space/WorldTypesModal.ts:298", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.save", + "group": "Space: world types", + "subgroup": "General", + "label": "Save", + "loc": "src/space/WorldTypesModal.ts:309", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldName", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "World", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldWeight", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Weight", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldMap", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Map", + "loc": "src/space/WorldTypesModal.ts:425", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldOrbit", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Orbit", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldStars", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Stars", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldTemperature", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Temperature", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldSize", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Size", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldGenerator", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Generator", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldOptions", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Options", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldPalette", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Palette", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldBase", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Base", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.worldNotes", + "group": "Space: world types", + "subgroup": "Worlds tab", + "label": "Notes", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.starName", + "group": "Space: world types", + "subgroup": "Stars tab", + "label": "Star", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.starWeight", + "group": "Space: world types", + "subgroup": "Stars tab", + "label": "Weight", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.starNotes", + "group": "Space: world types", + "subgroup": "Stars tab", + "label": "Notes", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.featureName", + "group": "Space: world types", + "subgroup": "Sector features tab", + "label": "Feature", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.featureChance", + "group": "Space: world types", + "subgroup": "Sector features tab", + "label": "Chance", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.featureNotes", + "group": "Space: world types", + "subgroup": "Sector features tab", + "label": "Notes", + "loc": "src/space/WorldTypesModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewMap", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Map", + "loc": "src/space/WorldTypesModal.ts:464", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewOrbit", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Orbit", + "loc": "src/space/WorldTypesModal.ts:465", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewStar", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Star", + "loc": "src/space/WorldTypesModal.ts:466", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewTemperature", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Temperature", + "loc": "src/space/WorldTypesModal.ts:467", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorldTypes.previewRolls", + "group": "Space: world types", + "subgroup": "Preview", + "label": "Rolls", + "loc": "src/space/WorldTypesModal.ts:473", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Space: world types", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.generatorsTab", + "group": "Generator page", + "subgroup": "Library", + "label": "Generators", + "loc": "src/worldgen/GeneratorLibrary.ts:70", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.mapsTab", + "group": "Generator page", + "subgroup": "Library", + "label": "Maps", + "loc": "src/worldgen/GeneratorLibrary.ts:71", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.filter", + "group": "Generator page", + "subgroup": "Library", + "label": "Filter…", + "loc": "src/worldgen/GeneratorLibrary.ts:50", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.generatorRow", + "group": "Generator page", + "subgroup": "Library", + "label": "(generator row: click to load)", + "loc": "src/worldgen/GeneratorLibrary.ts:113", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.generatorRowTick", + "group": "Generator page", + "subgroup": "Library", + "label": "(row checkbox)", + "loc": "src/worldgen/GeneratorLibrary.ts:263", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.selectAll", + "group": "Generator page", + "subgroup": "Library", + "label": "Select all shown", + "loc": "src/worldgen/GeneratorLibrary.ts:246", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.openFile", + "group": "Generator page", + "subgroup": "Library", + "label": "Open file", + "loc": "src/worldgen/GeneratorLibrary.ts:125", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.relearn", + "group": "Generator page", + "subgroup": "Library", + "label": "Re-learn", + "loc": "src/worldgen/GeneratorLibrary.ts:126", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.blend", + "group": "Generator page", + "subgroup": "Library", + "label": "Blend", + "loc": "src/worldgen/GeneratorLibrary.ts:127", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.delete", + "group": "Generator page", + "subgroup": "Library", + "label": "Delete", + "loc": "src/worldgen/GeneratorLibrary.ts:131", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.mapRow", + "group": "Generator page", + "subgroup": "Library", + "label": "(map row: tick to learn from)", + "loc": "src/worldgen/GeneratorLibrary.ts:192", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.learnName", + "group": "Generator page", + "subgroup": "Library", + "label": "Generator name", + "loc": "src/worldgen/GeneratorLibrary.ts:206", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenLib.learn", + "group": "Generator page", + "subgroup": "Library", + "label": "Learn generator", + "loc": "src/worldgen/GeneratorLibrary.ts:210", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.saveDraft", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Save generator", + "loc": "src/worldgen/GeneratorPanel.ts:336", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.discardDraft", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Discard", + "loc": "src/worldgen/GeneratorPanel.ts:349", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.name", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Name", + "loc": "src/worldgen/GeneratorPanel.ts:358", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.rename", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Rename", + "loc": "src/worldgen/GeneratorPanel.ts:359", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.generatorPalette", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Palette", + "loc": "src/worldgen/GeneratorPanel.ts:395", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.relearn", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Re-learn / Re-blend", + "loc": "src/worldgen/GeneratorPanel.ts:417", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.openFile", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Open file", + "loc": "src/worldgen/GeneratorPanel.ts:436", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.sourceInfluence", + "group": "Generator page", + "subgroup": "Recipe", + "label": " influence", + "loc": "src/worldgen/GeneratorPanel.ts:457", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.sourceCompass", + "group": "Generator page", + "subgroup": "Recipe", + "label": "(direction arrows ↖↑↗←•→↙↓↘)", + "loc": "src/worldgen/GeneratorPanel.ts:461", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.backToMapSize", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Back to map size", + "loc": "src/worldgen/GeneratorPanel.ts:522", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.resetSettings", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Reset settings to defaults", + "loc": "src/worldgen/GeneratorPanel.ts:536", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.sizePresets", + "group": "Generator page", + "subgroup": "Recipe", + "label": "(size presets)", + "loc": "src/worldgen/GeneratorPanel.ts:593", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.connectTo", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Connect to", + "loc": "src/worldgen/GeneratorPanel.ts:619", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.connectSide", + "group": "Generator page", + "subgroup": "Recipe", + "label": "(side: east/west/north/south of it)", + "loc": "src/worldgen/GeneratorPanel.ts:622", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.regionsHint", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Turn on regions and overworlds / ✕", + "loc": "src/worldgen/GeneratorPanel.ts:631", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.leanToNeighbours", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Lean toward neighbours", + "loc": "src/worldgen/GeneratorPanel.ts:665", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.guaranteedFeatures", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Guaranteed features", + "loc": "src/worldgen/GeneratorPanel.ts:1046", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.connectedLand", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Connected land", + "loc": "src/worldgen/GeneratorPanel.ts:1048", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.impassableSearch", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Impassable terrain", + "loc": "src/worldgen/GeneratorPanel.ts:1502", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.impassableRemove", + "group": "Generator page", + "subgroup": "Recipe", + "label": "× (remove chip)", + "loc": "src/worldgen/GeneratorPanel.ts:1515", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.impassableSuggestAdd", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Add / Add all", + "loc": "src/worldgen/GeneratorPanel.ts:1064", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.mix", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Mix", + "loc": "src/worldgen/GeneratorPanel.ts:1118", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.minPatches", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Min", + "loc": "src/worldgen/GeneratorPanel.ts:1132", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.maxPatches", + "group": "Generator page", + "subgroup": "Recipe", + "label": "Max", + "loc": "src/worldgen/GeneratorPanel.ts:1132", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.sectionFold", + "group": "Generator page", + "subgroup": "Recipe", + "label": "(section heading fold)", + "loc": "src/worldgen/GeneratorPanel.ts:1415", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.seed", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Seed", + "loc": "src/worldgen/GeneratorPanel.ts:556", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.seedLock", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "(lock seed)", + "loc": "src/worldgen/GeneratorPanel.ts:559", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.reroll", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Re-roll / Regenerate", + "loc": "src/worldgen/GeneratorPanel.ts:560", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.previewSize", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Size (cols × rows)", + "loc": "src/worldgen/GeneratorPanel.ts:562", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.previewPalette", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Palette", + "loc": "src/worldgen/GeneratorPanel.ts:567", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.newMapName", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Name for the new map", + "loc": "src/worldgen/GeneratorPanel.ts:690", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.createMap", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Create map", + "loc": "src/worldgen/GeneratorPanel.ts:691", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.saveName", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Save name (optional)", + "loc": "src/worldgen/GeneratorPanel.ts:697", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.saveSnapshot", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Save", + "loc": "src/worldgen/GeneratorPanel.ts:698", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.loadSelect", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "(saved snapshot list)", + "loc": "src/worldgen/GeneratorPanel.ts:700", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.loadSnapshot", + "group": "Generator page", + "subgroup": "Preview & saves", + "label": "Load", + "loc": "src/worldgen/GeneratorPanel.ts:701", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.featureSize", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Feature size", + "loc": "src/worldgen/GeneratorPanel.ts:1012", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.clumping", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Clumping", + "loc": "src/worldgen/GeneratorPanel.ts:1013", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "Engine tuning should have its own separate overkill setting. Basically all these ones marked \"overkill\" for generator settings should go into an \"advanced\" dropdown that defaults closed rather than them being gated under the global overkill setting. That way people can muck about with them when they wanna go a bit further on one gen or another, instead of having to flip and stick with a top-level setting. " + }, + { + "id": "GenPage.lineWidth", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Line width", + "loc": "src/worldgen/GeneratorPanel.ts:1016", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.edgeSmoothing", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Edge smoothing", + "loc": "src/worldgen/GeneratorPanel.ts:1021", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.removeSmallPatches", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Remove small patches", + "loc": "src/worldgen/GeneratorPanel.ts:1023", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.keepRare", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Keep rare terrain", + "loc": "src/worldgen/GeneratorPanel.ts:1025", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.symmetry", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Symmetry", + "loc": "src/worldgen/GeneratorPanel.ts:1027", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.edgeStyle", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Edge style", + "loc": "src/worldgen/GeneratorPanel.ts:1029", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.edgeStrength", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Edge strength", + "loc": "src/worldgen/GeneratorPanel.ts:1032", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.directionalBias", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Directional bias", + "loc": "src/worldgen/GeneratorPanel.ts:1036", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.scatter", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Scatter", + "loc": "src/worldgen/GeneratorPanel.ts:1037", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.spacing", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Spacing", + "loc": "src/worldgen/GeneratorPanel.ts:1039", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.randomness", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Randomness", + "loc": "src/worldgen/GeneratorPanel.ts:1041", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.near", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Near", + "loc": "src/worldgen/GeneratorPanel.ts:1146", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.mixStrength", + "group": "Generator page", + "subgroup": "Engine tuning", + "label": "Mix strength", + "loc": "src/worldgen/GeneratorPanel.ts:1176", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page/Engine tuning", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.drawPaths", + "group": "Generator page", + "subgroup": "Paths", + "label": "Draw paths", + "loc": "src/worldgen/GeneratorPanel.ts:1204", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeFold", + "group": "Generator page", + "subgroup": "Paths", + "label": "(show routes chevron)", + "loc": "src/worldgen/GeneratorPanel.ts:1225", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "ditto for the above, make sure these go into an \"advanced\" section, Maybe the advanced section can have collapsible sub-sections as well so its clean to view. " + }, + { + "id": "GenPage.pathTypeOn", + "group": "Generator page", + "subgroup": "Paths", + "label": "Draw paths", + "loc": "src/worldgen/GeneratorPanel.ts:1227", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeAmount", + "group": "Generator page", + "subgroup": "Paths", + "label": "Amount", + "loc": "src/worldgen/GeneratorPanel.ts:1261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeWiggle", + "group": "Generator page", + "subgroup": "Paths", + "label": "Wiggle", + "loc": "src/worldgen/GeneratorPanel.ts:1277", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeLength", + "group": "Generator page", + "subgroup": "Paths", + "label": "Length", + "loc": "src/worldgen/GeneratorPanel.ts:1278", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeFollow", + "group": "Generator page", + "subgroup": "Paths", + "label": "Follow terrain", + "loc": "src/worldgen/GeneratorPanel.ts:1279", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.pathTypeAvoid", + "group": "Generator page", + "subgroup": "Paths", + "label": "Avoid impassable terrain and the map border", + "loc": "src/worldgen/GeneratorPanel.ts:1290", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeOn", + "group": "Generator page", + "subgroup": "Paths", + "label": "(route checkbox)", + "loc": "src/worldgen/GeneratorPanel.ts:1315", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeCount", + "group": "Generator page", + "subgroup": "Paths", + "label": "Count", + "loc": "src/worldgen/GeneratorPanel.ts:1330", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeAs", + "group": "Generator page", + "subgroup": "Paths", + "label": "As", + "loc": "src/worldgen/GeneratorPanel.ts:1347", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeWiggle", + "group": "Generator page", + "subgroup": "Paths", + "label": "Wiggle (route)", + "loc": "src/worldgen/GeneratorPanel.ts:1373", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeLength", + "group": "Generator page", + "subgroup": "Paths", + "label": "Length (route)", + "loc": "src/worldgen/GeneratorPanel.ts:1374", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenPage.routeFollow", + "group": "Generator page", + "subgroup": "Paths", + "label": "Follow terrain (route)", + "loc": "src/worldgen/GeneratorPanel.ts:1375", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.biome", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Biome", + "loc": "src/worldgen/BiomePanel.ts:150", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.openNote", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Open note", + "loc": "src/worldgen/BiomePanel.ts:160", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.restoreDefault", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Restore default", + "loc": "src/worldgen/BiomePanel.ts:165", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.back", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Back to generators", + "loc": "src/worldgen/BiomePanel.ts:173", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.weightSlider", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Weight", + "loc": "src/worldgen/BiomePanel.ts:191", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.weightNumber", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "(weight value)", + "loc": "src/worldgen/BiomePanel.ts:192", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.minPatches", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Min patches", + "loc": "src/worldgen/BiomePanel.ts:193", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.blendWidth", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Blend width", + "loc": "src/worldgen/BiomePanel.ts:231", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.landShareOn", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Land share (on/off)", + "loc": "src/worldgen/BiomePanel.ts:242", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.landShare", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Land share", + "loc": "src/worldgen/BiomePanel.ts:243", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.minIslands", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Min islands", + "loc": "src/worldgen/BiomePanel.ts:261", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.shore", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Shore", + "loc": "src/worldgen/BiomePanel.ts:270", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.transitionNext", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Next to", + "loc": "src/worldgen/BiomePanel.ts:299", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.transitionBetween", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "put", + "loc": "src/worldgen/BiomePanel.ts:301", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.transitionRemove", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Remove", + "loc": "src/worldgen/BiomePanel.ts:309", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.transitionAdd", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Add transition", + "loc": "src/worldgen/BiomePanel.ts:315", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.seed", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Seed", + "loc": "src/worldgen/BiomePanel.ts:330", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.reroll", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Re-roll", + "loc": "src/worldgen/BiomePanel.ts:332", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.size", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Size", + "loc": "src/worldgen/BiomePanel.ts:338", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.aroundIt", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Around it", + "loc": "src/worldgen/BiomePanel.ts:346", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "BiomePage.palette", + "group": "Generator page", + "subgroup": "Biome (blend field)", + "label": "Palette", + "loc": "src/worldgen/BiomePanel.ts:353", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.newRadio", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "New generator", + "loc": "src/hex-map/MakeGeneratorModal.ts:68", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.name", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Name", + "loc": "src/hex-map/MakeGeneratorModal.ts:70", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.overwriteRadio", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Overwrite existing", + "loc": "src/hex-map/MakeGeneratorModal.ts:80", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.overwriteList", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Generator to overwrite", + "loc": "src/hex-map/MakeGeneratorModal.ts:96", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.make", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Make generator / Overwrite", + "loc": "src/hex-map/MakeGeneratorModal.ts:90", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MakeGen.closeButtons", + "group": "Generator page", + "subgroup": "Make generator from a map", + "label": "Cancel", + "loc": "src/hex-map/MakeGeneratorModal.ts:92", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Generator page", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.paletteSelect", + "group": "Palette editor", + "subgroup": "Toolbar", + "label": "Palette", + "loc": "src/palettes/PaletteEditorView.ts:99", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addPalette", + "group": "Palette editor", + "subgroup": "Toolbar", + "label": "Add palette…", + "loc": "src/palettes/PaletteEditorView.ts:103", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.openNote", + "group": "Palette editor", + "subgroup": "Toolbar", + "label": "Open note", + "loc": "src/palettes/PaletteEditorView.ts:112", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.filter", + "group": "Palette editor", + "subgroup": "Toolbar", + "label": "Filter terrains…", + "loc": "src/palettes/PaletteEditorView.ts:118", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.guessTypes", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Guess types from names", + "loc": "src/palettes/PaletteEditorView.ts:140", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.rowDrag", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Drag to reorder (⠿)", + "loc": "src/palettes/PaletteEditorView.ts:260", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.color", + "group": "Palette editor", + "subgroup": "Terrains", + "label": " color", + "loc": "src/palettes/PaletteEditorView.ts:277", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.name", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Terrain name", + "loc": "src/palettes/PaletteEditorView.ts:283", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.type", + "group": "Palette editor", + "subgroup": "Terrains", + "label": " type", + "loc": "src/palettes/PaletteEditorView.ts:301", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.category", + "group": "Palette editor", + "subgroup": "Terrains", + "label": " category", + "loc": "src/palettes/PaletteEditorView.ts:312", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.icon", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Choose icon", + "loc": "src/palettes/PaletteEditorView.ts:326", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.tintOn", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Tint icon", + "loc": "src/palettes/PaletteEditorView.ts:345", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.tintColor", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Icon tint", + "loc": "src/palettes/PaletteEditorView.ts:347", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.impassable", + "group": "Palette editor", + "subgroup": "Terrains", + "label": " impassable", + "loc": "src/palettes/PaletteEditorView.ts:361", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.delete", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Delete terrain (×)", + "loc": "src/palettes/PaletteEditorView.ts:370", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addTerrain", + "group": "Palette editor", + "subgroup": "Terrains", + "label": "Add terrain", + "loc": "src/palettes/PaletteEditorView.ts:178", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapPalette", + "group": "Palette editor", + "subgroup": "Palette settings & path types", + "label": "Submap palette", + "loc": "src/palettes/PaletteEditorView.ts:195", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.pathTypeRow", + "group": "Palette editor", + "subgroup": "Palette settings & path types", + "label": "(path type row)", + "loc": "src/palettes/PaletteEditorView.ts:228", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addPathType", + "group": "Palette editor", + "subgroup": "Palette settings & path types", + "label": "Add path type", + "loc": "src/palettes/PaletteEditorView.ts:236", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultPalette", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Palette", + "loc": "src/palettes/PaletteEditorView.ts:410", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultCols", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Columns", + "loc": "src/palettes/PaletteEditorView.ts:417", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultRows", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Rows", + "loc": "src/palettes/PaletteEditorView.ts:419", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultGenerator", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Generator", + "loc": "src/palettes/PaletteEditorView.ts:429", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.generatorOptions", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Generator options", + "loc": "src/palettes/PaletteEditorView.ts:444", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultBaseTerrain", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Base terrain", + "loc": "src/palettes/PaletteEditorView.ts:455", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.submapDefaultDelete", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Remove default (×)", + "loc": "src/palettes/PaletteEditorView.ts:459", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addDefaultTerrain", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Terrain to add a default for", + "loc": "src/palettes/PaletteEditorView.ts:473", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "PaletteEditor.addDefault", + "group": "Palette editor", + "subgroup": "Submap defaults", + "label": "Add default", + "loc": "src/palettes/PaletteEditorView.ts:475", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Palette editor", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.refreshList", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Refresh list (↺)", + "loc": "src/random-tables/RandomTableView.ts:149", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "we should confirm that it does it at a good cadence for all of these \"sink refresh\" bits " + }, + { + "id": "RTView.tablesTab", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Tables", + "loc": "src/random-tables/RandomTableView.ts:156", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowsTab", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Workflows", + "loc": "src/random-tables/RandomTableView.ts:160", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.tabMiddleClick", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(middle-click a tab)", + "loc": "src/random-tables/RandomTableView.ts:172", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowsHintTurnOn", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Turn on workflows", + "loc": "src/random-tables/RandomTableView.ts:89", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowsHintHide", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Hide this hint (✕)", + "loc": "src/advancedHints.ts:36", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.filterSearch", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Filter tables…", + "loc": "src/random-tables/RandomTableView.ts:198", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.tablesTree", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(table folder tree)", + "loc": "src/random-tables/RandomTableView.ts:607", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.folderToggle", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(folder ▶/▼)", + "loc": "src/random-tables/FolderTree.ts:161", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMiddleClick", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(middle-click a table)", + "loc": "src/random-tables/RandomTableView.ts:1121", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.dragToMove", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(drag table onto folder)", + "loc": "src/random-tables/RandomTableView.ts:1137", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.folderMenuRollPicker", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Exclude from roll picker / Include in roll picker", + "loc": "src/random-tables/RandomTableView.ts:1153", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.folderMenuEncounters", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Exclude from encounters table / Include in encounters table", + "loc": "src/random-tables/RandomTableView.ts:1180", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMenuOpenNewTab", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Open in new tab", + "loc": "src/random-tables/RandomTableView.ts:1213", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMenuRollPicker", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Exclude from roll picker / Include in roll picker", + "loc": "src/random-tables/RandomTableView.ts:1227", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMenuEncounters", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Exclude from encounters table / Include in encounters table", + "loc": "src/random-tables/RandomTableView.ts:1247", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fileMenuDelete", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Delete table", + "loc": "src/random-tables/RandomTableView.ts:1270", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.newTableName", + "group": "Random tables", + "subgroup": "Tables list", + "label": "New table name…", + "loc": "src/random-tables/RandomTableView.ts:283", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.newTableButton", + "group": "Random tables", + "subgroup": "Tables list", + "label": "+ new", + "loc": "src/random-tables/RandomTableView.ts:305", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.generateFromFolder", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Generate from folder or file (optional)…", + "loc": "src/random-tables/RandomTableView.ts:367", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.newWorkflow", + "group": "Random tables", + "subgroup": "Tables list", + "label": "+ new workflow", + "loc": "src/random-tables/RandomTableView.ts:271", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowsTree", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(workflow folder tree)", + "loc": "src/random-tables/RandomTableView.ts:735", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowMenuOpenNewTab", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Open in new tab", + "loc": "src/random-tables/RandomTableView.ts:781", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowMenuDelete", + "group": "Random tables", + "subgroup": "Tables list", + "label": "Delete workflow", + "loc": "src/random-tables/RandomTableView.ts:795", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowMiddleClick", + "group": "Random tables", + "subgroup": "Tables list", + "label": "(middle-click a workflow)", + "loc": "src/random-tables/RandomTableView.ts:769", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables/Tables list", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.edit", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Edit", + "loc": "src/random-tables/RandomTableView.ts:1478", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.openNote", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Open note", + "loc": "src/random-tables/RandomTableView.ts:1494", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.exportPdf", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Export PDF", + "loc": "src/random-tables/RandomTableView.ts:1503", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.exportMarkdown", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Export Markdown", + "loc": "src/random-tables/RandomTableView.ts:1513", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.refreshLinked", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Refresh", + "loc": "src/random-tables/RandomTableView.ts:1523", + "suggestion": "overkill", + "choice": "overkill", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.dieSelect", + "group": "Random tables", + "subgroup": "Table detail", + "label": "(die: — no die —, d4…d1000)", + "loc": "src/random-tables/RandomTableView.ts:1537", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixKeepRanges", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Keep ranges → set weights", + "loc": "src/random-tables/RandomTableView.ts:1428", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixKeepWeights", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Keep weights → redo ranges", + "loc": "src/random-tables/RandomTableView.ts:1431", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixBiggerDie", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Use a d", + "loc": "src/random-tables/RandomTableView.ts:1437", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixAddRanges", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Add roll ranges", + "loc": "src/random-tables/RandomTableView.ts:1445", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.fixRollerLink", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Replace old roller link", + "loc": "src/random-tables/RandomTableView.ts:1450", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.descriptionCollapse", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Collapse description (▼)", + "loc": "src/random-tables/RandomTableView.ts:1569", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.tableCollapse", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Collapse table (▼)", + "loc": "src/random-tables/RandomTableView.ts:1605", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.entryLink", + "group": "Random tables", + "subgroup": "Table detail", + "label": "(result link)", + "loc": "src/random-tables/RandomTableView.ts:1648", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.entryCopy", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Copy entry (⎘)", + "loc": "src/random-tables/RandomTableView.ts:1676", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.addEntriesEmpty", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Add entries", + "loc": "src/random-tables/RandomTableView.ts:1622", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.copyRollLink", + "group": "Random tables", + "subgroup": "Table detail", + "label": "🎲 Copy link", + "loc": "src/random-tables/RandomTableView.ts:1694", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.roll", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Roll", + "loc": "src/random-tables/RandomTableView.ts:1708", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.resultText", + "group": "Random tables", + "subgroup": "Table detail", + "label": "(roll result)", + "loc": "src/random-tables/RandomTableView.ts:1721", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.resultCopy", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Copy", + "loc": "src/random-tables/RandomTableView.ts:1727", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.resultOpenNote", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Open note", + "loc": "src/random-tables/RandomTableView.ts:1737", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.historyCopy", + "group": "Random tables", + "subgroup": "Table detail", + "label": "Copy (⎘) in Recent rolls", + "loc": "src/random-tables/RandomTableView.ts:1876", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.usedByWorkflowLink", + "group": "Random tables", + "subgroup": "Table detail", + "label": "(Workflows using this table)", + "loc": "src/random-tables/RandomTableView.ts:1766", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.newWorkflowWithTable", + "group": "Random tables", + "subgroup": "Table detail", + "label": "+ new workflow with this table", + "loc": "src/random-tables/RandomTableView.ts:1779", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.tableSelect", + "group": "Random tables", + "subgroup": "Rolling", + "label": "— choose a table —", + "loc": "src/random-tables/RandomTableModal.ts:116", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.openInRoller", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Open in roller view", + "loc": "src/random-tables/RandomTableModal.ts:125", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.edit", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Edit", + "loc": "src/random-tables/RandomTableModal.ts:184", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.roll", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Roll", + "loc": "src/random-tables/RandomTableModal.ts:135", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.resultText", + "group": "Random tables", + "subgroup": "Rolling", + "label": "(roll result)", + "loc": "src/random-tables/RandomTableModal.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.useResult", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Use result", + "loc": "src/random-tables/RandomTableModal.ts:262", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.addSectionSelect", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Section to add the result to", + "loc": "src/random-tables/RandomTableModal.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.addToHex", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Add to this hex", + "loc": "src/random-tables/RandomTableModal.ts:41", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.copy", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Copy", + "loc": "src/random-tables/RandomTableModal.ts:280", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.entryCopy", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Copy entry (⎘)", + "loc": "src/random-tables/RandomTableModal.ts:350", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.addEntries", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Add entries", + "loc": "src/random-tables/RandomTableModal.ts:309", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollModal.closeButtons", + "group": "Random tables", + "subgroup": "Rolling", + "label": "(modal ✕)", + "loc": "src/random-tables/RandomTableModal.ts:84", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.roll", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Roll", + "loc": "src/random-tables/RollerBlock.ts:48", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.openTable", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Open table", + "loc": "src/random-tables/RollerBlock.ts:58", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.resultText", + "group": "Random tables", + "subgroup": "Rolling", + "label": "(roll result)", + "loc": "src/random-tables/RollerBlock.ts:66", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.copy", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Copy", + "loc": "src/random-tables/RollerBlock.ts:73", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RollerBlock.historyCopy", + "group": "Random tables", + "subgroup": "Rolling", + "label": "Copy (⎘)", + "loc": "src/random-tables/RollerBlock.ts:92", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.importPicker", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Search for a file to link...", + "loc": "src/random-tables/RandomTableEditorModal.ts:210", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.name", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Name", + "loc": "src/random-tables/RandomTableEditorModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.sortWeight", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Wt ↑", + "loc": "src/random-tables/RandomTableEditorModal.ts:149", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.sortAlpha", + "group": "Random tables", + "subgroup": "Table editor", + "label": "A→z", + "loc": "src/random-tables/RandomTableEditorModal.ts:166", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.minusOneAll", + "group": "Random tables", + "subgroup": "Table editor", + "label": "-1", + "loc": "src/random-tables/RandomTableEditorModal.ts:185", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.plusOneAll", + "group": "Random tables", + "subgroup": "Table editor", + "label": "+1", + "loc": "src/random-tables/RandomTableEditorModal.ts:194", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.import", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Import…", + "loc": "src/random-tables/RandomTableEditorModal.ts:204", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.rowDrag", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Drag to reorder (⠿)", + "loc": "src/random-tables/RandomTableEditorModal.ts:274", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.rowResult", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Result…", + "loc": "src/random-tables/RandomTableEditorModal.ts:283", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.rowWeight", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Weight (0 = never rolled)", + "loc": "src/random-tables/RandomTableEditorModal.ts:305", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.rowDelete", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Remove row (×)", + "loc": "src/random-tables/RandomTableEditorModal.ts:317", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.newResult", + "group": "Random tables", + "subgroup": "Table editor", + "label": "New result…", + "loc": "src/random-tables/RandomTableEditorModal.ts:374", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.newWeight", + "group": "Random tables", + "subgroup": "Table editor", + "label": "(new row weight)", + "loc": "src/random-tables/RandomTableEditorModal.ts:380", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.add", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Add", + "loc": "src/random-tables/RandomTableEditorModal.ts:387", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.description", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Description", + "loc": "src/random-tables/RandomTableEditorModal.ts:405", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.linkedFolder", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Linked folder", + "loc": "src/random-tables/RandomTableEditorModal.ts:467", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.excludeRollPicker", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Exclude from roll picker", + "loc": "src/random-tables/RandomTableEditorModal.ts:486", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.excludeEncounters", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Exclude from encounters table", + "loc": "src/random-tables/RandomTableEditorModal.ts:494", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableEditor.closeButtons", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Close", + "loc": "src/random-tables/RandomTableEditorModal.ts:640", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableRanges.addRanges", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Add ranges (a backup is made first)", + "loc": "src/random-tables/tableMaintenance.ts:260", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableRanges.dontAskAgain", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Don't ask again", + "loc": "src/random-tables/tableMaintenance.ts:268", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "TableRanges.closeButtons", + "group": "Random tables", + "subgroup": "Table editor", + "label": "Not now", + "loc": "src/random-tables/tableMaintenance.ts:266", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.openTablesView", + "group": "Random tables", + "subgroup": "Table picker", + "label": "🎲 Open tables view", + "loc": "src/hex-map/FolderTreePickerModal.ts:85", + "suggestion": "drop", + "choice": "drop", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.filter", + "group": "Random tables", + "subgroup": "Table picker", + "label": "Filter tables…", + "loc": "src/hex-map/FolderTreePickerModal.ts:93", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.folderToggles", + "group": "Random tables", + "subgroup": "Table picker", + "label": "(folder rows)", + "loc": "src/hex-map/FolderTreePickerModal.ts:174", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.newTableName", + "group": "Random tables", + "subgroup": "Table picker", + "label": "table-name", + "loc": "src/hex-map/FolderTreePickerModal.ts:190", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.createButton", + "group": "Random tables", + "subgroup": "Table picker", + "label": "+ create", + "loc": "src/hex-map/FolderTreePickerModal.ts:194", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "FolderTree.closeButtons", + "group": "Random tables", + "subgroup": "Table picker", + "label": "×", + "loc": "src/hex-map/FolderTreePickerModal.ts:77", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Random tables", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowEdit", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "Edit", + "loc": "src/random-tables/RandomTableView.ts:924", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowRoll", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "Roll workflow", + "loc": "src/random-tables/RandomTableView.ts:955", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowCopyLink", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "🔗 Copy link", + "loc": "src/random-tables/RandomTableView.ts:963", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowStepLink", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "(step table link)", + "loc": "src/random-tables/RandomTableView.ts:1015", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "RTView.workflowTemplateLink", + "group": "Workflows", + "subgroup": "Workflow detail", + "label": "(template link)", + "loc": "src/random-tables/RandomTableView.ts:1053", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.name", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Name", + "loc": "src/random-tables/WorkflowEditorModal.ts:88", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepDrag", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Drag to reorder (⠿)", + "loc": "src/random-tables/WorkflowEditorModal.ts:343", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepFormula", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "E.g. 2D6+6", + "loc": "src/random-tables/WorkflowEditorModal.ts:360", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepTable", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "— select table —", + "loc": "src/random-tables/WorkflowEditorModal.ts:379", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepRolls", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Number of rolls", + "loc": "src/random-tables/WorkflowEditorModal.ts:420", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepLabel", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Label…", + "loc": "src/random-tables/WorkflowEditorModal.ts:434", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.stepDelete", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Remove step (×)", + "loc": "src/random-tables/WorkflowEditorModal.ts:454", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addType", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Table / Dice", + "loc": "src/random-tables/WorkflowEditorModal.ts:505", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addTable", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "— select table —", + "loc": "src/random-tables/WorkflowEditorModal.ts:543", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addFormula", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "E.g. 2D6+6", + "loc": "src/random-tables/WorkflowEditorModal.ts:532", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addRolls", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Number of rolls", + "loc": "src/random-tables/WorkflowEditorModal.ts:572", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addLabel", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Label (auto)…", + "loc": "src/random-tables/WorkflowEditorModal.ts:578", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.addStep", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Add step", + "loc": "src/random-tables/WorkflowEditorModal.ts:585", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.template", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Template", + "loc": "src/random-tables/WorkflowEditorModal.ts:145", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.description", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Description", + "loc": "src/random-tables/WorkflowEditorModal.ts:164", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.resultsFolder", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Results folder", + "loc": "src/random-tables/WorkflowEditorModal.ts:200", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.export", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Export…", + "loc": "src/random-tables/WorkflowEditorModal.ts:690", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowEditor.closeButtons", + "group": "Workflows", + "subgroup": "Workflow editor", + "label": "Close", + "loc": "src/random-tables/WorkflowEditorModal.ts:696", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.rollAll", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Roll all", + "loc": "src/random-tables/WorkflowWizardModal.ts:148", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.rerollAll", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Reroll all", + "loc": "src/random-tables/WorkflowWizardModal.ts:155", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.slotValue", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "—", + "loc": "src/random-tables/WorkflowWizardModal.ts:320", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.slotPick", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "— pick —", + "loc": "src/random-tables/WorkflowWizardModal.ts:337", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.slotRoll", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Roll / Reroll", + "loc": "src/random-tables/WorkflowWizardModal.ts:359", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.slotSum", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "sum", + "loc": "src/random-tables/WorkflowWizardModal.ts:381", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.sumAll", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "sum all", + "loc": "src/random-tables/WorkflowWizardModal.ts:301", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.resultText", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Result", + "loc": "src/random-tables/WorkflowWizardModal.ts:179", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.copyResult", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Copy result", + "loc": "src/random-tables/WorkflowWizardModal.ts:186", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.addSectionSelect", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Section to add the result to", + "loc": "src/random-tables/RandomTableModal.ts:33", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.addToHex", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Add to this hex", + "loc": "src/random-tables/WorkflowWizardModal.ts:197", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.noteName", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Note name", + "loc": "src/random-tables/WorkflowWizardModal.ts:216", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.resultsFolder", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Results folder", + "loc": "src/random-tables/WorkflowWizardModal.ts:244", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.saveAsNote", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "Save as note", + "loc": "src/random-tables/WorkflowWizardModal.ts:254", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowWizard.closeButtons", + "group": "Workflows", + "subgroup": "Workflow wizard", + "label": "(modal ✕) / Replace confirm", + "loc": "src/random-tables/WorkflowWizardModal.ts:524", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Workflows", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.mapSelect", + "group": "Export", + "subgroup": "Map export", + "label": "Map", + "loc": "src/export/MapExportModal.ts:82", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.fileName", + "group": "Export", + "subgroup": "Map export", + "label": "File name", + "loc": "src/export/MapExportModal.ts:94", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showCoords", + "group": "Export", + "subgroup": "Map export", + "label": "Coordinates", + "loc": "src/export/MapExportModal.ts:108", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showIcons", + "group": "Export", + "subgroup": "Map export", + "label": "Icons", + "loc": "src/export/MapExportModal.ts:109", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showPaths", + "group": "Export", + "subgroup": "Map export", + "label": "Paths", + "loc": "src/export/MapExportModal.ts:110", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.boldPaths", + "group": "Export", + "subgroup": "Map export", + "label": "Bolder paths", + "loc": "src/export/MapExportModal.ts:111", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showHexNames", + "group": "Export", + "subgroup": "Map export", + "label": "Hex names", + "loc": "src/export/MapExportModal.ts:116", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showTokens", + "group": "Export", + "subgroup": "Map export", + "label": "Tokens", + "loc": "src/export/MapExportModal.ts:117", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showLinkBadges", + "group": "Export", + "subgroup": "Map export", + "label": "Link badges", + "loc": "src/export/MapExportModal.ts:118", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showLegend", + "group": "Export", + "subgroup": "Map export", + "label": "Legend", + "loc": "src/export/MapExportModal.ts:120", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showFactionOverlay", + "group": "Export", + "subgroup": "Map export", + "label": "Faction overlay", + "loc": "src/export/MapExportModal.ts:122", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.showRegionOverlay", + "group": "Export", + "subgroup": "Map export", + "label": "Region overlay", + "loc": "src/export/MapExportModal.ts:124", + "suggestion": "advanced", + "choice": "advanced", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnsFold", + "group": "Export", + "subgroup": "Map export", + "label": "PDF table columns", + "loc": "src/export/MapExportModal.ts:131", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualFold", + "group": "Export", + "subgroup": "Map export", + "label": "Hexcrawl manual", + "loc": "src/export/MapExportModal.ts:137", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.outputSize", + "group": "Export", + "subgroup": "Map export", + "label": "Output size", + "loc": "src/export/MapExportModal.ts:147", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.exportPng", + "group": "Export", + "subgroup": "Map export", + "label": "Export PNG", + "loc": "src/export/MapExportModal.ts:239", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.exportPdf", + "group": "Export", + "subgroup": "Map export", + "label": "Export PDF with reference table", + "loc": "src/export/MapExportModal.ts:244", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.exportManual", + "group": "Export", + "subgroup": "Map export", + "label": "Export hexcrawl manual (PDF)", + "loc": "src/export/MapExportModal.ts:251", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.closeButtons", + "group": "Export", + "subgroup": "Map export", + "label": "×", + "loc": "src/export/MapExportModal.ts:276", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapModal.exportForm", + "group": "Export", + "subgroup": "Map export", + "label": "(export form)", + "loc": "src/hex-map/MapModal.ts:226", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnName", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Name", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnTerrain", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Terrain", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnTowns", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Towns", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnDungeons", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Dungeons", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnFeatures", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Features", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnQuests", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Quests", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnFactions", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Factions", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnEncounters", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Encounters", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.pdfColumnDescription", + "group": "Export", + "subgroup": "Map export: PDF table columns", + "label": "Description", + "loc": "src/export/MapExportModal.ts:134", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.playerEdition", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Player version (leave out the hidden and secret sections)", + "loc": "src/export/MapExportModal.ts:139", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualPartLegend", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Map legend", + "loc": "src/export/MapExportModal.ts:141", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualPartTables", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Encounter tables", + "loc": "src/export/MapExportModal.ts:141", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualPartFactions", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Factions and regions", + "loc": "src/export/MapExportModal.ts:141", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "MapExport.manualPartIndex", + "group": "Export", + "subgroup": "Map export: Hexcrawl manual", + "label": "Index", + "loc": "src/export/MapExportModal.ts:141", + "suggestion": "simple", + "choice": "simple", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.fileName", + "group": "Export", + "subgroup": "Hex export", + "label": "File name", + "loc": "src/hex-map/HexExportModal.ts:55", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.includeGm", + "group": "Export", + "subgroup": "Hex export", + "label": "Include game master only sections (hidden, secret)", + "loc": "src/hex-map/HexExportModal.ts:64", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.exportPdf", + "group": "Export", + "subgroup": "Hex export", + "label": "Export PDF", + "loc": "src/hex-map/HexExportModal.ts:90", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.exportMarkdown", + "group": "Export", + "subgroup": "Hex export", + "label": "Export Markdown", + "loc": "src/hex-map/HexExportModal.ts:101", + "suggestion": "advanced", + "choice": "simple", + "source": "own", + "via": "", + "viaSuggested": false, + "overrides": "advanced (group group:Export)", + "twinOf": "", + "note": "" + }, + { + "id": "HexExport.closeButtons", + "group": "Export", + "subgroup": "Hex export", + "label": "×", + "loc": "src/hex-map/HexExportModal.ts:29", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.fileName", + "group": "Export", + "subgroup": "Workflow export", + "label": "File name", + "loc": "src/random-tables/WorkflowExportModal.ts:53", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.sampleCount", + "group": "Export", + "subgroup": "Workflow export", + "label": "Number of sample outputs", + "loc": "src/random-tables/WorkflowExportModal.ts:66", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.includeTemplate", + "group": "Export", + "subgroup": "Workflow export", + "label": "Include the workflow template", + "loc": "src/random-tables/WorkflowExportModal.ts:76", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.includeBreakdown", + "group": "Export", + "subgroup": "Workflow export", + "label": "Include the per-sample rolls breakdown", + "loc": "src/random-tables/WorkflowExportModal.ts:81", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.exportPdf", + "group": "Export", + "subgroup": "Workflow export", + "label": "Export PDF", + "loc": "src/random-tables/WorkflowExportModal.ts:104", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.exportMarkdown", + "group": "Export", + "subgroup": "Workflow export", + "label": "Export Markdown", + "loc": "src/random-tables/WorkflowExportModal.ts:112", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "WorkflowExport.closeButtons", + "group": "Export", + "subgroup": "Workflow export", + "label": "×", + "loc": "src/random-tables/WorkflowExportModal.ts:27", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Export", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmModal.confirm", + "group": "Confirm dialogs", + "subgroup": "Confirm modal (shared)", + "label": "", + "loc": "src/worldgen/ConfirmModal.ts:421", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmModal.closeButtons", + "group": "Confirm dialogs", + "subgroup": "Confirm modal (shared)", + "label": "Cancel", + "loc": "src/worldgen/ConfirmModal.ts:426", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmDelete.delete", + "group": "Confirm dialogs", + "subgroup": "Confirm delete table modal", + "label": "Delete", + "loc": "src/random-tables/ConfirmDeleteModal.ts:451", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmDelete.closeButtons", + "group": "Confirm dialogs", + "subgroup": "Confirm delete table modal", + "label": "Cancel", + "loc": "src/random-tables/ConfirmDeleteModal.ts:462", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenConfirm.confirm", + "group": "Confirm dialogs", + "subgroup": "Confirm dialog (Reset / Delete)", + "label": "Reset / Delete", + "loc": "src/worldgen/ConfirmModal.ts:22", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "GenConfirm.closeButtons", + "group": "Confirm dialogs", + "subgroup": "Confirm dialog (Reset / Delete)", + "label": "Cancel", + "loc": "src/worldgen/ConfirmModal.ts:27", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmDelete.delete_2", + "group": "Confirm dialogs", + "subgroup": "Confirm delete modal", + "label": "Delete", + "loc": "src/random-tables/ConfirmDeleteModal.ts:19", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + }, + { + "id": "ConfirmDelete.closeButtons_2", + "group": "Confirm dialogs", + "subgroup": "Confirm delete modal", + "label": "Cancel", + "loc": "src/random-tables/ConfirmDeleteModal.ts:30", + "suggestion": "keep", + "choice": "keep", + "source": "group", + "via": "group:Confirm dialogs", + "viaSuggested": true, + "overrides": "", + "twinOf": "", + "note": "" + } +] \ No newline at end of file diff --git a/dev/ui-inventory/inputs-tags-summary.md b/dev/ui-inventory/inputs-tags-summary.md new file mode 100644 index 00000000..694b1a6f --- /dev/null +++ b/dev/ui-inventory/inputs-tags-summary.md @@ -0,0 +1,226 @@ +# inputs-tags: resolved picks + +- Submission: `inputs-tags.json`, submitted 2026-10-11T21:22:52.655Z +- 1142 items: 72 own, 1055 group, 15 twin, 0 suggestion-unreviewed +- Group-level picks: 31 + +## Effective choice by source + +| choice | own | group | twin | suggestion-unreviewed | total | +|---|---|---|---|---|---| +| Keep | 15 | 847 | 13 | 0 | 875 | +| Simple | 22 | 72 | 0 | 0 | 94 | +| Adv. | 24 | 68 | 2 | 0 | 94 | +| Overkill | 11 | 47 | 0 | 0 | 58 | +| Drop | 0 | 21 | 0 | 0 | 21 | + +## By section + +| section | items | reviewed | Keep | Simple | Adv. | Overkill | Drop | +|---|---|---|---|---|---|---|---| +| Settings › Setup & feature switches | 9 | 9 | 9 | 0 | 0 | 0 | 0 | +| Settings › Look & labels | 10 | 10 | 1 | 9 | 0 | 0 | 0 | +| Settings › Defaults | 10 | 10 | 1 | 4 | 5 | 0 | 0 | +| Settings › Folders | 16 | 16 | 2 | 0 | 11 | 3 | 0 | +| Settings › Palette management | 12 | 12 | 2 | 7 | 3 | 0 | 0 | +| Settings › Maintenance | 2 | 2 | 0 | 0 | 0 | 2 | 0 | +| Settings › Legacy (pre-1.13) | 11 | 11 | 0 | 1 | 4 | 6 | 0 | +| Setup wizard › Welcome | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Setup wizard › Folders | 13 | 13 | 12 | 0 | 1 | 0 | 0 | +| Setup wizard › Map | 12 | 12 | 7 | 0 | 5 | 0 | 0 | +| Setup wizard › Done | 2 | 2 | 2 | 0 | 0 | 0 | 0 | +| Setup wizard › Navigation | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| Feature hints › Inline hints | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Feature hints › More options modal | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Feature hints › Turn on ? modal | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Feature hints › Ready for more? modal | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Commands & menus › Open views | 9 | 9 | 5 | 4 | 0 | 0 | 0 | +| Commands & menus › Map navigation commands | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Commands & menus › Maintenance commands | 4 | 4 | 0 | 0 | 0 | 4 | 0 | +| Commands & menus › Export commands | 5 | 5 | 0 | 2 | 3 | 0 | 0 | +| Commands & menus › Note right-click menus | 6 | 6 | 4 | 0 | 2 | 0 | 0 | +| Hex map view › Top bar | 9 | 9 | 6 | 3 | 0 | 0 | 0 | +| Hex map view › Map navigation | 9 | 9 | 9 | 0 | 0 | 0 | 0 | +| Hex map view › Work modes | 10 | 10 | 3 | 5 | 2 | 0 | 0 | +| Hex map view › Drawing tools | 11 | 11 | 5 | 2 | 4 | 0 | 0 | +| Hex map view › Tool right-click menus | 21 | 21 | 16 | 2 | 2 | 0 | 1 | +| Hex map view › Hex right-click menu | 15 | 15 | 14 | 1 | 0 | 0 | 0 | +| Hex map view › Overworld menu & minimap | 21 | 21 | 21 | 0 | 0 | 0 | 0 | +| Hex map view › Token right-click menu | 4 | 4 | 2 | 2 | 0 | 0 | 0 | +| Hex map view › Layers panel | 25 | 25 | 21 | 3 | 1 | 0 | 0 | +| Hex map view › Legend, grid edges & notices | 7 | 7 | 5 | 2 | 0 | 0 | 0 | +| Hex map view › Mouse & keyboard | 25 | 25 | 22 | 1 | 0 | 0 | 2 | +| Hex editor › Header | 17 | 17 | 15 | 1 | 0 | 0 | 1 | +| Hex editor › Section headers | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| Hex editor › Terrain | 6 | 6 | 6 | 0 | 0 | 0 | 0 | +| Hex editor › Notes | 23 | 23 | 19 | 0 | 4 | 0 | 0 | +| Hex editor › Linked notes | 31 | 31 | 30 | 1 | 0 | 0 | 0 | +| Hex editor › Icons | 10 | 10 | 10 | 0 | 0 | 0 | 0 | +| Hex table › Toolbar | 15 | 15 | 10 | 0 | 4 | 1 | 0 | +| Hex table › Rows & cells | 16 | 16 | 16 | 0 | 0 | 0 | 0 | +| Hex table › Terrain filter | 10 | 10 | 9 | 0 | 1 | 0 | 0 | +| Hex table › Linking | 8 | 8 | 8 | 0 | 0 | 0 | 0 | +| Map pickers & editors › Icons | 12 | 12 | 11 | 1 | 0 | 0 | 0 | +| Map pickers & editors › Tokens | 19 | 19 | 11 | 7 | 1 | 0 | 0 | +| Map pickers & editors › Path types | 25 | 25 | 19 | 3 | 2 | 1 | 0 | +| Map pickers & editors › Go to hex & help | 5 | 5 | 5 | 0 | 0 | 0 | 0 | +| Map pickers & editors › Locations | 8 | 8 | 7 | 0 | 0 | 0 | 1 | +| Map pickers & editors › Factions | 16 | 16 | 11 | 5 | 0 | 0 | 0 | +| Map pickers & editors › Terrain | 25 | 25 | 23 | 1 | 0 | 1 | 0 | +| Maps modal › Tabs & general | 6 | 6 | 6 | 0 | 0 | 0 | 0 | +| Maps modal › Maps list | 8 | 8 | 6 | 0 | 2 | 0 | 0 | +| Maps modal › Properties | 10 | 10 | 3 | 3 | 2 | 2 | 0 | +| Maps modal › Neighbouring regions | 6 | 6 | 6 | 0 | 0 | 0 | 0 | +| Maps modal › Weather & rumours | 4 | 4 | 0 | 0 | 4 | 0 | 0 | +| Maps modal › Background image | 5 | 5 | 4 | 0 | 1 | 0 | 0 | +| Maps modal › Regions tab | 5 | 5 | 5 | 0 | 0 | 0 | 0 | +| New maps & map links › New map form | 18 | 18 | 14 | 0 | 4 | 0 | 0 | +| New maps & map links › New map form: More | 6 | 6 | 0 | 1 | 4 | 1 | 0 | +| New maps & map links › Generator options (world) | 13 | 13 | 6 | 0 | 7 | 0 | 0 | +| New maps & map links › Generator options (space) | 8 | 8 | 6 | 0 | 2 | 0 | 0 | +| New maps & map links › New map from a hex | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| New maps & map links › New land beside a map | 13 | 13 | 12 | 0 | 0 | 1 | 0 | +| New maps & map links › Link submap & insert map link | 11 | 11 | 11 | 0 | 0 | 0 | 0 | +| New maps & map links › Link submap: inline create form | 10 | 10 | 0 | 0 | 0 | 0 | 10 | +| New maps & map links › Dead code | 3 | 3 | 0 | 0 | 0 | 0 | 3 | +| Regions, overworlds & biomes › Missing regions & go to region | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| Regions, overworlds & biomes › New overworld | 19 | 19 | 18 | 0 | 0 | 1 | 0 | +| Regions, overworlds & biomes › Biome pools | 10 | 10 | 10 | 0 | 0 | 0 | 0 | +| Regions, overworlds & biomes › Biome library & biome form | 29 | 29 | 27 | 0 | 0 | 1 | 1 | +| Regions, overworlds & biomes › Biome picker & paint | 7 | 7 | 6 | 1 | 0 | 0 | 0 | +| Regions, overworlds & biomes › Region settings | 15 | 15 | 13 | 0 | 0 | 2 | 0 | +| Regions, overworlds & biomes › Edit region | 12 | 12 | 7 | 5 | 0 | 0 | 0 | +| Regions, overworlds & biomes › Region areas | 10 | 10 | 10 | 0 | 0 | 0 | 0 | +| Space: world types › General | 14 | 14 | 14 | 0 | 0 | 0 | 0 | +| Space: world types › Worlds tab | 12 | 12 | 10 | 0 | 0 | 2 | 0 | +| Space: world types › Stars tab | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Space: world types › Sector features tab | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Space: world types › Preview | 5 | 5 | 0 | 0 | 0 | 5 | 0 | +| Generator page › Library | 13 | 13 | 13 | 0 | 0 | 0 | 0 | +| Generator page › Recipe | 25 | 25 | 25 | 0 | 0 | 0 | 0 | +| Generator page › Preview & saves | 11 | 11 | 9 | 0 | 0 | 2 | 0 | +| Generator page › Engine tuning | 15 | 15 | 4 | 0 | 0 | 11 | 0 | +| Generator page › Paths | 14 | 14 | 6 | 0 | 0 | 8 | 0 | +| Generator page › Biome (blend field) | 21 | 21 | 19 | 0 | 0 | 1 | 1 | +| Generator page › Make generator from a map | 6 | 6 | 6 | 0 | 0 | 0 | 0 | +| Palette editor › Toolbar | 4 | 4 | 4 | 0 | 0 | 0 | 0 | +| Palette editor › Terrains | 12 | 12 | 12 | 0 | 0 | 0 | 0 | +| Palette editor › Palette settings & path types | 3 | 3 | 3 | 0 | 0 | 0 | 0 | +| Palette editor › Submap defaults | 9 | 9 | 8 | 0 | 0 | 1 | 0 | +| Random tables › Tables list | 25 | 25 | 18 | 1 | 5 | 1 | 0 | +| Random tables › Table detail | 24 | 24 | 21 | 1 | 1 | 1 | 0 | +| Random tables › Rolling | 17 | 17 | 15 | 2 | 0 | 0 | 0 | +| Random tables › Table editor | 22 | 22 | 16 | 0 | 6 | 0 | 0 | +| Random tables › Table picker | 6 | 6 | 5 | 0 | 0 | 0 | 1 | +| Workflows › Workflow detail | 5 | 5 | 5 | 0 | 0 | 0 | 0 | +| Workflows › Workflow editor | 18 | 18 | 18 | 0 | 0 | 0 | 0 | +| Workflows › Workflow wizard | 15 | 15 | 15 | 0 | 0 | 0 | 0 | +| Export › Map export | 20 | 20 | 12 | 7 | 1 | 0 | 0 | +| Export › Map export: PDF table columns | 9 | 9 | 9 | 0 | 0 | 0 | 0 | +| Export › Map export: Hexcrawl manual | 5 | 5 | 0 | 5 | 0 | 0 | 0 | +| Export › Hex export | 5 | 5 | 4 | 1 | 0 | 0 | 0 | +| Export › Workflow export | 7 | 7 | 7 | 0 | 0 | 0 | 0 | +| Confirm dialogs › Confirm modal (shared) | 2 | 2 | 2 | 0 | 0 | 0 | 0 | +| Confirm dialogs › Confirm delete table modal | 2 | 2 | 2 | 0 | 0 | 0 | 0 | +| Confirm dialogs › Confirm dialog (Reset / Delete) | 2 | 2 | 2 | 0 | 0 | 0 | 0 | +| Confirm dialogs › Confirm delete modal | 2 | 2 | 2 | 0 | 0 | 0 | 0 | + +## Group-level picks and notes + +- `Setup wizard/Welcome`: **Keep** +- `Setup wizard/Folders`: **use suggestions** +- `Setup wizard/Map`: **use suggestions** +- `Setup wizard/Done`: **use suggestions** +- `Setup wizard/Navigation`: **use suggestions** +- `Feature hints/Inline hints`: **use suggestions** +- `Feature hints/More options modal`: **use suggestions** +- `Feature hints/Turn on ? modal`: **use suggestions** +- `Feature hints/Ready for more? modal`: **use suggestions** +- `Commands & menus/Open views`: **use suggestions** +- `Commands & menus/Map navigation commands`: **use suggestions** +- `Commands & menus/Maintenance commands`: **use suggestions** +- `Commands & menus/Export commands`: **use suggestions** +- `Commands & menus/Note right-click menus`: **use suggestions** +- `Hex map view`: **use suggestions** +- `New maps & map links`: **use suggestions** +- `Hex editor/Section headers`: **use suggestions** +- `Hex editor`: **use suggestions** +- `Hex table`: **use suggestions** +- `Map pickers & editors`: **use suggestions** +- `Maps modal`: **use suggestions** +- `Regions, overworlds & biomes`: **use suggestions** +- `Space: world types`: **use suggestions** +- `Generator page`: **use suggestions** +- `Generator page/Engine tuning`: **use suggestions** +- `Palette editor`: **use suggestions** +- `Random tables/Tables list`: **use suggestions** +- `Random tables`: **use suggestions** +- `Workflows`: **use suggestions** +- `Export`: **use suggestions** +- `Confirm dialogs`: **use suggestions** + +## Item notes (verbatim) + +- `Settings.generateWorldData` (Generate; Overkill, own): "but note this might need to be surfaced in the case of debugging etc, we might need to point users to "all" if "health"/"repair" type settings hide there. " +- `Settings.legacyCoordLabelSize` (Coordinate label (slider); Overkill, own): "this and other stuff like it should just map to the same setting ideally. " +- `Settings.legacyPaletteDeleteButton` (Delete; Simple, own): "i think custom palettes should be simple. We want a streamlined but still customizable experience for simple, not to hide every little possible scary thing. " +- `WorkModeMenu.god` (God: Change anything…; Adv., own): "Yes but ask to enable it and other things when they start poking around region/generators/etc." +- `HexEditor.neighborCentreDot` (Centre dot; Drop, group): "do these actually link directly to a given hex? If a map is big enough I could see wanting to let a note direct-link a centered view on it, if this is the case then we should consider keeping this, maybe even as simple. " +- `NewOverworld.seed` (Seed; Overkill, group): "just make sure its saved for the saved rolls etc, its fine if it shows up on saves too. " +- `GenPage.clumping` (Clumping; Overkill, group): "Engine tuning should have its own separate overkill setting. Basically all these ones marked "overkill" for generator settings should go into an "advanced" dropdown that defaults closed rather than them being gated under the global overkill setting. That way people can muck about with them when they wanna go a bit further on one gen or another, instead of having to flip and stick with a top-level setting. " +- `GenPage.pathTypeFold` ((show routes chevron); Overkill, group): "ditto for the above, make sure these go into an "advanced" section, Maybe the advanced section can have collapsible sub-sections as well so its clean to view. " +- `RTView.refreshList` (Refresh list (↺); Overkill, group): "we should confirm that it does it at a good cadence for all of these "sink refresh" bits " + +## Overrides (own pick differs from group/twin) + +- `Settings.legacyCoordLabelSize`: Overkill instead of simple (twin Settings.coordFontSize) +- `Settings.legacyCoordLabelFont`: Overkill instead of simple (twin Settings.coordFontFamily) +- `Settings.legacyCoordLabelColor`: Overkill instead of simple (twin Settings.coordFontColor) +- `Settings.legacyHexNameFont`: Overkill instead of simple (twin Settings.hexNameFont) +- `Settings.legacyHexNameSize`: Overkill instead of simple (twin Settings.hexNameSize) +- `Settings.legacyHexNameStyle`: Overkill instead of simple (twin Settings.hexNameStyle) +- `Settings.legacyPaletteDeleteButton`: Simple instead of advanced (twin Settings.paletteDelete) +- `HexExport.exportMarkdown`: Simple instead of advanced (group group:Export) + +## Twins picked differently (decide: follow the twin or keep both) + +- `Settings.legacyCoordLabelSize` = Overkill, but its twin `Settings.coordFontSize` = Simple +- `Settings.legacyCoordLabelFont` = Overkill, but its twin `Settings.coordFontFamily` = Simple +- `Settings.legacyCoordLabelColor` = Overkill, but its twin `Settings.coordFontColor` = Simple +- `Settings.legacyHexNameFont` = Overkill, but its twin `Settings.hexNameFont` = Simple +- `Settings.legacyHexNameSize` = Overkill, but its twin `Settings.hexNameSize` = Simple +- `Settings.legacyHexNameStyle` = Overkill, but its twin `Settings.hexNameStyle` = Simple +- `Settings.legacyPaletteDeleteButton` = Simple, but its twin `Settings.paletteDelete` = Adv. + +## Reviewed and different from the suggestion + +- `Settings.staggerOffset` (Stagger offset): suggested Adv., now Simple (own) +- `Settings.coordPlacement` (Coordinate placement): suggested Adv., now Simple (own) +- `Settings.coordFontSize` (Coordinate label size): suggested Overkill, now Simple (own) +- `Settings.coordFontFamily` (Coordinate label font): suggested Overkill, now Simple (own) +- `Settings.coordFontColor` (Coordinate label color): suggested Overkill, now Simple (own) +- `Settings.hexNameFont` (Hex name font): suggested Overkill, now Simple (own) +- `Settings.hexNameSize` (Hex name size): suggested Overkill, now Simple (own) +- `Settings.hexNameStyle` (Hex name style): suggested Overkill, now Simple (own) +- `Settings.hexGap` (Hex cell spacing): suggested Adv., now Simple (own) +- `Settings.defaultTableDice` (Default die for new tables): suggested Adv., now Simple (own) +- `Settings.collapseTerrain` (Terrain): suggested Adv., now Simple (own) +- `Settings.collapseFeatures` (Features): suggested Adv., now Simple (own) +- `Settings.collapseNotes` (Notes): suggested Adv., now Simple (own) +- `Settings.defaultPalette` (Palette for new maps): suggested Adv., now Simple (own) +- `Settings.paletteRowName` ((palette name)): suggested Adv., now Simple (own) +- `Settings.paletteRowEdit` (Edit): suggested Adv., now Simple (own) +- `Settings.addPalette` (Add palette): suggested Adv., now Simple (own) +- `Settings.legacyPaletteDeleteButton` (Delete): suggested Adv., now Simple (own) +- `HexExport.exportMarkdown` (Export Markdown): suggested Adv., now Simple (own) + +## Apply list (reviewed, not keep) + +Hand-off input for implementation: one line per tier, ids only. + +- **Simple** (94): `Settings.staggerOffset`, `Settings.coordPlacement`, `Settings.coordFontSize`, `Settings.coordFontFamily`, `Settings.coordFontColor`, `Settings.hexNameFont`, `Settings.hexNameSize`, `Settings.hexNameStyle`, `Settings.hexGap`, `Settings.defaultTableDice`, `Settings.collapseTerrain`, `Settings.collapseFeatures`, `Settings.collapseNotes`, `Settings.defaultPalette`, `Settings.paletteRowName`, `Settings.paletteRowEdit`, `Settings.addPalette`, `AddPalette.presetOption`, `AddPalette.copyOption`, `AddPalette.emptyPalette`, `Settings.legacyPaletteDeleteButton`, `Plugin.ribbonOpenHexMap`, `Plugin.cmd.openHexTable`, `Plugin.cmd.openPaletteEditor`, `Plugin.cmd.openRandomTables`, `Plugin.cmd.exportCurrentHex`, `Plugin.cmd.exportCurrentMap`, `MapToolbar.hexTableBtn`, `MapToolbar.randomTablesBtn`, `MapToolbar.workModeBtn`, `WorkModeMenu.play`, `WorkModeMenu.build`, `ModeBar.autoRoute`, `ModeBar.newPath`, `ModeBar.done`, `DrawingPanel.path`, `DrawingPanel.token`, `PathMenu.deletePath`, `PathMenu.rename`, `HexMenu.createToken`, `TokenMenu.edit`, `TokenMenu.remove`, `LayersMenu.nameFontBtn`, `LayersMenu.badgeSize`, `LayersMenu.badgeTypesMore`, `Legend.size`, `MapGrid.shrink`, `MapView.tokenDrag`, `HexEditor.exportHex`, `HexEditor.encountersRoll`, `IconPicker.manageIcons`, `Token.iconGrid`, `Token.shape`, `Token.size`, `Token.fillColor`, `Token.borderToggle`, `Token.borderColor`, `Token.saveButton`, `PathPicker.editToggle`, `PathPicker.drawMode`, `PathPicker.typeGrid`, `FactionEditor.pattern`, `FactionEditor.patternScale`, `FactionEditor.opacity`, `FactionEditor.outlineWidth`, `FactionEditor.clearColor`, `TerrainPicker.editToggle`, `MapModal.propsStagger`, `MapModal.propsDelete`, `MapModal.propsDeleteConfirm`, `NewMap.stagger`, `BiomePicker.enterRegion`, `EditRegion.name`, `EditRegion.enterRegion`, `EditRegion.openMapNote`, `EditRegion.locationsList`, `EditRegion.notes`, `RTView.tablesTree`, `RTView.roll`, `RollModal.roll`, `RollerBlock.roll`, `MapExport.boldPaths`, `MapExport.showLinkBadges`, `MapExport.showFactionOverlay`, `MapExport.pdfColumnsFold`, `MapExport.exportPng`, `MapExport.exportPdf`, `MapExport.exportManual`, `MapExport.playerEdition`, `MapExport.manualPartLegend`, `MapExport.manualPartTables`, `MapExport.manualPartFactions`, `MapExport.manualPartIndex`, `HexExport.exportMarkdown` +- **Adv.** (94): `Settings.templatePath`, `Settings.defaultNewMapCols`, `Settings.defaultNewMapRows`, `Settings.defaultSubmapCols`, `Settings.defaultSubmapRows`, `Settings.hexFolder`, `Settings.townsFolder`, `Settings.dungeonsFolder`, `Settings.questsFolder`, `Settings.featuresFolder`, `Settings.factionsFolder`, `Settings.regionsFolder`, `Settings.tablesFolder`, `Settings.workflowsFolder`, `Settings.templatesFolder`, `Settings.palettesFolder`, `Settings.addDefaultPalettes`, `Settings.paletteRowOpenNote`, `Settings.paletteDelete`, `Settings.legacyNewMapCols`, `Settings.legacyNewMapRows`, `Settings.legacySubmapCols`, `Settings.legacySubmapRows`, `Wizard.configureFoldersIndividually`, `Wizard.genOptWater`, `Wizard.genOptClimate`, `Wizard.genOptRelief`, `Wizard.genOptSea`, `Wizard.genOptOther`, `Plugin.cmd.exportNotePdf`, `Plugin.cmd.exportNoteMarkdown`, `Plugin.cmd.exportCurrentWorkflow`, `Plugin.fileMenuExportPdf`, `Plugin.fileMenuExportMarkdown`, `WorkModeMenu.god`, `ModeBar.crossImpassable`, `DrawingPanel.linkTable`, `DrawingPanel.linkSubmap`, `DrawingPanel.regionAreas`, `MapView.tableLinkToolPicker`, `PathMenu.splitHere`, `PathMenu.reverse`, `LayersMenu.regionOverlay`, `HexEditor.weatherSource`, `HexEditor.hooksSource`, `HexEditor.rolledSetMapTable`, `HexEditor.rolledSetHexTable`, `HexTable.xMin`, `HexTable.xMax`, `HexTable.yMin`, `HexTable.yMax`, `TerrainFilter.typeRow`, `Token.description`, `PathPicker.pathsOnMap`, `PathType.carves`, `MapModal.mapRowContextGenerator`, `MapModal.mapRowContextMakeGenerator`, `MapProps.sectionTablePicker`, `MapModal.propsTerrainTheme`, `MapModal.propsWeatherTable`, `MapModal.propsWeatherClear`, `MapModal.propsRumoursTable`, `MapModal.propsRumoursClear`, `MapProps.backgroundImagePicker`, `NewMap.rememberPalette`, `NewMap.rememberSize`, `NewMap.rememberGenerator`, `NewMap.rememberBase`, `NewMapSetup.backgroundImagePicker`, `NewMap.startCoords`, `NewMap.bgPick`, `NewMap.bgClear`, `NewMap.overlandWater`, `NewMap.overlandClimate`, `NewMap.overlandRelief`, `NewMap.overlandSea`, `NewMap.planetRelief`, `NewMap.regionDetailInfluence`, `NewMap.regionDetailVariety`, `NewMap.starRouteType`, `NewMap.orbitsPathType`, `RTView.folderMenuRollPicker`, `RTView.folderMenuEncounters`, `RTView.fileMenuRollPicker`, `RTView.fileMenuEncounters`, `RTView.generateFromFolder`, `RTView.copyRollLink`, `TableEditor.minusOneAll`, `TableEditor.plusOneAll`, `TableEditor.import`, `TableEditor.linkedFolder`, `TableEditor.excludeRollPicker`, `TableEditor.excludeEncounters`, `MapExport.showRegionOverlay` +- **Overkill** (58): `Settings.biomesFolder`, `Settings.biomePoolsFolder`, `Settings.worldTypesFolder`, `Settings.generateWorldData`, `Settings.generateFolders`, `Settings.legacyCoordLabelSize`, `Settings.legacyCoordLabelFont`, `Settings.legacyCoordLabelColor`, `Settings.legacyHexNameFont`, `Settings.legacyHexNameSize`, `Settings.legacyHexNameStyle`, `Plugin.cmd.addRollRanges`, `Plugin.cmd.checkTables`, `Plugin.cmd.addMapDataToHexNotes`, `Plugin.cmd.updateRegionFactionMapData`, `HexTable.refresh`, `PathType.carveWidth`, `TerrainPicker.refreshEncounterLinks`, `MapModal.propsFolderName`, `MapModal.propsRenameFolder`, `NewMap.folderName`, `WalkOW.seed`, `NewOverworld.seed`, `BiomeForm.chance`, `RegionGen.wigglyBorders`, `RegionGen.seed`, `WorldTypes.worldGenerator`, `WorldTypes.worldOptions`, `WorldTypes.previewMap`, `WorldTypes.previewOrbit`, `WorldTypes.previewStar`, `WorldTypes.previewTemperature`, `WorldTypes.previewRolls`, `GenPage.seed`, `GenPage.seedLock`, `GenPage.clumping`, `GenPage.edgeSmoothing`, `GenPage.removeSmallPatches`, `GenPage.keepRare`, `GenPage.edgeStrength`, `GenPage.directionalBias`, `GenPage.scatter`, `GenPage.spacing`, `GenPage.randomness`, `GenPage.near`, `GenPage.mixStrength`, `GenPage.pathTypeFold`, `GenPage.pathTypeAvoid`, `GenPage.routeOn`, `GenPage.routeCount`, `GenPage.routeAs`, `GenPage.routeWiggle`, `GenPage.routeLength`, `GenPage.routeFollow`, `BiomePage.seed`, `PaletteEditor.generatorOptions`, `RTView.refreshList`, `RTView.refreshLinked` +- **Drop** (21): `PainterMenu.newPath`, `MapView.dblRightClickExit`, `MapView.dblClickOffGridExit`, `HexEditor.neighborCentreDot`, `Locations.openButton`, `SubmapPicker.createSection`, `SubmapPicker.createName`, `SubmapPicker.createCols`, `SubmapPicker.createRows`, `SubmapPicker.createPalette`, `SubmapPicker.createStartX`, `SubmapPicker.createStartY`, `SubmapPicker.createStagger`, `SubmapPicker.createTerrainTheme`, `SubmapPicker.createAndLink`, `NewMapFields.name`, `NewMapFields.size`, `NewMapFields.palette`, `BiomeForm.mixNumber`, `BiomePage.weightNumber`, `FolderTree.openTablesView` + +Unreviewed items whose suggestion is not keep: 0 (not in the apply list; they need a decision first). diff --git a/dev/ui-inventory/inputs-tags.html b/dev/ui-inventory/inputs-tags.html new file mode 100644 index 00000000..f8e5475f --- /dev/null +++ b/dev/ui-inventory/inputs-tags.html @@ -0,0 +1,501 @@ + + + +loading + + +

+

+
+
+ + + + +
+
+
+ diff --git a/dev/ui-inventory/items.json b/dev/ui-inventory/items.json new file mode 100644 index 00000000..2ad28789 --- /dev/null +++ b/dev/ui-inventory/items.json @@ -0,0 +1,18334 @@ +[ + { + "id": "Settings.rerunSetupWizard", + "surface": "Settings tab", + "label": "Re-run setup wizard", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:247", + "desc": "Reopens the first-run setup wizard (both paths).", + "pick": "keep", + "why": "Easy way back to the guided start.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featureLevel", + "surface": "Settings tab: Features", + "label": "Feature level", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:894", + "desc": "Simple or Advanced; hides/shows power tools (both paths).", + "pick": "keep", + "why": "The master switch; natural home for a third 'All' level.", + "lists": "Simple, Advanced", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featureGenerators", + "surface": "Settings tab: Features", + "label": "Terrain generators", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:906", + "desc": "Turns on terrain generators alone while in Simple; greyed out in Advanced.", + "pick": "keep", + "why": "This switch is how a Simple user turns on one power feature without going full Advanced; hiding it removes that ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featureWorkflows", + "surface": "Settings tab: Features", + "label": "Workflows", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:906", + "desc": "Turns on workflows alone while in Simple; greyed out in Advanced.", + "pick": "keep", + "why": "This switch is how a Simple user turns on one power feature without going full Advanced; hiding it removes that ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featurePalettes", + "surface": "Settings tab: Features", + "label": "Custom palettes", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:906", + "desc": "Turns on custom palettes alone while in Simple; greyed out in Advanced.", + "pick": "keep", + "why": "This switch is how a Simple user turns on one power feature without going full Advanced; hiding it removes that ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.featureRegions", + "surface": "Settings tab: Features", + "label": "Regions and overworlds", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:906", + "desc": "Turns on regions/overworlds alone while in Simple; greyed out in Advanced.", + "pick": "keep", + "why": "This switch is how a Simple user turns on one power feature without going full Advanced; hiding it removes that ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.showHintsAgain", + "surface": "Settings tab: Features", + "label": "Show hints again", + "kind": "button", + "level": "conditional: some hints were closed", + "loc": "src/HexmakerSettingTab.ts:923", + "desc": "Brings back closed 'turn on advanced feature' hints (both paths).", + "pick": "keep", + "why": "Only appears after hints were closed; it's the way back to the Simple-user ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.mapKindWorld", + "surface": "Settings tab: Map types", + "label": "World / fantasy overland", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:695", + "desc": "Turns fantasy overland palettes, generators, icons on/off (both paths).", + "pick": "keep", + "why": "Core content switch; keeps unrelated content out.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.mapKindSpace", + "surface": "Settings tab: Map types", + "label": "Space", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:695", + "desc": "Turns space palettes, generators and icons on/off (both paths).", + "pick": "keep", + "why": "Core content switch.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Setup & feature switches" + }, + { + "id": "Settings.hexOrientation", + "surface": "Settings tab", + "label": "Hex orientation", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:310", + "desc": "Pointy-top or flat-top hexes (both paths).", + "pick": "keep", + "why": "Basic map look; also asked in the wizard.", + "lists": "Pointy-top, Flat-top", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.staggerOffset", + "surface": "Settings tab", + "label": "Stagger offset", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:320", + "desc": "Odd/Even toggle button: which rows/columns shift half a hex (both paths).", + "pick": "advanced", + "why": "Grid geometry choice beyond the basics; maps can also set it themselves.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.coordPlacement", + "surface": "Settings tab", + "label": "Coordinate placement", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:339", + "desc": "Where the hex coordinate label sits: top, middle, bottom (both paths).", + "pick": "advanced", + "why": "Map look option beyond the basics, not engine tuning.", + "lists": "Top, Middle, Bottom", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.coordFontSize", + "surface": "Settings tab", + "label": "Coordinate label size", + "kind": "slider", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:349", + "desc": "Size of the coordinate label (declarative path only label).", + "pick": "overkill", + "why": "Font micro-tuning for the coordinate label.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.coordFontFamily", + "surface": "Settings tab", + "label": "Coordinate label font", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:362", + "desc": "Font for the coordinate label (declarative path label).", + "pick": "overkill", + "why": "Font micro-tuning for the coordinate label.", + "lists": "Interface, Serif, Monospace", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.coordFontColor", + "surface": "Settings tab", + "label": "Coordinate label color", + "kind": "color", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:376", + "desc": "Colour of the coordinate label (declarative path label).", + "pick": "overkill", + "why": "Font micro-tuning for the coordinate label.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.hexNameFont", + "surface": "Settings tab", + "label": "Hex name font", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:385", + "desc": "Default font for hex names on maps and exports (declarative).", + "pick": "overkill", + "why": "Global font default for hex names; per-map layers menu covers normal use.", + "lists": "Name font families", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.hexNameSize", + "surface": "Settings tab", + "label": "Hex name size", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:395", + "desc": "Default size for hex names (declarative path label).", + "pick": "overkill", + "why": "Global font-size default for hex names; per-map layers menu covers normal use.", + "lists": "Small, Medium, Large, Huge", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.hexNameStyle", + "surface": "Settings tab", + "label": "Hex name style", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:405", + "desc": "Default bold/italic for hex names (declarative path label).", + "pick": "overkill", + "why": "Global font-style default for hex names; per-map layers menu covers normal use.", + "lists": "Name styles", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.hexGap", + "surface": "Settings tab", + "label": "Hex cell spacing", + "kind": "slider", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:415", + "desc": "Gap between hex cells (both paths).", + "pick": "advanced", + "why": "Map look option beyond the basics, not engine tuning.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Look & labels" + }, + { + "id": "Settings.defaultTableDice", + "surface": "Settings tab", + "label": "Default die for new tables", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:266", + "desc": "Die size new random tables start with, d4 to d1000 (both paths).", + "pick": "advanced", + "why": "A table-making preference beyond the basics; each table can still change its own die.", + "lists": "D4,D6,D8,D10,D12,D20,D100,D200,D500,D1000", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.collapseTerrain", + "surface": "Settings tab: Hex editor sections start collapsed", + "label": "Terrain", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:989", + "desc": "Hex editor opens with Terrain section collapsed (both paths).", + "pick": "advanced", + "why": "A layout preference for people who use the hex editor a lot; not needed to start.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.collapseFeatures", + "surface": "Settings tab: Hex editor sections start collapsed", + "label": "Features", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:996", + "desc": "Hex editor opens with Features section collapsed (both paths).", + "pick": "advanced", + "why": "A layout preference for people who use the hex editor a lot; not needed to start.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.collapseNotes", + "surface": "Settings tab: Hex editor sections start collapsed", + "label": "Notes", + "kind": "toggle", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1003", + "desc": "Hex editor opens with Notes section collapsed (both paths).", + "pick": "advanced", + "why": "A layout preference for people who use the hex editor a lot; not needed to start.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.templatePath", + "surface": "Settings tab", + "label": "Template path", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:293", + "desc": "Path to a custom hex note template (both paths).", + "pick": "advanced", + "why": "Custom hex note templates are a real feature, just not a first-day one.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultMap", + "surface": "Settings tab", + "label": "Default map", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:300", + "desc": "Map shown when the hex map opens (both paths).", + "pick": "keep", + "why": "Useful once you have several maps.", + "lists": "All maps in settings (top-level, submaps, regions alike)", + "focused": false, + "mix": "submaps/region maps listed flat beside top-level maps", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultNewMapCols", + "surface": "Settings tab", + "label": "Default new map columns", + "kind": "number", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:428", + "desc": "Starting columns for new top-level maps (declarative path).", + "pick": "advanced", + "why": "A convenience default for people who make many maps; the new-map form still asks.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultNewMapRows", + "surface": "Settings tab", + "label": "Default new map rows", + "kind": "number", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:440", + "desc": "Starting rows for new top-level maps (declarative path).", + "pick": "advanced", + "why": "A convenience default for people who make many maps; the new-map form still asks.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultSubmapCols", + "surface": "Settings tab", + "label": "Default submap columns", + "kind": "number", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:452", + "desc": "Starting columns for new submaps (declarative path).", + "pick": "advanced", + "why": "A convenience default for people who make many submaps; the form still asks.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.defaultSubmapRows", + "surface": "Settings tab", + "label": "Default submap rows", + "kind": "number", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:464", + "desc": "Starting rows for new submaps (declarative path).", + "pick": "advanced", + "why": "A convenience default for people who make many submaps; the form still asks.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Defaults" + }, + { + "id": "Settings.iconsFolder", + "surface": "Settings tab", + "label": "Custom icons folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:475", + "desc": "Folder of your own icon images added to the pickers (both paths).", + "pick": "keep", + "why": "Main way to add your own icons; pickers point users here.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.worldFolder", + "surface": "Settings tab: folders", + "label": "World notes folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:527", + "desc": "Root folder for all world notes; scopes link search (both paths).", + "pick": "keep", + "why": "The one folder a newcomer should care about.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.hexFolder", + "surface": "Settings tab: folders", + "label": "Hex notes folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:608", + "desc": "Where hex notes are stored (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.townsFolder", + "surface": "Settings tab: folders", + "label": "Towns folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:614", + "desc": "Folder that feeds the Towns picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.dungeonsFolder", + "surface": "Settings tab: folders", + "label": "Dungeons folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:620", + "desc": "Folder that feeds the Dungeons picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.questsFolder", + "surface": "Settings tab: folders", + "label": "Quests folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:626", + "desc": "Folder that feeds the Quests picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.featuresFolder", + "surface": "Settings tab: folders", + "label": "Features folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:632", + "desc": "Folder that feeds the Features picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.factionsFolder", + "surface": "Settings tab: folders", + "label": "Factions folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:638", + "desc": "Folder that feeds the Factions picker (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.regionsFolder", + "surface": "Settings tab: folders", + "label": "Regions folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:644", + "desc": "Folder for region notes used by the region overlay tool (both paths).", + "pick": "advanced", + "why": "Folder for the region areas overlay; beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.tablesFolder", + "surface": "Settings tab: folders", + "label": "Tables folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:650", + "desc": "Folder for random table notes (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.workflowsFolder", + "surface": "Settings tab: folders", + "label": "Workflows folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:656", + "desc": "Folder for workflow notes (both paths).", + "pick": "advanced", + "why": "Folder for workflows, an Advanced feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.templatesFolder", + "surface": "Settings tab: folders", + "label": "Templates folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:662", + "desc": "Folder for hex/town note templates (both paths).", + "pick": "advanced", + "why": "Folder layout choice beyond the defaults the wizard sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.palettesFolder", + "surface": "Settings tab: folders", + "label": "Palettes folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:668", + "desc": "Folder for palette notes (both paths).", + "pick": "advanced", + "why": "Folder for custom palettes, an Advanced feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.biomesFolder", + "surface": "Settings tab: folders", + "label": "Biomes folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:674", + "desc": "Folder for overworld biome notes (both paths).", + "pick": "overkill", + "why": "Storage location for generator biome data; a normal user never moves it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.biomePoolsFolder", + "surface": "Settings tab: folders", + "label": "Biome pools folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:680", + "desc": "Folder for biome pools of generated overworlds (both paths).", + "pick": "overkill", + "why": "Storage location for generator biome-pool data; a normal user never moves it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.worldTypesFolder", + "surface": "Settings tab: folders", + "label": "World types folder", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:686", + "desc": "Folder for world-type notes used by space generators (both paths).", + "pick": "overkill", + "why": "Storage location for space world-type data; a normal user never moves it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Folders" + }, + { + "id": "Settings.defaultPalette", + "surface": "Settings tab: Terrain palettes", + "label": "Palette for new maps", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:721", + "desc": "Palette a new map starts with (both paths).", + "pick": "advanced", + "why": "Part of custom palettes; the new-map form picks a palette anyway.", + "lists": "'First palette' + all installed palettes (+ missing saved one)", + "focused": false, + "mix": "space palettes listed even with Space off (no isKindEnabled filter)", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.addDefaultPalettes", + "surface": "Settings tab: Terrain palettes", + "label": "Add ", + "kind": "button", + "level": "conditional: a built-in palette was deleted", + "loc": "src/HexmakerSettingTab.ts:731", + "desc": "Restores deleted built-in palettes (both paths).", + "pick": "advanced", + "why": "Palette management (restore a deleted built-in), part of custom palettes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.paletteRowName", + "surface": "Settings tab: Terrain palettes", + "label": "(palette name)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:212", + "desc": "Inline rename box on each palette row (both paths).", + "pick": "advanced", + "why": "Palette management, part of the custom palettes feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.paletteRowEdit", + "surface": "Settings tab: Terrain palettes", + "label": "Edit", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:868", + "desc": "Opens the palette editor (asks to enable palettes in Simple).", + "pick": "advanced", + "why": "Opens the palette editor, part of the custom palettes feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.paletteRowOpenNote", + "surface": "Settings tab: Terrain palettes", + "label": "Open note", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:871", + "desc": "Opens the palette's markdown note (both paths).", + "pick": "advanced", + "why": "Palette notes are editable as a table; part of custom palettes, not dead.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.paletteDelete", + "surface": "Settings tab: Terrain palettes", + "label": "Delete (list delete)", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:748", + "desc": "Deletes an unused palette (declarative list delete affordance).", + "pick": "advanced", + "why": "Palette management, part of the custom palettes feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.addPalette", + "surface": "Settings tab: Terrain palettes", + "label": "Add palette", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:767", + "desc": "Opens the Add palette chooser (both paths).", + "pick": "advanced", + "why": "Adding palettes is part of the custom palettes feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "AddPalette.presetOption", + "surface": "Add palette modal", + "label": "", + "kind": "picker", + "level": "always (from Settings > Add palette)", + "loc": "src/palettes/AddPaletteModal.ts:30", + "desc": "Install a built-in palette preset (filtered by enabled map types).", + "pick": "simple", + "why": "Custom palettes are Simple (owner); installing a preset is how you add one. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "Built-in presets of enabled map types", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Palette management", + "prevPick": "advanced" + }, + { + "id": "AddPalette.copyOption", + "surface": "Add palette modal", + "label": "Copy of ", + "kind": "picker", + "level": "always (from Settings > Add palette)", + "loc": "src/palettes/AddPaletteModal.ts:46", + "desc": "Duplicate an existing palette.", + "pick": "simple", + "why": "Custom palettes are Simple (owner); copying one is the easy way to start your own. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "Every installed palette (space ones too with Space off)", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Palette management", + "prevPick": "advanced" + }, + { + "id": "AddPalette.emptyPalette", + "surface": "Add palette modal", + "label": "Empty palette", + "kind": "button", + "level": "always (from Settings > Add palette)", + "loc": "src/palettes/AddPaletteModal.ts:64", + "desc": "Create an empty palette.", + "pick": "simple", + "why": "Custom palettes are Simple (owner). Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management", + "prevPick": "advanced" + }, + { + "id": "AddPalette.preset", + "surface": "Add palette modal", + "label": " / (another copy)", + "kind": "button", + "level": "feature:palettes", + "loc": "src/palettes/AddPaletteModal.ts:30", + "desc": "Installs a built-in palette preset.", + "pick": "keep", + "why": "Easiest start.", + "lists": "PALETTE_PRESETS of enabled map kinds; installed ones labelled '(another copy)'.", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "AddPalette.closeButtons", + "surface": "Add palette modal", + "label": "(modal ✕)", + "kind": "button", + "level": "feature:palettes", + "loc": "src/palettes/AddPaletteModal.ts:20", + "desc": "Closes without adding.", + "pick": "keep", + "why": "Required.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Palette management" + }, + { + "id": "Settings.generateWorldData", + "surface": "Settings tab: Generate world data", + "label": "Generate", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:491", + "desc": "Creates terrain tables, roller links, hex-to-table links (both paths).", + "pick": "overkill", + "why": "Maintenance button: the wizard and painting already create this data.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Maintenance" + }, + { + "id": "Settings.generateFolders", + "surface": "Settings tab: folders", + "label": "Generate folders", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:534", + "desc": "Fills blank folder settings, creates folders and hex notes (both paths).", + "pick": "overkill", + "why": "Maintenance button that redoes the wizard's folder work.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Maintenance" + }, + { + "id": "Settings.legacyCoordLabelSize", + "surface": "Settings tab: legacy display()", + "label": "Coordinate label (slider)", + "kind": "slider", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1167", + "desc": "Legacy path: size slider in one combined 'Coordinate label' row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.coordFontSize (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the coordinate label size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.coordFontSize" + }, + { + "id": "Settings.legacyCoordLabelFont", + "surface": "Settings tab: legacy display()", + "label": "Coordinate label (font)", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1178", + "desc": "Legacy path: unlabelled font dropdown in the combined row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.coordFontFamily (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the coordinate label font; same tag as its twin.", + "lists": "Interface, Serif, Monospace", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.coordFontFamily" + }, + { + "id": "Settings.legacyCoordLabelColor", + "surface": "Settings tab: legacy display()", + "label": "Coordinate label (color)", + "kind": "color", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1193", + "desc": "Legacy path: unlabelled colour picker in the combined row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.coordFontColor (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the coordinate label colour; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.coordFontColor" + }, + { + "id": "Settings.legacyHexNameFont", + "surface": "Settings tab: legacy display()", + "label": "Hex name font (font)", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1214", + "desc": "Legacy path: first of 3 unlabelled dropdowns in one row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.hexNameFont (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the hex name font default; same tag as its twin.", + "lists": "Name font families", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.hexNameFont" + }, + { + "id": "Settings.legacyHexNameSize", + "surface": "Settings tab: legacy display()", + "label": "Hex name font (size)", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1221", + "desc": "Legacy path: size dropdown in the Hex name font row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.hexNameSize (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the hex name size default; same tag as its twin.", + "lists": "Small..Huge", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.hexNameSize" + }, + { + "id": "Settings.legacyHexNameStyle", + "surface": "Settings tab: legacy display()", + "label": "Hex name font (style)", + "kind": "dropdown", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1228", + "desc": "Legacy path: style dropdown in the Hex name font row.", + "pick": "overkill", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.hexNameStyle (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the hex name style default; same tag as its twin.", + "lists": "Name styles", + "focused": true, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.hexNameStyle" + }, + { + "id": "Settings.legacyNewMapCols", + "surface": "Settings tab: legacy display()", + "label": "Default new map size (Cols)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1263", + "desc": "Legacy path: text box (not number) for default columns.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.defaultNewMapCols (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the default new map size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.defaultNewMapCols" + }, + { + "id": "Settings.legacyNewMapRows", + "surface": "Settings tab: legacy display()", + "label": "Default new map size (Rows)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1272", + "desc": "Legacy path: text box for default rows.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.defaultNewMapRows (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the default new map size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.defaultNewMapRows" + }, + { + "id": "Settings.legacySubmapCols", + "surface": "Settings tab: legacy display()", + "label": "Default submap size (Cols)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1285", + "desc": "Legacy path: text box for submap columns.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.defaultSubmapCols (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the default submap size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.defaultSubmapCols" + }, + { + "id": "Settings.legacySubmapRows", + "surface": "Settings tab: legacy display()", + "label": "Default submap size (Rows)", + "kind": "text", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1294", + "desc": "Legacy path: text box for submap rows.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.defaultSubmapRows (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of the default submap size; same tag as its twin.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.defaultSubmapRows" + }, + { + "id": "Settings.legacyPaletteDeleteButton", + "surface": "Settings tab: legacy display()", + "label": "Delete", + "kind": "button", + "level": "always", + "loc": "src/HexmakerSettingTab.ts:1742", + "desc": "Legacy path: explicit Delete per palette row, disabled when in use.", + "pick": "advanced", + "why": "Pre-1.13 fallback copy of the same setting; follows Settings.paletteDelete (owner: \"should just map to the same setting\"). Earlier reason: Pre-1.13 copy of palette delete; palette management is custom palettes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Settings", + "subgroup": "Legacy (pre-1.13)", + "twinOf": "Settings.paletteDelete" + }, + { + "id": "Wizard.mapKindWorld", + "surface": "Setup wizard: Welcome", + "label": "World / fantasy overland", + "kind": "checkbox", + "level": "always", + "loc": "src/SetupWizardView.ts:243", + "desc": "Include fantasy overland content.", + "pick": "keep", + "why": "Good first question; scopes everything after.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Welcome" + }, + { + "id": "Wizard.mapKindSpace", + "surface": "Setup wizard: Welcome", + "label": "Space", + "kind": "checkbox", + "level": "always", + "loc": "src/SetupWizardView.ts:243", + "desc": "Include space content.", + "pick": "keep", + "why": "Good first question.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Welcome" + }, + { + "id": "Wizard.featureLevel", + "surface": "Setup wizard: Welcome", + "label": "How much do you want to start with? (Simple/Advanced)", + "kind": "radio", + "level": "always", + "loc": "src/SetupWizardView.ts:261", + "desc": "Choose Simple or Advanced feature level.", + "pick": "keep", + "why": "Right place to set the level; descriptions are long.", + "lists": "Simple, Advanced", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Welcome" + }, + { + "id": "Wizard.worldFolder", + "surface": "Setup wizard: Folders", + "label": "World folder", + "kind": "text", + "level": "always", + "loc": "src/SetupWizardView.ts:304", + "desc": "Root folder for all world data.", + "pick": "keep", + "why": "The one folder question that matters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.configureFoldersIndividually", + "surface": "Setup wizard: Folders", + "label": "Configure each folder path individually", + "kind": "checkbox", + "level": "always", + "loc": "src/SetupWizardView.ts:324", + "desc": "Reveals 11 per-folder path inputs.", + "pick": "advanced", + "why": "Per-folder setup is beyond what a newcomer needs; the defaults work.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.hex", + "surface": "Setup wizard: Folders", + "label": "Hex notes", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the hex notes folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.towns", + "surface": "Setup wizard: Folders", + "label": "Towns", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the towns folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.dungeons", + "surface": "Setup wizard: Folders", + "label": "Dungeons", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the dungeons folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.quests", + "surface": "Setup wizard: Folders", + "label": "Quests", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the quests folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.features", + "surface": "Setup wizard: Folders", + "label": "Features", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the features folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.factions", + "surface": "Setup wizard: Folders", + "label": "Factions", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the factions folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.regions", + "surface": "Setup wizard: Folders", + "label": "Regions", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the regions folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.tables", + "surface": "Setup wizard: Folders", + "label": "Tables", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the tables folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.workflows", + "surface": "Setup wizard: Folders", + "label": "Workflows", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the workflows folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.templates", + "surface": "Setup wizard: Folders", + "label": "Templates", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the templates folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.folder.icons", + "surface": "Setup wizard: Folders", + "label": "Icons", + "kind": "text", + "level": "conditional: 'configure individually' ticked", + "loc": "src/SetupWizardView.ts:350", + "desc": "Custom path for the icons folder.", + "pick": "keep", + "why": "No change of its own: it only shows inside the 'configure individually' box (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Folders" + }, + { + "id": "Wizard.mapName", + "surface": "Setup wizard: Map", + "label": "Map name", + "kind": "text", + "level": "always", + "loc": "src/SetupWizardView.ts:440", + "desc": "Name of your first map.", + "pick": "keep", + "why": "Essential.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.gridCols", + "surface": "Setup wizard: Map", + "label": "Grid size (columns)", + "kind": "number", + "level": "always", + "loc": "src/SetupWizardView.ts:469", + "desc": "Number of columns.", + "pick": "keep", + "why": "Essential map size.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.gridRows", + "surface": "Setup wizard: Map", + "label": "Grid size (rows)", + "kind": "number", + "level": "always", + "loc": "src/SetupWizardView.ts:479", + "desc": "Number of rows.", + "pick": "keep", + "why": "Essential map size.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.hexOrientation", + "surface": "Setup wizard: Map", + "label": "Hex orientation (Flat-top / Pointy-top)", + "kind": "radio", + "level": "always", + "loc": "src/SetupWizardView.ts:544", + "desc": "Choose flat-top or pointy-top hexes.", + "pick": "keep", + "why": "Clear choice with live preview.", + "lists": "Flat-top, Pointy-top", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.terrainPalette", + "surface": "Setup wizard: Map", + "label": "Terrain palette", + "kind": "dropdown", + "level": "always", + "loc": "src/SetupWizardView.ts:579", + "desc": "Palette for the first map (installed + presets of enabled kinds).", + "pick": "keep", + "why": "Core choice; preview swatches help.", + "lists": "Installed palettes + Presets optgroup (kind-filtered)", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.generatorCards", + "surface": "Setup wizard: Map", + "label": "Terrain (generator cards)", + "kind": "picker", + "level": "always (Simple: Blank + starter + every space gen)", + "loc": "src/SetupWizardView.ts:633", + "desc": "Pick how to fill the map: blank or a generator.", + "pick": "keep", + "why": "Good, but in Simple every space generator leaks through.", + "lists": "Blank, Overland/Star scatter; Advanced: all incl. learned", + "focused": false, + "mix": "Simple filter keeps all mapKind=space generators, not just the starter", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptWater", + "surface": "Setup wizard: Map", + "label": "Water", + "kind": "dropdown", + "level": "conditional: Overland generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "How much of the map is water.", + "pick": "advanced", + "why": "Generator options are part of using generators; Simple gets the dice re-roll.", + "lists": "10%..85%", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptClimate", + "surface": "Setup wizard: Map", + "label": "Climate", + "kind": "dropdown", + "level": "conditional: Overland generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "Overall climate of generated terrain.", + "pick": "advanced", + "why": "Generator options are part of using generators; Simple gets the dice re-roll.", + "lists": "Temperate, Lush, Arid, Frozen, Volcanic", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptRelief", + "surface": "Setup wizard: Map", + "label": "Relief", + "kind": "dropdown", + "level": "conditional: Overland generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "How hilly or mountainous the map is.", + "pick": "advanced", + "why": "Generator options are part of using generators; Simple gets the dice re-roll.", + "lists": "Flat, Normal, Rugged", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptSea", + "surface": "Setup wizard: Map", + "label": "Sea", + "kind": "dropdown", + "level": "conditional: Overland generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "Where the sea goes.", + "pick": "advanced", + "why": "Generator options are part of using generators; Simple gets the dice re-roll.", + "lists": "One side (random), N/E/S/W, island, scattered, none", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.genOptOther", + "surface": "Setup wizard: Map", + "label": "(other generator options)", + "kind": "dropdown", + "level": "conditional: another generator chosen", + "loc": "src/SetupWizardView.ts:647", + "desc": "Options of whichever other generator is picked (space, learned).", + "pick": "advanced", + "why": "Options of other generators are part of using generators; defaults and Re-roll cover Simple.", + "lists": "Per-generator option choices", + "focused": true, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.reroll", + "surface": "Setup wizard: Map", + "label": "Re-roll (dice)", + "kind": "button", + "level": "conditional: non-blank generator", + "loc": "src/SetupWizardView.ts:607", + "desc": "Generate again with a new random seed.", + "pick": "keep", + "why": "Simple and fun; replaces most generator options.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Map" + }, + { + "id": "Wizard.openHexMap", + "surface": "Setup wizard: Done", + "label": "Open hex map", + "kind": "button", + "level": "always (final step)", + "loc": "src/SetupWizardView.ts:841", + "desc": "Finish and open the new map.", + "pick": "keep", + "why": "Obvious action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Done" + }, + { + "id": "Wizard.exploreOnOwn", + "surface": "Setup wizard: Done", + "label": "I'll explore on my own", + "kind": "button", + "level": "always (final step)", + "loc": "src/SetupWizardView.ts:847", + "desc": "Finish without opening the map.", + "pick": "keep", + "why": "Fine secondary action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Done" + }, + { + "id": "Wizard.back", + "surface": "Setup wizard", + "label": "back", + "kind": "button", + "level": "always (not final step)", + "loc": "src/SetupWizardView.ts:943", + "desc": "Go to the previous step.", + "pick": "keep", + "why": "Standard navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Navigation" + }, + { + "id": "Wizard.next", + "surface": "Setup wizard", + "label": "Next", + "kind": "button", + "level": "always (not final step)", + "loc": "src/SetupWizardView.ts:957", + "desc": "Continue (runs that step's setup).", + "pick": "keep", + "why": "Standard navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Navigation" + }, + { + "id": "Wizard.remindLater", + "surface": "Setup wizard", + "label": "Remind me later", + "kind": "button", + "level": "always", + "loc": "src/SetupWizardView.ts:967", + "desc": "Close the wizard; it returns next launch.", + "pick": "keep", + "why": "Reasonable escape.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Navigation" + }, + { + "id": "Wizard.dontShowAgain", + "surface": "Setup wizard", + "label": "Don't show again", + "kind": "button", + "level": "always", + "loc": "src/SetupWizardView.ts:975", + "desc": "Close and never auto-open the wizard.", + "pick": "keep", + "why": "Reasonable escape; re-runnable from settings.", + "lists": "", + "focused": null, + "mix": "", + "group": "Setup wizard", + "subgroup": "Navigation" + }, + { + "id": "Hint.turnOnFeature", + "surface": "Advanced feature hints: Advanced hint (inline)", + "label": "Turn on ", + "kind": "button", + "level": "conditional: Simple, feature off, hint not closed", + "loc": "src/advancedHints.ts:158", + "desc": "Turns on the one hidden feature this hint is about.", + "pick": "keep", + "why": "Good ramp-up path, low cost.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Inline hints" + }, + { + "id": "Hint.close", + "surface": "Advanced feature hints: Advanced hint (inline, single and multi)", + "label": "X (Hide this hint)", + "kind": "button", + "level": "conditional: hint shown", + "loc": "src/advancedHints.ts:160", + "desc": "Hides this hint at this spot.", + "pick": "keep", + "why": "Must be dismissable.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Inline hints" + }, + { + "id": "Hints.show", + "surface": "Advanced feature hints: Advanced hints line (multi)", + "label": "Show", + "kind": "button", + "level": "conditional: Simple, 2+ features off", + "loc": "src/advancedHints.ts:191", + "desc": "Opens More options listing the hidden features.", + "pick": "keep", + "why": "One line instead of a stack of hints.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Inline hints" + }, + { + "id": "MoreFeatures.turnOn", + "surface": "Advanced feature hints: More options modal", + "label": "Turn on", + "kind": "button", + "level": "conditional: feature off", + "loc": "src/advancedHints.ts:235", + "desc": "Turns on one listed feature.", + "pick": "keep", + "why": "Focused, small modal.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "More options modal" + }, + { + "id": "MoreFeatures.turnOnAll", + "surface": "Advanced feature hints: More options modal", + "label": "Turn on all advanced features", + "kind": "button", + "level": "always", + "loc": "src/advancedHints.ts:241", + "desc": "Switches to Advanced.", + "pick": "keep", + "why": "Clear shortcut.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "More options modal" + }, + { + "id": "MoreFeatures.closeButtons", + "surface": "Advanced feature hints: More options modal", + "label": "Done", + "kind": "button", + "level": "always", + "loc": "src/advancedHints.ts:244", + "desc": "Closes the modal.", + "pick": "keep", + "why": "Standard close.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "More options modal" + }, + { + "id": "EnableFeature.turnOnOne", + "surface": "Advanced feature hints: Turn on ? modal", + "label": "Turn on ", + "kind": "button", + "level": "conditional: Simple user reaches a hidden feature", + "loc": "src/advancedHints.ts:274", + "desc": "Turns on just this feature, then continues.", + "pick": "keep", + "why": "Right moment to ask.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Turn on ? modal" + }, + { + "id": "EnableFeature.turnOnAll", + "surface": "Advanced feature hints: Turn on ? modal", + "label": "Turn on all advanced features", + "kind": "button", + "level": "conditional: as above", + "loc": "src/advancedHints.ts:276", + "desc": "Switches to Advanced, then continues.", + "pick": "keep", + "why": "Clear shortcut.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Turn on ? modal" + }, + { + "id": "EnableFeature.closeButtons", + "surface": "Advanced feature hints: Turn on ? modal", + "label": "Not now", + "kind": "button", + "level": "conditional: as above", + "loc": "src/advancedHints.ts:277", + "desc": "Closes without enabling.", + "pick": "keep", + "why": "Standard cancel.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Turn on ? modal" + }, + { + "id": "Nudge.turnOnAdvanced", + "surface": "Advanced feature hints: Ready for more? modal", + "label": "Turn on advanced features", + "kind": "button", + "level": "conditional: Simple, 2+ maps or 14 days", + "loc": "src/advancedHints.ts:318", + "desc": "Switches to Advanced.", + "pick": "keep", + "why": "One-time check-in; fine.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Ready for more? modal" + }, + { + "id": "Nudge.closeButtons", + "surface": "Advanced feature hints: Ready for more? modal", + "label": "Not now", + "kind": "button", + "level": "conditional: as above", + "loc": "src/advancedHints.ts:323", + "desc": "Closes; asks again in 14 days.", + "pick": "keep", + "why": "Standard cancel.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Ready for more? modal" + }, + { + "id": "Nudge.dontAskAgain", + "surface": "Advanced feature hints: Ready for more? modal", + "label": "Don't ask again", + "kind": "button", + "level": "conditional: as above", + "loc": "src/advancedHints.ts:324", + "desc": "Never show the check-in again.", + "pick": "keep", + "why": "Respects users who said no.", + "lists": "", + "focused": null, + "mix": "", + "group": "Feature hints", + "subgroup": "Ready for more? modal" + }, + { + "id": "Plugin.ribbonOpenHexMap", + "surface": "Command palette and ribbon", + "label": "Open hex map", + "kind": "ribbon", + "level": "always", + "loc": "src/HexmakerPlugin.ts:278", + "desc": "Opens the hex map.", + "pick": "simple", + "why": "The way into the plugin; pin it so no level ever hides it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openHexMap", + "surface": "Command palette and ribbon", + "label": "Open hex map", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:281", + "desc": "Opens the hex map.", + "pick": "keep", + "why": "Core.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openHexTable", + "surface": "Command palette and ribbon", + "label": "Open hex table", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:286", + "desc": "Opens the spreadsheet of hex notes.", + "pick": "simple", + "why": "The hex table is the basic overview of every hex; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openTerrainGenerator", + "surface": "Command palette and ribbon", + "label": "Open terrain generator", + "kind": "command", + "level": "always (prompts to enable in Simple)", + "loc": "src/HexmakerPlugin.ts:294", + "desc": "Opens the generator page.", + "pick": "keep", + "why": "Already feature-gated: in Simple it asks to turn generators on, which is the ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openPaletteEditor", + "surface": "Command palette and ribbon", + "label": "Open palette editor", + "kind": "command", + "level": "always (prompts to enable in Simple)", + "loc": "src/HexmakerPlugin.ts:299", + "desc": "Opens the palette editor page.", + "pick": "simple", + "why": "Custom palettes are Simple (owner tagged Add palette and Edit simple); the command should just open the editor. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views", + "prevPick": "keep" + }, + { + "id": "Plugin.cmd.editWorldTypes", + "surface": "Command palette and ribbon", + "label": "Edit world types...", + "kind": "command", + "level": "feature:generators", + "loc": "src/HexmakerPlugin.ts:304", + "desc": "Edits which worlds space generators place (Space on only).", + "pick": "keep", + "why": "World types are Advanced and this is already gated to generators and Space.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.newOverworld", + "surface": "Command palette and ribbon", + "label": "New overworld...", + "kind": "command", + "level": "feature:regions", + "loc": "src/HexmakerPlugin.ts:316", + "desc": "Creates an overworld that joins maps.", + "pick": "keep", + "why": "Already gated to the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "Plugin.cmd.openRandomTables", + "surface": "Command palette and ribbon", + "label": "Open random tables", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:355", + "desc": "Opens the random tables view.", + "pick": "simple", + "why": "Rolling tables is core to a hexcrawl; pin the command.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views" + }, + { + "id": "WorldTypes.command", + "surface": "Command palette and ribbon", + "label": "Edit world types…", + "kind": "command", + "level": "space (src/HexmakerPlugin.ts:311)", + "loc": "src/space/WorldTypesModal.ts:311", + "desc": "Opens the World types editor.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Plugin.cmd.editWorldTypes. Earlier reason: Same world types command as above; already gated to Space and generators.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Open views", + "twinOf": "Plugin.cmd.editWorldTypes" + }, + { + "id": "Plugin.cmd.mapGoUp", + "surface": "Command palette and ribbon", + "label": "Go up to parent map", + "kind": "command", + "level": "conditional: map has a parent", + "loc": "src/HexmakerPlugin.ts:325", + "desc": "Navigate to the parent map.", + "pick": "keep", + "why": "Hotkey-able navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Map navigation commands" + }, + { + "id": "Plugin.cmd.mapGoBack", + "surface": "Command palette and ribbon", + "label": "Go back to previous map", + "kind": "command", + "level": "conditional: map history", + "loc": "src/HexmakerPlugin.ts:335", + "desc": "Back in map history.", + "pick": "keep", + "why": "Navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Map navigation commands" + }, + { + "id": "Plugin.cmd.mapGoForward", + "surface": "Command palette and ribbon", + "label": "Go forward to the next map", + "kind": "command", + "level": "conditional: map history", + "loc": "src/HexmakerPlugin.ts:345", + "desc": "Forward in map history.", + "pick": "keep", + "why": "Navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Map navigation commands" + }, + { + "id": "Plugin.cmd.addRollRanges", + "surface": "Command palette and ribbon", + "label": "Add roll ranges to tables", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:363", + "desc": "Adds roll-range columns to older tables.", + "pick": "overkill", + "why": "Migration/maintenance command; already offered automatically after an update.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Maintenance commands" + }, + { + "id": "Plugin.cmd.checkTables", + "surface": "Command palette and ribbon", + "label": "Check tables", + "kind": "command", + "level": "always", + "loc": "src/HexmakerPlugin.ts:368", + "desc": "Checks table notes for problems.", + "pick": "overkill", + "why": "Diagnostic command for table notes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Maintenance commands" + }, + { + "id": "Plugin.cmd.addMapDataToHexNotes", + "surface": "Command palette and ribbon", + "label": "Add map data to this map's hex notes", + "kind": "command", + "level": "conditional: a map is open", + "loc": "src/HexmakerPlugin.ts:416", + "desc": "Adds a Map data box to every hex note (asks first).", + "pick": "overkill", + "why": "Backfill maintenance for older hex notes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Maintenance commands" + }, + { + "id": "Plugin.cmd.updateRegionFactionMapData", + "surface": "Command palette and ribbon", + "label": "Update map data in region and faction notes", + "kind": "command", + "level": "conditional: region/faction notes exist", + "loc": "src/HexmakerPlugin.ts:438", + "desc": "Adds/refreshes Map data boxes in region and faction notes.", + "pick": "overkill", + "why": "Backfill maintenance; notes refresh on open anyway.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Maintenance commands" + }, + { + "id": "Plugin.cmd.exportNotePdf", + "surface": "Command palette and ribbon", + "label": "Export current note to PDF", + "kind": "command", + "level": "conditional: markdown note active", + "loc": "src/HexmakerPlugin.ts:373", + "desc": "Exports the active note as PDF.", + "pick": "advanced", + "why": "Export option beyond hexcrawl basics; Obsidian also exports notes itself.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.cmd.exportNoteMarkdown", + "surface": "Command palette and ribbon", + "label": "Export current note to Markdown", + "kind": "command", + "level": "conditional: markdown note active", + "loc": "src/HexmakerPlugin.ts:383", + "desc": "Exports the active note as Markdown.", + "pick": "advanced", + "why": "Export option beyond hexcrawl basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.cmd.exportCurrentHex", + "surface": "Command palette and ribbon", + "label": "Export current hex (structured PDF / Markdown)", + "kind": "command", + "level": "conditional: hex note active", + "loc": "src/HexmakerPlugin.ts:393", + "desc": "Structured export of a hex note.", + "pick": "simple", + "why": "Basic export of one hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.cmd.exportCurrentWorkflow", + "surface": "Command palette and ribbon", + "label": "Export current workflow with rolled samples", + "kind": "command", + "level": "conditional: workflow note active", + "loc": "src/HexmakerPlugin.ts:403", + "desc": "Exports a workflow with sample rolls.", + "pick": "advanced", + "why": "Workflow export belongs with workflows, an Advanced feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.cmd.exportCurrentMap", + "surface": "Command palette and ribbon", + "label": "Export current map...", + "kind": "command", + "level": "conditional: a map exists", + "loc": "src/HexmakerPlugin.ts:456", + "desc": "Opens map export (PNG / PDF / manual).", + "pick": "simple", + "why": "Basic export: the map export entry point.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Export commands" + }, + { + "id": "Plugin.fileMenuExportPdf", + "surface": "Note right-click menus: File menu (right-click any note)", + "label": "Export to PDF", + "kind": "menu", + "level": "always (every .md file in vault)", + "loc": "src/HexmakerPlugin.ts:473", + "desc": "Exports any note as PDF.", + "pick": "advanced", + "why": "Export option beyond the basics; adds a menu item to every note.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "Plugin.fileMenuExportMarkdown", + "surface": "Note right-click menus: File menu (right-click any note)", + "label": "Export to Markdown", + "kind": "menu", + "level": "always (every .md file in vault)", + "loc": "src/HexmakerPlugin.ts:480", + "desc": "Exports any note as Markdown.", + "pick": "advanced", + "why": "Export option beyond the basics; adds a menu item to every note.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "Plugin.editorMenuInsertRoller", + "surface": "Note right-click menus: Editor menu (right-click in editor)", + "label": "Insert table roller", + "kind": "menu", + "level": "always (every editor)", + "loc": "src/HexmakerPlugin.ts:506", + "desc": "Inserts an embedded roller for a chosen table.", + "pick": "keep", + "why": "Useful in session notes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "Plugin.editorMenuInsertMapLink", + "surface": "Note right-click menus: Editor menu (right-click in editor)", + "label": "Insert map link", + "kind": "menu", + "level": "always (every editor)", + "loc": "src/HexmakerPlugin.ts:523", + "desc": "Inserts a link that opens a map.", + "pick": "keep", + "why": "Useful linking.", + "lists": "", + "focused": null, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "Plugin.insertRollerPicker", + "surface": "Note right-click menus: Insert table roller picker", + "label": "Search for a file to link...", + "kind": "picker", + "level": "conditional: from editor menu", + "loc": "src/hex-map/FileLinkSuggestModal.ts:19", + "desc": "Pick a table file to embed as a roller.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Editor.insertTableRoller. Earlier reason: Scoped to the tables folder.", + "lists": "Files under the tables folder (any extension)", + "focused": true, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus", + "twinOf": "Editor.insertTableRoller" + }, + { + "id": "Editor.insertTableRoller", + "surface": "Note right-click menus: Editor context menu → Insert table roller", + "label": "Search for a file to link...", + "kind": "picker", + "level": "always", + "loc": "src/HexmakerPlugin.ts:512", + "desc": "Pick a table to embed a roller block in the note.", + "pick": "keep", + "why": "Focused on tables", + "lists": "every file (no extension filter) under tablesFolder minus templates/_ : user tables + per-terrain description/encounter tables + region tables", + "focused": true, + "mix": "", + "group": "Commands & menus", + "subgroup": "Note right-click menus" + }, + { + "id": "MapToolbar.hexTableBtn", + "surface": "Hex map view: top bar", + "label": "Open hex table (⊞)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1473", + "desc": "Opens a spreadsheet of every hex note; middle-click for a new tab.", + "pick": "simple", + "why": "The hex table is the basic overview of every hex; pin its button.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.randomTablesBtn", + "surface": "Hex map view: top bar", + "label": "Open random tables (🎲)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1497", + "desc": "Opens the random tables browser to roll encounters and more.", + "pick": "simple", + "why": "Rolling tables is core to a hexcrawl; pin the toolbar entry.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.mapSwitcher", + "surface": "Hex map view: top bar", + "label": " ▾ (Manage maps)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1529", + "desc": "Opens the map list to switch, create, rename or set up maps.", + "pick": "keep", + "why": "The one place to pick/manage maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.workModeBtn", + "surface": "Hex map view: top bar", + "label": "Mode: Play / Build / God", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1551", + "desc": "Shows this map's mode; click to switch between Play, Build and God.", + "pick": "simple", + "why": "Play/Build is how a newcomer stops editing during a game; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.undo", + "surface": "Hex map view: top bar", + "label": "Undo (up to 20) ↩", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1555", + "desc": "Undo the last map change.", + "pick": "keep", + "why": "Essential safety net.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.redo", + "surface": "Hex map view: top bar", + "label": "Redo ↪", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1565", + "desc": "Redo what you just undid.", + "pick": "keep", + "why": "Pairs with undo.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.help", + "surface": "Hex map view: top bar", + "label": "Controls & tools (?)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1577", + "desc": "Opens the help sheet of mouse controls and tools.", + "pick": "keep", + "why": "Newcomer lifeline.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.drawingToolsToggle", + "surface": "Hex map view: top bar", + "label": "Drawing tools (pencil)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:22", + "desc": "Opens the panel of painting and drawing tools.", + "pick": "keep", + "why": "Entry point to all editing tools.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapToolbar.layersToggle", + "surface": "Hex map view: top bar", + "label": "Map overlays (layers)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:22", + "desc": "Opens the panel that shows or hides map layers and labels.", + "pick": "keep", + "why": "Entry to visibility toggles.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Top bar" + }, + { + "id": "MapNav.breadcrumb", + "surface": "Hex map view: map navigation", + "label": "Go to (breadcrumb)", + "kind": "button", + "level": "conditional: on a submap", + "loc": "src/hex-map/HexMapView.ts:690", + "desc": "Jump to any parent map above this one.", + "pick": "keep", + "why": "Clear way out of nested maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.back", + "surface": "Hex map view: map navigation", + "label": "← Back to (Alt+←)", + "kind": "button", + "level": "conditional: after moving between maps", + "loc": "src/hex-map/HexMapView.ts:723", + "desc": "Return to the map you were on before.", + "pick": "keep", + "why": "Expected browser-like navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.up", + "surface": "Hex map view: map navigation", + "label": "↑ Up to (Alt+↑)", + "kind": "button", + "level": "conditional: after moving between maps", + "loc": "src/hex-map/HexMapView.ts:723", + "desc": "Go to the parent map of this one.", + "pick": "keep", + "why": "Core for nested maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.forward", + "surface": "Hex map view: map navigation", + "label": "→ Forward to (Alt+→)", + "kind": "button", + "level": "conditional: after moving between maps", + "loc": "src/hex-map/HexMapView.ts:723", + "desc": "Go forward again after going back.", + "pick": "keep", + "why": "Standard back/forward navigation; only shows after moving between maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.regionFlowerHere", + "surface": "Hex map view: map navigation", + "label": "Here: . Click to edit this region.", + "kind": "button", + "level": "conditional: inside a region of an overworld", + "loc": "src/hex-map/HexMapView.ts:859", + "desc": "Centre petal of the neighbour flower; opens the region editor.", + "pick": "keep", + "why": "Only shows inside an overworld region, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.regionFlowerPetal", + "surface": "Hex map view: map navigation", + "label": " petal", + "kind": "button", + "level": "conditional: inside a region of an overworld", + "loc": "src/hex-map/HexMapView.ts:878", + "desc": "Jump to the neighbouring region in that direction.", + "pick": "keep", + "why": "Fast walk between adjacent regions.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.regionFlowerNewLand", + "surface": "Hex map view: map navigation", + "label": "+ (new land petal)", + "kind": "button", + "level": "conditional: region of overworld; mode: build/god", + "loc": "src/hex-map/HexMapView.ts:878", + "desc": "Walk into empty land next door: pick or roll its biome and make a region.", + "pick": "keep", + "why": "Core overworld-building action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.mapPadGo", + "surface": "Hex map view: map navigation", + "label": "D-pad neighbour map (◀▲▶▼)", + "kind": "button", + "level": "conditional: map on a side-by-side world grid", + "loc": "src/hex-map/HexMapView.ts:921", + "desc": "Jump to the neighbouring map on that side.", + "pick": "keep", + "why": "Only shows on side-by-side world grids, which are already an advanced setup.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "MapNav.mapPadNew", + "surface": "Hex map view: map navigation", + "label": "+ (new neighbouring map)", + "kind": "button", + "level": "feature:regions", + "loc": "src/hex-map/HexMapView.ts:921", + "desc": "Make a new map on that side (asks for a terrain generator).", + "pick": "keep", + "why": "Already gated to the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Map navigation" + }, + { + "id": "WorkModeMenu.play", + "surface": "Hex map view: work-mode menu", + "label": "Play: Run a game…", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:758", + "desc": "Lock the map; move tokens, read notes and roll only.", + "pick": "simple", + "why": "Play is the safe mode for running sessions; pin it (God stays Advanced).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "WorkModeMenu.build", + "surface": "Hex map view: work-mode menu", + "label": "Build: Add to and edit the map…", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:758", + "desc": "Paint, draw paths, make maps and regions.", + "pick": "simple", + "why": "Build is where all map-making happens; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "WorkModeMenu.god", + "surface": "Hex map view: work-mode menu", + "label": "God: Change anything…", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:758", + "desc": "Unlocks rerolls, regenerating, swapping hexes and deleting.", + "pick": "advanced", + "why": "God mode is a real feature (rerolls, swaps, deletes) beyond what a newcomer needs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.stop", + "surface": "Hex map view: mode bar", + "label": "Stop this tool (✕)", + "kind": "button", + "level": "conditional: a tool is on", + "loc": "src/hex-map/HexMapView.ts:1032", + "desc": "Turn off the active tool.", + "pick": "keep", + "why": "Obvious exit; shows what's active.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.autoRoute", + "surface": "Hex map view: mode bar", + "label": "Auto-route", + "kind": "toggle", + "level": "conditional: path tool on", + "loc": "src/hex-map/pathTool.ts:1423", + "desc": "On: a far click routes around terrain. Off: draw hex by hex.", + "pick": "simple", + "why": "Same basic path choice while drawing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.crossImpassable", + "surface": "Hex map view: mode bar", + "label": "Cross impassable", + "kind": "checkbox", + "level": "conditional: path tool, palette has impassable terrain", + "loc": "src/hex-map/pathTool.ts:1453", + "desc": "Let new path legs go through impassable terrain like water.", + "pick": "advanced", + "why": "A path-drawing option beyond the basics; only shows when relevant.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.pathNameChip", + "surface": "Hex map view: mode bar", + "label": " (Rename this path)", + "kind": "button", + "level": "conditional: a path is selected", + "loc": "src/hex-map/pathTool.ts:1462", + "desc": "Shows the selected path's name; click to rename.", + "pick": "keep", + "why": "Shows which path is selected; a plain, useful label.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.newPath", + "surface": "Hex map view: mode bar", + "label": "New path", + "kind": "button", + "level": "conditional: path tool on", + "loc": "src/hex-map/pathTool.ts:1469", + "desc": "Start a separate path with the next click (Alt+click does the same).", + "pick": "simple", + "why": "Needed to draw a second road.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.done", + "surface": "Hex map view: mode bar", + "label": "Done", + "kind": "button", + "level": "conditional: path selected or drawing", + "loc": "src/hex-map/pathTool.ts:1477", + "desc": "Finish this branch or deselect the path (Esc).", + "pick": "simple", + "why": "Finishing a path is basic drawing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "ModeBar.confirmIntoRegions", + "surface": "Hex map view: mode bar", + "label": "Confirm into regions / Update regions", + "kind": "button", + "level": "conditional: overworld path selected, build", + "loc": "src/hex-map/HexMapView.ts:6253", + "desc": "Copy this overworld path into every region it crosses.", + "pick": "keep", + "why": "Only shows for overworld paths, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Work modes" + }, + { + "id": "DrawingPanel.centerHex", + "surface": "Hex map view: drawing tools panel", + "label": "Center hex", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2023", + "desc": "Type coordinates to jump the view to that hex.", + "pick": "keep", + "why": "Plain navigation a normal user uses; placement can be fixed separately.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.terrain", + "surface": "Hex map view: drawing tools panel", + "label": "Terrain", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2031", + "desc": "Pick a terrain and paint it on hexes (brush size, eyedropper).", + "pick": "keep", + "why": "Core map painting.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.biome", + "surface": "Hex map view: drawing tools panel", + "label": "Biome", + "kind": "button", + "level": "conditional: overworld; mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2043", + "desc": "Pick a biome and paint it on the overworld; regions are made as you go.", + "pick": "keep", + "why": "The overworld's core paint tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.icon", + "surface": "Hex map view: drawing tools panel", + "label": "Icon", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2051", + "desc": "Pick an icon and stamp it on hexes (optionally GM-only).", + "pick": "keep", + "why": "Core for marking features.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.path", + "surface": "Hex map view: drawing tools panel", + "label": "Path", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2062", + "desc": "Draw roads, rivers and other paths across hexes.", + "pick": "simple", + "why": "Drawing roads and rivers is basic map-making.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.linkTable", + "surface": "Hex map view: drawing tools panel", + "label": "Link table", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2073", + "desc": "Pick a random table, then click hexes to link it as their encounter table.", + "pick": "advanced", + "why": "Bulk table linking is a real feature beyond the basics; the hex editor covers one-offs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.linkSubmap", + "surface": "Hex map view: drawing tools panel", + "label": "Link submap", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2083", + "desc": "Pick a map, then click hexes to link it as a location.", + "pick": "advanced", + "why": "Bulk submap linking is a real feature, though rarely used; the hex menu covers one-offs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.factions", + "surface": "Hex map view: drawing tools panel", + "label": "Factions", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2093", + "desc": "Pick a faction and paint its territory on hexes.", + "pick": "keep", + "why": "Faction territory is a common hexcrawl layer.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.regionAreas", + "surface": "Hex map view: drawing tools panel", + "label": "Region areas", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:2103", + "desc": "Paint named geographic areas (overlay) onto hexes.", + "pick": "advanced", + "why": "Region areas overlay is a real feature beyond a newcomer's needs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "DrawingPanel.token", + "surface": "Hex map view: drawing tools panel", + "label": "Token", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2113", + "desc": "Make or pick a token (party, NPC) and place it on a hex.", + "pick": "simple", + "why": "Placing the party is token basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools" + }, + { + "id": "MapView.tableLinkToolPicker", + "surface": "Hex map view: Map toolbar › Link table tool", + "label": "Select table", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:2424", + "desc": "Pick a random table, then click hexes to link it.", + "pick": "advanced", + "why": "The picker this control opens; it follows DrawingPanel.linkTable. Earlier reason: Focused on tables, but terrain tables crowd it", + "lists": ".md under tablesFolder, linkable: user tables + 2 tables per terrain (terrain/…) + region tables + weather/hooks starters (FolderTreePickerModal.ts:105-113)", + "focused": true, + "mix": "", + "group": "Hex map view", + "subgroup": "Drawing tools", + "twinOf": "DrawingPanel.linkTable", + "prevPick": "keep" + }, + { + "id": "PainterMenu.switchTerrain", + "surface": "Hex map view: tool right-click menu", + "label": "Switch terrain", + "kind": "menu", + "level": "conditional: terrain tool on", + "loc": "src/hex-map/HexMapView.ts:2145", + "desc": "Re-open the terrain picker.", + "pick": "keep", + "why": "Natural in-tool action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchIcon", + "surface": "Hex map view: tool right-click menu", + "label": "Switch icon", + "kind": "menu", + "level": "conditional: icon tool on", + "loc": "src/hex-map/HexMapView.ts:2149", + "desc": "Re-open the icon picker.", + "pick": "keep", + "why": "Natural in-tool action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchTable", + "surface": "Hex map view: tool right-click menu", + "label": "Switch table", + "kind": "menu", + "level": "conditional: link-table tool on", + "loc": "src/hex-map/HexMapView.ts:2153", + "desc": "Pick a different table to link.", + "pick": "keep", + "why": "Matches its tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchSubmap", + "surface": "Hex map view: tool right-click menu", + "label": "Switch submap", + "kind": "menu", + "level": "conditional: link-submap tool on", + "loc": "src/hex-map/HexMapView.ts:2157", + "desc": "Pick a different map to link.", + "pick": "keep", + "why": "Only shows while the Link submap tool is on; gating the tool covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchFaction", + "surface": "Hex map view: tool right-click menu", + "label": "Switch faction", + "kind": "menu", + "level": "conditional: factions tool on", + "loc": "src/hex-map/HexMapView.ts:2161", + "desc": "Pick a different faction to paint.", + "pick": "keep", + "why": "Matches its tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchRegion", + "surface": "Hex map view: tool right-click menu", + "label": "Switch region", + "kind": "menu", + "level": "conditional: region areas tool on", + "loc": "src/hex-map/HexMapView.ts:2165", + "desc": "Pick a different region area to paint.", + "pick": "keep", + "why": "Only shows while the Region areas tool is on; gating the tool covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchPathType", + "surface": "Hex map view: tool right-click menu", + "label": "Switch path type", + "kind": "menu", + "level": "conditional: path tool on", + "loc": "src/hex-map/HexMapView.ts:2169", + "desc": "Pick a different path type (road, river…).", + "pick": "keep", + "why": "Natural in-tool action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchToken", + "surface": "Hex map view: tool right-click menu", + "label": "Switch token", + "kind": "menu", + "level": "conditional: token tool on", + "loc": "src/hex-map/HexMapView.ts:2173", + "desc": "Pick a different token to place.", + "pick": "keep", + "why": "Matches its tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.switchBiome", + "surface": "Hex map view: tool right-click menu", + "label": "Switch biome", + "kind": "menu", + "level": "conditional: biome tool on", + "loc": "src/hex-map/HexMapView.ts:2176", + "desc": "Pick a different biome to paint.", + "pick": "keep", + "why": "Matches its tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.exitTool", + "surface": "Hex map view: tool right-click menu", + "label": "Exit tool", + "kind": "menu", + "level": "conditional: any tool on", + "loc": "src/hex-map/PainterContextMenu.ts:24", + "desc": "Turn off the active tool.", + "pick": "keep", + "why": "Obvious; cheap.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.eraseToggle", + "surface": "Hex map view: tool right-click menu", + "label": "Erase mode / Paint (Link, Draw) mode", + "kind": "menu", + "level": "conditional: terrain/icon/link/path tool on", + "loc": "src/hex-map/HexMapView.ts:2146", + "desc": "Flip the tool between adding and erasing.", + "pick": "keep", + "why": "Only way to erase with a tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PainterMenu.newPath", + "surface": "Hex map view: tool right-click menu", + "label": "New path", + "kind": "menu", + "level": "conditional: path tool on, not erasing", + "loc": "src/hex-map/HexMapView.ts:2171", + "desc": "Start a separate path with the next click.", + "pick": "drop", + "why": "Third way to start a new path; the mode bar's New path button (and Alt+click) replace it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.splitHere", + "surface": "Hex map view: tool right-click menu", + "label": "Split here", + "kind": "menu", + "level": "conditional: right-click on a path (path tool)", + "loc": "src/hex-map/pathTool.ts:296", + "desc": "Cut the path in two at this point.", + "pick": "advanced", + "why": "Path surgery is a real editing option beyond what a newcomer needs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.deleteBranch", + "surface": "Hex map view: tool right-click menu", + "label": "Delete this fork / Delete main line", + "kind": "menu", + "level": "conditional: path with forks", + "loc": "src/hex-map/pathTool.ts:297", + "desc": "Remove just this branch of a forked path.", + "pick": "keep", + "why": "Only shows on forked paths; deleting a fork is normal path editing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.deletePath", + "surface": "Hex map view: tool right-click menu", + "label": "Delete path: ", + "kind": "menu", + "level": "conditional: right-click on a path", + "loc": "src/hex-map/pathTool.ts:299", + "desc": "Delete the whole path.", + "pick": "simple", + "why": "Basic path fix: remove a path.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.rename", + "surface": "Hex map view: tool right-click menu", + "label": "Rename…", + "kind": "menu", + "level": "conditional: right-click on a path", + "loc": "src/hex-map/pathTool.ts:300", + "desc": "Give the path a name.", + "pick": "simple", + "why": "Named roads and rivers matter in play.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.changeType", + "surface": "Hex map view: tool right-click menu", + "label": "Change type…", + "kind": "menu", + "level": "conditional: right-click on a path", + "loc": "src/hex-map/pathTool.ts:301", + "desc": "Turn the path into another type (e.g. trail to road).", + "pick": "keep", + "why": "Normal path fix-up (trail to road), used by anyone drawing paths.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.reverse", + "surface": "Hex map view: tool right-click menu", + "label": "Reverse", + "kind": "menu", + "level": "conditional: right-click on a path", + "loc": "src/hex-map/pathTool.ts:302", + "desc": "Flip the path's direction.", + "pick": "advanced", + "why": "A real path option, but direction rarely matters to a newcomer.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.switchToType", + "surface": "Hex map view: tool right-click menu", + "label": "Switch to to edit ", + "kind": "menu", + "level": "conditional: right-click on another type's path", + "loc": "src/hex-map/pathTool.ts:1075", + "desc": "Switch the path tool to that path's type to edit it.", + "pick": "keep", + "why": "Resolves a confusing dead click.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.confirmIntoRegions", + "surface": "Hex map view: tool right-click menu", + "label": "Confirm into regions / Update regions", + "kind": "menu", + "level": "conditional: overworld path, build", + "loc": "src/hex-map/HexMapView.ts:6274", + "desc": "Copy this overworld path into the regions it crosses.", + "pick": "keep", + "why": "Only shows for overworld paths, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "PathMenu.removeFromRegions", + "surface": "Hex map view: tool right-click menu", + "label": "Remove from regions", + "kind": "menu", + "level": "conditional: confirmed overworld path", + "loc": "src/hex-map/HexMapView.ts:6274", + "desc": "Take this overworld path back out of its regions.", + "pick": "keep", + "why": "Only shows for confirmed overworld paths, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Tool right-click menus" + }, + { + "id": "HexMenu.center", + "surface": "Hex map view: hex right-click menu", + "label": "Center on this hex", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4773", + "desc": "Pan the view so this hex is in the middle.", + "pick": "keep", + "why": "Harmless, standard map-menu action; not backend.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.openNote", + "surface": "Hex map view: hex right-click menu", + "label": "Open note", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4777", + "desc": "Open (or create) this hex's note.", + "pick": "keep", + "why": "Core: notes are the content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.enterRegion", + "surface": "Hex map view: hex right-click menu", + "label": "Enter region: ", + "kind": "menu", + "level": "conditional: hex has a region map", + "loc": "src/hex-map/HexMapView.ts:4792", + "desc": "Go into the region map made from this hex.", + "pick": "keep", + "why": "Core nested-map navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.openLocation", + "surface": "Hex map view: hex right-click menu", + "label": "Open: ", + "kind": "menu", + "level": "conditional: hex has 1-2 linked maps", + "loc": "src/hex-map/HexMapView.ts:4795", + "desc": "Go to a map linked from this hex (town, dungeon).", + "pick": "keep", + "why": "Core nested-map navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.locationsList", + "surface": "Hex map view: hex right-click menu", + "label": "Locations (n)…", + "kind": "menu", + "level": "conditional: hex has 3+ linked maps", + "loc": "src/hex-map/HexMapView.ts:4801", + "desc": "List every map linked from this hex.", + "pick": "keep", + "why": "Scales when many locations.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.newMap", + "surface": "Hex map view: hex right-click menu", + "label": "New map from this hex…", + "kind": "menu", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:4803", + "desc": "Make a new map (town, dungeon, region) linked to this hex.", + "pick": "keep", + "why": "Main way to add detail maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.linkExistingMap", + "surface": "Hex map view: hex right-click menu", + "label": "Link existing map…", + "kind": "menu", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:4804", + "desc": "Link a map you already have to this hex.", + "pick": "keep", + "why": "Standard way to attach a town or dungeon map you already made.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.manageLocations", + "surface": "Hex map view: hex right-click menu", + "label": "Manage locations…", + "kind": "menu", + "level": "conditional: hex has linked maps; build", + "loc": "src/hex-map/HexMapView.ts:4807", + "desc": "Open the list to unlink or reorder this hex's maps.", + "pick": "keep", + "why": "The way to unlink or reorder a hex's maps when it has only one or two.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.linkTable", + "surface": "Hex map view: hex right-click menu", + "label": "Link table", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4810", + "desc": "Pick a random table to link as this hex's encounter table.", + "pick": "keep", + "why": "Linking an encounter table to a hex is standard hexcrawl use.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.swapHex", + "surface": "Hex map view: hex right-click menu", + "label": "Swap hex", + "kind": "menu", + "level": "mode: god", + "loc": "src/hex-map/HexMapView.ts:4828", + "desc": "Swap this hex's contents with another hex.", + "pick": "keep", + "why": "Already gated to God mode.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.createToken", + "surface": "Hex map view: hex right-click menu", + "label": "Create token here", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4833", + "desc": "Make a new token on this hex.", + "pick": "simple", + "why": "Quickest way to put the party on a hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.clearTerrain", + "surface": "Hex map view: hex right-click menu", + "label": "Clear terrain", + "kind": "menu", + "level": "conditional: hex has terrain; build", + "loc": "src/hex-map/HexMapView.ts:4839", + "desc": "Remove this hex's terrain.", + "pick": "keep", + "why": "Standard one-hex fix; not everyone reaches for the erase tool.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.removeIconOverride", + "surface": "Hex map view: hex right-click menu", + "label": "Remove icon override", + "kind": "menu", + "level": "conditional: hex has icon override; build", + "loc": "src/hex-map/HexMapView.ts:4844", + "desc": "Remove the custom icon stamped on this hex.", + "pick": "keep", + "why": "Standard one-hex fix (the label could lose the jargon).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "HexMenu.lockedHint", + "surface": "Hex map view: hex right-click menu", + "label": "Switch to Build to … (disabled)", + "kind": "menu", + "level": "conditional: mode hides items", + "loc": "src/hex-map/modeMenu.ts:52", + "desc": "One greyed line saying which mode unlocks hidden items.", + "pick": "keep", + "why": "Explains missing items without clutter.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu" + }, + { + "id": "MapView.linkTableMenuPicker", + "surface": "Hex map view: Hex right-click › Link table", + "label": "Link table", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4811", + "desc": "Link one table to this hex.", + "pick": "keep", + "why": "The picker this control opens; it follows HexMenu.linkTable. Earlier reason: Same list as the tool", + "lists": ".md under tablesFolder, linkable (same as tool)", + "focused": true, + "mix": "", + "group": "Hex map view", + "subgroup": "Hex right-click menu", + "twinOf": "HexMenu.linkTable" + }, + { + "id": "OverworldMenu.enterRegion", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Enter region: ", + "kind": "menu", + "level": "conditional: hex has a region", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "Go into this overworld hex's region map.", + "pick": "keep", + "why": "Core overworld navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.editRegion", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Edit region…", + "kind": "menu", + "level": "conditional: hex has a region", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "Edit the region's name, biome and notes.", + "pick": "keep", + "why": "Main region editing entry.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.setBiome", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Set biome…", + "kind": "menu", + "level": "conditional: empty overworld hex", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "Pick a biome for an empty overworld hex (makes a region).", + "pick": "keep", + "why": "How empty land starts.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.center", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Center on this hex", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "Pan the view so this hex is in the middle.", + "pick": "keep", + "why": "Same harmless centre action as the hex menu; overworld already gated.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.locations", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Locations (n)…", + "kind": "menu", + "level": "conditional: hex has linked maps", + "loc": "src/hex-map/HexMapView.ts:4871", + "desc": "List maps linked from this overworld hex.", + "pick": "keep", + "why": "Navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMenu.createToken", + "surface": "Hex map view: overworld hex right-click menu", + "label": "Create token here", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4882", + "desc": "Put a token (e.g. the party) on this overworld hex.", + "pick": "keep", + "why": "Placing the party on the overworld is normal use; overworld already gated.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.viewRegions", + "surface": "Hex map view: overworld minimap", + "label": "View: Regions", + "kind": "radio", + "level": "conditional: overworld", + "loc": "src/hex-map/overworldMinimap.ts:61", + "desc": "Show every region's hexes stitched together.", + "pick": "keep", + "why": "Core overworld view switch.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.viewBiomes", + "surface": "Hex map view: overworld minimap", + "label": "View: Biomes", + "kind": "radio", + "level": "conditional: overworld", + "loc": "src/hex-map/overworldMinimap.ts:61", + "desc": "Show one biome per hex.", + "pick": "keep", + "why": "Core overworld view switch.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.biomeLibrary", + "surface": "Hex map view: overworld minimap", + "label": "Biomes…", + "kind": "button", + "level": "conditional: overworld, Biomes view", + "loc": "src/hex-map/overworldMinimap.ts:71", + "desc": "Add your own biomes or edit the built-in ones.", + "pick": "keep", + "why": "Biome library, already only on overworlds (regions feature).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.toggle", + "surface": "Hex map view: overworld minimap", + "label": "Show / Hide the overworld map", + "kind": "button", + "level": "conditional: in a region of an overworld", + "loc": "src/hex-map/overworldMinimap.ts:79", + "desc": "Expand or collapse the overworld minimap.", + "pick": "keep", + "why": "Simple show/hide.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "Minimap.canvasClick", + "surface": "Hex map view: overworld minimap", + "label": "Overworld minimap (click to go)", + "kind": "button", + "level": "conditional: minimap expanded", + "loc": "src/hex-map/overworldMinimap.ts:122", + "desc": "Click a region on the minimap to go there.", + "pick": "keep", + "why": "Fast overworld navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap" + }, + { + "id": "OverworldMinimap.viewRegions", + "surface": "Overworld minimap", + "label": "View: Regions", + "kind": "button", + "level": "conditional: on an overworld (feature:regions)", + "loc": "src/hex-map/overworldMinimap.ts:393", + "desc": "Shows the overworld as stitched region hexes.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.viewRegions. Earlier reason: Region basics on an overworld: shows today on any overworld at any level; pin so walking an existing overworld never hides.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.viewRegions", + "prevPick": "simple" + }, + { + "id": "OverworldMinimap.viewBiomes", + "surface": "Overworld minimap", + "label": "View: Biomes", + "kind": "button", + "level": "conditional: on an overworld (feature:regions)", + "loc": "src/hex-map/overworldMinimap.ts:393", + "desc": "Shows the overworld as one biome per hex.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.viewBiomes. Earlier reason: Region basics on an overworld: the other half of the view switch; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.viewBiomes", + "prevPick": "simple" + }, + { + "id": "OverworldMinimap.biomes", + "surface": "Overworld minimap", + "label": "Biomes…", + "kind": "button", + "level": "conditional: overworld in Biomes view", + "loc": "src/hex-map/overworldMinimap.ts:403", + "desc": "Opens the biome library.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.biomeLibrary. Earlier reason: Already regions-gated; the biome library.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.biomeLibrary" + }, + { + "id": "OverworldMinimap.toggle", + "surface": "Overworld minimap", + "label": "Show/Hide the overworld map", + "kind": "button", + "level": "conditional: on an overworld or one of its regions", + "loc": "src/hex-map/overworldMinimap.ts:411", + "desc": "Collapses or expands the minimap.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.toggle. Earlier reason: Region basics on an overworld: show or hide the minimap; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.toggle", + "prevPick": "simple" + }, + { + "id": "OverworldMinimap.canvasClick", + "surface": "Overworld minimap", + "label": "(minimap hex click)", + "kind": "button", + "level": "conditional: minimap expanded", + "loc": "src/hex-map/overworldMinimap.ts:454", + "desc": "Click a hex to go to its region, or show it on the overworld.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows Minimap.canvasClick. Earlier reason: Region basics on an overworld: click to go there; pin it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "Minimap.canvasClick", + "prevPick": "simple" + }, + { + "id": "OverworldMenu.enterRegion_2", + "surface": "Overworld hex right-click menu", + "label": "Enter region", + "kind": "menu", + "level": "conditional: hex has a region", + "loc": "src/overworld/overworldInput.ts:71", + "desc": "Goes into the hex's region map.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.enterRegion. Earlier reason: Core navigation (also left click).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.enterRegion" + }, + { + "id": "OverworldMenu.editRegion_2", + "surface": "Overworld hex right-click menu", + "label": "Edit region…", + "kind": "menu", + "level": "conditional: hex has a region", + "loc": "src/overworld/overworldInput.ts:72", + "desc": "Opens name, biome, facts and notes for the region.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.editRegion. Earlier reason: Core.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.editRegion" + }, + { + "id": "OverworldMenu.setBiome_2", + "surface": "Overworld hex right-click menu", + "label": "Set biome…", + "kind": "menu", + "level": "mode: build/god (disabled in Play)", + "loc": "src/overworld/overworldInput.ts:75", + "desc": "Places a biome on an empty hex.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.setBiome. Earlier reason: Core build action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.setBiome" + }, + { + "id": "OverworldMenu.center_2", + "surface": "Overworld hex right-click menu", + "label": "Center on this hex", + "kind": "menu", + "level": "always", + "loc": "src/overworld/overworldInput.ts:77", + "desc": "Pans the view to this hex.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.center. Earlier reason: Harmless, standard map-menu action; same as the hex menu.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.center" + }, + { + "id": "OverworldMenu.locations_2", + "surface": "Overworld hex right-click menu", + "label": "Locations (n)…", + "kind": "menu", + "level": "conditional: hex has locations", + "loc": "src/overworld/overworldInput.ts:78", + "desc": "Lists the hex's locations.", + "pick": "keep", + "why": "Same control inventoried twice (another render path or pass); follows OverworldMenu.locations. Earlier reason: Core navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Overworld menu & minimap", + "twinOf": "OverworldMenu.locations" + }, + { + "id": "TokenMenu.info", + "surface": "Hex map view: token right-click menu", + "label": "Token info", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:8010", + "desc": "Show the token's info card.", + "pick": "keep", + "why": "Reading a token's card is normal play, especially when editing is locked.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Token right-click menu" + }, + { + "id": "TokenMenu.edit", + "surface": "Hex map view: token right-click menu", + "label": "Edit token", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:8011", + "desc": "Change the token's name, image, colour.", + "pick": "simple", + "why": "Token basics: change a token you placed.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Token right-click menu" + }, + { + "id": "TokenMenu.openNote", + "surface": "Hex map view: token right-click menu", + "label": "Open note", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:8012", + "desc": "Open the token's note.", + "pick": "keep", + "why": "Tokens are notes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Token right-click menu" + }, + { + "id": "TokenMenu.remove", + "surface": "Hex map view: token right-click menu", + "label": "Remove token", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:8017", + "desc": "Take the token off the map.", + "pick": "simple", + "why": "Token basics: take a token off the map.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Token right-click menu" + }, + { + "id": "LayersMenu.coordinates", + "surface": "Hex map view: layers panel", + "label": "Coordinates", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:105", + "desc": "Show each hex's x,y numbers.", + "pick": "keep", + "why": "Coordinates are how GMs refer to hexes.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.hexNames", + "surface": "Hex map view: layers panel", + "label": "Hex names", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:106", + "desc": "Show hex names on the map.", + "pick": "keep", + "why": "Core label.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.tokenNames", + "surface": "Hex map view: layers panel", + "label": "Token names", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:107", + "desc": "Show names under tokens.", + "pick": "keep", + "why": "Plain layer toggle, same as the other label toggles.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameFontBtn", + "surface": "Hex map view: layers panel", + "label": "Aa (Hex name font)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:319", + "desc": "Unfolds font controls for hex names.", + "pick": "simple", + "why": "Hex name font is look and feel; the owner tagged the matching settings Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel", + "prevPick": "advanced" + }, + { + "id": "LayersMenu.nameFontFamily", + "surface": "Hex map view: layers panel", + "label": "Font", + "kind": "dropdown", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:337", + "desc": "Font family for hex names.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "Name font families: Theme, Serif, Sans, Handwritten", + "focused": true, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameSize", + "surface": "Hex map view: layers panel", + "label": "Name size S / M / L / XL", + "kind": "radio", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:347", + "desc": "Size of hex names.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameBold", + "surface": "Hex map view: layers panel", + "label": "Bold (B)", + "kind": "toggle", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:371", + "desc": "Make hex names bold.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameItalic", + "surface": "Hex map view: layers panel", + "label": "Italic (I)", + "kind": "toggle", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:372", + "desc": "Make hex names italic.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.nameFontReset", + "surface": "Hex map view: layers panel", + "label": "Use the default name font (settings)", + "kind": "button", + "level": "conditional: Aa unfolded", + "loc": "src/hex-map/HexSidePanel.ts:374", + "desc": "Reset this map's name font to the plugin default.", + "pick": "keep", + "why": "No change of its own: it only shows inside the Aa fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.terrainIcons", + "surface": "Hex map view: layers panel", + "label": "Show terrain icons", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:102", + "desc": "Show the icon each terrain draws in its hexes.", + "pick": "keep", + "why": "Useful clean-up of a busy map.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.iconOverrides", + "surface": "Hex map view: layers panel", + "label": "Show icon overrides", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:103", + "desc": "Show the custom icons stamped on hexes.", + "pick": "keep", + "why": "Plain layer toggle.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.paths", + "surface": "Hex map view: layers panel", + "label": "Show paths", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:104", + "desc": "Show roads, rivers and other paths.", + "pick": "keep", + "why": "Common layer toggle.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.tokens", + "surface": "Hex map view: layers panel", + "label": "Show tokens", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:153", + "desc": "Show tokens on the map.", + "pick": "keep", + "why": "Common layer toggle.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.factionOverlay", + "surface": "Hex map view: layers panel", + "label": "Show faction overlay", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:178", + "desc": "Tint hexes by faction territory.", + "pick": "keep", + "why": "Main faction view.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.regionOverlay", + "surface": "Hex map view: layers panel", + "label": "Show region overlay", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:202", + "desc": "Tint hexes by painted region areas.", + "pick": "advanced", + "why": "Overlay for the Region areas tool, which is Advanced.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.gmLayer", + "surface": "Hex map view: layers panel", + "label": "Show GM layer", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:226", + "desc": "Show GM-only icons (hide when sharing with players).", + "pick": "keep", + "why": "Key for play.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.linkBadges", + "surface": "Hex map view: layers panel", + "label": "Show link badges", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:430", + "desc": "Show small icons for towns, dungeons etc. on hexes.", + "pick": "keep", + "why": "Shows where content is.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeSize", + "surface": "Hex map view: layers panel", + "label": "Badge size S / M / L", + "kind": "radio", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:436", + "desc": "Size of the link badges.", + "pick": "simple", + "why": "Badge size is look and feel, like the coordinate/name font settings the owner tagged Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel", + "prevPick": "overkill" + }, + { + "id": "LayersMenu.badgeTypesMore", + "surface": "Hex map view: layers panel", + "label": "Pick badge types (▸)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:451", + "desc": "Unfold per-type badge chips.", + "pick": "simple", + "why": "Choosing which badges show is look and feel. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel", + "prevPick": "advanced" + }, + { + "id": "LayersMenu.badgeTowns", + "surface": "Hex map view: layers panel", + "label": "Towns badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide towns badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeDungeons", + "surface": "Hex map view: layers panel", + "label": "Dungeons badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide dungeons badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeFeatures", + "surface": "Hex map view: layers panel", + "label": "Features badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide features badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeQuests", + "surface": "Hex map view: layers panel", + "label": "Quests badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide quests badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.badgeFactions", + "surface": "Hex map view: layers panel", + "label": "Factions badges", + "kind": "toggle", + "level": "conditional: badge types unfolded", + "loc": "src/hex-map/HexSidePanel.ts:484", + "desc": "Show or hide factions badges only.", + "pick": "keep", + "why": "No change of its own: it only shows inside the badge-types fold (tagged advanced), so tagging that hides it too.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "LayersMenu.legend", + "surface": "Hex map view: layers panel", + "label": "Show legend", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-map/HexSidePanel.ts:251", + "desc": "Show the terrain legend in the corner.", + "pick": "keep", + "why": "Helps read the map.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Layers panel" + }, + { + "id": "Legend.size", + "surface": "Hex map view: terrain legend", + "label": "Legend size S / M / L", + "kind": "radio", + "level": "conditional: legend shown", + "loc": "src/hex-map/terrainLegend.ts:160", + "desc": "Change the legend's size.", + "pick": "simple", + "why": "Legend size is look and feel. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices", + "prevPick": "advanced" + }, + { + "id": "Legend.minimize", + "surface": "Hex map view: terrain legend", + "label": "Minimize (–)", + "kind": "button", + "level": "conditional: legend shown", + "loc": "src/hex-map/terrainLegend.ts:171", + "desc": "Fold the legend into a small chip.", + "pick": "keep", + "why": "Get it out of the way.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "Legend.hide", + "surface": "Hex map view: terrain legend", + "label": "Hide legend (×)", + "kind": "button", + "level": "conditional: legend shown", + "loc": "src/hex-map/terrainLegend.ts:183", + "desc": "Turn the legend off (back on in layers).", + "pick": "keep", + "why": "Standard close button on a panel; the layers toggle brings it back.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "Legend.expandChip", + "surface": "Hex map view: terrain legend", + "label": "Legend (Show the legend)", + "kind": "button", + "level": "conditional: legend minimized", + "loc": "src/hex-map/terrainLegend.ts:145", + "desc": "Unfold the minimized legend.", + "pick": "keep", + "why": "Pairs with minimize.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "MapGrid.expand", + "surface": "Hex map view: grid edges", + "label": "+ (grow edge, 4 sides)", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/HexMapView.ts:1961", + "desc": "Add a row or column of hexes on that side.", + "pick": "keep", + "why": "Basic map growing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "MapGrid.shrink", + "surface": "Hex map view: grid edges", + "label": "− / OK? (shrink edge, 4 sides)", + "kind": "button", + "level": "mode: god", + "loc": "src/hex-map/HexMapView.ts:1966", + "desc": "Remove the edge row/column (asks OK? if it has content).", + "pick": "simple", + "why": "Fixing an oversized map is basic; it's God-only today, so if God mode goes Advanced it must stay reachable (e.g. in Build, with its OK? confirm).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "PathTool.rerouteInstead", + "surface": "Hex map view: notice", + "label": "Reroute instead", + "kind": "button", + "level": "conditional: terrain stroke pinned a path", + "loc": "src/paths/routePins.ts:196", + "desc": "Let paths reroute around newly painted terrain instead of staying put.", + "pick": "keep", + "why": "Only appears right after painting pinned a path; it answers that moment.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Legend, grid edges & notices" + }, + { + "id": "MapView.calibrationDone", + "surface": "Hex map view: hex/grid interactions", + "label": "Done calibrating (✓)", + "kind": "button", + "level": "conditional: calibrating background image", + "loc": "src/hex-map/HexMapView.ts:3680", + "desc": "Finish lining up the background image with the grid.", + "pick": "keep", + "why": "Only exit for calibration.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.missingRestore", + "surface": "Hex map view: hex/grid interactions", + "label": "Restore", + "kind": "button", + "level": "conditional: map note was deleted", + "loc": "src/hex-map/MapModal.ts:46", + "desc": "Write the missing map's note back from the last saved copy.", + "pick": "keep", + "why": "Recovery from accidental deletion.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.missingRemove", + "surface": "Hex map view: hex/grid interactions", + "label": "Remove", + "kind": "button", + "level": "conditional: map note was deleted", + "loc": "src/hex-map/MapModal.ts:52", + "desc": "Drop the missing map from the list (no files deleted).", + "pick": "keep", + "why": "Recovery choice.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.hexClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Click hex", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:4897", + "desc": "Open the hex editor for that hex.", + "pick": "keep", + "why": "Primary interaction.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.hexCtrlClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Ctrl/Cmd+click hex", + "kind": "button", + "level": "conditional: hex has a linked map", + "loc": "src/hex-map/HexMapView.ts:4953", + "desc": "Jump into the map linked from this hex.", + "pick": "keep", + "why": "Fast dive; hinted in tooltips.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.hexCtrlShiftClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Ctrl/Cmd+Shift+click hex", + "kind": "button", + "level": "conditional: hex has a linked map", + "loc": "src/hex-map/HexMapView.ts:4957", + "desc": "Open the linked map in a new tab.", + "pick": "keep", + "why": "Invisible shortcut; costs nothing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.hexRightClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Right-click hex", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1451", + "desc": "Open the hex's action menu.", + "pick": "keep", + "why": "Primary secondary action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.locationBadge", + "surface": "Hex map view: hex/grid interactions", + "label": "Location badge (Enter location / Locations)", + "kind": "button", + "level": "conditional: hex has linked maps", + "loc": "src/hex-map/HexMapView.ts:4423", + "desc": "Click the badge to enter the location, or list several.", + "pick": "keep", + "why": "Visible way into submaps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.regionShadowHex", + "surface": "Hex map view: hex/grid interactions", + "label": "Neighbouring region hex (shadow)", + "kind": "button", + "level": "conditional: region with neighbours", + "loc": "src/hex-map/HexMapView.ts:4638", + "desc": "Click a ghosted hex of a neighbouring region to go there.", + "pick": "keep", + "why": "Seamless region walking.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.overworldClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Click overworld hex", + "kind": "button", + "level": "conditional: overworld", + "loc": "src/hex-map/HexMapView.ts:4936", + "desc": "Enter that region, or set a biome on empty land.", + "pick": "keep", + "why": "Primary overworld action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.tokenDrag", + "surface": "Hex map view: hex/grid interactions", + "label": "Drag token", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:7853", + "desc": "Drag a token to move it to another hex.", + "pick": "simple", + "why": "Moving the party is the core play action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.tokenRightClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Right-click token", + "kind": "menu", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:7840", + "desc": "Open the token's menu.", + "pick": "keep", + "why": "Primary token actions.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.wheelZoom", + "surface": "Hex map view: hex/grid interactions", + "label": "Mouse wheel", + "kind": "slider", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1100", + "desc": "Zoom in and out.", + "pick": "keep", + "why": "Basic navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.dragPan", + "surface": "Hex map view: hex/grid interactions", + "label": "Drag (left/middle/right)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1147", + "desc": "Pan the map.", + "pick": "keep", + "why": "Basic navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.dblRightClickExit", + "surface": "Hex map view: hex/grid interactions", + "label": "Double right-click", + "kind": "button", + "level": "conditional: a tool is on", + "loc": "src/hex-map/HexMapView.ts:1395", + "desc": "Turn off the active tool.", + "pick": "drop", + "why": "Fourth way to leave a tool; Esc, the ✕ and right-click Exit tool replace it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.dblClickOffGridExit", + "surface": "Hex map view: hex/grid interactions", + "label": "Double-click off the grid", + "kind": "button", + "level": "conditional: terrain/icon tool on", + "loc": "src/hex-map/HexMapView.ts:1458", + "desc": "Turn off terrain or icon painting.", + "pick": "drop", + "why": "Fifth way to leave a tool and easy to trigger by accident; Esc and ✕ replace it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "MapView.gmIconRightClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Right-click hex (GM icon paint)", + "kind": "button", + "level": "conditional: icon tool in GM-only mode", + "loc": "src/hex-map/HexMapView.ts:1408", + "desc": "Remove one of the selected GM icon from that hex.", + "pick": "keep", + "why": "How you remove a GM icon while painting GM icons; only in that mode.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "PathTool.anchorRightClick", + "surface": "Hex map view: hex/grid interactions", + "label": "Right-click path anchor", + "kind": "button", + "level": "conditional: path tool on", + "loc": "src/hex-map/pathTool.ts:1063", + "desc": "Delete that anchor point of the path.", + "pick": "keep", + "why": "Natural way to delete a path point while the path tool is on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "PathTool.anchorDrag", + "surface": "Hex map view: hex/grid interactions", + "label": "Drag path point/line", + "kind": "button", + "level": "conditional: path tool on", + "loc": "src/hex-map/HexMapView.ts:1270", + "desc": "Drag a point or line of the path to reshape it.", + "pick": "keep", + "why": "Natural path editing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.escape", + "surface": "Hex map view: keyboard shortcuts", + "label": "Esc", + "kind": "command", + "level": "conditional: a tool is on", + "loc": "src/hex-map/HexMapView.ts:1043", + "desc": "Step out of the active tool.", + "pick": "keep", + "why": "Expected.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.undoRedo", + "surface": "Hex map view: keyboard shortcuts", + "label": "Ctrl/Cmd+Z, Ctrl/Cmd+Shift+Z", + "kind": "command", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:990", + "desc": "Undo and redo on the map.", + "pick": "keep", + "why": "Expected.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.altArrows", + "surface": "Hex map view: keyboard shortcuts", + "label": "Alt+← / Alt+↑ / Alt+→", + "kind": "command", + "level": "always", + "loc": "src/hex-map/HexMapView.ts:1001", + "desc": "Back, up to parent, forward between maps.", + "pick": "keep", + "why": "Invisible, cheap.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.deleteAnchor", + "surface": "Hex map view: keyboard shortcuts", + "label": "Backspace / Delete", + "kind": "command", + "level": "conditional: path tool on", + "loc": "src/hex-map/HexMapView.ts:1055", + "desc": "Remove the hovered (or last) path anchor.", + "pick": "keep", + "why": "Invisible, cheap.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.altClickNewPath", + "surface": "Hex map view: keyboard shortcuts", + "label": "Alt+click", + "kind": "command", + "level": "conditional: path tool on", + "loc": "src/hex-map/pathTool.ts:1472", + "desc": "Start a new path on top of another.", + "pick": "keep", + "why": "Invisible shortcut; costs nothing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "Keys.calibrationArrows", + "surface": "Hex map view: keyboard shortcuts", + "label": "Arrow keys (Shift = 10px)", + "kind": "command", + "level": "conditional: calibrating background", + "loc": "src/hex-map/HexMapView.ts:3605", + "desc": "Nudge the background image or grid during calibration.", + "pick": "keep", + "why": "Only during background calibration, where fine nudging is the point.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex map view", + "subgroup": "Mouse & keyboard" + }, + { + "id": "HexEditor.centerOnHex", + "surface": "Hex editor: header", + "label": "⌖", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:196", + "desc": "Pan the map so this hex is in the middle.", + "pick": "keep", + "why": "Cheap, obvious orientation aid.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.openNote", + "surface": "Hex editor: header", + "label": "Open note", + "kind": "button", + "level": "conditional: hex note exists", + "loc": "src/hex-map/HexEditorModal.ts:216", + "desc": "Open this hex's Markdown note in a tab.", + "pick": "keep", + "why": "Core: the note is the real data.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.exportHex", + "surface": "Hex editor: header", + "label": "Export", + "kind": "button", + "level": "conditional: hex note exists", + "loc": "src/hex-map/HexEditorModal.ts:224", + "desc": "Export this one hex as a PDF or Markdown file.", + "pick": "simple", + "why": "Basic export of one hex from its editor.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.runWorkflow", + "surface": "Hex editor: header", + "label": "Run workflow", + "kind": "button", + "level": "feature:workflows", + "loc": "src/hex-map/HexEditorModal.ts:236", + "desc": "Pick a workflow and roll it, adding the result to this hex.", + "pick": "keep", + "why": "Workflows are Advanced and this is already gated to that feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.workflowPicker", + "surface": "Hex editor: header", + "label": "Pick a workflow to run…", + "kind": "picker", + "level": "feature:workflows", + "loc": "src/hex-map/HexEditorModal.ts:1660", + "desc": "Choose which workflow note to run for this hex.", + "pick": "keep", + "why": "Workflows are Advanced and this is already gated to that feature.", + "lists": "md notes under workflowsFolder; if that is blank (default) falls back to worldFolder. Excludes _ notes and template folders", + "focused": false, + "mix": "with workflowsFolder blank: every note under the world folder (hexes, towns, tables, biomes, palettes, generators, region notes)", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborTile", + "surface": "Hex editor: header", + "label": "Neighbour hex tiles", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:578", + "desc": "Jump the editor to one of the six neighbouring hexes.", + "pick": "keep", + "why": "Fast hex-by-hex stocking.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborCrossRegion", + "surface": "Hex editor: header", + "label": "Neighbour tile (other region)", + "kind": "button", + "level": "conditional: a map joins past this edge", + "loc": "src/hex-map/HexEditorModal.ts:600", + "desc": "Cross into the neighbouring region's hex across the map edge.", + "pick": "keep", + "why": "Natural continuation of neighbour navigation.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborWalkOverworld", + "surface": "Hex editor: header", + "label": "Neighbour tile (new region)", + "kind": "button", + "level": "conditional: region of an overworld, edge hex", + "loc": "src/hex-map/HexEditorModal.ts:621", + "desc": "Walk off the edge to make the next overworld region (pick/roll a biome).", + "pick": "keep", + "why": "Only in an overworld region, already gated by the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborNewLand", + "surface": "Hex editor: header", + "label": "Neighbour tile (new land)", + "kind": "button", + "level": "conditional: edge hex; asks to enable regions+generators", + "loc": "src/hex-map/HexEditorModal.ts:636", + "desc": "Walk off the map edge to create new land next door.", + "pick": "keep", + "why": "In Simple it asks to turn the feature on, which is the ramp.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.neighborCentreDot", + "surface": "Hex editor: header", + "label": "Centre dot", + "kind": "button", + "level": "conditional: hex has a region or one location map", + "loc": "src/hex-map/HexEditorModal.ts:660", + "desc": "Enter the map linked to this hex (its region or location).", + "pick": "drop", + "why": "Duplicates the Maps chips right below it in the same editor; the chips replace it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.nameInput", + "surface": "Hex editor: header", + "label": "Name", + "kind": "text", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:449", + "desc": "Give this hex a name (optional); autosaves.", + "pick": "keep", + "why": "Core and lightweight.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsChip", + "surface": "Hex editor: header", + "label": "Maps: region/location chips", + "kind": "button", + "level": "conditional: hex has linked maps", + "loc": "src/hex-map/HexEditorModal.ts:694", + "desc": "Open a map linked to this hex (its region or a location).", + "pick": "keep", + "why": "Main way into child maps from a hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsAdd", + "surface": "Hex editor: header", + "label": "+ (Maps)", + "kind": "menu", + "level": "conditional: host can make child maps", + "loc": "src/hex-map/HexEditorModal.ts:709", + "desc": "Menu to make, link or manage maps for this hex.", + "pick": "keep", + "why": "Single entry point for child maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsNewMap", + "surface": "Hex editor: header", + "label": "New map from this hex…", + "kind": "command", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:713", + "desc": "Create a new map (e.g. a town or dungeon map) inside this hex.", + "pick": "keep", + "why": "Core for nested maps.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsLinkExisting", + "surface": "Hex editor: header", + "label": "Link existing map…", + "kind": "command", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:715", + "desc": "Attach a map you already have to this hex.", + "pick": "keep", + "why": "Standard way to attach a map you already made (same as the hex menu).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.mapsManageLocations", + "surface": "Hex editor: header", + "label": "Manage locations (N)…", + "kind": "command", + "level": "conditional: hex has locations; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:718", + "desc": "Reorder or unlink location maps on this hex.", + "pick": "keep", + "why": "Only when the hex has locations; normal housekeeping.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.closeButtons", + "surface": "Hex editor: header", + "label": "Close (×)", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:428", + "desc": "Close the editor (unsaved text is saved first).", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Header" + }, + { + "id": "HexEditor.collapseTerrain", + "surface": "Hex editor: section headers", + "label": "Terrain ▶/▼", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:276", + "desc": "Fold or unfold the terrain picker; starts folded if the hex has terrain.", + "pick": "keep", + "why": "Keeps the big swatch grid out of the way.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Section headers" + }, + { + "id": "HexEditor.collapseNotes", + "surface": "Hex editor: section headers", + "label": "Notes ▶/▼", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:298", + "desc": "Fold or unfold the note text boxes (remembered).", + "pick": "keep", + "why": "Cheap; state remembered.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Section headers" + }, + { + "id": "HexEditor.collapseLinked", + "surface": "Hex editor: section headers", + "label": "Linked notes ▶/▼", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:356", + "desc": "Fold or unfold the six link fields (remembered).", + "pick": "keep", + "why": "Lets users hide the densest group.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Section headers" + }, + { + "id": "HexEditor.collapseIcons", + "surface": "Hex editor: section headers", + "label": "Icons ▶/▼", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:414", + "desc": "Fold or unfold the icon pickers (remembered).", + "pick": "keep", + "why": "Icon grids are huge; should default folded.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Section headers" + }, + { + "id": "HexEditor.terrainChangeHint", + "surface": "Hex editor: terrain", + "label": "▸ change", + "kind": "button", + "level": "conditional: terrain folded; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:286", + "desc": "Hint on the folded header that clicking opens the terrain picker.", + "pick": "keep", + "why": "Affordance only; no extra decision.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.terrainFilter", + "surface": "Hex editor: terrain", + "label": "Filter terrains…", + "kind": "search", + "level": "conditional: palette has >12 terrains; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:815", + "desc": "Type to narrow the terrain swatches.", + "pick": "keep", + "why": "Scales a long palette instead of trimming it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.terrainPicker", + "surface": "Hex editor: terrain", + "label": "Terrain swatches", + "kind": "picker", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:860", + "desc": "Click a terrain to paint this hex with it.", + "pick": "keep", + "why": "Core.", + "lists": "terrains of this map's palette (getMapPalette)", + "focused": true, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.terrainClear", + "surface": "Hex editor: terrain", + "label": "Clear", + "kind": "button", + "level": "conditional: hex has terrain; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:846", + "desc": "Remove this hex's terrain (back to the map's base).", + "pick": "keep", + "why": "Needed undo-ish action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.bodyFieldUseOnMap", + "surface": "Hex editor: terrain", + "label": "Use \"X\" on the map", + "kind": "button", + "level": "conditional: note text disagrees with map; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:1493", + "desc": "Old note says a different terrain/region: apply that to the map.", + "pick": "keep", + "why": "Only when the note and map disagree; resolves it without losing hand edits.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.bodyFieldUpdateNote", + "surface": "Hex editor: terrain", + "label": "Change the note to \"X\"", + "kind": "button", + "level": "conditional: note text disagrees with map", + "loc": "src/hex-map/HexEditorModal.ts:1510", + "desc": "Rewrite the note's Terrain/Region line to match the map.", + "pick": "keep", + "why": "Only when the note and map disagree; resolves it without losing hand edits.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Terrain" + }, + { + "id": "HexEditor.description", + "surface": "Hex editor: notes", + "label": "Description", + "kind": "textarea", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "desc": "What the party sees in this hex; autosaves.", + "pick": "keep", + "why": "Core hexcrawl content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.descriptionRoll", + "surface": "Hex editor: notes", + "label": "📖", + "kind": "button", + "level": "conditional: terrain description table exists", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "desc": "Roll on this terrain's description table and add the result.", + "pick": "keep", + "why": "One-click content; core loop.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.landmark", + "surface": "Hex editor: notes", + "label": "Landmark", + "kind": "textarea", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "desc": "A notable landmark visible in this hex.", + "pick": "keep", + "why": "Core hexcrawl content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.landmarkRoll", + "surface": "Hex editor: notes", + "label": "📖", + "kind": "button", + "level": "conditional: landmark table exists", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "desc": "Roll on the landmark table and add the result.", + "pick": "keep", + "why": "Same pattern as Description.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hidden", + "surface": "Hex editor: notes", + "label": "Hidden", + "kind": "textarea", + "level": "conditional: GM layer on", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "desc": "Things found only by searching this hex.", + "pick": "keep", + "why": "Core GM content; GM-gated already.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hiddenRoll", + "surface": "Hex editor: notes", + "label": "📖", + "kind": "button", + "level": "conditional: GM layer on + hidden table exists", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "desc": "Roll on the hidden table and add the result.", + "pick": "keep", + "why": "Same pattern.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.secret", + "surface": "Hex editor: notes", + "label": "Secret", + "kind": "textarea", + "level": "conditional: GM layer on", + "loc": "src/hex-map/HexEditorModal.ts:1575", + "desc": "GM-only secrets for this hex.", + "pick": "keep", + "why": "Core GM content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.secretRoll", + "surface": "Hex editor: notes", + "label": "📖", + "kind": "button", + "level": "conditional: GM layer on + secret table exists", + "loc": "src/hex-map/HexEditorModal.ts:1584", + "desc": "Roll on the secret table and add the result.", + "pick": "keep", + "why": "Same pattern.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.gmLayerShow", + "surface": "Hex editor: notes", + "label": "Show them", + "kind": "button", + "level": "conditional: GM layer off", + "loc": "src/hex-map/HexEditorModal.ts:319", + "desc": "Turn on the GM layer so Hidden and Secret appear here.", + "pick": "keep", + "why": "Explains missing fields; one click.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledSectionsFold", + "surface": "Hex editor: notes", + "label": "Weather · Hooks & Rumors", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:329", + "desc": "Fold/unfold the weather and rumours boxes (open if they have text).", + "pick": "keep", + "why": "Plain fold for a standard section.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.weather", + "surface": "Hex editor: notes", + "label": "Weather", + "kind": "textarea", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:332", + "desc": "Weather notes for this hex.", + "pick": "keep", + "why": "Weather is real hexcrawl content and starts folded.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.weatherRoll", + "surface": "Hex editor: notes", + "label": "🎲 (Weather)", + "kind": "button", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:1710", + "desc": "Roll weather from the hex/map/starter table; first click may ask for a table.", + "pick": "keep", + "why": "One-click weather roll, same pattern as the other rolls.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.weatherSource", + "surface": "Hex editor: notes", + "label": "⋯ (Weather)", + "kind": "menu", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:1711", + "desc": "Choose which table Weather rolls on (map's or this hex's).", + "pick": "advanced", + "why": "Per-hex table choice is a real option beyond the basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hooks", + "surface": "Hex editor: notes", + "label": "Hooks & Rumors", + "kind": "textarea", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:332", + "desc": "Rumours and adventure hooks heard in this hex.", + "pick": "keep", + "why": "Real hexcrawl content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hooksRoll", + "surface": "Hex editor: notes", + "label": "🎲 (Hooks & Rumors)", + "kind": "button", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:1710", + "desc": "Roll a rumour from the hex/map/starter table and add it.", + "pick": "keep", + "why": "One-click content.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.hooksSource", + "surface": "Hex editor: notes", + "label": "⋯ (Hooks & Rumors)", + "kind": "menu", + "level": "always (folded)", + "loc": "src/hex-map/HexEditorModal.ts:1711", + "desc": "Choose which table rumours roll on (map's or this hex's).", + "pick": "advanced", + "why": "Per-hex table choice is a real option beyond the basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledSetMapTable", + "surface": "Hex editor: notes", + "label": "Set/Change the map's … table…", + "kind": "command", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:1760", + "desc": "Pick the table the whole map uses for weather/rumours.", + "pick": "advanced", + "why": "A map property beyond the basics; the first roll asks for a table anyway.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledSetHexTable", + "surface": "Hex editor: notes", + "label": "Use a different table for this hex…", + "kind": "command", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1761", + "desc": "Override the weather/rumour table for this hex only.", + "pick": "advanced", + "why": "Per-hex table override is a real option beyond the basics.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledUseMapTable", + "surface": "Hex editor: notes", + "label": "Use the map's table on this hex", + "kind": "command", + "level": "conditional: hex has own table", + "loc": "src/hex-map/HexEditorModal.ts:1763", + "desc": "Remove this hex's own table so it uses the map's again.", + "pick": "keep", + "why": "Only when the hex has its own table; it's the way back.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.rolledTablePicker", + "surface": "Hex editor: notes", + "label": "Weather/rumour table chooser", + "kind": "picker", + "level": "conditional: from ⋯ menu or 🎲 with no table", + "loc": "src/hex-map/HexEditorModal.ts:1722", + "desc": "Pick a random table for weather or rumours.", + "pick": "keep", + "why": "Needed once per map, but must list tables only.", + "lists": "FileLinkSuggestModal with folderOverride \"\" (not nullish) = whole vault, md only, minus _ notes and templates", + "focused": false, + "mix": "every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.moreInNoteFold", + "surface": "Hex editor: notes", + "label": "More in this note (N)", + "kind": "toggle", + "level": "conditional: note has unknown headings", + "loc": "src/hex-map/HexEditorModal.ts:345", + "desc": "Fold/unfold extra sections from the note the editor has no field for.", + "pick": "keep", + "why": "Nothing hidden; folded by default.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.moreInNoteText", + "surface": "Hex editor: notes", + "label": " (other sections)", + "kind": "textarea", + "level": "conditional: note has unknown headings", + "loc": "src/hex-map/HexEditorModal.ts:348", + "desc": "Edit a custom section of the note under its own heading.", + "pick": "keep", + "why": "Respects hand edits.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.sectionTablePicker", + "surface": "Hex editor: Weather/Rumours ⋯", + "label": "(set map's / this hex's table)", + "kind": "picker", + "level": "conditional: Weather/Hooks ⋯ menu", + "loc": "src/hex-map/HexEditorModal.ts:1722", + "desc": "Pick the random table the 🎲 rolls for Weather or Hooks & Rumors.", + "pick": "keep", + "why": "Needed, but must list only tables", + "lists": "every .md in the WHOLE vault (folderOverride \"\" disables the root) minus templates/_ (HexEditorModal.ts:1722)", + "focused": false, + "mix": "hex notes, biome notes, region notes, map tables, daily notes, any vault note — not just tables", + "group": "Hex editor", + "subgroup": "Notes" + }, + { + "id": "HexEditor.encountersLink", + "surface": "Hex editor: linked notes", + "label": "Encounters Table", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create an encounter table to link to this hex.", + "pick": "keep", + "why": "Core, but list should be encounter tables only.", + "lists": "md notes under tablesFolder (world/tables) minus _/templates, minus terrain/ subfolder and tables with encounter-filter:false (landmark/hidden/secret/weather/rumors/region tables)", + "focused": false, + "mix": "any other roll table (treasure, names, imported tables), not just encounter tables; the terrain encounter tables are excluded", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every table available for Encounters Table.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new table with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked table in the random tables view.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsLink", + "surface": "Hex editor: linked notes", + "label": "Towns", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a town note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under townsFolder minus _/templates; townsFolder defaults to \"\" = whole vault", + "focused": false, + "mix": "only if Towns folder is blank (the default before setup): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Towns.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.townsRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsLink", + "surface": "Hex editor: linked notes", + "label": "Dungeons", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a dungeon note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under dungeonsFolder minus _/templates; blank default = whole vault", + "focused": false, + "mix": "only if Dungeons folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Dungeons.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.dungeonsRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsLink", + "surface": "Hex editor: linked notes", + "label": "Quests", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a quest note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under questsFolder minus _/templates; blank default = whole vault", + "focused": false, + "mix": "only if Quests folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Quests.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.questsRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsLink", + "surface": "Hex editor: linked notes", + "label": "Factions", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a faction note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under factionsFolder minus _/templates; blank default = whole vault", + "focused": false, + "mix": "only if Factions folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Factions.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.factionsRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresLink", + "surface": "Hex editor: linked notes", + "label": "Features", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1144", + "desc": "Search, pick or create a feature note to link to this hex.", + "pick": "keep", + "why": "Core link field.", + "lists": "md notes under featuresFolder minus _/templates; blank default = whole vault", + "focused": false, + "mix": "only if Features folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresShowAll", + "surface": "Hex editor: linked notes", + "label": "▾", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexEditorModal.ts:1151", + "desc": "Show every note available for Features.", + "pick": "keep", + "why": "Part of the combo box.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresCreate", + "surface": "Hex editor: linked notes", + "label": "+ Create \"…\"", + "kind": "button", + "level": "conditional: typed name has no match", + "loc": "src/hex-map/HexEditorModal.ts:1272", + "desc": "Make a new note with the typed name and link it.", + "pick": "keep", + "why": "Fast stocking without leaving the hex.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresOpenLink", + "surface": "Hex editor: linked notes", + "label": "", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1440", + "desc": "Open the linked note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.featuresRemove", + "surface": "Hex editor: linked notes", + "label": "×", + "kind": "button", + "level": "conditional: hex has links here", + "loc": "src/hex-map/HexEditorModal.ts:1459", + "desc": "Unlink this note from the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.encountersRoll", + "surface": "Hex editor: linked notes", + "label": "🎲 (Encounters)", + "kind": "button", + "level": "conditional: hex has an encounter table", + "loc": "src/hex-map/HexEditorModal.ts:1450", + "desc": "Roll on the linked encounter table and add the result.", + "pick": "simple", + "why": "Rolling a hex's encounter is the core play-time action.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Linked notes" + }, + { + "id": "HexEditor.iconOverride", + "surface": "Hex editor: icons", + "label": "Icon override", + "kind": "picker", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:922", + "desc": "Pick an icon for this hex instead of the terrain's icon.", + "pick": "keep", + "why": "Common; but whole library is a lot (filter helps).", + "lists": "plugin.availableIcons minus hiddenIcons: bundled icons of enabled map kinds + custom icons folder", + "focused": true, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.iconTerrainDefault", + "surface": "Hex editor: icons", + "label": "— terrain default —", + "kind": "button", + "level": "mode: build", + "loc": "src/hex-map/HexEditorModal.ts:926", + "desc": "Remove the override so the terrain's own icon shows.", + "pick": "keep", + "why": "Needed reset.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.iconPackTabs", + "surface": "Hex editor: icons", + "label": "All / / Custom tabs", + "kind": "radio", + "level": "mode: build", + "loc": "src/HexmakerModal.ts:108", + "desc": "Show icons from one pack only (with counts).", + "pick": "keep", + "why": "Scales a huge list.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.iconPlaceKinds", + "surface": "Hex editor: icons", + "label": "All places / Settlements / Castles…", + "kind": "radio", + "level": "conditional: Places tab active", + "loc": "src/HexmakerModal.ts:133", + "desc": "Narrow the Places pack to one kind of place.", + "pick": "keep", + "why": "A plain picker filter that helps find a place icon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIcons", + "surface": "Hex editor: icons", + "label": "Game master icons", + "kind": "picker", + "level": "conditional: GM layer on; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:941", + "desc": "Click to add GM-only icons (repeatable, ×N badge).", + "pick": "keep", + "why": "GM-only icons are what the GM layer is for; already GM-layer gated.", + "lists": "same list as Icon override (availableIcons minus hiddenIcons)", + "focused": true, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconsRemoveOne", + "surface": "Hex editor: icons", + "label": "Right-click icon", + "kind": "button", + "level": "conditional: GM layer on; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:1037", + "desc": "Right-click a GM icon to remove one copy.", + "pick": "keep", + "why": "How you remove one GM icon; only with the GM layer on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconsClearAll", + "surface": "Hex editor: icons", + "label": "— clear all —", + "kind": "button", + "level": "conditional: GM layer on; mode: build", + "loc": "src/hex-map/HexEditorModal.ts:1050", + "desc": "Remove every GM icon from this hex.", + "pick": "keep", + "why": "Clear for the GM icons; only with the GM layer on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconFilterSearch", + "surface": "Hex editor: icons", + "label": "Filter icons… (GM)", + "kind": "search", + "level": "conditional: GM layer on; mode: build", + "loc": "src/HexmakerModal.ts:45", + "desc": "Type to narrow the GM icon grid.", + "pick": "keep", + "why": "Filter for the GM icon grid; only with the GM layer on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconPackTabs", + "surface": "Hex editor: icons", + "label": "All / / Custom tabs (GM)", + "kind": "radio", + "level": "conditional: GM layer on; mode: build", + "loc": "src/HexmakerModal.ts:108", + "desc": "Show GM icons from one pack only.", + "pick": "keep", + "why": "Pack tabs for the GM icon grid; only with the GM layer on.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexEditor.gmIconPlaceKinds", + "surface": "Hex editor: icons", + "label": "Place kind chips (GM)", + "kind": "radio", + "level": "conditional: GM layer on, Places tab", + "loc": "src/HexmakerModal.ts:133", + "desc": "Narrow GM Places icons to one kind.", + "pick": "keep", + "why": "A plain picker filter, same as on the main icon grid.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex editor", + "subgroup": "Icons" + }, + { + "id": "HexTable.refresh", + "surface": "Hex table: toolbar", + "label": "Refresh", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:143", + "desc": "Reload every row from the notes.", + "pick": "overkill", + "why": "Refresh button; the table already live-updates.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.xMin", + "surface": "Hex table: toolbar", + "label": "X: Min", + "kind": "number", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:153", + "desc": "Only show hexes with X at least this.", + "pick": "advanced", + "why": "Coordinate range filters are a real option beyond the basic filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.xMax", + "surface": "Hex table: toolbar", + "label": "X: Max", + "kind": "number", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:164", + "desc": "Only show hexes with X at most this.", + "pick": "advanced", + "why": "Coordinate range filters are a real option beyond the basic filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.yMin", + "surface": "Hex table: toolbar", + "label": "Y: Min", + "kind": "number", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:179", + "desc": "Only show hexes with Y at least this.", + "pick": "advanced", + "why": "Coordinate range filters are a real option beyond the basic filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.yMax", + "surface": "Hex table: toolbar", + "label": "Y: Max", + "kind": "number", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:190", + "desc": "Only show hexes with Y at most this.", + "pick": "advanced", + "why": "Coordinate range filters are a real option beyond the basic filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.terrainFilter", + "surface": "Hex table: toolbar", + "label": "Terrain: all", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:204", + "desc": "Open a filter to show only (or hide) some terrains.", + "pick": "keep", + "why": "Most useful filter in the table.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasTown", + "surface": "Hex table: toolbar", + "label": "Town", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:240", + "desc": "Only show hexes that link a town.", + "pick": "keep", + "why": "Quick 'where are my towns' answer.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasDungeon", + "surface": "Hex table: toolbar", + "label": "Dungeon", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:252", + "desc": "Only show hexes that link a dungeon.", + "pick": "keep", + "why": "Same.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasFeature", + "surface": "Hex table: toolbar", + "label": "Feature", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:264", + "desc": "Only show hexes that link a feature.", + "pick": "keep", + "why": "Same everyday 'which hexes have X' filter as Town and Dungeon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasQuest", + "surface": "Hex table: toolbar", + "label": "Quest", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:276", + "desc": "Only show hexes that link a quest.", + "pick": "keep", + "why": "Same everyday 'which hexes have X' filter as Town and Dungeon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.hasFaction", + "surface": "Hex table: toolbar", + "label": "Faction", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:288", + "desc": "Only show hexes that link a faction.", + "pick": "keep", + "why": "Same everyday 'which hexes have X' filter as Town and Dungeon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.mapSelect", + "surface": "Hex table: toolbar", + "label": "All maps / ", + "kind": "dropdown", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:299", + "desc": "Choose which map's hexes the table lists.", + "pick": "keep", + "why": "Essential once there are several maps.", + "lists": "\"All maps\" + every map in settings.maps (overworlds, regions, locations, all kinds)", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.sortCycle", + "surface": "Hex table: toolbar", + "label": "Sort: xy / yx / type", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:329", + "desc": "Cycle the sort: by X, by Y, or by terrain type.", + "pick": "keep", + "why": "Sorting a table is standard use (the cycling button could be clearer).", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.sortDirection", + "surface": "Hex table: toolbar", + "label": "↑ asc / ↓ desc", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:341", + "desc": "Flip the sort direction.", + "pick": "keep", + "why": "Sort direction is standard table use.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.clearFilters", + "surface": "Hex table: toolbar", + "label": "Clear filters", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:355", + "desc": "Reset every filter in the toolbar.", + "pick": "keep", + "why": "Escape hatch for all the filters.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Toolbar" + }, + { + "id": "HexTable.jumpToHex", + "surface": "Hex table: rows", + "label": "◎", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:802", + "desc": "Center the hex map on this row's hex.", + "pick": "keep", + "why": "Core link between table and map.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.openHexNote", + "surface": "Hex table: rows", + "label": "", + "kind": "button", + "level": "conditional: hex note exists", + "loc": "src/hex-table/HexTableView.ts:812", + "desc": "Open this hex's note.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.terrainCell", + "surface": "Hex table: rows", + "label": "Terrain cell", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:889", + "desc": "Click to change this hex's terrain.", + "pick": "keep", + "why": "Bulk terrain fixing from the table.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.townsCell", + "surface": "Hex table: rows", + "label": "Towns cell", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:970", + "desc": "Empty: pick/create a town; one: open it; several: pick one.", + "pick": "keep", + "why": "Useful, though overloaded by link count.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.dungeonsCell", + "surface": "Hex table: rows", + "label": "Dungeons cell", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:970", + "desc": "Empty: pick/create a dungeon; one: open it; several: pick one.", + "pick": "keep", + "why": "Same.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.encountersCell", + "surface": "Hex table: rows", + "label": "Enc. Table cell", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:970", + "desc": "Empty: pick/create a table; one: open it in the tables view.", + "pick": "keep", + "why": "Same.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.encountersMiddleClick", + "surface": "Hex table: rows", + "label": "Middle-click Enc. Table", + "kind": "button", + "level": "conditional: exactly one table linked", + "loc": "src/hex-table/HexTableView.ts:947", + "desc": "Middle-click to open the encounter table in a new tab.", + "pick": "keep", + "why": "Invisible shortcut that follows Obsidian's middle-click habit; costs nothing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.otherLinkCell", + "surface": "Hex table: rows", + "label": "Features/Quests/Factions cell", + "kind": "button", + "level": "conditional: cell has links", + "loc": "src/hex-table/HexTableView.ts:1031", + "desc": "Show the linked notes as a read-only list.", + "pick": "keep", + "why": "Shows which notes are linked; making it editable is a fix, not a cut.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.textCell", + "surface": "Hex table: rows", + "label": "Text cells (Description…Hooks)", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:1054", + "desc": "Click to read and edit this note section in a popup.", + "pick": "keep", + "why": "Core quick-edit.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.columnResize", + "surface": "Hex table: rows", + "label": "Column edge drag", + "kind": "slider", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:1119", + "desc": "Drag a header edge to resize the column (not remembered).", + "pick": "keep", + "why": "Standard table behaviour.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.hiddenSecretColumns", + "surface": "Hex table: rows", + "label": "Hidden / Secret columns", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:44", + "desc": "Shown regardless of the GM layer; click to edit like other text cells.", + "pick": "keep", + "why": "Real hex content; following the GM layer is a fix, not a cut.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexTable.weatherHooksColumns", + "surface": "Hex table: rows", + "label": "Weather / Hooks & Rumors columns", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTableView.ts:46", + "desc": "Click to edit weather or rumours text for the hex.", + "pick": "keep", + "why": "Real hexcrawl content, same as the other text columns.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexCell.textarea", + "surface": "Hex table: cell popup", + "label": "
text", + "kind": "textarea", + "level": "conditional: text column", + "loc": "src/hex-table/HexCellModal.ts:38", + "desc": "Read and edit the full section text; saves on close.", + "pick": "keep", + "why": "Core quick-edit.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexCell.rollOnTable", + "surface": "Hex table: cell popup", + "label": "🎲 Roll on table", + "kind": "button", + "level": "conditional: description/landmark/hidden/secret table exists", + "loc": "src/hex-table/HexCellModal.ts:46", + "desc": "Roll on the matching table and append the result.", + "pick": "keep", + "why": "Same as hex editor 📖; no weather/rumour roll here.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexCell.linkList", + "surface": "Hex table: cell popup", + "label": "", + "kind": "picker", + "level": "conditional: Features/Quests/Factions column", + "loc": "src/hex-table/HexCellModal.ts:33", + "desc": "Read-only list of linked notes (not clickable).", + "pick": "keep", + "why": "Shows which notes are linked; making it clickable is a fix, not a cut.", + "lists": "the links in that cell", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "HexCell.closeButtons", + "surface": "Hex table: cell popup", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexCellModal.ts:69", + "desc": "Close the popup (saves the text).", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Rows & cells" + }, + { + "id": "TerrainFilter.noTerrain", + "surface": "Hex table: terrain filter", + "label": "No terrain", + "kind": "checkbox", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:156", + "desc": "Include (click) or exclude (right-click) hexes with no terrain.", + "pick": "keep", + "why": "Finding unpainted hexes is common.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.typeRow", + "surface": "Hex table: terrain filter", + "label": " row", + "kind": "checkbox", + "level": "conditional: palette has typed terrains", + "loc": "src/hex-table/TerrainFilterModal.ts:160", + "desc": "Include/exclude every terrain of one type (water, land…).", + "pick": "advanced", + "why": "Filtering by terrain type is a real option beyond the basic terrain filter.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.terrainRow", + "surface": "Hex table: terrain filter", + "label": " rows", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:168", + "desc": "Include (click) or exclude (right-click) a terrain.", + "pick": "keep", + "why": "Core of the filter.", + "lists": "selected map's palette, or with All maps every terrain of every palette (getAllTerrains), deduped by name", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.excludeRightClick", + "surface": "Hex table: terrain filter", + "label": "Right-click to exclude", + "kind": "button", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:94", + "desc": "Right-click any row to exclude it instead of include.", + "pick": "keep", + "why": "Invisible right-click option on the filter; costs nothing.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.categoryHeading", + "surface": "Hex table: terrain filter", + "label": " heading", + "kind": "button", + "level": "conditional: untyped terrains with categories", + "loc": "src/hex-table/TerrainFilterModal.ts:130", + "desc": "Click to include all in a category; right-click to exclude all.", + "pick": "keep", + "why": "Only shows when terrains have categories; a plain select-all for the group.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.clearAll", + "surface": "Hex table: terrain filter", + "label": "Clear all", + "kind": "button", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:206", + "desc": "Untick everything in the terrain filter.", + "pick": "keep", + "why": "Needed reset.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "TerrainFilter.closeButtons", + "surface": "Hex table: terrain filter", + "label": "Done / ×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/TerrainFilterModal.ts:216", + "desc": "Close the filter (it applies live).", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "HexTerrainPicker.terrains", + "surface": "Hex table: select terrain", + "label": "Select terrain", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/HexTerrainPickerModal.ts:129", + "desc": "Click a terrain to paint this hex with it.", + "pick": "keep", + "why": "Core; note no filter box unlike the hex editor.", + "lists": "terrains of the hex's map palette", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "HexTerrainPicker.clear", + "surface": "Hex table: select terrain", + "label": "Clear terrain", + "kind": "button", + "level": "conditional: hex has terrain", + "loc": "src/hex-table/HexTerrainPickerModal.ts:160", + "desc": "Remove this hex's terrain.", + "pick": "keep", + "why": "Needed reset.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "HexTerrainPicker.closeButtons", + "surface": "Hex table: select terrain", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/HexTerrainPickerModal.ts:120", + "desc": "Close without changing terrain.", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Terrain filter" + }, + { + "id": "LinkPicker.townsList", + "surface": "Hex table: add link", + "label": "Select existing: (Towns)", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "desc": "Click a town note to link it to the hex.", + "pick": "keep", + "why": "Core; but no search box on a flat list.", + "lists": "md notes under townsFolder minus _/templates; blank folder (default) = whole vault", + "focused": false, + "mix": "only if Towns folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.dungeonsList", + "surface": "Hex table: add link", + "label": "Select existing: (Dungeons)", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "desc": "Click a dungeon note to link it to the hex.", + "pick": "keep", + "why": "Core; no search box.", + "lists": "md notes under dungeonsFolder minus _/templates; blank folder (default) = whole vault", + "focused": false, + "mix": "only if Dungeons folder is blank (default): every note in the vault: hexes, map/region notes, biomes, palettes, tables, generators, towns", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.encountersList", + "surface": "Hex table: add link", + "label": "Select existing: (Encounters Table)", + "kind": "picker", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:206", + "desc": "Click a table to link it as this hex's encounter table.", + "pick": "keep", + "why": "Core, but list is unfiltered.", + "lists": "every md note under tablesFolder minus _/templates; NO encounter filter (unlike the hex editor)", + "focused": false, + "mix": "terrain description + encounter tables, landmark/hidden/secret, weather/rumours, region tables and any other roll table", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.createName", + "surface": "Hex table: add link", + "label": "Or create new: ", + "kind": "text", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:232", + "desc": "Type a name for a new note to create and link.", + "pick": "keep", + "why": "Fast stocking.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.createButton", + "surface": "Hex table: add link", + "label": "Create", + "kind": "button", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:237", + "desc": "Create the typed note and link it to the hex.", + "pick": "keep", + "why": "Obvious.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "LinkPicker.closeButtons", + "surface": "Hex table: add link", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/LinkPickerModal.ts:199", + "desc": "Close without linking.", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "MultiLinkNav.items", + "surface": "Hex table: pick linked note", + "label": "", + "kind": "picker", + "level": "conditional: cell has 2+ links", + "loc": "src/hex-table/MultiLinkNavModal.ts:20", + "desc": "Pick which of the linked notes to open.", + "pick": "keep", + "why": "Simple disambiguation.", + "lists": "the links already in that hex cell (towns, dungeons or encounter tables)", + "focused": true, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "MultiLinkNav.closeButtons", + "surface": "Hex table: pick linked note", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-table/MultiLinkNavModal.ts:13", + "desc": "Close the list.", + "pick": "keep", + "why": "Standard.", + "lists": "", + "focused": null, + "mix": "", + "group": "Hex table", + "subgroup": "Linking" + }, + { + "id": "IconFilter.search", + "surface": "Icon picker filter bar (shared)", + "label": "Filter icons...", + "kind": "search", + "level": "always (every icon grid using addIconFilter)", + "loc": "src/HexmakerModal.ts:45", + "desc": "Type to filter icons by name or kind.", + "pick": "keep", + "why": "Essential for large icon sets.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconFilter.packTabs", + "surface": "Icon picker filter bar (shared)", + "label": "All / Terrain / Places / Space / Custom (+counts)", + "kind": "radio", + "level": "always", + "loc": "src/HexmakerModal.ts:108", + "desc": "Tabs that filter icons by pack.", + "pick": "keep", + "why": "Scales the picker; check Space tab follows map kinds.", + "lists": "Icon packs with counts; Custom always shown", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconFilter.placeKindChips", + "surface": "Icon picker filter bar (shared)", + "label": "All places / Settlements / Castles / ...", + "kind": "radio", + "level": "conditional: Places tab active", + "loc": "src/HexmakerModal.ts:134", + "desc": "Sub-filter chips for place icons.", + "pick": "keep", + "why": "A plain picker filter that helps find a place icon; no cost when unused.", + "lists": "Place icon kinds present", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.gmLayerOnly", + "surface": "Icon picker modal", + "label": "GM layer only", + "kind": "checkbox", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:45", + "desc": "Paint the icon so only the GM sees it.", + "pick": "keep", + "why": "GM-only icons are what the GM layer is for; part of running a game.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.manageIcons", + "surface": "Icon picker modal", + "label": "Manage icons / ← pick icons", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:57", + "desc": "Switch to hiding, reordering and uploading icons.", + "pick": "simple", + "why": "Hiding, reordering and uploading icons is ordinary look-and-feel customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons", + "prevPick": "advanced" + }, + { + "id": "IconPicker.remove", + "surface": "Icon picker modal", + "label": "Remove", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:79", + "desc": "Paint 'no icon' (erase).", + "pick": "keep", + "why": "Eraser", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.grid", + "surface": "Icon picker modal", + "label": "(icon tiles)", + "kind": "picker", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:89", + "desc": "Choose the icon to paint on hexes.", + "pick": "keep", + "why": "The point of the form", + "lists": "plugin.availableIcons minus hiddenIcons: bundled terrain + places + space (if space kind on) + custom folder images", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.packTabs", + "surface": "Icon picker modal", + "label": "All / Terrain / Places / Space / Custom", + "kind": "button", + "level": "mode: build/god", + "loc": "src/HexmakerModal.ts:109", + "desc": "Narrow the grid to one icon pack.", + "pick": "keep", + "why": "Scales the picker", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.hideToggle", + "surface": "Icon picker modal", + "label": "eye / eye-off", + "kind": "button", + "level": "conditional: manage mode", + "loc": "src/hex-map/IconPickerModal.ts:138", + "desc": "Hide or show an icon in every picker.", + "pick": "keep", + "why": "Only inside Manage icons; gating that mode covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.dragReorder", + "surface": "Icon picker modal", + "label": "⠿ (drag to reorder)", + "kind": "button", + "level": "conditional: manage mode", + "loc": "src/hex-map/IconPickerModal.ts:157", + "desc": "Drag icons to set their order.", + "pick": "keep", + "why": "Only inside Manage icons; gating that mode covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.uploadDropZone", + "surface": "Icon picker modal", + "label": "Drag & drop images here, or click to browse", + "kind": "button", + "level": "conditional: manage mode, icons folder set", + "loc": "src/hex-map/IconPickerModal.ts:204", + "desc": "Upload your own icon images.", + "pick": "keep", + "why": "Only inside Manage icons; gating that mode covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "IconPicker.closeButtons", + "surface": "Icon picker modal", + "label": "×", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/IconPickerModal.ts:29", + "desc": "Close.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Icons" + }, + { + "id": "Token.notePicker", + "surface": "Token modal", + "label": "Note", + "kind": "picker", + "level": "conditional: new token only", + "loc": "src/hex-map/TokenModal.ts:94", + "desc": "Search for a note to link the token to, or type a name to make one.", + "pick": "keep", + "why": "Core, but the list must be focused on characters/places, not world plumbing", + "lists": "up to 50 .md under worldFolder (whole tree) + towns/dungeons/features/quests/factions/regions folders, minus tables, workflows, hexes, export, icons, palettes, generators, templates, _ notes (TokenModal.ts:379-402)", + "focused": false, + "mix": "biome notes (world/biomes), biome-pool notes (world/biome-pools), world-type notes (world/world-types), region notes, factions, quests, features, loose world/ notes", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.noteStatus", + "surface": "Token modal", + "label": "Links to … / Creates a new note: …", + "kind": "text", + "level": "conditional: new token only", + "loc": "src/hex-map/TokenModal.ts:115", + "desc": "Says whether Save will link an existing note or create a new one.", + "pick": "keep", + "why": "Prevents silent wrong-note links; cheap one-liner", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.iconPackTabs", + "surface": "Token modal", + "label": "All / Terrain / Places / Space / Custom", + "kind": "button", + "level": "always", + "loc": "src/HexmakerModal.ts:109", + "desc": "Tabs that narrow the icon grid to one icon pack.", + "pick": "keep", + "why": "Scales the big icon list; Terrain/Space tabs are noise for a token though", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.iconGrid", + "surface": "Token modal", + "label": "Icon", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:199", + "desc": "Pick the picture shown on the token.", + "pick": "simple", + "why": "Token basics: what the token looks like.", + "lists": "'no icon' + plugin.availableIcons minus settings.hiddenIcons (bundled terrain, places, space if enabled, custom folder) (TokenModal.ts:196-229)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.shape", + "surface": "Token modal", + "label": "Shape", + "kind": "dropdown", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:233", + "desc": "Circle, square or hexagon token.", + "pick": "simple", + "why": "Token look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "prevPick": "advanced" + }, + { + "id": "Token.size", + "surface": "Token modal", + "label": "Size", + "kind": "radio", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:244", + "desc": "Small, medium or large token.", + "pick": "simple", + "why": "Token basics: tells a party from a dragon.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.fillColor", + "surface": "Token modal", + "label": "Fill color", + "kind": "color", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:262", + "desc": "Background color behind the icon.", + "pick": "simple", + "why": "Token basics: tells tokens apart.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.borderToggle", + "surface": "Token modal", + "label": "Border color (on/off)", + "kind": "toggle", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:284", + "desc": "Turn a colored ring around the token on or off.", + "pick": "simple", + "why": "Token look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "prevPick": "advanced" + }, + { + "id": "Token.borderColor", + "surface": "Token modal", + "label": "Border color", + "kind": "color", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:292", + "desc": "Pick the ring color.", + "pick": "simple", + "why": "Token look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens", + "prevPick": "advanced" + }, + { + "id": "Token.description", + "surface": "Token modal", + "label": "Description", + "kind": "textarea", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:315", + "desc": "Short text saved in the note's frontmatter, shown in token info.", + "pick": "advanced", + "why": "A real token field, but the linked note already holds text; more than a newcomer needs.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.removeButton", + "surface": "Token modal", + "label": "Remove token", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TokenModal.ts:333", + "desc": "Take this token off the map (the note stays).", + "pick": "keep", + "why": "Obvious action when editing", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.saveButton", + "surface": "Token modal", + "label": "Next: place on map / Save", + "kind": "button", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:340", + "desc": "Save the token (new: then click a hex to place it).", + "pick": "simple", + "why": "Token basics: the form does nothing without it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "Token.closeButtons", + "surface": "Token modal", + "label": "Cancel", + "kind": "button", + "level": "always", + "loc": "src/hex-map/TokenModal.ts:372", + "desc": "Close without saving.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.jumpButton", + "surface": "Token info modal", + "label": "⌖", + "kind": "button", + "level": "always", + "loc": "src/hex-map/TokenInfoModal.ts:31", + "desc": "Center the map on the token's hex.", + "pick": "keep", + "why": "Useful in play; unlabeled glyph though", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.openNoteLink", + "surface": "Token info modal", + "label": "Open note", + "kind": "button", + "level": "conditional: note exists", + "loc": "src/hex-map/TokenInfoModal.ts:44", + "desc": "Open the token's note in a tab.", + "pick": "keep", + "why": "Obvious action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.editButton", + "surface": "Token info modal", + "label": "Edit token", + "kind": "button", + "level": "conditional: edit allowed", + "loc": "src/hex-map/TokenInfoModal.ts:56", + "desc": "Open the token editor.", + "pick": "keep", + "why": "Obvious action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.noteLinks", + "surface": "Token info modal", + "label": "(links inside the note preview)", + "kind": "button", + "level": "conditional: note has links", + "loc": "src/hex-map/TokenInfoModal.ts:91", + "desc": "Click a link in the note preview to open it in a new tab.", + "pick": "keep", + "why": "Natural reading behaviour", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.removeButton", + "surface": "Token info modal", + "label": "× remove / Confirm remove?", + "kind": "button", + "level": "conditional: remove allowed", + "loc": "src/hex-map/TokenInfoModal.ts:117", + "desc": "Remove the token from the map, with a confirm click.", + "pick": "keep", + "why": "Fine; confirm is good", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "TokenInfo.closeButtons", + "surface": "Token info modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/TokenInfoModal.ts:20", + "desc": "Close the info box.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Tokens" + }, + { + "id": "PathName.nameInput", + "surface": "Rename path modal", + "label": "(path name)", + "kind": "text", + "level": "mode: build/god", + "loc": "src/hex-map/PathNameModal.ts:45", + "desc": "Type the path's new name.", + "pick": "keep", + "why": "Single-purpose form; drop the map-note-tables blurb above it", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathName.saveButton", + "surface": "Rename path modal", + "label": "Save", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/PathNameModal.ts:48", + "desc": "Save the new name (disabled while the name is taken or empty).", + "pick": "keep", + "why": "Primary action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathName.closeButtons", + "surface": "Rename path modal", + "label": "Cancel", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/PathNameModal.ts:49", + "desc": "Close without renaming.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.editToggle", + "surface": "Path type picker modal", + "label": "✏ Edit / ← Done", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/PathPickerModal.ts:158", + "desc": "Switch the picker into editing the palette's path types.", + "pick": "simple", + "why": "Editing path types is palette customization, which the owner wants in Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types", + "prevPick": "advanced" + }, + { + "id": "PathPicker.drawMode", + "surface": "Path type picker modal", + "label": "1. How to draw: Hex by hex / Auto-route", + "kind": "radio", + "level": "conditional: path tool", + "loc": "src/hex-map/PathPickerModal.ts:107", + "desc": "Choose drawing hex-by-hex or letting the path find its own way.", + "pick": "simple", + "why": "Hex-by-hex vs auto-route is the basic path choice.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.removeTile", + "surface": "Path type picker modal", + "label": "Remove", + "kind": "button", + "level": "conditional: erase allowed", + "loc": "src/hex-map/PathPickerModal.ts:187", + "desc": "Switch to erasing paths.", + "pick": "keep", + "why": "Standard eraser", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.typeGrid", + "surface": "Path type picker modal", + "label": "2. Pick a path type to start drawing", + "kind": "picker", + "level": "mode: build/god", + "loc": "src/hex-map/PathPickerModal.ts:198", + "desc": "Choose road, river, etc. and start drawing.", + "pick": "simple", + "why": "Picking road or river is the start of every path.", + "lists": "path types of the map's palette (plugin.getPathTypes(paletteName), PathPickerModal.ts:176)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.pathsOnMap", + "surface": "Path type picker modal", + "label": "Paths on this map", + "kind": "picker", + "level": "conditional: path tool", + "loc": "src/hex-map/PathPickerModal.ts:229", + "desc": "List of drawn paths; click one to select it on the map.", + "pick": "advanced", + "why": "A second way to find a path; useful, but beyond basic drawing.", + "lists": "every path on the open map with type swatch, name and summary (pathsOnMap.list)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.editTypeTile", + "surface": "Path type picker modal", + "label": "(type tile, edit mode)", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/PathPickerModal.ts:268", + "desc": "Click a path type to open its editor.", + "pick": "keep", + "why": "Only inside the path type edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.dragReorder", + "surface": "Path type picker modal", + "label": "⠿ (drag to reorder)", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/PathPickerModal.ts:285", + "desc": "Drag path types to change their order.", + "pick": "keep", + "why": "Only inside the path type edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.addTypeTile", + "surface": "Path type picker modal", + "label": "+ Add", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/PathPickerModal.ts:315", + "desc": "Add a new path type and open its editor.", + "pick": "keep", + "why": "Only inside the path type edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathPicker.closeButtons", + "surface": "Path type picker modal", + "label": "×", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/PathPickerModal.ts:133", + "desc": "Close the picker (leaves the path tool if nothing picked).", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.name", + "surface": "Path type editor modal", + "label": "Name", + "kind": "text", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:78", + "desc": "Name of this path type.", + "pick": "keep", + "why": "Basic identity", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.color", + "surface": "Path type editor modal", + "label": "Color", + "kind": "color", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:88", + "desc": "Line color.", + "pick": "keep", + "why": "Basic look", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.width", + "surface": "Path type editor modal", + "label": "Width", + "kind": "slider", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:99", + "desc": "Line thickness, 1-10.", + "pick": "keep", + "why": "Basic look; preview shows it", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.lineStyle", + "surface": "Path type editor modal", + "label": "Line style", + "kind": "dropdown", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:111", + "desc": "Solid, dashed or dotted line.", + "pick": "keep", + "why": "Basic look (roads vs trails)", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.routing", + "surface": "Path type editor modal", + "label": "Routing", + "kind": "dropdown", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:125", + "desc": "Whether the line runs through hex centres, edge middles or along borders.", + "pick": "keep", + "why": "Path types are Advanced and this editor is only reached through them; a visible line choice.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.avoidImpassable", + "surface": "Path type editor modal", + "label": "Avoid impassable terrain", + "kind": "toggle", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:140", + "desc": "Auto-route goes around water/impassable terrain.", + "pick": "keep", + "why": "Path types are Advanced and this editor is only reached through them; a real path option.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.autoRoute", + "surface": "Path type editor modal", + "label": "Auto-route", + "kind": "dropdown", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:149", + "desc": "Direct or winding auto-routed paths.", + "pick": "keep", + "why": "Path types are Advanced and this editor is only reached through them; a visible style choice.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.carves", + "surface": "Path type editor modal", + "label": "Carves terrain", + "kind": "text", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:163", + "desc": "Terrain the path stamps into regions when confirmed (free text).", + "pick": "advanced", + "why": "Overworld-only path option; belongs with the regions feature.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.carveWidth", + "surface": "Path type editor modal", + "label": "Carve width", + "kind": "dropdown", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:173", + "desc": "Carve only the path hexes (0) or their neighbours too (1).", + "pick": "overkill", + "why": "A 0/1 numeric internal for carving; nobody needs it to draw paths.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.saveButton", + "surface": "Path type editor modal", + "label": "Save", + "kind": "button", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:185", + "desc": "Save the path type.", + "pick": "keep", + "why": "Primary action (closing also autosaves)", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.deleteButton", + "surface": "Path type editor modal", + "label": "Delete", + "kind": "button", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:194", + "desc": "Delete this path type (asks first; removes its paths).", + "pick": "keep", + "why": "Needed, has confirm", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.deleteConfirm", + "surface": "Path type editor modal", + "label": "Yes, delete / Cancel", + "kind": "button", + "level": "conditional: after Delete", + "loc": "src/hex-map/PathTypeEditorModal.ts:212", + "desc": "Confirm or cancel deleting the type.", + "pick": "keep", + "why": "Safety confirm", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "PathType.closeButtons", + "surface": "Path type editor modal", + "label": "×", + "kind": "button", + "level": "conditional: editing a path type", + "loc": "src/hex-map/PathTypeEditorModal.ts:225", + "desc": "Close (changes are autosaved).", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Path types" + }, + { + "id": "GotoHex.xInput", + "surface": "Go to hex modal", + "label": "X:", + "kind": "number", + "level": "always", + "loc": "src/hex-map/GotoHexModal.ts:21", + "desc": "Column of the hex to jump to.", + "pick": "keep", + "why": "Single-purpose and small", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "GotoHex.yInput", + "surface": "Go to hex modal", + "label": "Y:", + "kind": "number", + "level": "always", + "loc": "src/hex-map/GotoHexModal.ts:26", + "desc": "Row of the hex to jump to.", + "pick": "keep", + "why": "Single-purpose and small", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "GotoHex.goButton", + "surface": "Go to hex modal", + "label": "Go", + "kind": "button", + "level": "always", + "loc": "src/hex-map/GotoHexModal.ts:40", + "desc": "Center the map on that hex.", + "pick": "keep", + "why": "Primary action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "GotoHex.closeButtons", + "surface": "Go to hex modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/GotoHexModal.ts:14", + "desc": "Close.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "HexHelp.closeButtons", + "surface": "Hex map help modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/HexHelpModal.ts:10", + "desc": "Close the controls & tools help.", + "pick": "keep", + "why": "Read-only help; no inputs", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Go to hex & help" + }, + { + "id": "Locations.search", + "surface": "Locations modal", + "label": "Find a location…", + "kind": "search", + "level": "conditional: hex has locations", + "loc": "src/hex-map/LocationsModal.ts:45", + "desc": "Filter this hex's linked maps by name.", + "pick": "keep", + "why": "Only opened when a hex has many locations", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.list", + "surface": "Locations modal", + "label": "(location name)", + "kind": "picker", + "level": "conditional: hex has locations", + "loc": "src/hex-map/LocationsModal.ts:111", + "desc": "Click a location to open its map.", + "pick": "keep", + "why": "The point of the form", + "lists": "maps linked to this hex (mapStore.get(map,x_y).locations, LocationsModal.ts:38)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.openButton", + "surface": "Locations modal", + "label": "Open", + "kind": "button", + "level": "conditional: hex has locations", + "loc": "src/hex-map/LocationsModal.ts:118", + "desc": "Open that location's map.", + "pick": "drop", + "why": "Same row already opens the map when you click its name; the name replaces it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.unlink", + "surface": "Locations modal", + "label": "✕", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/LocationsModal.ts:122", + "desc": "Unlink the map from this hex (map is kept).", + "pick": "keep", + "why": "Needed management action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.dragReorder", + "surface": "Locations modal", + "label": "⋮⋮ (drag)", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/LocationsModal.ts:89", + "desc": "Drag to reorder this hex's locations.", + "pick": "keep", + "why": "Normal housekeeping, only in build mode with several locations.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.newLocation", + "surface": "Locations modal", + "label": "New location…", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/LocationsModal.ts:62", + "desc": "Make a new map for this hex.", + "pick": "keep", + "why": "Primary create action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.linkExisting", + "surface": "Locations modal", + "label": "Link existing map…", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/LocationsModal.ts:66", + "desc": "Link a map you already have to this hex.", + "pick": "keep", + "why": "Common action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "Locations.closeButtons", + "surface": "Locations modal", + "label": "×", + "kind": "button", + "level": "conditional: hex has locations", + "loc": "src/hex-map/LocationsModal.ts:42", + "desc": "Close.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Locations" + }, + { + "id": "FactionPicker.grid", + "surface": "Faction picker modal", + "label": "(faction tiles)", + "kind": "picker", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:207", + "desc": "Pick a faction to paint onto hexes.", + "pick": "keep", + "why": "The point of the form; dead-ends when factions folder is blank (default)", + "lists": ".md anywhere under factionsFolder (incl. subfolders), linkable (no _ / templates), sorted (FactionPickerModal.ts:180-183)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.removeTile", + "surface": "Faction picker modal", + "label": "Remove", + "kind": "button", + "level": "conditional: erase allowed", + "loc": "src/hex-map/FactionPickerModal.ts:193", + "desc": "Switch to erasing factions from hexes.", + "pick": "keep", + "why": "Standard eraser", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.editTile", + "surface": "Faction picker modal", + "label": "✏", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:221", + "desc": "Edit the faction's name, color and pattern.", + "pick": "keep", + "why": "Hover-only pencil; fine", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.newName", + "surface": "Faction picker modal", + "label": "New faction name…", + "kind": "text", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:270", + "desc": "Type a name for a new faction.", + "pick": "keep", + "why": "Quick create", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.createButton", + "surface": "Faction picker modal", + "label": "Create", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:274", + "desc": "Create the faction note and open its editor.", + "pick": "keep", + "why": "Quick create", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionPicker.closeButtons", + "surface": "Faction picker modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:300", + "desc": "Close.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.openNote", + "surface": "Faction editor modal", + "label": "Open note →", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:46", + "desc": "Open the faction's note.", + "pick": "keep", + "why": "Obvious action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.name", + "surface": "Faction editor modal", + "label": "Name", + "kind": "text", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:74", + "desc": "Rename the faction (renames the note).", + "pick": "keep", + "why": "Basic", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.color", + "surface": "Faction editor modal", + "label": "Color", + "kind": "color", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:81", + "desc": "Faction overlay color on the map.", + "pick": "keep", + "why": "Basic look", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.pattern", + "surface": "Faction editor modal", + "label": "Pattern", + "kind": "dropdown", + "level": "always", + "loc": "src/hex-map/overlayPatternControls.ts:139", + "desc": "Fill pattern for the overlay (stripes, dots…; 10 options).", + "pick": "simple", + "why": "Faction look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.patternScale", + "surface": "Faction editor modal", + "label": "Pattern scale", + "kind": "slider", + "level": "always", + "loc": "src/hex-map/overlayPatternControls.ts:149", + "desc": "Size of the pattern.", + "pick": "simple", + "why": "Faction look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.opacity", + "surface": "Faction editor modal", + "label": "Opacity", + "kind": "slider", + "level": "always", + "loc": "src/hex-map/overlayPatternControls.ts:159", + "desc": "How see-through the overlay is.", + "pick": "simple", + "why": "Faction look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.outlineWidth", + "surface": "Faction editor modal", + "label": "Outline width", + "kind": "slider", + "level": "always", + "loc": "src/hex-map/overlayPatternControls.ts:169", + "desc": "Thickness of the faction border.", + "pick": "simple", + "why": "Faction look is ordinary customization. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.save", + "surface": "Faction editor modal", + "label": "Save", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:102", + "desc": "Save name, color and style.", + "pick": "keep", + "why": "Primary action", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "FactionEditor.clearColor", + "surface": "Faction editor modal", + "label": "Clear color", + "kind": "button", + "level": "conditional: faction has a color", + "loc": "src/hex-map/FactionPickerModal.ts:126", + "desc": "Remove the faction's color and close.", + "pick": "simple", + "why": "Pairs with the faction colour, which is Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions", + "prevPick": "advanced" + }, + { + "id": "FactionEditor.closeButtons", + "surface": "Faction editor modal", + "label": "×", + "kind": "button", + "level": "always", + "loc": "src/hex-map/FactionPickerModal.ts:36", + "desc": "Close without saving.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Factions" + }, + { + "id": "TerrainPicker.editToggle", + "surface": "Terrain picker modal", + "label": "✏ Edit / ← Done", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:52", + "desc": "Switch the paint picker into editing the palette.", + "pick": "simple", + "why": "Editing the palette from the paint picker is ordinary palette customization, which the owner wants in Simple. Owner (pass 3): \"a streamlined but still customizable experience for simple, not to hide every little possible scary thing.\"", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain", + "prevPick": "advanced" + }, + { + "id": "TerrainPicker.fullEditor", + "surface": "Terrain picker modal", + "label": "Full editor…", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:63", + "desc": "Open the full palette editor.", + "pick": "keep", + "why": "Only inside the palette edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.brushSize", + "surface": "Terrain picker modal", + "label": "Brush: 1× 3× 7×", + "kind": "radio", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:83", + "desc": "How many hexes one click paints.", + "pick": "keep", + "why": "Speeds up painting; small", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.eyedropper", + "surface": "Terrain picker modal", + "label": "⌖ Pick", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:104", + "desc": "Pick a terrain by clicking a hex on the map.", + "pick": "keep", + "why": "Handy and small", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.clear", + "surface": "Terrain picker modal", + "label": "Clear", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:119", + "desc": "Paint hexes back to no terrain.", + "pick": "keep", + "why": "Eraser", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.grid", + "surface": "Terrain picker modal", + "label": "(terrain tiles)", + "kind": "picker", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:132", + "desc": "Choose the terrain to paint.", + "pick": "keep", + "why": "The point of the form", + "lists": "terrains of the map's palette (or the region's palette on an overworld) (HexMapView.ts:2246)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.editTile", + "surface": "Terrain picker modal", + "label": "(terrain tile, edit mode)", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:175", + "desc": "Click a terrain to edit it.", + "pick": "keep", + "why": "Only inside the palette edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.dragReorder", + "surface": "Terrain picker modal", + "label": "⠿ (drag to reorder)", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:198", + "desc": "Drag terrains to reorder the palette.", + "pick": "keep", + "why": "Only inside the palette edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.addTile", + "surface": "Terrain picker modal", + "label": "+ Add", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:232", + "desc": "Add a terrain (blank or copied from another palette).", + "pick": "keep", + "why": "Only inside the palette edit mode; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.refreshEncounterLinks", + "surface": "Terrain picker modal", + "label": "Refresh all encounter table links", + "kind": "button", + "level": "conditional: edit mode", + "loc": "src/hex-map/TerrainPickerModal.ts:275", + "desc": "Re-link every hex's encounter table to its terrain.", + "pick": "overkill", + "why": "Maintenance button that re-links tables; should run on its own.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainPicker.closeButtons", + "surface": "Terrain picker modal", + "label": "×", + "kind": "button", + "level": "mode: build/god", + "loc": "src/hex-map/TerrainPickerModal.ts:33", + "desc": "Close (leaves the tool if nothing picked).", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainTemplate.newBlank", + "surface": "Add terrain (template) modal", + "label": "New blank", + "kind": "button", + "level": "conditional: edit mode → Add", + "loc": "src/hex-map/TerrainPickerModal.ts:309", + "desc": "Add an empty terrain.", + "pick": "keep", + "why": "Only inside palette edit mode → Add; gating that toggle covers it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainTemplate.copyList", + "surface": "Add terrain (template) modal", + "label": "Or copy from an existing palette:", + "kind": "picker", + "level": "conditional: edit mode → Add", + "loc": "src/hex-map/TerrainPickerModal.ts:329", + "desc": "Copy a terrain from another palette.", + "pick": "keep", + "why": "Only inside palette edit mode → Add; gating that toggle covers it.", + "lists": "terrains of every other palette not already in this one, grouped by palette name (TerrainPickerModal.ts:316-322)", + "focused": true, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainTemplate.closeButtons", + "surface": "Add terrain (template) modal", + "label": "×", + "kind": "button", + "level": "conditional: edit mode → Add", + "loc": "src/hex-map/TerrainPickerModal.ts:345", + "desc": "Close without adding.", + "pick": "keep", + "why": "Standard", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.name", + "surface": "Terrain entry editor modal", + "label": "Name", + "kind": "text", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:57", + "desc": "Terrain name (renames it on every hex).", + "pick": "keep", + "why": "Basic", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.type", + "surface": "Terrain entry editor modal", + "label": "Type", + "kind": "dropdown", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:73", + "desc": "What kind of terrain it is (forest, water…) for generators.", + "pick": "keep", + "why": "Only in the terrain editor (palette editing, Advanced); generators and biomes need it.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.impassable", + "surface": "Terrain entry editor modal", + "label": "Impassable", + "kind": "toggle", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:85", + "desc": "Auto-routed paths go around this terrain.", + "pick": "keep", + "why": "Only in the terrain editor (palette editing, Advanced); a real terrain option.", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.color", + "surface": "Terrain entry editor modal", + "label": "Color", + "kind": "color", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:94", + "desc": "Hex fill color.", + "pick": "keep", + "why": "Basic look", + "lists": "", + "focused": null, + "mix": "", + "group": "Map pickers & editors", + "subgroup": "Terrain" + }, + { + "id": "TerrainEntry.icon", + "surface": "Terrain entry editor modal", + "label": "Icon", + "kind": "dropdown", + "level": "conditional: editing a terrain", + "loc": "src/hex-map/TerrainEntryEditorModal.ts:102", + "desc": "Icon drawn on hexes of this terrain.", + "pick": "keep", + "why": "Basic look, but a huge